-
Notifications
You must be signed in to change notification settings - Fork 4
/
locallib.php
1438 lines (1291 loc) · 56.2 KB
/
locallib.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Reservation plugin local lib functions
*
* @package mod_reservation
* @copyright 2011 onwards Roberto Pinna
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Gets a full reservation record
*
* @param integer $reservationid reservation id
* @return object|bool The reservation or false
*/
function reservation_get_reservation($reservationid) {
global $DB;
if ($reservation = $DB->get_record('reservation', ['id' => $reservationid])) {
if ($sublimits = $DB->get_records('reservation_limit', ['reservationid' => $reservationid], 'id')) {
$i = 1;
foreach ($sublimits as $sublimit) {
$reservation->sublimits[$i] = new stdClass();
$reservation->sublimits[$i]->field = $sublimit->field;
$reservation->sublimits[$i]->operator = $sublimit->operator;
$reservation->sublimits[$i]->matchvalue = $sublimit->matchvalue;
$reservation->sublimits[$i]->limit = $sublimit->requestlimit;
}
return $reservation;
}
}
return false;
}
/**
* Return a list of reservations in specified course or with specified location
*
* @param integer $courseid A course id
* @param string $location The location name
* @return array|bool The reservations list or false
*/
function reservation_get_reservations_by_course($courseid, $location='') {
global $DB;
$searchfields = ['courseid' => $courseid];
$locationquery = ')';
if (!empty($location)) {
$locationquery = ' OR res.location = :location)';
$searchfields['location'] = $location;
}
return $DB->get_records_sql('SELECT res.*, c.fullname as coursename
FROM {reservation} res,
{course} c
WHERE res.course = c.id
AND (res.course = :courseid'.$locationquery,
$searchfields);
}
/**
* Return a menu list of parentable reservation
*
* @param integer $reservationid A reservation id
* @return array The reservations menu list or false
*/
function reservation_get_parentable($reservationid) {
global $DB, $COURSE;
$searchfields = [];
$additionalquery = '';
$connectto = get_config('reservation', 'connect_to');
if (($connectto === false) || ($connectto == 'course')) {
$searchfields['courseid'] = $COURSE->id;
$additionalquery .= ' AND (res.course = :courseid)';
}
if (!empty($reservationid)) {
$searchfields['reservationid'] = $reservationid;
$additionalquery .= ' AND (res.id <> :reservationid)';
if ($DB->get_records('reservation', ['parent' => $reservationid])) {
return [];
}
}
return $DB->get_records_sql('SELECT res.id, c.fullname as coursename, c.category as category, res.name as name
FROM {reservation} res,
{course} c
WHERE res.course = c.id
AND (res.parent = 0)' . $additionalquery . ' ORDER BY category, coursename, name', $searchfields);
}
/**
* Returns a list of reservations connected to the passed one
*
* @param stdClass $reservation A reservation object
* @return array the reservations list
*/
function reservation_get_connected($reservation) {
global $DB;
$searchfields = ['reservationid' => $reservation->id];
$additionalquery = '';
if (!empty($reservation->parent)) {
$additionalquery .= ' AND ((res.parent = :parent) OR (res.id = :parent2))';
$searchfields['parent'] = $reservation->parent;
$searchfields['parent2'] = $reservation->parent;
} else {
$additionalquery .= 'AND (res.parent = :reservationid2)';
$searchfields['reservationid2'] = $reservation->id;
}
return $DB->get_records_sql('SELECT res.id, c.fullname as coursename, c.category as category, res.name as name
FROM {reservation} res,
{course} c
WHERE res.course = c.id
AND (res.id <> :reservationid)'.$additionalquery.
' ORDER BY category, coursename, name', $searchfields);
}
/**
* Reserve a seat for given user if not already reserved
*
* @param stdClass $reservation reservation object
* @param stdClass $seats availabilty counters
* @param string $note User note
* @param integer $userid user id
*
* @return object with boolean and a warning string
*/
function reservation_reserve($reservation, $seats, $note='', $userid=0) {
global $DB, $USER;
$result = [];
$result['status'] = false;
$result['error'] = '';
if (($seats->available > 0) || ($seats->total > 0)) {
if (!empty($userid)) {
$queryparameters = ['userid' => $userid,
'reservation' => $reservation->id,
'timecancelled' => '0',
];
if (!$DB->get_record('reservation_request', $queryparameters)) {
$cr = reservation_reserved_on_connected($reservation, $userid);
if ($cr === false) {
$request = new stdClass();
$request->userid = $userid;
$request->reservation = $reservation->id;
$request->timecreated = time();
if ($requestid = $DB->insert_record('reservation_request', $request)) {
$usernote = new stdClass();
if (($reservation->note >= 1) && (!empty($note))) {
$usernote->request = $requestid;
$usernote->note = strip_tags($note);
$DB->insert_record('reservation_note', $usernote);
}
$request = $DB->get_record('reservation_request', ['id' => $requestid]);
$course = $DB->get_record('course', ['id' => $reservation->course]);
$cm = get_coursemodule_from_instance('reservation', $reservation->id, $course->id);
$context = context_module::instance($cm->id);
\mod_reservation\event\request_added::create_from_request($reservation, $context,
$request, $usernote)->trigger();
reservation_set_user_event($reservation, $request);
// Update completion state.
$completion = new completion_info($course);
if ($completion->is_enabled($cm) && $reservation->completionreserved) {
$completion->update_state($cm, COMPLETION_COMPLETE, $userid);
}
$user = $DB->get_record('user', ['id' => $userid]);
reservation_notify('reservers', $user, $reservation, $course, $cm);
$result['status'] = true;
}
}
} else {
if ($userid == $USER->id) {
$result['error'] = 'alreadybooked';
} else {
$result['error'] = 'useralreadybooked';
}
}
} else {
$result['error'] = 'reservationdenied';
}
} else {
$result['error'] = 'nomorerequest';
}
return $result;
}
/**
* Cancel current user active request
*
* @param stdClass $reservation
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @return boolean true if cancellation succeded, false on errors
*/
function reservation_cancel($reservation, $course, $cm, $context) {
global $USER, $DB;
$queryparameters = ['userid' => $USER->id, 'reservation' => $reservation->id, 'timecancelled' => '0'];
if ($request = $DB->get_record('reservation_request', $queryparameters)) {
$DB->set_field('reservation_request', 'timecancelled', time(), ['id' => $request->id]);
\mod_reservation\event\request_cancelled::create_from_request($reservation, $context, $request)->trigger();
reservation_remove_user_event($reservation, $request);
// Update completion state.
$completion = new \completion_info($course);
if ($completion->is_enabled($cm) && $reservation->completionreserved) {
$completion->update_state($cm, COMPLETION_INCOMPLETE);
}
reservation_notify('cancellers', $USER, $reservation, $course, $cm);
return true;
}
return false;
}
/**
* Send a email to user about an action or an event
*
* @param string $notify the selected notify mail
* @param stdClass $user user object
* @param stdClass $reservation reservation object
* @param stdClass $course course object
* @param stdClass $cm cm object
* @return void
*/
function reservation_notify($notify, $user, $reservation, $course, $cm) {
global $CFG;
$notifieslist = get_config('reservation', 'notifies');
if ($notifieslist === false) {
$notifieslist = 'teachers,students,grades';
}
$notifies = explode(',', $notifieslist);
if (in_array($notify, $notifies)) {
$strreservations = get_string('modulenameplural', 'reservation');
$reservationinfo = new stdClass();
$reservationinfo->reservation = format_string($reservation->name, true);
$reservationinfo->url = $CFG->wwwroot.'/mod/reservation/view.php?id='.$cm->id;
$postsubject = $course->shortname.': '.$strreservations.': '.format_string($reservation->name, true);
$posttext = $course->shortname.' -> '.$strreservations.' -> '.format_string($reservation->name, true)."\n";
$posttext .= '---------------------------------------------------------------------'."\n";
$posttext .= get_string($notify.'mail', 'reservation', $reservationinfo);
$posttext .= "\n".'---------------------------------------------------------------------'."\n";
$posthtml = '';
if ($user->mailformat == 1) { // HTML.
$posthtml = '<p>';
$posthtml .= '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->shortname.'</a> ->';
$posthtml .= '<a href="'.$CFG->wwwroot.'/mod/reservation/index.php?id='.$course->id.'">'.
$strreservations.'</a> ->';
$posthtml .= '<a href="'.$CFG->wwwroot.'/mod/reservation/view.php?id='.$cm->id.'">'.
format_string($reservation->name, true).'</a>';
$posthtml .= '</p>';
$posthtml .= '<hr />';
$posthtml .= '<p>'.get_string($notify.'mailhtml', 'reservation', $reservationinfo).'</p>';
$posthtml .= '<hr />';
}
if (! email_to_user($user, $CFG->noreplyaddress, $postsubject, $posttext, $posthtml)) {
notice('Could not send out mail to '.$user->email);
}
}
}
/**
* Return a connected reservation where the user is already reserved, if exists
*
* @param stdClass $reservation reservation object
* @param integer $userid
* @return object with course name, reservation name, reservation id
*/
function reservation_reserved_on_connected($reservation, $userid) {
global $DB;
$searchfields = ['reservationid' => $reservation->id, 'userid' => $userid];
$additionalquery = '';
if (!empty($reservation->parent)) {
$additionalquery .= ' AND ((res.parent = :parent) OR (res.id = :parent2))';
$searchfields['parent'] = $reservation->parent;
$searchfields['parent2'] = $reservation->parent;
} else {
$additionalquery .= ' AND (res.parent = :reservationid2)';
$searchfields['reservationid2'] = $reservation->id;
}
$res = $DB->get_record_sql('SELECT res.*
FROM {reservation} res,
{reservation_request} req
WHERE (res.id = req.reservation)
AND (req.userid = :userid)
AND (req.timecancelled = 0)
AND (res.id <> :reservationid)'.$additionalquery, $searchfields);
if ($res) {
if ($course = $DB->get_record('course', ['id' => $res->course])) {
if ($cm = get_coursemodule_from_instance('reservation', $res->id, $res->course)) {
$result = new stdClass();
$result->id = $cm->id;
$result->name = $res->name;
$result->coursename = $course->fullname;
$result->category = $course->category;
return $result;
}
}
} else {
return false;
}
}
/**
* Return all requests user data
*
* @param stdClass $reservation reservation object
* @param boolean $full define if return a full list or active only requests
* @param array $fields which data field but returned
* @param integer $groupid define if return all users or only members of specified group (NOT USED)
* @param integer $groupmode how groups are showed
* @return array|bool list of request for that reservation
*/
function reservation_get_requests($reservation, $full=false, $fields=null, $groupid=0, $groupmode=NOGROUPS) {
global $CFG, $DB, $USER;
$clear = '';
if (!$full) {
$clear = ' AND r.timecancelled=0';
}
$requests = $DB->get_records_sql('SELECT u.*, r.*'.
' FROM {reservation_request} r, {user} u'.
' WHERE u.deleted = 0 AND r.reservation = :reservationid'.$clear.
' AND r.userid = u.id ORDER BY r.id', ['reservationid' => $reservation->id]);
if (!empty($requests)) {
if (!empty($fields)) {
require_once($CFG->dirroot.'/user/profile/lib.php');
}
$number = 1;
foreach ($requests as $requestid => $request) {
// Add request order numbers.
$requests[$requestid]->number = $number;
if ($request->timecancelled == 0) {
$number++;
}
// Set current user information.
if (($request->userid == $USER->id) && ($request->timecancelled == '0')) {
$requests[0] = $request;
}
// Fill extra fields.
if (!empty($fields)) {
$userdata = new stdClass();
$userdata->id = $request->userid;
$userdata = profile_user_record($request->userid);
foreach ($fields as $fieldid => $field) {
if (($field->custom !== false) && ($field->custom !== 'groups')) {
$requests[$requestid]->$fieldid = '';
if (isset($userdata->$fieldid)) {
$requests[$requestid]->$fieldid = format_string($userdata->$fieldid);
}
}
}
}
// Add user note.
if ($reservation->note >= 1) {
$requests[$requestid]->note = $DB->get_field('reservation_note', 'note', ['request' => $requestid]);
}
// Set user groups.
if ($groupmode != NOGROUPS) {
if (($groupid == 0) || groups_is_member($groupid, $request->userid)) {
$groups = groups_get_user_groups($reservation->course, $request->userid);
if (!empty($groups['0'])) {
$usergroups = [];
foreach ($groups['0'] as $group) {
$usergroups[] = format_string(groups_get_group_name($group));
}
$requests[$requestid]->groups = implode(', ', $usergroups);
} else {
$requests[$requestid]->groups = '';
}
} else {
unset($requests[$requestid]);
continue;
}
}
}
}
return $requests;
}
/**
* Sorts an array (you know the kind) by key
* and by the comparison operator you prefer.
* Note that instead of most important criteron first, it's
* least important criterion first.
* The default sort order is ascending, and the default sort
* type is strnatcmp.
*
* @param array $array
* @param array $sortorders Associative array with attribute names as keys and ASC or DESC as values
* @return array sorted array
*/
function reservation_multisort($array, $sortorders) {
if (!empty($sortorders)) {
$orders = array_reverse($sortorders, true);
foreach ($orders as $key => $order) {
$callback = function($a, $b) use ($order, $key) {
$o = 1;
if ($order == SORT_DESC) {
$o = -1;
}
if (is_numeric($a->$key) && is_numeric($b->$key)) {
return ($a->$key - $b->$key) * $o;
} else {
return strnatcasecmp($a->$key, $b->$key) * $o;
}
};
uasort($array, $callback);
}
}
return $array;
}
/**
* Set grades for a give reservation
*
* @param stdClass $reservation
* @param integer $teacherid
* @param array $grades Associative array with requestids as keys and grades as value
*/
function reservation_set_grades($reservation, $teacherid, $grades) {
global $DB;
if (!empty($grades)) {
$now = time();
$requests = $DB->get_records('reservation_request', ['reservation' => $reservation->id]);
foreach ($grades as $requestid => $grade) {
$request = $requests[$requestid];
if ($grade != $request->grade) {
$request->teacher = $teacherid;
$request->grade = $grade;
$request->mailed = 0;
$request->timegraded = $now;
$DB->update_record('reservation_request', $request);
require_once(__DIR__.'/lib.php');
reservation_update_grades($reservation, $request->userid);
}
}
}
}
/**
* Delete given reservation requests data and grades
*
* @param stdClass $reservation
* @param array $requestids
*/
function reservation_delete_requests($reservation, $requestids) {
global $DB;
$course = $DB->get_record('course', ['id' => $reservation->course]);
$cm = get_coursemodule_from_instance('reservation', $reservation->id, $course->id);
$context = context_module::instance($cm->id);
if (is_array($requestids) && !empty($requestids)) {
require_once(__DIR__.'/lib.php');
foreach ($requestids as $num => $requestid) {
if (!empty($requestid)) {
unset($requestids[$num]);
$request = $DB->get_record('reservation_request', ['id' => $requestid]);
$requestnote = $DB->get_record('reservation_note', ['request' => $requestid]);
$requestnote = !empty($requestnote) ? $requestnote : new stdClass();
$DB->set_field('reservation_request', 'grade', -1, ['id' => $requestid]);
$userid = $DB->get_field('reservation_request', 'userid', ['id' => $requestid]);
reservation_update_grades($reservation, $userid);
reservation_remove_user_event($reservation, $request);
$DB->delete_records('reservation_request', ['id' => $requestid]);
$DB->delete_records('reservation_note', ['request' => $requestid]);
// Update completion state.
$completion = new completion_info($course);
if ($completion->is_enabled($cm)) {
$completion->update_state($cm, COMPLETION_INCOMPLETE, $userid);
}
\mod_reservation\event\request_deleted::create_from_request($reservation,
$context,
$request,
$requestnote)->trigger();
}
}
}
}
/**
* Get list of teachers for this reservation
*
* @param stdClass $reservation
* @param integer $cmid
* @return array list of fullnames of teachers
*/
function reservation_get_teacher_names($reservation, $cmid=null) {
global $DB;
$teachernames = [];
if (strlen($reservation->teachers) > 0) {
$context = context_course::instance($reservation->course);
$capability = 'moodle/course:viewhiddenactivities';
if (isset($reservation->coursemodule) && !empty($reservation->coursemodule)) {
$cmid = $reservation->coursemodule;
}
if ($cmid != null) {
$context = context_module::instance($cmid);
$capability = 'mod/reservation:addinstance';
}
$teachers = explode(',', $reservation->teachers);
foreach ($teachers as $teacherid) {
if (!empty($teacherid)) {
if ($teacher = $DB->get_record('user', ['id' => $teacherid])) {
if (has_capability($capability, $context, $teacherid)) {
$teachernames[] = fullname($teacher);
}
}
}
}
}
return implode(', ', $teachernames);
}
/**
* Get list of users custom profile fields
*
* @return array list of custom profile fields
*/
function reservation_get_profilefields() {
global $DB;
$infofields = $DB->get_records('user_info_field');
$customfields = [];
foreach ($infofields as $infofield) {
$customfields[$infofield->shortname] = new stdClass();
$customfields[$infofield->shortname]->name = $infofield->name;
$customfields[$infofield->shortname]->id = $infofield->id;
}
return $customfields;
}
/**
* Get complete user profile fields (standard + custom fields)
*
* @param integer $userid
* @return stdClass User data
*/
function reservation_get_userdata($userid) {
global $DB, $CFG;
if ($userdata = $DB->get_record('user', ['id' => $userid])) {
require_once($CFG->dirroot.'/user/profile/lib.php');
$profiledata = profile_user_record($userid);
if (!empty($profiledata)) {
foreach ($profiledata as $fieldname => $value) {
$userdata->{$fieldname} = $value;
}
}
}
return $userdata;
}
/**
* Setup array of required counters for sublimit check
*
* @param stdClass $reservation
* @param array $customfields
* @return array Counters
*/
function reservation_setup_counters($reservation, $customfields) {
global $DB;
$counters = [];
$counters[0] = new stdClass();
$counters[0]->count = 0;
$counters[0]->overbooked = 0;
$counters[0]->deletedrequests = 0;
if ($reservationlimits = $DB->get_records('reservation_limit', ['reservationid' => $reservation->id])) {
$i = 1;
foreach ($reservationlimits as $reservationlimit) {
$counters[$i] = $reservationlimit;
$counters[$i]->count = 0;
$counters[$i]->overbooked = 0;
if (isset($customfields[$reservationlimit->field])) {
$counters[$i]->field = $reservationlimit->field;
$counters[$i]->fieldname = format_string($customfields[$reservationlimit->field]->name);
} else {
$counters[$i]->field = $reservationlimit->field;
$counters[$i]->fieldname = get_string($reservationlimit->field);
}
$i++;
}
}
return $counters;
}
/**
* Update counters for the given reservation request
*
* @param stdClass $reservation
* @param array $counters
* @param stdClass $request
* @return array Updated counters
*/
function reservation_update_counters($reservation, $counters, $request) {
$counters[0]->matchlimit = 0;
if ($request->timecancelled != '0') {
$counters[0]->deletedrequests++;
} else {
$maxrequests = get_config('reservation', 'max_requests');
$maxrequests = max($maxrequests, ($counters[0]->count + 1));
if ($reservation->maxrequest > 0) {
$maxrequests = $reservation->maxrequest;
}
if ($counters[0]->count < $maxrequests) {
$counters[0]->count++;
} else {
$counters[0]->overbooked++;
}
for ($i = 1; $i < count($counters); $i++) {
$fieldname = $counters[$i]->field;
if (isset($request->$fieldname)) {
if ((($request->$fieldname == $counters[$i]->matchvalue) && !$counters[$i]->operator) ||
(($request->$fieldname != $counters[$i]->matchvalue) && $counters[$i]->operator)) {
$counters[$i]->count++;
$counters[0]->matchlimit++;
if ($counters[$i]->count > $counters[$i]->requestlimit) {
$counters[$i]->overbooked++;
}
}
} else if ($fieldname == 'group') {
$groups = groups_get_user_groups($reservation->course, $request->userid);
if (!empty($groups) && !empty($groups['0'])) {
$groupsnames = [];
foreach ($groups['0'] as $groupid) {
$groupsnames[] = groups_get_group_name($groupid);
}
if ((!$counters[$i]->operator && in_array($counters[$i]->matchvalue, $groupsnames)) ||
($counters[$i]->operator && in_array($counters[$i]->matchvalue, $groupsnames))) {
$counters[$i]->count++;
$counters[0]->matchlimit++;
if ($counters[$i]->count > $counters[$i]->requestlimit) {
$counters[$i]->overbooked++;
}
}
}
}
}
}
return $counters;
}
/**
* Get list of sublimit fields
*
* @param array $counters
* @param array $customfields
* @param array $fields
* @return array Sublimits fields
*/
function reservation_setup_sublimit_fields($counters, $customfields, $fields = []) {
foreach ($counters as $counter) {
if (isset($counter->field)) {
if (isset($customfields[$counter->field])) {
if (!isset($fields[$counter->field])) {
$fields[$counter->field] = new stdClass();
$fields[$counter->field]->custom = $customfields[$counter->field]->id;
}
} else if ($counter->field != 'group') {
if (!isset($fields[$counter->field])) {
$fields[$counter->field] = new stdClass();
$fields[$counter->field]->custom = false;
}
}
}
}
return $fields;
}
/**
* Calculate available seats for USER.
*
* @param stdClass $reservation
* @param array $counters
* @param context $context
*
* @return object seat availability
*/
function reservation_get_availability($reservation, $counters, $context) {
global $USER;
$availablesublimit = 0;
$limitoverbook = 0;
$nolimit = true;
$totalrequestlimit = 0;
$totalrequestcount = 0;
// Set available seats in global count.
$seats = new stdClass();
$maxrequests = get_config('reservation', 'max_requests');
$seats->available = max($maxrequests, ($counters[0]->count + 1));
$seats->overbook = 0;
if ($reservation->maxrequest > 0) {
$seats->available = $reservation->maxrequest;
$seats->overbook = round($reservation->maxrequest * $reservation->overbook / 100);
}
$seats->available = $seats->available - $counters[0]->count > 0 ? $seats->available - $counters[0]->count : 0;
$seats->overbook = $seats->overbook - $counters[0]->overbooked > 0 ? $seats->overbook - $counters[0]->overbooked : 0;
$seats->total = $seats->available + $seats->overbook;
if (has_capability('mod/reservation:manualreserve', $context)) {
return $seats;
} else {
$userdata = reservation_get_userdata($USER->id);
if (count($counters) - 1 > 0) {
for ($i = 1; $i < count($counters); $i++) {
if ($counters[$i]->field != 'group') {
if ((($userdata->{$counters[$i]->field} == $counters[$i]->matchvalue) && !$counters[$i]->operator) ||
(($userdata->{$counters[$i]->field} != $counters[$i]->matchvalue) && $counters[$i]->operator)) {
if ($availablesublimit <= ($counters[$i]->requestlimit - $counters[$i]->count)) {
$availablesublimit = $counters[$i]->requestlimit - $counters[$i]->count;
$limitoverbook = round($counters[$i]->requestlimit * $reservation->overbook / 100);
$limitoverbook -= $counters[$i]->overbooked;
}
$nolimit = false;
}
} else {
$groups = groups_get_user_groups($reservation->course, $USER->id);
if (!empty($groups) && !empty($groups['0'])) {
$groupsnames = [];
foreach ($groups['0'] as $groupid) {
$groupsnames[] = groups_get_group_name($groupid);
}
if (($counters[$i]->operator && !in_array($counters[$i]->matchvalue, $groupsnames)) ||
(!$counters[$i]->operator && in_array($counters[$i]->matchvalue, $groupsnames))) {
if ($availablesublimit <= ($counters[$i]->requestlimit - $counters[$i]->count)) {
$availablesublimit = $counters[$i]->requestlimit - $counters[$i]->count;
$limitoverbook = round($counters[$i]->requestlimit * $reservation->overbook / 100);
$limitoverbook -= $counters[$i]->overbooked;
}
}
}
}
$totalrequestlimit += $counters[$i]->requestlimit;
$totalrequestcount += $counters[$i]->count;
}
if ($nolimit) {
$availablesublimit = $seats->available - $totalrequestlimit + $totalrequestcount;
}
if ($seats->available > $availablesublimit) {
$seats = new stdClass();
$seats->available = $availablesublimit;
$seats->overbook = $limitoverbook;
$seats->total = $seats->available + $seats->overbook;
return $seats;
}
} else {
return $seats;
}
}
$seats = new stdClass();
$seats->available = 0;
$seats->overbook = 0;
$seats->total = 0;
return $seats;
}
/**
* Validation callback function - verified the column line of csv file.
* Converts standard column names to lowercase.
*
* @param csv_import_reader $cir
* @param array $fields standard user fields
* @param array $requiredfields mandatory user fields
* @param moodle_url $returnurl return url in case of any error
* @throws moodle_exception
* @return array list of fields
*/
function reservation_validate_upload_columns(csv_import_reader $cir, $fields, $requiredfields, moodle_url $returnurl) {
$columns = $cir->get_columns();
if (empty($columns)) {
$cir->close();
$cir->cleanup();
throw new moodle_exception('cannotreadtmpfile', 'error', $returnurl);
}
if (count($columns) < count($requiredfields)) {
$cir->close();
$cir->cleanup();
throw new moodle_exception('csvfewcolumns', 'error', $returnurl);
}
// Test columns.
$processed = [];
$required = 0;
foreach ($columns as $key => $field) {
$lcfield = core_text::strtolower($field);
if (in_array($field, $fields) || in_array($lcfield, $fields)) {
// Standard fields are only lowercase.
$newfield = $lcfield;
} else if (preg_match('/^(field|operator|matchvalue|sublimit)\d+$/', $lcfield)) {
// Sublimit fields - not used.
$newfield = $lcfield;
} else {
$cir->close();
$cir->cleanup();
throw new moodle_exception('invalidfieldname', 'error', $returnurl, $field);
}
if (in_array($newfield, $processed)) {
$cir->close();
$cir->cleanup();
throw new moodle_exception('duplicatefieldname', 'error', $returnurl, $newfield);
}
if (in_array($newfield, $requiredfields)) {
$required++;
}
$processed[$key] = $newfield;
}
if ($required < count($requiredfields)) {
$cir->close();
$cir->cleanup();
throw new moodle_exception('missingrequiredfield', 'error', $returnurl);
}
return $processed;
}
/**
* Creates an user event for given reservation
*
* @param stdClass $reservation
* @param stdClass $request
*/
function reservation_set_user_event($reservation, $request) {
global $CFG, $DB, $USER, $PAGE;
$events = get_config('reservation', 'events');
if ($events === false) {
$events = 'reservation,event';
}
if ($DB->get_record('user', ['id' => $request->userid]) && !empty($events)) {
$enabledevents = explode(',', $events);
if (in_array('userevent', $enabledevents)) {
require_once($CFG->dirroot.'/calendar/lib.php');
$event = new stdClass();
$event->name = get_string('eventreminder', 'reservation', $reservation->name);
$coursemodule = get_coursemodule_from_instance('reservation', $reservation->id)->id;
$event->description = format_module_intro('reservation', $reservation, $coursemodule);
$event->userid = $request->userid;
$event->modulename = '';
$event->instance = 0;
$event->eventtype = 'user';
$event->timestart = $reservation->timestart;
$event->visible = instance_is_visible('reservation', $reservation);
$event->timeduration = max($reservation->timeend - $reservation->timestart, 0);
$context = $PAGE->context;
$selfreserve = true;
if (($USER->id != $request->userid) && has_capability('mod/reservation:manualreserve', $context)) {
$selfreserve = false;
}
$newevent = calendar_event::create($event, $selfreserve);
$DB->set_field('reservation_request', 'eventid', $newevent->id, ['id' => $request->id]);
}
}
}
/**
* Remove the user event for given reservation
*
* @param stdClass $reservation
* @param stdClass $request
* @throws moodle_exception
*/
function reservation_remove_user_event($reservation, $request) {
global $CFG, $DB;
$events = get_config('reservation', 'events');
if ($events === false) {
$events = 'reservation,event';
}
if ($DB->get_record('user', ['id' => $request->userid, 'deleted' => 0]) && !empty($events)) {
$enabledevents = explode(',', $events);
if (in_array('userevent', $enabledevents)) {
require_once($CFG->dirroot.'/calendar/lib.php');
$events = calendar_get_events_by_id([$request->eventid]);
if (!empty($events)) {
$deleted = false;
foreach ($events as $event) {
if (!$deleted) {
calendar_event::load($event)->delete();
$deleted = true;
} else {
throw new moodle_exception('Found more than one user event for reservation '. $reservation->id);
}
}
}
}
}
}
/**
* Get array of defined table fields
*
* @param array $customfields
* @param stdClass $status
* @return array
*/
function reservation_get_fields($customfields, $status) {
$fields = [];
// Get request table display fields.
$fieldslist = get_config('reservation', 'fields');
// Add fields to requests table.
$field = strtok($fieldslist, ',');
while ($field !== false) {
if (isset($customfields[$field])) {
if (!isset($fields[$field])) {
$fields[$field] = new stdClass();
$fields[$field]->custom = $customfields[$field]->id;
}
$fields[$field]->name = format_string($customfields[$field]->name);
} else {
if (!isset($fields[$field])) {
$fields[$field] = new stdClass();
$fields[$field]->custom = false;
}
if ($field == 'phone1') {
$fields[$field]->name = get_string('phone');
} else {
$fields[$field]->name = get_string($field);
}
}
$field = strtok(',');