forked from totara/facetoface-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
4243 lines (3643 loc) · 145 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 Totara LMS
*
* Copyright (C) 2010, 2011 Totara Learning Solutions LTD
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Alastair Munro <[email protected]>
* @author Aaron Barnes <[email protected]>
* @author Francois Marier <[email protected]>
* @package modules
* @subpackage facetoface
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/grade/lib.php');
require_once($CFG->dirroot.'/lib/adminlib.php');
require_once($CFG->dirroot . '/user/selector/lib.php');
if (file_exists($CFG->libdir.'/completionlib.php')) {
require_once($CFG->libdir.'/completionlib.php');
}
/**
* Definitions for setting notification types
*/
/**
* Utility definitions
*/
define('MDL_F2F_ICAL', 1);
define('MDL_F2F_TEXT', 2);
define('MDL_F2F_BOTH', 3);
define('MDL_F2F_INVITE', 4);
define('MDL_F2F_CANCEL', 8);
/**
* Definitions for use in forms
*/
define('MDL_F2F_INVITE_BOTH', 7); // Send a copy of both 4+1+2
define('MDL_F2F_INVITE_TEXT', 6); // Send just a plain email 4+2
define('MDL_F2F_INVITE_ICAL', 5); // Send just a combined text/ical message 4+1
define('MDL_F2F_CANCEL_BOTH', 11); // Send a copy of both 8+2+1
define('MDL_F2F_CANCEL_TEXT', 10); // Send just a plan email 8+2
define('MDL_F2F_CANCEL_ICAL', 9); // Send just a combined text/ical message 8+1
// Name of the custom field where the manager's email address is stored
define('MDL_MANAGERSEMAIL_FIELD', 'managersemail');
// Custom field related constants
define('CUSTOMFIELD_DELIMITER', '##SEPARATOR##');
define('CUSTOMFIELD_TYPE_TEXT', 0);
define('CUSTOMFIELD_TYPE_SELECT', 1);
define('CUSTOMFIELD_TYPE_MULTISELECT', 2);
// Calendar-related constants
define('CALENDAR_MAX_NAME_LENGTH', 15);
define('F2F_CAL_NONE', 0);
define('F2F_CAL_COURSE', 1);
define('F2F_CAL_SITE', 2);
// Signup status codes (remember to update $MDL_F2F_STATUS)
define('MDL_F2F_STATUS_USER_CANCELLED', 10);
// SESSION_CANCELLED is not yet implemented
define('MDL_F2F_STATUS_SESSION_CANCELLED', 20);
define('MDL_F2F_STATUS_DECLINED', 30);
define('MDL_F2F_STATUS_REQUESTED', 40);
define('MDL_F2F_STATUS_APPROVED', 50);
define('MDL_F2F_STATUS_WAITLISTED', 60);
define('MDL_F2F_STATUS_BOOKED', 70);
define('MDL_F2F_STATUS_NO_SHOW', 80);
define('MDL_F2F_STATUS_PARTIALLY_ATTENDED', 90);
define('MDL_F2F_STATUS_FULLY_ATTENDED', 100);
// This array must match the status codes above, and the values
// must equal the end of the constant name but in lower case
global $MDL_F2F_STATUS;
$MDL_F2F_STATUS = array(
MDL_F2F_STATUS_USER_CANCELLED => 'user_cancelled',
// SESSION_CANCELLED is not yet implemented
// MDL_F2F_STATUS_SESSION_CANCELLED => 'session_cancelled',
MDL_F2F_STATUS_DECLINED => 'declined',
MDL_F2F_STATUS_REQUESTED => 'requested',
MDL_F2F_STATUS_APPROVED => 'approved',
MDL_F2F_STATUS_WAITLISTED => 'waitlisted',
MDL_F2F_STATUS_BOOKED => 'booked',
MDL_F2F_STATUS_NO_SHOW => 'no_show',
MDL_F2F_STATUS_PARTIALLY_ATTENDED => 'partially_attended',
MDL_F2F_STATUS_FULLY_ATTENDED => 'fully_attended',
);
/**
* Returns the human readable code for a face-to-face status
*
* @param int $statuscode One of the MDL_F2F_STATUS* constants
* @return string Human readable code
*/
function facetoface_get_status($statuscode) {
global $MDL_F2F_STATUS;
// Check code exists
if (!isset($MDL_F2F_STATUS[$statuscode])) {
print_error('F2F status code does not exist: '.$statuscode);
}
// Get code
$string = $MDL_F2F_STATUS[$statuscode];
// Check to make sure the status array looks to be up-to-date
if (constant('MDL_F2F_STATUS_'.strtoupper($string)) != $statuscode) {
print_error('F2F status code array does not appear to be up-to-date: '.$statuscode);
}
return $string;
}
/**
* Prints the cost amount along with the appropriate currency symbol.
*
* To set your currency symbol, set the appropriate 'locale' in
* lang/en_utf8/langconfig.php (or the equivalent file for your
* language).
*
* @param $amount Numerical amount without currency symbol
* @param $htmloutput Whether the output is in HTML or not
*/
function format_cost($amount, $htmloutput=true) {
setlocale(LC_MONETARY, get_string('locale', 'langconfig'));
$localeinfo = localeconv();
$symbol = $localeinfo['currency_symbol'];
if (empty($symbol)) {
// Cannot get the locale information, default to en_US.UTF-8
return '$' . $amount;
}
// Character between the currency symbol and the amount
$separator = '';
if ($localeinfo['p_sep_by_space']) {
$separator = $htmloutput ? ' ' : ' ';
}
// The symbol can come before or after the amount
if ($localeinfo['p_cs_precedes']) {
return $symbol . $separator . $amount;
}
else {
return $amount . $separator . $symbol;
}
}
/**
* Returns the effective cost of a session depending on the presence
* or absence of a discount code.
*
* @param class $sessiondata contains the discountcost and normalcost
*/
function facetoface_cost($userid, $sessionid, $sessiondata, $htmloutput=true) {
global $CFG,$DB;
$count = $DB->count_records_sql("SELECT COUNT(*)
FROM {facetoface_signups} su,
{facetoface_sessions} se
WHERE su.sessionid = ?
AND su.userid = ?
AND su.discountcode IS NOT NULL
AND su.sessionid = se.id", array($sessionid, $userid));
if ($count > 0) {
return format_cost($sessiondata->discountcost, $htmloutput);
} else {
return format_cost($sessiondata->normalcost, $htmloutput);
}
}
/**
* Human-readable version of the duration field used to display it to
* users
*
* @param integer $duration duration in hours
* @return string
*/
function format_duration($duration) {
$components = explode(':', $duration);
// Default response
$string = '';
// Check for bad characters
if (trim(preg_match('/[^0-9:\.\s]/', $duration))) {
return $string;
}
if ($components and count($components) > 1) {
// e.g. "1:30" => "1 hour and 30 minutes"
$hours = round($components[0]);
$minutes = round($components[1]);
}
else {
// e.g. "1.5" => "1 hour and 30 minutes"
$hours = floor($duration);
$minutes = round(($duration - floor($duration)) * 60);
}
// Check if either minutes is out of bounds
if ($minutes >= 60) {
return $string;
}
if (1 == $hours) {
$string = get_string('onehour', 'facetoface');
} elseif ($hours > 1) {
$string = get_string('xhours', 'facetoface', $hours);
}
// Insert separator between hours and minutes
if ($string != '') {
$string .= ' ';
}
if (1 == $minutes) {
$string .= get_string('oneminute', 'facetoface');
} elseif ($minutes > 0) {
$string .= get_string('xminutes', 'facetoface', $minutes);
}
return $string;
}
/**
* Converts minutes to hours
*/
function facetoface_minutes_to_hours($minutes) {
if (!intval($minutes)) {
return 0;
}
if ($minutes > 0) {
$hours = floor($minutes / 60.0);
$mins = $minutes - ($hours * 60.0);
return "$hours:$mins";
}
else {
return $minutes;
}
}
/**
* Converts hours to minutes
*/
function facetoface_hours_to_minutes($hours)
{
$components = explode(':', $hours);
if ($components and count($components) > 1) {
// e.g. "1:45" => 105 minutes
$hours = $components[0];
$minutes = $components[1];
return $hours * 60.0 + $minutes;
}
else {
// e.g. "1.75" => 105 minutes
return round($hours * 60.0);
}
}
/**
* Turn undefined manager messages into empty strings and deal with checkboxes
*/
function facetoface_fix_settings($facetoface) {
if (empty($facetoface->emailmanagerconfirmation)) {
$facetoface->confirmationinstrmngr = null;
}
if (empty($facetoface->emailmanagerreminder)) {
$facetoface->reminderinstrmngr = null;
}
if (empty($facetoface->emailmanagercancellation)) {
$facetoface->cancellationinstrmngr = null;
}
if (empty($facetoface->usercalentry)) {
$facetoface->usercalentry = 0;
}
if (empty($facetoface->thirdpartywaitlist)) {
$facetoface->thirdpartywaitlist = 0;
}
if (empty($facetoface->approvalreqd)) {
$facetoface->approvalreqd = 0;
}
}
/**
* 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.
*/
function facetoface_add_instance($facetoface) {
global $DB;
$facetoface->timemodified = time();
facetoface_fix_settings($facetoface);
if ($facetoface->id = $DB->insert_record('facetoface', $facetoface)) {
facetoface_grade_item_update($facetoface);
}
// Update any calendar entries
if ($sessions = facetoface_get_sessions($facetoface->id)) {
foreach ($sessions as $session) {
facetoface_update_calendar_entries($session, $facetoface);
}
}
return $facetoface->id;
}
/**
* 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.
*/
function facetoface_update_instance($facetoface, $instanceflag = true) {
global $DB;
if ($instanceflag) {
$facetoface->id = $facetoface->instance;
}
facetoface_fix_settings($facetoface);
if ($return = $DB->update_record('facetoface', $facetoface)) {
facetoface_grade_item_update($facetoface);
//update any calendar entries
if ($sessions = facetoface_get_sessions($facetoface->id)) {
foreach ($sessions as $session) {
facetoface_update_calendar_entries($session, $facetoface);
}
}
}
return $return;
}
/**
* Given an ID of an instance of this module, this function will
* permanently delete the instance and any data that depends on it.
*/
function facetoface_delete_instance($id) {
global $CFG, $DB;
if (!$facetoface = $DB->get_record('facetoface', array('id' => $id))) {
return false;
}
$result = true;
$transaction = $DB->start_delegated_transaction();
$DB->delete_records_select(
'facetoface_signups_status',
"signupid IN
(
SELECT
id
FROM
{facetoface_signups}
WHERE
sessionid IN
(
SELECT
id
FROM
{facetoface_sessions}
WHERE
facetoface = ? ))
", array($facetoface->id));
$DB->delete_records_select('facetoface_signups', "sessionid IN (SELECT id FROM {facetoface_sessions} WHERE facetoface = ?)", array($facetoface->id));
$DB->delete_records_select('facetoface_sessions_dates', "sessionid in (SELECT id FROM {facetoface_sessions} WHERE facetoface = ?)", array($facetoface->id));
$DB->delete_records('facetoface_sessions', array('facetoface' => $facetoface->id));
$DB->delete_records('facetoface', array('id' => $facetoface->id));
$DB->delete_records('event', array('modulename' => 'facetoface', 'instance' => $facetoface->id));
facetoface_grade_item_delete($facetoface);
$transaction->allow_commit();
return $result;
}
/**
* Prepare the user data to go into the database.
*/
function cleanup_session_data($session) {
// Convert hours (expressed like "1.75" or "2" or "3.5") to minutes
$session->duration = facetoface_hours_to_minutes($session->duration);
// Only numbers allowed here
$session->capacity = preg_replace('/[^\d]/', '', $session->capacity);
$MAX_CAPACITY = 100000;
if ($session->capacity < 1) {
$session->capacity = 1;
}
elseif ($session->capacity > $MAX_CAPACITY) {
$session->capacity = $MAX_CAPACITY;
}
// Get the decimal point separator
setlocale(LC_MONETARY, get_string('locale', 'langconfig'));
$localeinfo = localeconv();
$symbol = $localeinfo['decimal_point'];
if (empty($symbol)) {
// Cannot get the locale information, default to en_US.UTF-8
$symbol = '.';
}
// Only numbers or decimal separators allowed here
$session->normalcost = round(preg_replace("/[^\d$symbol]/", '', $session->normalcost));
$session->discountcost = round(preg_replace("/[^\d$symbol]/", '', $session->discountcost));
return $session;
}
/**
* Create a new entry in the facetoface_sessions table
*/
function facetoface_add_session($session, $sessiondates) {
global $USER, $DB;
$session->timecreated = time();
$session = cleanup_session_data($session);
$eventname = $DB->get_field('facetoface', 'name,id', array('id' => $session->facetoface));
$session->id = $DB->insert_record('facetoface_sessions', $session);
if (empty($sessiondates)) {
// Insert a dummy date record
$date = new stdClass();
$date->sessionid = $session->id;
$date->timestart = 0;
$date->timefinish = 0;
$DB->insert_record('facetoface_sessions_dates', $date);
}
else {
foreach ($sessiondates as $date) {
$date->sessionid = $session->id;
$DB->insert_record('facetoface_sessions_dates', $date);
}
}
//create any calendar entries
$session->sessiondates = $sessiondates;
facetoface_update_calendar_entries($session);
return $session->id;
}
/**
* Modify an entry in the facetoface_sessions table
*/
function facetoface_update_session($session, $sessiondates) {
global $DB;
$session->timemodified = time();
$session = cleanup_session_data($session);
$transaction = $DB->start_delegated_transaction();
$DB->update_record('facetoface_sessions', $session);
$DB->delete_records('facetoface_sessions_dates', array('sessionid' => $session->id));
if (empty($sessiondates)) {
// Insert a dummy date record
$date = new stdClass();
$date->sessionid = $session->id;
$date->timestart = 0;
$date->timefinish = 0;
$DB->insert_record('facetoface_sessions_dates', $date);
}
else {
foreach ($sessiondates as $date) {
$date->sessionid = $session->id;
$DB->insert_record('facetoface_sessions_dates', $date);
}
}
// Update any calendar entries
$session->sessiondates = $sessiondates;
facetoface_update_calendar_entries($session);
$transaction->allow_commit();
return facetoface_update_attendees($session);
}
/**
* Update calendar entries for a given session
*
* @param int $session ID of session to update event for
* @param int $facetoface ID of facetoface activity (optional)
*/
function facetoface_update_calendar_entries($session, $facetoface = null){
global $USER, $DB;
if (empty($facetoface)) {
$facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface));
}
//remove from all calendars
facetoface_delete_user_calendar_events($session, 'booking');
facetoface_delete_user_calendar_events($session, 'session');
facetoface_remove_session_from_calendar($session, $facetoface->course);
facetoface_remove_session_from_calendar($session, SITEID);
if (empty($facetoface->showoncalendar) && empty($facetoface->usercalentry)) {
return true;
}
//add to NEW calendartype
if ($facetoface->usercalentry) {
//get ALL enrolled/booked users
$users = facetoface_get_attendees($session->id);
if (!in_array($USER->id, $users)) {
facetoface_add_session_to_calendar($session, $facetoface, 'user', $USER->id, 'session');
}
foreach ($users as $user) {
$eventtype = $user->statuscode == MDL_F2F_STATUS_BOOKED ? 'booking' : 'session';
facetoface_add_session_to_calendar($session, $facetoface, 'user', $user->id, $eventtype);
}
}
if ($facetoface->showoncalendar == F2F_CAL_COURSE) {
facetoface_add_session_to_calendar($session, $facetoface, 'course');
} else if ($facetoface->showoncalendar == F2F_CAL_SITE) {
facetoface_add_session_to_calendar($session, $facetoface, 'site');
}
return true;
}
/**
* Update attendee list status' on booking size change
*/
function facetoface_update_attendees($session) {
global $USER, $DB;
// Get facetoface
$facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface));
// Get course
$course = $DB->get_record('course', array('id' => $facetoface->course));
// Update user status'
$users = facetoface_get_attendees($session->id);
if ($users) {
// No/deleted session dates
if (empty($session->datetimeknown)) {
// Convert any bookings to waitlists
foreach ($users as $user) {
if ($user->statuscode == MDL_F2F_STATUS_BOOKED) {
if (!facetoface_user_signup($session, $facetoface, $course, $user->discountcode, $user->notificationtype, MDL_F2F_STATUS_WAITLISTED, $user->id)) {
// rollback_sql();
return false;
}
}
}
// Session dates exist
} else {
// Convert earliest signed up users to booked, and make the rest waitlisted
$capacity = $session->capacity;
// Count number of booked users
$booked = 0;
foreach ($users as $user) {
if ($user->statuscode == MDL_F2F_STATUS_BOOKED) {
$booked++;
}
}
// If booked less than capacity, book some new users
if ($booked < $capacity) {
foreach ($users as $user) {
if ($booked >= $capacity) {
break;
}
if ($user->statuscode == MDL_F2F_STATUS_WAITLISTED) {
if (!facetoface_user_signup($session, $facetoface, $course, $user->discountcode, $user->notificationtype, MDL_F2F_STATUS_BOOKED, $user->id)) {
// rollback_sql();
return false;
}
$booked++;
}
}
}
}
}
return $session->id;
}
/**
* Return an array of all facetoface activities in the current course
*/
function facetoface_get_facetoface_menu() {
global $CFG, $DB;
if ($facetofaces = $DB->get_records_sql("SELECT f.id, c.shortname, f.name
FROM {course} c, {facetoface} f
WHERE c.id = f.course
ORDER BY c.shortname, f.name")) {
$i=1;
foreach ($facetofaces as $facetoface) {
$f = $facetoface->id;
$facetofacemenu[$f] = $facetoface->shortname.' --- '.$facetoface->name;
$i++;
}
return $facetofacemenu;
} else {
return '';
}
}
/**
* Delete entry from the facetoface_sessions table along with all
* related details in other tables
*
* @param object $session Record from facetoface_sessions
*/
function facetoface_delete_session($session) {
global $CFG, $DB;
$facetoface = $DB->get_record('facetoface', array('id' => $session->facetoface));
// Cancel user signups (and notify users)
$signedupusers = $DB->get_records_sql(
"
SELECT DISTINCT
userid
FROM
{facetoface_signups} s
LEFT JOIN
{facetoface_signups_status} ss
ON ss.signupid = s.id
WHERE
s.sessionid = ?
AND ss.superceded = 0
AND ss.statuscode >= ?
", array($session->id, MDL_F2F_STATUS_REQUESTED));
if ($signedupusers and count($signedupusers) > 0) {
foreach ($signedupusers as $user) {
if (facetoface_user_cancel($session, $user->userid, true)) {
facetoface_send_cancellation_notice($facetoface, $session, $user->userid);
}
else {
return false; // Cannot rollback since we notified users already
}
}
}
$transaction = $DB->start_delegated_transaction();
// Remove entries from the teacher calendars
$DB->delete_records_select('event', "modulename = 'facetoface' AND
eventtype = 'facetofacesession' AND
instance = ? AND description LIKE ?",
array($facetoface->id, "%attendees.php?s={$session->id}%"));
if ($facetoface->showoncalendar == F2F_CAL_COURSE) {
// Remove entry from course calendar
facetoface_remove_session_from_calendar($session, $facetoface->course);
} else if ($facetoface->showoncalendar == F2F_CAL_SITE) {
// Remove entry from site-wide calendar
facetoface_remove_session_from_calendar($session, SITEID);
}
// Delete session details
$DB->delete_records('facetoface_sessions', array('id' => $session->id));
$DB->delete_records('facetoface_sessions_dates', array('sessionid' => $session->id));
$DB->delete_records_select(
'facetoface_signups_status',
"signupid IN
(
SELECT
id
FROM
{facetoface_signups}
WHERE
sessionid = {$session->id}
)
");
$DB->delete_records('facetoface_signups', array('sessionid' => $session->id));
$transaction->allow_commit();
return true;
}
/**
* Subsitute the placeholders in email templates for the actual data
*
* Expects the following parameters in the $data object:
* - datetimeknown
* - details
* - discountcost
* - duration
* - normalcost
* - sessiondates
*
* @access public
* @param string $msg Email message
* @param string $facetofacename F2F name
* @param int $reminderperiod Num business days before event to send reminder
* @param obj $user The subject of the message
* @param obj $data Session data
* @param int $sessionid Session ID
* @return string
*/
function facetoface_email_substitutions($msg, $facetofacename, $reminderperiod, $user, $data, $sessionid) {
global $CFG, $DB;
if (empty($msg)) {
return '';
}
if ($data->datetimeknown) {
// Scheduled session
$sessiondate = userdate($data->sessiondates[0]->timestart, get_string('strftimedate'));
$starttime = userdate($data->sessiondates[0]->timestart, get_string('strftimetime'));
$finishtime = userdate($data->sessiondates[0]->timefinish, get_string('strftimetime'));
$alldates = '';
foreach ($data->sessiondates as $date) {
if ($alldates != '') {
$alldates .= "\n";
}
$alldates .= userdate($date->timestart, get_string('strftimedate')).', ';
$alldates .= userdate($date->timestart, get_string('strftimetime')).
' to '.userdate($date->timefinish, get_string('strftimetime'));
}
}
else {
// Wait-listed session
$sessiondate = get_string('unknowndate', 'facetoface');
$alldates = get_string('unknowndate', 'facetoface');
$starttime = get_string('unknowntime', 'facetoface');
$finishtime = get_string('unknowntime', 'facetoface');
}
$msg = str_replace(get_string('placeholder:facetofacename', 'facetoface'), $facetofacename, $msg);
$msg = str_replace(get_string('placeholder:firstname', 'facetoface'), $user->firstname, $msg);
$msg = str_replace(get_string('placeholder:lastname', 'facetoface'), $user->lastname, $msg);
$msg = str_replace(get_string('placeholder:cost', 'facetoface'), facetoface_cost($user->id, $sessionid, $data, false), $msg);
$msg = str_replace(get_string('placeholder:alldates', 'facetoface'), $alldates, $msg);
$msg = str_replace(get_string('placeholder:sessiondate', 'facetoface'), $sessiondate, $msg);
$msg = str_replace(get_string('placeholder:starttime', 'facetoface'), $starttime, $msg);
$msg = str_replace(get_string('placeholder:finishtime', 'facetoface'), $finishtime, $msg);
$msg = str_replace(get_string('placeholder:duration', 'facetoface'), format_duration($data->duration), $msg);
if (empty($data->details)) {
$msg = str_replace(get_string('placeholder:details', 'facetoface'), '', $msg);
}
else {
$msg = str_replace(get_string('placeholder:details', 'facetoface'), html_to_text($data->details), $msg);
}
$msg = str_replace(get_string('placeholder:reminderperiod', 'facetoface'), $reminderperiod, $msg);
// Replace more meta data
$msg = str_replace(get_string('placeholder:attendeeslink', 'facetoface'), $CFG->wwwroot.'/mod/facetoface/attendees.php?s='.$data->id, $msg);
// Custom session fields (they look like "session:shortname" in the templates)
$customfields = facetoface_get_session_customfields();
$customdata = $DB->get_records('facetoface_session_data', array('sessionid' => $data->id), '', 'fieldid, data');
foreach ($customfields as $field) {
$placeholder = "[session:{$field->shortname}]";
$value = '';
if (!empty($customdata[$field->id])) {
if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
$value = str_replace(CUSTOMFIELD_DELIMITER, ', ', $customdata[$field->id]->data);
} else {
$value = $customdata[$field->id]->data;
}
}
$msg = str_replace($placeholder, $value, $msg);
}
return $msg;
}
/**
* Function to be run periodically according to the moodle cron
* Finds all facetoface notifications that have yet to be mailed out, and mails them.
*/
function facetoface_cron() {
global $CFG, $USER,$DB;
$signupsdata = facetoface_get_unmailed_reminders();
if (!$signupsdata) {
echo "\n".get_string('noremindersneedtobesent', 'facetoface')."\n";
return true;
}
$timenow = time();
foreach ($signupsdata as $signupdata) {
if (facetoface_has_session_started($signupdata, $timenow)) {
// Too late, the session already started
// Mark the reminder as being sent already
$newsubmission = new stdClass();
$newsubmission->id = $signupdata->id;
$newsubmission->mailedreminder = 1; // magic number to show that it was not actually sent
if (!$DB->update_record('facetoface_signups', $newsubmission)) {
echo "ERROR: could not update mailedreminder for submission ID $signupdata->id";
}
continue;
}
$earlieststarttime = $signupdata->sessiondates[0]->timestart;
foreach ($signupdata->sessiondates as $date) {
if ($date->timestart < $earlieststarttime) {
$earlieststarttime = $date->timestart;
}
}
$reminderperiod = $signupdata->reminderperiod;
// Convert the period from business days (no weekends) to calendar days
for ($reminderday = 0; $reminderday < $reminderperiod + 1; $reminderday++ ) {
$reminderdaytime = $earlieststarttime - ($reminderday * 24 * 3600);
//use %w instead of %u for Windows compatability
$reminderdaycheck = userdate($reminderdaytime, '%w');
// note w runs from Sun=0 to Sat=6
if ($reminderdaycheck == 0 || $reminderdaycheck == 6) {
// Saturdays and Sundays are not included in the
// reminder period as entered by the user, extend
// that period by 1
$reminderperiod++;
}
}
$remindertime = $earlieststarttime - ($reminderperiod * 24 * 3600);
if ($timenow < $remindertime) {
// Too early to send reminder
continue;
}
if (!$user = $DB->get_record('user', array('id' => $signupdata->userid))) {
continue;
}
// Hack to make sure that the timezone and languages are set properly in emails
// (i.e. it uses the language and timezone of the recipient of the email)
$USER->lang = $user->lang;
$USER->timezone = $user->timezone;
if (!$course = $DB->get_record('course', array('id' => $signupdata->course))) {
continue;
}
if (!$facetoface = $DB->get_record('facetoface', array('id' => $signupdata->facetofaceid))) {
continue;
}
$postsubject = '';
$posttext = '';
$posttextmgrheading = '';
if (empty($signupdata->mailedreminder)) {
$postsubject = $facetoface->remindersubject;
$posttext = $facetoface->remindermessage;
$posttextmgrheading = $facetoface->reminderinstrmngr;
}
if (empty($posttext)) {
// The reminder message is not set, don't send anything
continue;
}
$postsubject = facetoface_email_substitutions($postsubject, $signupdata->facetofacename, $signupdata->reminderperiod,
$user, $signupdata, $signupdata->sessionid);
$posttext = facetoface_email_substitutions($posttext, $signupdata->facetofacename, $signupdata->reminderperiod,
$user, $signupdata, $signupdata->sessionid);
$posttextmgrheading = facetoface_email_substitutions($posttextmgrheading, $signupdata->facetofacename, $signupdata->reminderperiod,
$user, $signupdata, $signupdata->sessionid);
$posthtml = ''; // FIXME
if ($fromaddress = get_config(NULL, 'facetoface_fromaddress')) {
$from = new stdClass();
$from->maildisplay = true;
$from->email = $fromaddress;
} else {
$from = null;
}
if (email_to_user($user, $from, $postsubject, $posttext, $posthtml)) {
echo "\n".get_string('sentreminderuser', 'facetoface').": $user->firstname $user->lastname $user->email";
$newsubmission = new stdClass();
$newsubmission->id = $signupdata->id;
$newsubmission->mailedreminder = $timenow;
if (!$DB->update_record('facetoface_signups', $newsubmission)) {
echo "ERROR: could not update mailedreminder for submission ID $signupdata->id";
}
if (empty($posttextmgrheading)) {
continue; // no manager message set
}
$managertext = $posttextmgrheading.$posttext;
$manager = $user;
$manager->email = facetoface_get_manageremail($user->id);
if (empty($manager->email)) {
continue; // don't know who the manager is
}
// Send email to mamager
if (email_to_user($manager, $from, $postsubject, $managertext, $posthtml)) {
echo "\n".get_string('sentremindermanager', 'facetoface').": $user->firstname $user->lastname $manager->email";
}
else {
$errormsg = array();
$errormsg['submissionid'] = $signupdata->id;
$errormsg['userid'] = $user->id;
$errormsg['manageremail'] = $manager->email;
echo get_string('error:cronprefix', 'facetoface').' '.get_string('error:cannotemailmanager', 'facetoface', $errormsg)."\n";
}
}
else {
$errormsg = array();
$errormsg['submissionid'] = $signupdata->id;
$errormsg['userid'] = $user->id;
$errormsg['useremail'] = $user->email;
echo get_string('error:cronprefix', 'facetoface').' '.get_string('error:cannotemailuser', 'facetoface', $errormsg)."\n";
}
}
print "\n";
return true;
}
/**
* Returns true if the session has started, that is if one of the
* session dates is in the past.
*
* @param class $session record from the facetoface_sessions table
* @param integer $timenow current time
*/
function facetoface_has_session_started($session, $timenow) {
if (!$session->datetimeknown) {
return false; // no date set
}
foreach ($session->sessiondates as $date) {
if ($date->timestart < $timenow) {
return true;
}
}
return false;
}
/**
* Returns true if the session has started and has not yet finished.
*
* @param class $session record from the facetoface_sessions table
* @param integer $timenow current time
*/
function facetoface_is_session_in_progress($session, $timenow) {
if (!$session->datetimeknown) {
return false;