forked from Wunderbyte-GmbH/moodle-mod_booking
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.php
1247 lines (1121 loc) · 46.2 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php // $Id: lib.php,v 1.59.2.29 2011/02/01 11:09:31 dasistwas Exp $
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/mod/booking/icallib.php');
$COLUMN_HEIGHT = 300;
/// Standard functions /////////////////////////////////////////////////////////
function booking_user_outline($course, $user, $mod, $booking) {
global $DB;
if ($answer = $DB->get_record('booking_answers', array('bookingid' => $booking->id, 'userid' => $user->id))) {
$result = new stdClass();
$result->info = "'".format_string(booking_get_option_text($booking, $answer->optionid))."'";
$result->time = $answer->timemodified;
return $result;
}
return NULL;
}
function booking_user_complete($course, $user, $mod, $booking) {
global $DB;
if ($answer = $DB->get_record('booking_answers', array("bookingid" => $booking->id, "userid" => $user->id))) {
$result = new stdClass();
$result->info = "'".format_string(booking_get_option_text($booking, $answer->optionid))."'";
$result->time = $answer->timemodified;
echo get_string("answered", "booking").": $result->info. ".get_string("updated", '', userdate($result->time));
} else {
print_string("notanswered", "booking");
}
}
function booking_supports($feature) {
switch($feature) {
case FEATURE_GROUPS: return false;
case FEATURE_GROUPINGS: return false;
case FEATURE_GROUPMEMBERSONLY: return false;
case FEATURE_MOD_INTRO: return true;
case FEATURE_COMPLETION_TRACKS_VIEWS: return false;
case FEATURE_COMPLETION_HAS_RULES: return false;
case FEATURE_GRADE_HAS_GRADE: return false;
case FEATURE_GRADE_OUTCOMES: return false;
case FEATURE_BACKUP_MOODLE2: return true;
default: return null;
}
}
function booking_add_instance($booking) {
global $DB;
// Given an object containing all the necessary data,
// (defined by the form in mod.html) this function
// will create a new instance and return the id number
// of the new instance.
$booking->timemodified = time();
if (empty($booking->timerestrict)) {
$booking->timeopen = 0;
$booking->timeclose = 0;
}
// Copy the text fields out:
$booking->bookedtext = $booking->bookedtext['text'];
$booking->waitingtext = $booking->waitingtext['text'];
$booking->statuschangetext = $booking->statuschangetext['text'];
$booking->deletedtext = $booking->deletedtext['text'];
//insert answer options from mod_form
$booking->id = $DB->insert_record("booking", $booking);
if(!empty($booking->option)){
foreach ($booking->option as $key => $value) {
$value = trim($value);
if (isset($value) && $value <> '') {
$option = new stdClass();
$option->text = $value;
$option->bookingid = $booking->id;
if (isset($booking->limit[$key])) {
$option->maxanswers = $booking->limit[$key];
}
$option->timemodified = time();
$DB->insert_record("booking_options", $option);
}
}
}
return $booking->id;
}
function booking_update_instance($booking) {
global $DB;
// Given an object containing all the necessary data,
// (defined by the form in mod.html) this function
// will update an existing instance with new data.
// we have to prepare the bookingclosingtimes as an $arrray, currently they are in $booking as $key (string)
$booking->id = $booking->instance;
$booking->timemodified = time();
if (empty($booking->timerestrict)) {
$booking->timeopen = 0;
$booking->timeclose = 0;
}
// Copy the text fields out:
$booking->bookedtext = $booking->bookedtext['text'];
$booking->waitingtext = $booking->waitingtext['text'];
$booking->statuschangetext = $booking->statuschangetext['text'];
$booking->deletedtext = $booking->deletedtext['text'];
//update, delete or insert answers
if(!empty($booking->option)){
foreach ($booking->option as $key => $value) {
$value = trim($value);
$option = new stdClass();
$option->text = $value;
$option->bookingid = $booking->id;
if (isset($booking->limit[$key])) {
$option->maxanswers = $booking->limit[$key];
}
$option->timemodified = time();
if (isset($booking->optionid[$key]) && !empty($booking->optionid[$key])){//existing booking record
$option->id=$booking->optionid[$key];
if (isset($value) && $value <> '') {
$DB->update_record("booking_options", $option);
} else { //empty old option - needs to be deleted.
$DB->delete_records("booking_options", array("id"=>$option->id));
}
} else {
if (isset($value) && $value <> '') {
$DB->insert_record("booking_options", $option);
}
}
}
}
return $DB->update_record('booking', $booking);
}
function booking_update_options($optionvalues){
global $DB;
$option = new stdClass();
$option->bookingid = $optionvalues->bookingid;
$option->text = trim($optionvalues->text);
if ($optionvalues->limitanswers == 0){
$optionvalues->limitanswers = 0;
$option->maxanswers = 0;
$option->maxoverbooking = 0;
} else {
$option->maxanswers = $optionvalues->maxanswers;
$option->maxoverbooking = $optionvalues->maxoverbooking;
$option->limitanswers = 1;
}
if(isset($optionvalues->restrictanswerperiod)){
$option->bookingclosingtime = $optionvalues->bookingclosingtime;
} else {
$option->bookingclosingtime = 0;
}
$option->courseid = $optionvalues->courseid;
if (isset($optionvalues->startendtimeknown)){
$option->coursestarttime = $optionvalues->coursestarttime;
$option->courseendtime = $optionvalues->courseendtime;
} else {
$option->coursestarttime = 0;
$option->courseendtime = 0;
}
$option->description = $optionvalues->description;
$option->limitanswers = $optionvalues->limitanswers;
$option->timemodified = time();
if (isset($optionvalues->optionid) && !empty($optionvalues->optionid) && $optionvalues->id != "add"){//existing booking record
$option->id=$optionvalues->optionid;
if (isset($optionvalues->text) && $optionvalues->text <> '') {
return $DB->update_record("booking_options", $option);
}
} elseif (isset($optionvalues->text) && $optionvalues->text <> '') {
return $DB->insert_record("booking_options", $option);
}
}
/**
* Checks the status of the specified user
* @param $userid userid of the user
* @param $optionid booking option to check
* @param $bookingid booking id
* @param $cmid course module id
* @return localised string of user status
*/
function booking_get_user_status($userid,$optionid,$bookingid,$cmid){
global $DB;
$option = $DB->get_record('booking_options', array('id' => $optionid));
$current = $DB->get_record('booking_answers', array('bookingid' => $bookingid, 'userid' => $userid, 'optionid' => $optionid));
$allresponses = $DB->get_records_select('booking_answers', "bookingid = $bookingid AND optionid = $optionid",array(), 'timemodified', 'userid');
$context = get_context_instance(CONTEXT_MODULE,$cmid);
$i=1;
if(!empty($allresponses)){
foreach($allresponses as $answer){
if (has_capability('mod/booking:choose', $context, $answer->userid)){
$sortedresponses[$i++] = $answer->userid;
}
}
$useridaskey = array_flip($sortedresponses);
if($option->limitanswers){
if($useridaskey[$userid] > $option->maxanswers + $option->maxoverbooking){
$status = "Problem, please contact the admin";
} elseif (($useridaskey[$userid]) > $option->maxanswers) { // waitspaceavailable
$status = get_string('onwaitinglist','booking');
} elseif ($useridaskey[$userid] <= $option->maxanswers) {
$status = get_string('booked','booking');
} else {
$status = get_string('notbooked','booking');
}
} else {
if (!empty($useridaskey[$userid])){
$status = get_string('booked','booking');
} else {
$status = get_string('notbooked','booking');
}
}
return $status;
}
return get_string('notbooked','booking');
}
/**
* Display a message about the maximum nubmer of bookings this user is allowed to make
* @param object $booking
* @param object $user
* @param object[] $bookinglist
* @return string
*/
function booking_show_maxperuser($booking, $user, $bookinglist) {
if (!$booking->maxperuser) {
return ''; // No per-user limits.
}
$outdata = new stdClass();
$outdata->limit = $booking->maxperuser;
$outdata->count = booking_get_user_booking_count($booking, $user, $bookinglist);
return html_writer::tag('p', get_string('maxperuserwarning', 'mod_booking', $outdata));
}
function booking_get_user_booking_count($booking, $user, $bookinglist) {
$count = 0;
$now = time();
foreach ($bookinglist as $optionid => $optbookings) {
if (!isset($booking->option[$optionid])) {
continue; // Booking not for one of the available options (shouldn't happen?)
}
if ($booking->option[$optionid]->courseendtime < $now) {
continue; // Booking is in the past - ignore it.
}
foreach ($optbookings as $optbooking) {
if ($optbooking->id == $user->id) {
$count++; // Current booking for this user.
}
}
}
return $count;
}
/**
* Echoes HTML code for booking table with all booking options and booking status
* @param $booking object containing complete details of the booking instance
* @param $user object of current user
* @param $cm module object
* @param $allresponses array of all responses
* @param $singleuser 0 show all booking options, 1 show only my booking options
* @return nothing
*/
function booking_show_form($booking, $user, $cm, $allresponses,$singleuser=0) {
global $DB, $OUTPUT;
//$optiondisplay is an array of the display info for a booking $cdisplay[$optionid]->text - text name of option.
// ->maxanswers -maxanswers for this option
// ->full - whether this option is full or not. 0=not full, 1=full
// ->maxoverbooking - waitinglist places dor option
// ->waitingfull - whether waitinglist is full or not 0=not, 1=full
$bookingfull = false;
$cdisplay = new stdClass();
if ($booking->limitanswers) { //set bookingfull to true by default if limitanswers.
$bookingfull = true;
$waitingfull = true;
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$table = NULL;
$displayoptions = new stdClass();
$displayoptions->para = false;
$tabledata = array();
$current = array();
$underlimit = ($booking->maxperuser == 0);
$underlimit = $underlimit || (booking_get_user_booking_count($booking, $user, $allresponses) < $booking->maxperuser);
foreach ($booking->option as $option) {
$optiondisplay = new stdClass();
$optiondisplay->delete = "";
$optiondisplay->button = "";
$hiddenfields = array('answer' => $option->id);
// determine the ranking in order of booking time. necessary to decide whether user is on waitinglist or in regular booking
if(@$allresponses[$option->id]){
foreach($allresponses[$option->id] as $rank => $userobject){
if ($user->id == $userobject->id){
$current[$option->id] = $rank; //ranking of the user in order of subscription time
}
}
}
$inpast = $option->courseendtime && ($option->courseendtime < time());
$extraclass = $inpast ? ' inpast' : '';
if (!empty($current[$option->id])) {
if (!$option->limitanswers){
if ($inpast) {
$optiondisplay->booked = get_string('bookedpast','booking');
} else {
$optiondisplay->booked = get_string('booked','booking');
}
$rowclasses[] = "mod-booking-booked".$extraclass;
if(($booking->allowupdate and $option->status != 'closed') or has_capability('mod/booking:deleteresponses', $context)){
$buttonoptions = array('id' => $cm->id, 'action' => 'delbooking', 'optionid' => $option->id, 'sesskey' => $user->sesskey);
$url = new moodle_url('view.php',$buttonoptions);
$url->params($buttonoptions);
$optiondisplay->delete = $OUTPUT->single_button($url,get_string('cancelbooking','booking'),'post').'<br />';
}
} elseif ($current[$option->id] > $option->maxanswers + $option->maxoverbooking){
$optiondisplay->booked = "Problem, please contact the admin";
} elseif ($current[$option->id] > $option->maxanswers) { // waitspaceavailable
$optiondisplay->booked = get_string('onwaitinglist','booking');
$rowclasses[] = "mod-booking-watinglist".$extraclass;
if(($booking->allowupdate and $option->status != 'closed') or has_capability('mod/booking:deleteresponses', $context)){
$buttonoptions = array('id' => $cm->id, 'action' => 'delbooking', 'optionid' => $option->id, 'sesskey' => $user->sesskey);
$url = new moodle_url('view.php',$buttonoptions);
$optiondisplay->delete = $OUTPUT->single_button($url,get_string('cancelbooking','booking'),'post').'<br />';
}
} elseif ($current[$option->id] <= $option->maxanswers) {
if ($inpast) {
$optiondisplay->booked = get_string('bookedpast','booking');
} else {
$optiondisplay->booked = get_string('booked','booking');
}
$rowclasses[] = "mod-booking-booked".$extraclass;
if(($booking->allowupdate and $option->status != 'closed') or has_capability('mod/booking:deleteresponses', $context)){
$buttonoptions = array('id' => $cm->id, 'action' => 'delbooking', 'optionid' => $option->id, 'sesskey' => $user->sesskey);
$url = new moodle_url('view.php',$buttonoptions);
$optiondisplay->delete = $OUTPUT->single_button($url,get_string('cancelbooking','booking'),'post').'<br />';
}
}
if(!$booking->allowupdate){
$optiondisplay->button = "";
}
} else {
$optiondisplay->booked = get_string('notbooked','booking');
if (!$singleuser){
$rowclasses[] = $extraclass;
} else {
$rowclasses[] = "mod-booking-invisible".$extraclass;
}
$buttonoptions = array('answer' => $option->id, 'id' => $cm->id,'sesskey' => $user->sesskey);
$url = new moodle_url('view.php',$buttonoptions);
$url->params($hiddenfields);
$optiondisplay->button = $OUTPUT->single_button($url, get_string('booknow','booking'),'post');
}
if ( $booking->option[$option->id]->limitanswers && ($booking->option[$option->id]->status == "full")) {
$optiondisplay->button = '';
} elseif ($booking->option[$option->id]->status == "closed") {
$optiondisplay->button = '';
}
if (!$underlimit) {
$optiondisplay->button = '';
}
// 'check if user is logged in' <- checking the capability actually
// 'don't show booking button if the logged in user is the guest user.' <- test directly with $USER->username == 'guest'
if (has_capability('mod/booking:choose', $context, $user->id, false)) {
$bookingbutton = $optiondisplay->button;
}
/*else {
$bookingbutton = get_string('havetologin', 'booking')."<br />";
}*/
if (!$option->limitanswers){
$stravailspaces = get_string("unlimited", 'booking');
} else {
$stravailspaces = get_string("placesavailable", "booking").": ".$option->availspaces." / ".$option->maxanswers."<br />".get_string("waitingplacesavailable", "booking").": ".$option->availwaitspaces." / ".$option->maxoverbooking;
}
if (has_capability('mod/booking:readresponses', $context)){
$numberofresponses = 0;
if(isset($allresponses[$option->id])){
$numberofresponses = count($allresponses[$option->id]);
}
$optiondisplay->manage = "<a href=\"report.php?id=$cm->id&optionid=$option->id\">".get_string("viewallresponses", "booking", $numberofresponses)."</a>";
} else {
$optiondisplay->manage = "";
}
if (has_capability('mod/booking:updatebooking', $context)){
$is_admin = "<a href=\"editoptions.php?id=$cm->id&optionid=$option->id\"><img src='pix/edit.gif' title='".get_string("updatebooking", "booking")."' alt='".get_string("updatebooking", "booking")."'></a> ";
$is_admin .= "<a href=\"report.php?id=".$cm->id."&optionid=".$option->id."&action=deletebookingoption&sesskey=".sesskey()."\"><img src='pix/delete.gif' title='".get_string('deletebookingoption','booking')."' alt='".get_string('deletebookingoption','booking')."'></a>";
}
else
$is_admin = "";
$tabledata[] = array ($bookingbutton.$optiondisplay->booked."<br />".get_string($option->status, "booking")."<br />".$optiondisplay->delete.$optiondisplay->manage,
"<b>".format_text($option->text. ' ', FORMAT_MOODLE, $displayoptions)."</b>".$is_admin."<p>".$option->description."</p>",
$option->coursestarttimetext." - <br />".$option->courseendtimetext,
$stravailspaces);
}
$table = new html_table();
$table->attributes['class'] = 'box generalbox boxaligncenter mod-booking-table';
$table->attributes['style'] = 'width: auto;';
$table->data = array();
$strselect = get_string("select", "booking");
$strbooking = get_string("booking", "booking");
$strdate = get_string("coursedate", "booking");
$stravailability = get_string("availability", "booking");
$table->head = array($strselect, $strbooking, $strdate, $stravailability);
$table->align = array ("left", "left", "left", "left");
$table->rowclasses = $rowclasses;
$table->data = $tabledata;
echo (html_writer::table($table));
}
/**
* Saves the booking for the user
* @return true if booking was possible, false if meanwhile the booking got full
*/
function booking_user_submit_response($optionid, $booking, $user, $courseid, $cm) {
global $DB;
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
// check if optionid exists as real option
if(!$DB->get_field('booking_options','id', array('id' => $optionid))){
return false;
}
if($booking->option[$optionid]->limitanswers) {
// retrieve all answers for this option ID
$answers[$optionid] = $DB->get_records("booking_answers", array("optionid" => $optionid));
if ($answers[$optionid]) {
$countanswers[$optionid] = 0;
foreach ($answers[$optionid] as $a) { //only return enrolled users.
if (has_capability('mod/booking:choose', $context, $a->userid, false)) {
$countanswers[$optionid]++;
}
}
}
$maxans[$optionid] = $booking->option[$optionid]->maxanswers + $booking->option[$optionid]->maxoverbooking;
// if answers for one option are limited and total answers are not exceeded then
$countanswers = 0;
if (!($booking->option[$optionid]->limitanswers && ($countanswers[$optionid] >= $maxans[$optionid]) )) {
// check if actual answer is also already made by this user
if(!($currentanswerid = $DB->get_field('booking_answers','id', array('userid' => $user->id, 'optionid' => $optionid)))){
$newanswer = new stdClass();
$newanswer->bookingid = $booking->id;
$newanswer->userid = $user->id;
$newanswer->optionid = $optionid;
$newanswer->timemodified = time();
if (!$DB->insert_record("booking_answers", $newanswer)) {
error("Could not register your booking because of a database error");
}
booking_check_enrol_user($booking->option[$optionid], $booking, $user->id);
}
add_to_log($courseid, "booking", "choose", "view.php?id=$cm->id", $booking->id, $cm->id);
if ($booking->sendmail){
booking_send_confirmation_email($user, $booking, $optionid,$cm->id);
}
return true;
} else { //check to see if current booking already selected - if not display error
$optionname = $DB->get_field('booking_options', 'text', array('id' => $optionid));
return false;
}
} else if (!($booking->option[$optionid]->limitanswers)){
if(!($currentanswerid = $DB->get_field('booking_answers','id', array('userid' => $user->id, 'optionid' => $optionid)))){
$newanswer = new stdClass();
$newanswer->bookingid = $booking->id;
$newanswer->userid = $user->id;
$newanswer->optionid = $optionid;
$newanswer->timemodified = time();
if (!$DB->insert_record("booking_answers", $newanswer)) {
error("Could not register your booking because of a database error");
}
booking_check_enrol_user($booking->option[$optionid], $booking, $user->id);
}
add_to_log($courseid, "booking", "choose", "view.php?id=$cm->id", $booking->id, $cm->id);
if ($booking->sendmail){
booking_send_confirmation_email($user, $booking, $optionid,$cm->id);
}
return true;
}
}
/**
* Automatically enrol the user in the relevant course, if that setting is on and a
* course has been specified.
* @param object $option
* @param object $booking
* @param int $userid
*/
function booking_check_enrol_user($option, $booking, $userid) {
global $DB;
if (!$booking->autoenrol) {
return; // Autoenrol not enabled.
}
if (!$option->courseid) {
return; // No course specified.
}
if (!enrol_is_enabled('manual')) {
return; // Manual enrolment not enabled.
}
if (!$enrol = enrol_get_plugin('manual')) {
return; // No manual enrolment plugin
}
if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$option->courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
return; // No manual enrolment instance on this course.
}
$instance = reset($instances); // Use the first manual enrolment plugin in the course.
$enrol->enrol_user($instance, $userid, $instance->roleid); // Enrol using the default role.
}
/**
* Automatically unenrol the user from the relevant course, if that setting is on and a
* course has been specified.
* @param object $option
* @param object $booking
* @param int $userid
*/
function booking_check_unenrol_user($option, $booking, $userid) {
global $DB;
if (!$booking->autoenrol) {
return; // Autoenrol not enabled.
}
if (!$option->courseid) {
return; // No course specified.
}
if (!enrol_is_enabled('manual')) {
return; // Manual enrolment not enabled.
}
if (!$enrol = enrol_get_plugin('manual')) {
return; // No manual enrolment plugin
}
if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$option->courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
return; // No manual enrolment instance on this course.
}
$instance = reset($instances); // Use the first manual enrolment plugin in the course.
$enrol->unenrol_user($instance, $userid); // Unenrol the user.
}
// this function is not yet implemented and needs to be changed a lot before using it
function booking_show_statistic (){
global $DB;
echo "<table cellpadding=\"5\" cellspacing=\"0\" class=\"results anonymous\">";
echo "<tr>";
foreach ($booking->option as $optionid => $option) {
echo "<th class=\"col$count header\" scope=\"col\">";
echo format_string($option->text);
echo "</th>";
$column[$optionid] = 0;
if (isset($allresponses[$optionid])) {
$column[$optionid] = count($allresponses[$optionid]);
if ($column[$optionid] > $maxcolumn) {
$maxcolumn = $column[$optionid];
}
} else {
$column[$optionid] = 0;
}
}
echo "</tr><tr>";
$height = 0;
$count = 1;
foreach ($booking->option as $optionid => $option) {
if ($maxcolumn) {
$height = $COLUMN_HEIGHT * ((float)$column[$optionid] / (float)$maxcolumn);
}
echo "<td style=\"vertical-align:bottom\" align=\"center\" class=\"col$count data\">";
echo "<img src=\"column.png\" height=\"$height\" width=\"49\" alt=\"\" />";
echo "</td>";
$count++;
}
echo "</tr><tr>";
$count = 1;
foreach ($booking->option as $optionid => $option) {
echo "<td align=\"center\" class=\"col$count count\">";
if ($booking->limitanswers) {
echo get_string("taken", "booking").":";
echo $column[$optionid].'<br />';
echo get_string("limit", "booking").":";
$option = $GB->get_record("booking_options", array("id", $optionid));
echo $option->maxanswers;
} else {
echo $column[$optionid];
echo '<br />('.format_float(((float)$column[$optionid]/(float)$totalresponsecount)*100.0,1).'%)';
}
echo "</td>";
$count++;
}
echo "</tr></table>";
}
function booking_confirm_booking($optionid, $booking, $user, $cm, $url){
global $OUTPUT;
echo $OUTPUT->header();
$optionidarray['answer'] = $optionid;
$optionidarray['confirm'] = 1;
$optionidarray['sesskey'] = $user->sesskey;
$optionidarray['id'] = $cm->id;
$requestedcourse = "<br />".$booking->option[$optionid]->text;
if($booking->option[$optionid]->coursestarttime != 0){
$requestedcourse .= "<br />".$booking->option[$optionid]->coursestarttimetext." - ".$booking->option[$optionid]->courseendtimetext;
}
$message = "<h2>".get_string('confirmbookingoffollowing','booking')."</h2>".$requestedcourse;
$message .= "<p><b>".get_string('agreetobookingpolicy','booking').":</b></p>";
$message .= "<p>".$booking->bookingpolicy."<p>";
echo $OUTPUT->confirm($message, new moodle_url('/mod/booking/view.php', $optionidarray),$url);
echo $OUTPUT->footer();
}
/**
* deletes a single booking of a user if user cancels the booking, sends mail to supportuser and newbookeduser
* @return true if booking was deleted successfully, otherwise false
*/
function booking_delete_singlebooking($answer,$booking,$optionid,$newbookeduserid,$cmid) {
global $USER, $DB;
if(!$DB->delete_records('booking_answers', array('id' => $answer->id))){
return false;
}
if ($answer->userid == $USER->id) {
$user = $USER;
} else {
$user = $DB->get_record('user', array('id' => $answer->userid));
}
booking_check_unenrol_user($booking->option[$optionid], $booking, $user->id);
$supportuser = generate_email_supportuser();
$params = booking_generate_email_params($booking, $booking->option[$optionid], $user, $cmid);
$messagetext = get_string('deletedbookingmessage', 'booking', $params);
$deletedbookingusermessage = booking_get_email_body($booking, 'deletedtext', 'deletedbookingmessage', $params);
$bookingmanager = $DB->get_record('user', array('username' => $booking->bookingmanager));
if ($booking->sendmail){
// Generate ical attachment to go with the message.
$attachname = '';
$ical = new booking_ical($booking, $booking->option[$optionid], $user, $supportuser);
if ($attachment = $ical->get_attachment(true)) {
$attachname = $ical->get_name();
}
$messagehtml = format_text($deletedbookingusermessage, FORMAT_HTML);
$deletedbookingusermessage = strip_tags(str_replace(array('<br />', '</p>'), '', $messagehtml));
email_to_user($user, $supportuser, get_string('deletedbookingusersubject','booking', $params),
$deletedbookingusermessage, $messagehtml, $attachment, $attachname);
}
if ($booking->copymail){
email_to_user($bookingmanager, $supportuser, get_string('deletedbookingsubject','booking', $params), $messagetext);
}
if ($newbookeduserid) {
booking_check_enrol_user($booking->option[$optionid], $booking, $newbookeduserid);
if ($booking->sendmail == 1) {
$newbookeduser = $DB->get_record('user', array('id' => $newbookeduserid));
$params = booking_generate_email_params($booking, $booking->option[$optionid], $newbookeduser, $cmid);
$messagetextnewuser = booking_get_email_body($booking, 'statuschangetext', 'statuschangebookedmessage', $params);
$messagehtml = format_text($messagetextnewuser, FORMAT_HTML);
$message = strip_tags(str_replace(array('<br />', '</p>'), '', $messagehtml));
// Generate ical attachment to go with the message.
$attachname = '';
$ical = new booking_ical($booking, $booking->option[$optionid], $newbookeduser, $supportuser);
if ($attachment = $ical->get_attachment()) {
$attachname = $ical->get_name();
}
email_to_user($newbookeduser, $supportuser, get_string('statuschangebookedsubject','booking', $params),
$message, $messagehtml, $attachment, $attachname);
}
}
return true;
}
function booking_delete_responses($attemptidsarray, $booking, $cmid) {
global $DB;
if(!is_array($attemptidsarray) || empty($attemptidsarray)) {
return false;
}
foreach($attemptidsarray as $optionid => $userids){
if(!is_array($userids) || empty($userids)) {
return false;
}
foreach($userids as $num => $userid) {
if(empty($userid)) {
unset($userids[$num]);
}
}
foreach($userids as $userid) {
$answer = $DB->get_record('booking_answers', array('bookingid' => $booking->id,
'userid' => $userid,
'optionid' => $optionid));
$newbookeduser = booking_check_statuschange($optionid, $booking, $userid, $cmid);
booking_delete_singlebooking($answer, $booking, $optionid, $newbookeduser, $cmid);
}
}
return true;
}
function booking_delete_instance($id) {
global $DB;
// Given an ID of an instance of this module,
// this function will permanently delete the instance
// and any data that depends on it.
if (! $booking = $DB->get_record("booking", array("id" => "$id"))) {
return false;
}
$result = true;
if (! $DB->delete_records("booking_answers", array("bookingid" => "$booking->id"))) {
$result = false;
}
if (! $DB->delete_records("booking_options", array("bookingid" => "$booking->id"))) {
$result = false;
}
if (! $DB->delete_records("booking", array("id" => "$booking->id"))) {
$result = false;
}
return $result;
}
function booking_get_participants($bookingid) {
global $CFG, $DB;
//Returns the users with data in one booking
//(users with records in booking_responses, students)
//Get students
$students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
FROM {$CFG->prefix}user u,
{$CFG->prefix}booking_answers a
WHERE a.bookingid = '$bookingid' and
u.id = a.userid");
//Return students array (it contains an array of unique users)
return ($students);
}
function booking_get_option_text($booking, $id) {
global $DB;
// Returns text string which is the answer that matches the id
if ($result = $DB->get_record("booking_options", array("id" => $id))) {
return $result->text;
} else {
return get_string("notanswered", "booking");
}
}
function booking_get_groupmodedata() {
}
/**
* Gets the principal information of booking status and booking options
* to be used by other functions
* @param $bookingid id of the module
* @return object with $booking->option as an array for the booking option valus for each booking option
*/
function booking_get_booking($cm) {
global $DB;
$bookingid = $cm->instance;
// Gets a full booking record
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
/// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
$allresponses = array();
/// bookinglist $bookinglist[optionid][sortnumber] = userobject;
$bookinglist = array();
/// First get all the users who have access here
$allresponses = get_users_by_capability($context, 'mod/booking:choose', 'u.id, u.picture, u.firstname, u.lastname, u.idnumber, u.email', 'u.lastname ASC, u.firstname ASC', '', '', '', '', true, true);
if (($options = $DB->get_records('booking_options', array('bookingid' => $bookingid), 'id')) && ($booking = $DB->get_record("booking", array("id" => $bookingid)))) {
$answers = $DB->get_records('booking_answers', array('bookingid' => $bookingid), 'id');
foreach ($options as $option){
$booking->option[$option->id] = $option;
if(!$option->coursestarttime == 0){
$booking->option[$option->id]->coursestarttimetext = userdate($option->coursestarttime, get_string('strftimedatetime'));
} else {
$booking->option[$option->id]->coursestarttimetext = get_string("starttimenotset", 'booking');
}
if(!$option->courseendtime == 0){
$booking->option[$option->id]->courseendtimetext = userdate($option->courseendtime, get_string('strftimedatetime'),'',false);
} else {
$booking->option[$option->id]->courseendtimetext = get_string("endtimenotset", 'booking');
}
// we have to change $taken is different from booking_show_results
$answerstocount = array();
if($answers){
foreach($answers as $answer){
if ($answer->optionid == $option->id && isset($allresponses[$answer->userid])){
$answerstocount[] = $answer;
}
}
}
$taken = count($answerstocount);
$totalavailable = $option->maxanswers + $option->maxoverbooking;
if (!$option->limitanswers){
$booking->option[$option->id]->status = "available";
$booking->option[$option->id]->taken = $taken;
$booking->option[$option->id]->availspaces = "unlimited";
} else {
if ($taken < $option->maxanswers) {
$booking->option[$option->id]->status = "available";
$booking->option[$option->id]->availspaces = $option->maxanswers - $taken;
$booking->option[$option->id]->taken = $taken;
$booking->option[$option->id]->availwaitspaces = $option->maxoverbooking;
} elseif ($taken >= $option->maxanswers && $taken < $totalavailable ){
$booking->option[$option->id]->status = "waitspaceavailable";
$booking->option[$option->id]->availspaces = 0;
$booking->option[$option->id]->taken = $option->maxanswers;
$booking->option[$option->id]->availwaitspaces = $option->maxoverbooking - ($taken - $option->maxanswers);
} elseif ($taken >= $totalavailable){
$booking->option[$option->id]->status = "full";
$booking->option[$option->id]->availspaces = 0;
$booking->option[$option->id]->taken = $option->maxanswers;
$booking->option[$option->id]->availwaitspaces = 0;
}
}
if(time() > $booking->option[$option->id]->bookingclosingtime and $booking->option[$option->id]->bookingclosingtime != 0){
$booking->option[$option->id]->status = "closed";
}
if ($option->bookingclosingtime){
$booking->option[$option->id]->bookingclosingtime = userdate($option->bookingclosingtime, get_string('strftimedate'),'',false);
} else {
$booking->option[$option->id]->bookingclosingtime = false;
}
}
return $booking;
} elseif ($booking = $DB->get_record("booking", array("id" => $bookingid))) {
return $booking;
}
return false;
}
function booking_get_view_actions() {
return array('view','view all','report');
}
function booking_get_post_actions() {
return array('choose','choose again');
}
/**
* Implementation of the function for printing the form elements that control
* whether the course reset functionality affects the booking.
* @param $mform form passed by reference
*/
function booking_reset_course_form_definition(&$mform) {
$mform->addElement('header', 'bookingheader', get_string('modulenameplural', 'booking'));
$mform->addElement('advcheckbox', 'reset_booking', get_string('removeresponses','booking'));
}
/**
* Course reset form defaults.
*/
function booking_reset_course_form_defaults($course) {
return array('reset_booking'=>1);
}
/**
* Actual implementation of the rest coures functionality, delete all the
* booking responses for course $data->courseid.
* @param $data the data submitted from the reset course.
* @return array status array
*/
function booking_reset_userdata($data) {
global $CFG, $DB;
$componentstr = get_string('modulenameplural', 'booking');
$status = array();
if (!empty($data->reset_booking)) {
$bookingssql = "SELECT ch.id
FROM {$CFG->prefix}booking ch
WHERE ch.course={$data->courseid}";
$DB->delete_records_select('booking_answers', "bookingid IN ($bookingssql)");
$status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'booking'), 'error'=>false);
}
/// updating dates - shift may be negative too
if ($data->timeshift) {
shift_course_mod_dates('booking', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
$status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
}
return $status;
}
/**
* Gives a list of booked users sorted in an array by booking option
* @param $cm module id
* @param $booking booking object
* @return array sorted list by booking date of all users, booking option as key
*/
function booking_get_spreadsheet_data($booking, $cm) {
global $CFG, $USER, $DB;
$bookinglistsorted = array();
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
/// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
$allresponses = array();
/// bookinglist $bookinglist[optionid][sortnumber] = userobject;
$bookinglist = array();
/// First get all the users who have access here
$allresponses = get_users_by_capability($context, 'mod/booking:choose', 'u.id, u.picture, u.firstname, u.lastname, u.idnumber, u.email', 'u.lastname ASC, u.firstname ASC', '', '', '', '', true, true);
/// Get all the recorded responses for this booking
$rawresponses = $DB->get_records('booking_answers', array('bookingid' => $booking->id), "optionid, timemodified ASC");
$optionids = $DB->get_records_select('booking_options', "bookingid = $booking->id",array(),'id','id');
/// Use the responses to move users into the correct column
$sortnumber = 1;
if ($rawresponses) {
foreach ($rawresponses as $response) {
if (isset($allresponses[$response->userid])) { // This person is enrolled and in correct group
$bookinglist[$response->optionid][$sortnumber++] = $allresponses[$response->userid];
}
}
}
if (empty($bookinglist)) {
unset($bookinglist);
} else {
foreach($optionids as $optionid => $optionobject){
if(!empty($bookinglist[$optionid])){
$userperbookingoption = count($bookinglist[$optionid]);
$i = 1;
foreach($bookinglist[$optionid] as $key => $value){
unset($bookinglist[$optionid][$key]);
$bookinglistsorted[$optionid][$i++] = $value;
}
} else {
unset($bookinglist[$optionid]);
}
}
}
return $bookinglistsorted;
}
/**
* Divides all users in booked and waiting list users
* @param $bookingoption bookingoption object
* @param $allresponses all responses for that bookingoption
* @return array of arrays with keys waitinglist and booked
*/
function booking_user_status($bookingoption,$allresponses){
$userarray['waitinglist'] = false;
$userarray['booked'] = false;
$i =1;
if(is_array($allresponses)){
foreach ($allresponses as $user) {
if ($i <= $bookingoption->maxanswers || !$bookingoption->limitanswers){ //booked user
$userarray['booked'][] = $user;
} else if ($i <= $bookingoption->maxoverbooking + $bookingoption->maxanswers){ //waitlistusers;
$userarray['waitinglist'][] = $user;
}
$i++;
}
}
return $userarray;
}
/**
* Sends confirmation mail after user successfully booked
* @param $user the user who booked
* @param $booking the booking instance
* @param $optionid the booking optionid the user chose
* @param $cmid module id in the url
* @return true or false according to success of operation
*/
function booking_send_confirmation_email($user,$booking,$optionid,$cmid){
global $DB;
// Used to store the ical attachment (if required)