-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathlib.php
executable file
·1435 lines (1271 loc) · 51.5 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
// This file is part of mod_organizer for Moodle - http://moodle.org/
//
// It 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.
//
// It 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/>.
/**
* lib.php
*
* @package mod_organizer
* @author Andreas Hruska (andreas.hruska@tuwien.ac.at)
* @author Katarzyna Potocka (katarzyna.potocka@tuwien.ac.at)
* @author Thomas Niedermaier (thomas.niedermaier@gmail.com)
* @author Andreas Windbichler
* @author Ivan Šakić
* @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core_calendar\action_factory;
use core_calendar\local\event\entities\action_interface;
defined('MOODLE_INTERNAL') || die();
define('ORGANIZER_MESSAGES_NONE', 0);
define('ORGANIZER_MESSAGES_RE_UNREG', 1);
define('ORGANIZER_MESSAGES_ALL', 2);
define('ORGANIZER_DELETE_EVENTS', 1);
define('ORGANIZER_VISIBILITY_ALL', 0);
define('ORGANIZER_VISIBILITY_ANONYMOUS', 1);
define('ORGANIZER_VISIBILITY_SLOT', 2);
define('ORGANIZER_GROUPMODE_NOGROUPS', 0);
define('ORGANIZER_GROUPMODE_EXISTINGGROUPS', 1);
define('ORGANIZER_GROUPMODE_NEWGROUPSLOT', 2);
define('ORGANIZER_GROUPMODE_NEWGROUPBOOKING', 3);
define('ORGANIZER_CALENDAR_EVENTTYPE_APPOINTMENT', 'Appointment');
define('ORGANIZER_CALENDAR_EVENTTYPE_SLOT', 'Slot');
define('ORGANIZER_CALENDAR_EVENTTYPE_INSTANCE', 'Instance');
define('EIGHTDAYS', 691200);
define('ORGANIZER_PRINTSLOTUSERFIELDS', 9);
define('USERSLOTS_MIN_NOT_REACHED', 0);
define('USERSLOTS_MIN_REACHED', 1);
define('USERSLOTS_MAX_REACHED', 2);
define('GRADEAGGREGATIONMETHOD_AVERAGE', 1);
define('GRADEAGGREGATIONMETHOD_SUM', 2);
define('GRADEAGGREGATIONMETHOD_BEST', 3);
define('GRADEAGGREGATIONMETHOD_WORST', 4);
require_once(dirname(__FILE__) . '/slotlib.php');
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will create a new instance and return the id number
* of the new instance.
*
* @param object $organizer An object from the form in mod_form.php
* @return int The id of the newly inserted organizer record
* @throws dml_exception
*/
function organizer_add_instance($organizer) {
global $DB;
$organizer->timemodified = time();
if (isset($organizer->allowregistrationsfromdate) && $organizer->allowregistrationsfromdate == 0) {
$organizer->allowregistrationsfromdate = null;
}
if (isset($organizer->duedate) && $organizer->duedate == 0) {
$organizer->duedate = null;
}
$organizer->id = $DB->insert_record('organizer', $organizer);
organizer_grade_item_update($organizer);
organizer_change_event_instance($organizer);
$_SESSION["organizer_new_instance"] = $organizer->id;
return $organizer->id;
}
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @param object $organizer An object from the form in mod_form.php
* @return boolean Success/Fail
* @throws dml_exception
*/
function organizer_update_instance($organizer) {
global $DB;
$organizer->id = $organizer->instance;
$organizer->timemodified = time();
if (isset($organizer->allowregistrationsfromdate) && $organizer->allowregistrationsfromdate == 0) {
$organizer->allowregistrationsfromdate = null;
}
if (isset($organizer->duedate) && $organizer->duedate == 0) {
$organizer->duedate = null;
}
$newname = $organizer->name;
$organizerold = $DB->get_record('organizer', ['id' => $organizer->id], 'name, gradeaggregationmethod');
organizer_grade_item_update($organizer);
$DB->update_record('organizer', $organizer);
if (isset($organizer->queue) && $organizer->queue == 0) {
organizer_remove_waitingqueueentries($organizer);
}
// If grade aggregation method has changed regrade all grades.
if ($organizerold->gradeaggregationmethod != $organizer->gradeaggregationmethod) {
organizer_update_all_grades($organizer->id);
}
// Update event entries.
$params = ['modulename' => 'organizer', 'instance' => $organizer->id,
'eventtype' => ORGANIZER_CALENDAR_EVENTTYPE_INSTANCE];
$query = 'SELECT id
FROM {event}
WHERE modulename = :modulename
AND instance = :instance
AND eventtype = :eventtype';
$eventids = $DB->get_fieldset_sql($query, $params);
organizer_change_event_instance($organizer, $eventids);
if ($organizerold->name != $newname) {
organizer_change_eventnames($organizer->id, $organizerold->name, $newname);
}
return true;
}
/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @param int $id Id of the module instance
* @return boolean Success/Failure
* @throws dml_exception
*/
function organizer_delete_instance($id) {
global $DB;
if (!$organizer = $DB->get_record('organizer', ['id' => $id])) {
return false;
}
$slots = $DB->get_records('organizer_slots', ['organizerid' => $id]);
foreach ($slots as $slot) {
$DB->delete_records('organizer_slot_trainer', ['slotid' => $slot->id]);
$apps = $DB->get_records('organizer_slot_appointments', ['slotid' => $slot->id]);
foreach ($apps as $app) {
if (ORGANIZER_DELETE_EVENTS) {
$DB->delete_records('event', ['id' => $app->eventid]);
$DB->delete_records('event', ['uuid' => $app->id,
'modulename' => 'organizer', 'instance' => $organizer->id,
'eventtype' => ORGANIZER_CALENDAR_EVENTTYPE_APPOINTMENT]);
}
$DB->delete_records('organizer_slot_appointments', ['id' => $app->id]);
} // Foreach app.
if (ORGANIZER_DELETE_EVENTS) {
$DB->delete_records('event', ['uuid' => $slot->id,
'modulename' => 'organizer', 'instance' => $organizer->id, 'eventtype' => ORGANIZER_CALENDAR_EVENTTYPE_SLOT]);
}
$DB->delete_records('organizer_slots', ['id' => $slot->id]);
} // Foreach slot.
if (ORGANIZER_DELETE_EVENTS) {
$DB->delete_records('event', [
'modulename' => 'organizer', 'instance' => $organizer->id, 'eventtype' => ORGANIZER_CALENDAR_EVENTTYPE_INSTANCE]);
}
$DB->delete_records('organizer', ['id' => $organizer->id]);
organizer_grade_item_update($organizer);
return true;
}
/**
* Return a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
* $return->time = the time they did it
* $return->info = a short text description
*
* @return null
*/
function organizer_user_outline($course, $user, $mod, $organizer) {
// Tscpr: do we need this function if it's returning just nothing?
$return = new stdClass;
$return->time = time();
$return->info = '';
return $return;
}
/**
* Print a detailed representation of what a user has done with
* a given particular instance of this module, for user activity reports.
*
* @return boolean
*/
function organizer_user_complete($course, $user, $mod, $organizer) {
// Tscpr: do we need this function if we don't support completions?
return false;
}
/**
* Given a course and a time, this module should find recent activity
* that has occurred in organizer activities and print it out.
* Return true if there was output, or false is there was none.
*
* @return boolean
*/
function organizer_print_recent_activity($course, $viewfullnames, $timestart) {
return false; // True if anything was printed, otherwise false.
}
/**
* Add elements to reset course form for organizer module.
*
* @param MoodleQuickForm $mform Form to define elements on.
*/
function organizer_reset_course_form_definition(&$mform) {
$mform->addElement('header', 'organizerheader', get_string('modulenameplural', 'organizer'));
$mform->addElement('checkbox', 'reset_organizer_all', get_string('resetorganizerall', 'organizer'));
$mform->addElement('checkbox', 'delete_organizer_grades', get_string('deleteorganizergrades', 'organizer'));
}
/**
* Reset user data for the organizer module during course reset.
*
* @param stdClass $data Data submitted by the reset course form.
* @return array Status information list for the reset process.
* @throws dml_exception
*/
function organizer_reset_userdata($data) {
global $DB;
if (!$DB->count_records('organizer', ['course' => $data->courseid])) {
return [];
}
$componentstr = get_string('modulenameplural', 'organizer');
$status = [];
if (isset($data->reset_organizer_all)) {
$params = ['courseid' => $data->courseid];
$slotquery = 'SELECT s.*
FROM {organizer_slots} s
INNER JOIN {organizer} m ON s.organizerid = m.id
WHERE m.course = :courseid';
$appquery = 'SELECT a.*
FROM {organizer_slot_appointments} a
INNER JOIN {organizer_slots} s ON a.slotid = s.id
INNER JOIN {organizer} m ON s.organizerid = m.id
WHERE m.course = :courseid';
$slots = $DB->get_records_sql($slotquery, $params);
$appointments = $DB->get_records_sql($appquery, $params);
$ok = true;
foreach ($slots as $slot) {
$DB->delete_records('event', ['id' => $slot->eventid]);
// Tscpr: Petr Skoda told us that $DB->delete_records will throw an exeption if it fails, otherwise it always succeeds.
$ok &= $DB->delete_records('organizer_slots', ['id' => $slot->id]);
}
foreach ($appointments as $appointment) {
$DB->delete_records('event', ['id' => $appointment->eventid]);
// Tscpr: Petr Skoda told us that $DB->delete_records will throw an exeption if it fails, otherwise it always succeeds.
$ok &= $DB->delete_records('organizer_slot_appointments', ['id' => $appointment->id]);
}
$status[] = ['component' => $componentstr, 'item' => get_string('reset_organizer_all', 'organizer'),
'error' => !$ok];
}
if (isset($data->delete_organizer_grades)) {
$ok = organizer_reset_gradebook($data->courseid);
$status[] = ['component' => $componentstr, 'item' => get_string('delete_organizer_grades', 'organizer'),
'error' => !$ok];
}
if ($data->timeshift) {
$ok = shift_course_mod_dates(
'organizer',
['allowregistrationsfromdate', 'duedate'], $data->timeshift, $data->courseid
);
$status[] = ['component' => $componentstr, 'item' => get_string('timeshift', 'organizer'),
'error' => !$ok];
}
return $status;
}
/**
* Reset organizer grades for a given course ID.
*
* @param int $courseid ID of the course being reset.
* @return bool Gradebook reset status.
* @throws dml_exception
*/
function organizer_reset_gradebook($courseid) {
global $DB;
$params = ['courseid' => $courseid];
$sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
FROM {organizer} a, {course_modules} cm, {modules} m
WHERE m.name=\'organizer\' AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
$ok = true;
if ($assignments = $DB->get_records_sql($sql, $params)) {
foreach ($assignments as $assignment) {
$status = organizer_grade_item_update($assignment, 'reset');
$ok &= $status == GRADE_UPDATE_OK;
}
}
return $ok;
}
/**
* Retrieve grades for a user in an organizer instance.
*
* @param stdClass $organizer Organizer instance object.
* @param int $userid User ID to fetch grades for, or 0 for all users.
* @return array List of grade records.
* @throws dml_exception
*/
function organizer_get_user_grade($organizer, $userid = 0) {
global $DB;
$params = ['organizerid' => $organizer->id, 'userid' => $userid];
if ($userid) {
$query = 'SELECT
a.id AS id,
a.userid AS userid,
a.grade AS rawgrade,
s.starttime AS dategraded,
s.starttime AS datesubmitted,
a.feedback AS feedback
FROM {organizer_slot_appointments} a
INNER JOIN {organizer_slots} s ON a.slotid = s.id
WHERE s.organizerid = :organizerid AND a.userid = :userid
ORDER BY id DESC';
return $DB->get_records_sql($query, $params);
} else {
return [];
}
}
/**
* Update activity grades.
*
* @param object $organizer
* @param int $userid specific user only, 0 means all
*/
function organizer_update_grades($organizer, $userid = 0) {
global $CFG;
include_once($CFG->libdir . '/gradelib.php');
if ($organizer->grade == 0) {
return organizer_grade_item_update($organizer);
} else {
if ($grades = organizer_get_user_grade($organizer, $userid)) {
$grade = reset($grades);
if ($organizer->grade > 0) { // Numerical.
switch ($organizer->gradeaggregationmethod) {
case GRADEAGGREGATIONMETHOD_AVERAGE:
$sum = 0;
$i = 0;
foreach ($grades as $value) {
if ($value->rawgrade) {
$i++;
$sum += $value->rawgrade;
}
}
$grade->rawgrade = $i ? $sum / $i : 0;
break;
case GRADEAGGREGATIONMETHOD_SUM:
$sum = 0;
foreach ($grades as $value) {
if ($value->rawgrade) {
$sum += $value->rawgrade;
}
}
$grade->rawgrade = $sum;
break;
case GRADEAGGREGATIONMETHOD_BEST:
$max = 0;
foreach ($grades as $value) {
if (is_numeric($value->rawgrade)) {
if ((float) $value->rawgrade > (float) $max) {
$max = $value->rawgrade;
}
}
}
$grade->rawgrade = $max;
break;
case GRADEAGGREGATIONMETHOD_WORST:
$min = INF;
foreach ($grades as $value) {
if (is_numeric($value->rawgrade)) {
if ((float) $value->rawgrade < (float) $min) {
$min = $value->rawgrade;
}
}
}
$grade->rawgrade = $min;
break;
default:
// If no grade method is selected take average method.
$sum = 0;
$i = 0;
foreach ($grades as $value) {
if ($value->rawgrade) {
$i++;
$sum += $value->rawgrade;
}
}
$grade->rawgrade = $sum / $i;
}
}
return organizer_grade_item_update($organizer, $grade);
} else {
return organizer_grade_item_update($organizer);
}
}
}
/**
* Create/update grade items for given organizer.
*
* @param stdClass $organizer Organizer instance object
* @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
*/
function organizer_grade_item_update($organizer, $grades = null) {
global $CFG;
include_once($CFG->libdir . '/gradelib.php');
if (!isset($organizer->courseid)) {
$organizer->courseid = $organizer->course;
}
if (isset($organizer->cmidnumber)) {
$params = ['itemname' => $organizer->name, 'idnumber' => $organizer->cmidnumber];
} else {
$params = ['itemname' => $organizer->name];
}
if (isset($organizer->grade) && $organizer->grade > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $organizer->grade;
$params['grademin'] = 0;
} else if (isset($organizer->grade) && $organizer->grade < 0) {
$params['gradetype'] = GRADE_TYPE_SCALE;
$params['scaleid'] = -$organizer->grade;
} else {
$params['gradetype'] = GRADE_TYPE_NONE;
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = null;
}
return grade_update('mod/organizer', $organizer->courseid, 'mod', 'organizer', $organizer->id, 0, $grades, $params);
}
/**
* Display a formatted grade for an organizer activity.
*
* @param stdClass $organizer Organizer instance object.
* @param float|int $grade Raw grade from the gradebook.
* @param int $userid User ID for scale grade processing.
* @return string Formatted grade string or no-grade string.
*/
function organizer_display_grade($organizer, $grade, $userid) {
global $DB;
$nograde = get_string('nograde');
static $scalegrades = []; // Cache scales for each organizer - they might have different scales!!
if ($organizer->grade > 0) { // Normal number.
if ($grade == -1 || $grade == null) {
return $nograde;
} else {
$returnstr = organizer_clean_num($grade) . '/' . organizer_clean_num($organizer->grade);
return $returnstr;
}
} else { // Scale.
if (empty($scalegrades[$organizer->id])) {
if ($scale = $DB->get_record('scale', ['id' => -($organizer->scale)])) {
$scalegrades[$organizer->id] = make_menu_from_list($scale->scale);
} else {
return $nograde;
}
}
if (isset($scalegrades[$organizer->id][intval($grade)])) {
return $scalegrades[$organizer->id][intval($grade)];
} else {
return $nograde;
}
}
}
/**
* Update all grades for the specified organizer.
*
* This function retrieves all students or groups enrolled in the specified organizer,
* calculates their grades, and updates them accordingly in the gradebook.
*
* @param int $organizerid The ID of the organizer whose grades need to be updated.
* @return int The number of student grades updated.
* @throws dml_exception If any database operation fails.
*/
function organizer_update_all_grades($organizerid) {
global $DB;
[$cm, , $organizer, $context] = organizer_get_course_module_data(null, $organizerid);
$studentids = [];
if ($organizer->isgrouporganizer != ORGANIZER_GROUPMODE_EXISTINGGROUPS) {
$students = get_enrolled_users($context, 'mod/organizer:register');
foreach ($students as $student) {
$studentids[] = $student->id;
}
} else if ($cm->groupingid != 0) {
$query = "SELECT u.id FROM {user} u
INNER JOIN {groups_members} gm ON u.id = gm.userid
INNER JOIN {groups} g ON gm.groupid = g.id
INNER JOIN {groupings_groups} gg ON g.id = gg.groupid
WHERE gg.groupingid = :grouping";
$par = ['grouping' => $cm->groupingid];
$studentids = $DB->get_fieldset_sql($query, $par);
}
foreach ($studentids as $studentid) {
organizer_update_grades($organizer, $studentid);
}
return count($studentids);
}
/**
* Creates a grades menu for an organizer based on the grading type.
*
* This function generates a grade menu for the organizer activity. If the grading type
* is a scale, it fetches the corresponding scale items from the database and adds a "No grade" option.
* For numeric grading, it creates a menu with grades ranging from 0 to the maximum grade allowed.
*
* @param int $gradingtype The grading type of the organizer:
* - Negative values indicate a scale ID.
* - Positive values specify a maximum numeric grade.
* @return array An associative array representing the grades menu.
* Keys are grades or scale indices, and values are their string representations.
* Includes a "No grade" option.
* @throws dml_exception If there's an error fetching scale data from the database.
*/
function organizer_make_grades_menu_organizer($gradingtype) {
global $DB;
$grades = [];
if ($gradingtype < 0) {
if ($scale = $DB->get_record('scale', ['id' => (-$gradingtype)])) {
$menu = make_menu_from_list($scale->scale);
$menu['0'] = get_string('nograde');
return $menu;
}
} else if ($gradingtype > 0) {
$grades['-1'] = get_string('nograde');
for ($i = $gradingtype; $i >= 0; $i--) {
$grades[$i] = organizer_clean_num($i) . ' / ' . organizer_clean_num($gradingtype);
}
return $grades;
}
return $grades;
}
/**
* Cleans up a numeric value by removing unnecessary trailing zeros from decimal numbers.
*
* This function checks whether the given number is an integer or a decimal.
* If it is a decimal, it removes trailing zeros and the decimal point if there are no significant decimals left.
*
* @param string|float|int $num The numeric value to clean. It can be a string, float, or integer.
* @return string The cleaned numeric value as a string.
*/
function organizer_clean_num($num) {
$pos = strpos($num, '.');
if ($pos === false) { // It is integer number.
return $num;
} else { // It is decimal number.
return rtrim(rtrim($num, '0'), '.');
}
}
/**
* Retrieves the event action instance for a trainer in an organizer module.
*
* @param object $organizer The organizer module instance.
* @return string A localized string representing the event action instance.
*/
function organizer_get_eventaction_instance_trainer($organizer) {
$a = organizer_get_counters($organizer);
if ($organizer->isgrouporganizer == ORGANIZER_GROUPMODE_EXISTINGGROUPS) {
if ($a->attended == 0) {
return get_string('mymoodle_registered_group_short', 'organizer', $a);
} else {
return get_string('mymoodle_attended_group_short', 'organizer', $a);
}
} else {
if ($a->attended == 0) {
return get_string('mymoodle_registered_short', 'organizer', $a);
} else {
return get_string('mymoodle_attended_short', 'organizer', $a);
}
}
}
/**
* Retrieves the event action instance for a student in an organizer module.
*
* @param object $organizer The organizer module instance.
* @return string A localized string representing the event action instance.
*/
function organizer_get_eventaction_instance_student($organizer) {
$a = new stdClass();
if ($organizer->isgrouporganizer == ORGANIZER_GROUPMODE_EXISTINGGROUPS) {
$group = organizer_fetch_group($organizer);
$a->booked = organizer_count_bookedslots($organizer->id, null, $group->id);
$a->groupname = $group->name;
$a->slotsmin = $organizer->userslotsmin;
if (organizer_multiplebookings_status($a->booked, $organizer) != USERSLOTS_MIN_NOT_REACHED) {
$str = get_string('mymoodle_reg_slot_group', 'organizer', $a);
} else {
$str = get_string('mymoodle_no_reg_slot_group', 'organizer');
}
} else {
$a->booked = organizer_count_bookedslots($organizer->id);
$a->slotsmin = $organizer->userslotsmin;
if (organizer_multiplebookings_status($a->booked, $organizer) != USERSLOTS_MIN_NOT_REACHED) {
$str = get_string('mymoodle_reg_slot', 'organizer', $a);
} else {
$str = get_string('mymoodle_no_reg_slot', 'organizer');
}
if (isset($organizer->duedate)) {
$a = new stdClass();
$a->date = userdate($organizer->duedate, get_string('fulldatetemplate', 'organizer'));
$a->time = userdate($organizer->duedate, get_string('timetemplate', 'organizer'));
if ($organizer->duedate > time()) {
$orgexpires = get_string('mymoodle_organizer_expires', 'organizer', $a);
} else {
$orgexpires = get_string('mymoodle_organizer_expired', 'organizer', $a);
}
$str .= " " . $orgexpires;
}
}
return $str;
}
/**
* Fetches the group associated with a user in the specified organizer module.
*
* This function determines the group to which a user belongs in the given course and
* organizer module. If no user ID is provided, it defaults to the ID of the currently logged-in user.
*
* If the organizer parameter is passed as an integer ID, the corresponding organizer record
* will be fetched from the database.
*
* @param object|int $organizer The organizer module instance or its ID.
* @param int|null $userid The user ID for whom the group is to be fetched. Defaults to the current user.
* @return object The group object that the user belongs to.
* @throws dml_exception If there is a problem with retrieving records from the database.
*/
function organizer_fetch_group($organizer, $userid = null) {
global $DB, $USER;
if ($userid == null) {
$userid = $USER->id;
}
if (is_number($organizer) && $organizer == intval($organizer)) {
$organizer = $DB->get_record('organizer', ['id' => $organizer]);
}
$usergrouparrays = groups_get_user_groups($organizer->course, $userid);
$usergroups = reset($usergrouparrays);
$usergroup = reset($usergroups);
$group = groups_get_group($usergroup);
return $group;
}
/**
* Function to be run periodically according to the moodle cron
* This function searches for things that need to be done, such
* as sending out mail, toggling flags etc ...
*
* @return bool|mixed
* @throws coding_exception
* @throws dml_exception
* @throws moodle_exception
**/
function organizer_cron() {
global $DB;
include_once(__DIR__ . '/messaging.php');
include_once(__DIR__ . '/locallib.php');
$now = time();
/* Handle deleted users in slots */
$sql = <<<SQL
SELECT
s.id,
u.id AS userid,
s.id AS slotid,
s.organizerid,
o.isgrouporganizer,
o.queue
FROM
{organizer_slots} s
JOIN
{organizer_slot_appointments} sa ON sa.slotid = s.id
JOIN
{organizer} o ON o.id = s.organizerid
JOIN
{user} u ON u.id = sa.userid
WHERE
(u.deleted = 1 OR u.suspended = 1) AND
s.starttime >= :now
SQL;
$deletedusers = $DB->get_records_sql($sql, ['now' => $now]);
foreach ($deletedusers as $du) {
$org = new stdClass;
$org->id = $du->organizerid;
$org->isgrouporganizer = $du->isgrouporganizer;
organizer_unregister_single_appointment($du->slotid, $du->userid, $org);
if ($du->isgrouporganizer != ORGANIZER_GROUPMODE_EXISTINGGROUPS) {
if ($du->queue) {
$slotx = new organizer_slot($du->slotid);
if ($next = $slotx->get_next_in_queue()) {
organizer_register_appointment($du->slotid, 0, $next->userid, true);
organizer_delete_from_queue($du->slotid, $next->userid);
}
}
}
}
// Handle queued deleted or suspended users!
$sql = <<<SQL
SELECT
s.id,
u.id AS userid,
s.id AS slotid,
s.organizerid,
o.isgrouporganizer,
o.queue
FROM
{organizer_slots} s
JOIN
{organizer_slot_queues} sa ON sa.slotid = s.id
JOIN
{organizer} o ON o.id = s.organizerid
JOIN
{user} u ON u.id = sa.userid
WHERE
(u.deleted = 1 OR u.suspended = 1) AND
s.starttime >= :now
SQL;
$deletedusers = $DB->get_records_sql($sql, ['now' => $now]);
foreach ($deletedusers as $du) {
organizer_delete_from_queue($du->slotid, $du->userid);
}
$success = true;
$params = ['now' => $now, 'now2' => $now];
$appsquery = "SELECT a.*, s.location, s.starttime, s.organizerid, s.teachervisible FROM {organizer_slot_appointments} a
INNER JOIN {organizer_slots} s ON a.slotid = s.id WHERE
s.starttime - s.notificationtime < :now AND s.starttime > :now2 AND
a.notified = 0";
$apps = $DB->get_records_sql($appsquery, $params);
foreach ($apps as $app) {
$customdata = ['showsendername' => intval($app->teachervisible == 1)];
$success &= organizer_send_message_from_trainer(intval($app->userid), $app,
'appointment_reminder_student', null, $customdata);
}
if (empty($apps)) {
$ids = [0];
} else {
$ids = array_keys($apps);
}
[$insql, $inparams] = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
$DB->execute("UPDATE {organizer_slot_appointments} SET notified = 1 WHERE id $insql", $inparams);
$organizerconfig = get_config('organizer');
if (isset($organizerconfig->digest) && $organizerconfig->digest == 'never') {
return $success;
} else if (isset($organizerconfig->digest)) {
$time = $organizerconfig->digest + mktime(0, 0, 0, date("m"), date("d"), date("Y"));
if (abs(time() - $time) >= 300) {
return $success;
}
}
$params['tomorrowstart'] = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
$params['tomorrowend'] = mktime(0, 0, 0, date("m"), date("d") + 2, date("Y"));
$slotsquery = "SELECT DISTINCT t.trainerid FROM {organizer_slots} s INNER JOIN {organizer_slot_trainer} t ON s.id = t.slotid
WHERE s.starttime >= :tomorrowstart AND
s.starttime < :tomorrowend AND
s.notified = 0";
$trainerids = $DB->get_fieldset_sql($slotsquery, $params);
if (empty($trainerids)) {
$trainerids = [0];
}
[$insql, $inparams] = $DB->get_in_or_equal($trainerids, SQL_PARAMS_NAMED);
$slotsquery = "SELECT s.*, t.trainerid
FROM {organizer_slots} s INNER JOIN {organizer_slot_trainer} t ON s.id = t.slotid
WHERE s.starttime >= :tomorrowstart AND
s.starttime < :tomorrowend AND
s.notified = 0 AND
t.trainerid $insql";
$params = array_merge($params, $inparams);
$slots = $DB->get_records_sql($slotsquery, $params);
foreach ($trainerids as $trainerid) {
$digest = '';
$found = false;
foreach ($slots as $slot) {
if ($slot->trainerid == $trainerid) {
$time = userdate($slot->starttime, get_string('timetemplate', 'organizer'));
$digest .= "$time @ $slot->location\n";
$found = true;
}
}
if (empty($slots)) {
$ids = [0];
} else {
$ids = array_keys($slots);
}
if ($found) {
// Reminder for trainer in cron job.
$success &= $thissuccess = organizer_send_message(
intval($trainerid), intval($trainerid), reset($slots),
'appointment_reminder_teacher', $digest
);
if ($thissuccess) {
[$insql, ] = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
$DB->execute("UPDATE {organizer_slots} SET notified = 1 WHERE id $insql");
}
}
}
return $success;
}
/**
* Creates and sends a digest message for an organizer trainer.
*
* This function generates a digest of upcoming appointment slots that
* meet the criteria for notification. The digest includes the date, time,
* and location of each slot. It updates the notification status of the slots
* to prevent duplicate notifications and sends the digest message to the
* trainer.
*
* @param int $trainerid The ID of the trainer for whom the digest is created.
* @return bool True if the digest message is successfully sent, false otherwise.
*/
function organizer_create_digest($trainerid) {
include_once(dirname(__FILE__) . '/messaging.php');
global $DB;
$now = time();
$params = ['now' => $now, 'trainerid' => $trainerid];
$slotsquery = 'SELECT s.*, t.trainerid, t.slotid FROM {organizer_slots} s INNER JOIN {organizer_slot_trainer} t
ON s.id = t.slotid
WHERE s.starttime - s.notificationtime < :now AND
s.notified = 0 AND t.trainerid = :trainerid';
$digest = '';
$slots = $DB->get_records_sql($slotsquery, $params);
foreach ($slots as $slot) {
if (isset($slot)) {
$date = userdate($slot->starttime, get_string('datetemplate', 'organizer'));
$time = userdate($slot->starttime, get_string('timetemplate', 'organizer'));
}
$digest .= $date.', '.$time.' @ '.$slot->location.'; ';
$DB->execute("UPDATE {organizer_slots} SET notified = 1 WHERE id = $slot->slotid");
}
// Send digest from trainer to itself. Is this used??
$success = organizer_send_message($trainerid, $trainerid, $slot, 'appointment_reminder_teacher:digest', $digest);
return $success;
}
/**
* Must return an array of users who are participants for a given instance
* of organizer. Must include every user involved in the instance,
* independent of his role (student, teacher, admin...). The returned
* objects must contain at least id property.
* See other modules as example.
*
* @param int $organizerid ID of an instance of this module
* @return boolean|array false if no participants, array of objects otherwise
*/
function organizer_get_participants($organizerid) {
return false;
}
/**
* This function returns if a scale is being used by one organizer
* if it has support for grading and scales. Commented code should be
* modified if necessary. See forum, glossary or journal modules
* as reference.
*
* @param int $organizerid ID of an instance of this module
* @return mixed
*/
function organizer_scale_used($organizerid, $scaleid) {
global $DB;
if ($organizerid && $scaleid && $DB->record_exists('organizer', ['id' => $organizerid, 'grade' => -$scaleid])) {
return true;
} else {
return false;
}
}
/**
* Checks if scale is being used by any instance of organizer.
* This function was added in 1.9
*
* This is used to find out if scale used anywhere
*
* @param $scaleid int
* @return boolean True if the scale is used by any organizer
*/
function organizer_scale_used_anywhere($scaleid) {
global $DB;
if ($scaleid && $DB->record_exists('organizer', ['grade' => -$scaleid])) {
return true;
} else {
return false;
}
}