Proyectos de Subversion Moodle

Rev

Rev 1435 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1434 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * local_moofactory_notification plugin
19
 *
20
 * @package     local_moofactory_notification
21
 * @copyright   2020 Patrick ROCHET <patrick.r@lmsfactory.com>
22
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
use function PHPSTORM_META\type;
26
 
27
require_once("classes/info_moofactory_notification.php");
28
require_once($CFG->dirroot . '/course/format/moofactory/lib.php');
29
 
30
function test()
31
{
32
    $number = rand(1, 999);
33
    set_config('test', $number, 'local_moofactory_notification');
34
}
35
 
36
function local_moofactory_notification_extend_navigation_course($navigation, $course, $context)
37
{
38
    global $OUTPUT, $PAGE, $DB;
39
 
40
    if (has_capability('moodle/course:configurecustomfields', $context)) {
41
        // Actualisation de la valeur par défaut du champs notification des inscriptions aux cours en fonction de la valeur de définie au niveau du plugin
42
        $array = array();
43
        $record = $DB->get_record('local_mf_notification', array('id' => get_config('local_moofactory_notification', 'coursesenrollmentsnotification')));
44
        $notifdefaultvalue = $record->name;
45
        $id = $DB->get_field('customfield_field', 'id', array('shortname' => 'courseenrollmentsnotification'));
46
        if ($id) {
47
            $field = \core_customfield\field_controller::create($id);
48
            $handler = $field->get_handler();
49
            require_login();
50
            if (!$handler->can_configure()) {
51
                print_error('nopermissionconfigure', 'core_customfield');
52
            }
53
 
54
            $records = $DB->get_records('local_mf_notification', array('type' => 'courseenroll'), 'base DESC, name ASC');
55
            foreach ($records as $record) {
56
                $array[] = $record->name;
57
            }
58
            $options = implode("\n", $array);
59
 
60
            $data = new stdClass();
61
            $data->configdata = array("required" => "0", "uniquevalues" => "0", "options" => $options, "defaultvalue" => $notifdefaultvalue, "checkbydefault" => "0",  "locked" => "0",  "visibility" => "2");
62
 
63
            $handler->save_field_configuration($field, $data);
64
        }
65
 
66
        // Actualisation de la valeur par défaut du champs notification des inscriptions 2 aux cours en fonction de la valeur de définie au niveau du plugin
67
        $array = array();
68
        $id = $DB->get_field('customfield_field', 'id', array('shortname' => 'courseenrollmentsnotification2'));
69
        if ($id) {
70
            $field = \core_customfield\field_controller::create($id);
71
            $handler = $field->get_handler();
72
            require_login();
73
            if (!$handler->can_configure()) {
74
                print_error('nopermissionconfigure', 'core_customfield');
75
            }
76
 
77
            $records = $DB->get_records('local_mf_notification', array('type' => 'courseenroll'), 'base DESC, name ASC');
78
            foreach ($records as $record) {
79
                $array[] = $record->name;
80
            }
81
            $options = implode("\n", $array);
82
 
83
            $data = new stdClass();
84
            $data->configdata = array("required" => "0", "uniquevalues" => "0", "options" => $options, "defaultvalue" => $notifdefaultvalue, "checkbydefault" => "0",  "locked" => "0",  "visibility" => "2");
85
 
86
            $handler->save_field_configuration($field, $data);
87
        }
88
 
89
        // Actualisation de la valeur par défaut du champs notification non accès aux cours en fonction de la valeur de définie au niveau du plugin
90
        $array = array();
91
        $record = $DB->get_record('local_mf_notification', array('id' => get_config('local_moofactory_notification', 'coursesaccessnotification')));
92
        $notifdefaultvalue = $record->name;
93
        $id = $DB->get_field('customfield_field', 'id', array('shortname' => 'courseaccessnotification'));
94
        if ($id) {
95
            $field = \core_customfield\field_controller::create($id);
96
            $handler = $field->get_handler();
97
            require_login();
98
            if (!$handler->can_configure()) {
99
                print_error('nopermissionconfigure', 'core_customfield');
100
            }
101
 
102
            $records = $DB->get_records('local_mf_notification', array('type' => 'courseaccess'), 'base DESC, name ASC');
103
            foreach ($records as $record) {
104
                $array[] = $record->name;
105
            }
106
            $options = implode("\n", $array);
107
 
108
            $data = new stdClass();
109
            $data->configdata = array("required" => "0", "uniquevalues" => "0", "options" => $options, "defaultvalue" => $notifdefaultvalue, "checkbydefault" => "0",  "locked" => "0",  "visibility" => "2");
110
 
111
            $handler->save_field_configuration($field, $data);
112
        }
113
 
114
        // Actualisation de la valeur par défaut du champs notification des évènements de cours en fonction de la valeur de définie au niveau du plugin
115
        $array = array();
116
        $record = $DB->get_record('local_mf_notification', array('id' => get_config('local_moofactory_notification', 'courseseventsnotification')));
117
        $notifdefaultvalue = $record->name;
118
        $id = $DB->get_field('customfield_field', 'id', array('shortname' => 'courseeventsnotification'));
119
        if ($id) {
120
            $field = \core_customfield\field_controller::create($id);
121
            $handler = $field->get_handler();
122
            require_login();
123
            if (!$handler->can_configure()) {
124
                print_error('nopermissionconfigure', 'core_customfield');
125
            }
126
 
127
            $records = $DB->get_records('local_mf_notification', array('type' => 'courseevent'), 'base DESC, name ASC');
128
            foreach ($records as $record) {
129
                $array[] = $record->name;
130
            }
131
            $options = implode("\n", $array);
132
 
133
            $data = new stdClass();
134
            $data->configdata = array("required" => "0", "uniquevalues" => "0", "options" => $options, "defaultvalue" => $notifdefaultvalue, "checkbydefault" => "0",  "locked" => "0",  "visibility" => "2");
135
 
136
            $handler->save_field_configuration($field, $data);
137
        }
138
    }
139
 
140
    if (has_capability('local/moofactory_notification:setnotifications', $context)) {
141
        $path = $PAGE->url->get_path();
142
        $js = "";
143
        $enabled = get_config('local_moofactory_notification', 'enabled');
144
        $coursesenrollments = get_config('local_moofactory_notification', 'coursesenrollments');
145
        $coursesenrollmentstime = get_config('local_moofactory_notification', 'coursesenrollmentstime');
146
        $coursesaccess = get_config('local_moofactory_notification', 'coursesaccess');
147
        $coursesaccesstime = get_config('local_moofactory_notification', 'coursesaccesstime');
148
        $coursesevents = get_config('local_moofactory_notification', 'coursesevents');
149
 
150
        if ($path == "/course/edit.php") {
151
            $courseid = $PAGE->url->get_param("id");
152
            $courseenrollmentstime = local_moofactory_notification_getCustomfield($courseid, 'courseenrollmentstime', 'text');
153
            $courseaccesstime = local_moofactory_notification_getCustomfield($courseid, 'courseaccesstime', 'text');
154
 
155
            $js .= "$('<hr>').insertBefore($('#id_customfield_courseaccess').closest('.fitem'));";
156
            $js .= "$('<hr>').insertBefore($('#id_customfield_courseevents').closest('.fitem'));";
157
 
158
            $js .= "$('#id_customfield_courseenrollmentsnotification option[value=\"0\"]').remove();";
159
            $js .= "$('#id_customfield_courseaccessnotification option[value=\"0\"]').remove();";
160
            $js .= "$('#id_customfield_courseeventsnotification option[value=\"0\"]').remove();";
161
            $configvars = ['daysbeforeevents1', 'hoursbeforeevents1', 'daysbeforeevents2', 'hoursbeforeevents2', 'daysbeforeevents3', 'hoursbeforeevents3'];
162
            if (!$enabled) {
163
                $js .= "$('#id_customfield_courseenrollments').attr('disabled', 'disabled');";
164
                $js .= "$('#id_customfield_courseenrollmentstime').attr('disabled', 'disabled');";
165
                $js .= "$('#id_customfield_courseenrollmentsnotification').attr('disabled', 'disabled');";
166
                $js .= "$('#id_customfield_courseaccess').attr('disabled', 'disabled');";
167
                $js .= "$('#id_customfield_courseaccesstime').attr('disabled', 'disabled');";
168
                $js .= "$('#id_customfield_courseaccessnotification').attr('disabled', 'disabled');";
169
                $js .= "$('#id_customfield_courseevents').attr('disabled', 'disabled');";
170
                $js .= "$('#id_customfield_courseeventscheckavailability').attr('disabled', 'disabled');";
171
                $js .= "$('#id_customfield_courseeventscheckdateavailability').attr('disabled', 'disabled');";
172
                $js .= "$('#id_customfield_courseeventscheckgroupavailability').attr('disabled', 'disabled');";
173
                $js .= "$('#id_customfield_courseeventsnotification').attr('disabled', 'disabled');";
174
                foreach ($configvars as $configvar) {
175
                    $name = 'id_customfield_' . $configvar;
176
                    $js .= "$('#$name').attr('disabled', 'disabled');";
177
                }
178
            } else {
179
                if (!$coursesenrollments) {
180
                    $js .= "$('#id_customfield_courseenrollments').attr('disabled', 'disabled');";
181
                    $js .= "$('#id_customfield_courseenrollmentstime').attr('disabled', 'disabled');";
182
                    $js .= "$('#id_customfield_courseenrollmentsnotification').attr('disabled', 'disabled');";
183
                }
184
                if (!$coursesaccess) {
185
                    $js .= "$('#id_customfield_courseaccess').attr('disabled', 'disabled');";
186
                    $js .= "$('#id_customfield_courseaccesstime').attr('disabled', 'disabled');";
187
                    $js .= "$('#id_customfield_courseaccessnotification').attr('disabled', 'disabled');";
188
                }
189
                if (!$coursesevents) {
190
                    $js .= "$('#id_customfield_courseevents').attr('disabled', 'disabled');";
191
                    $js .= "$('#id_customfield_courseeventscheckavailability').attr('disabled', 'disabled');";
192
                    $js .= "$('#id_customfield_courseeventscheckdateavailability').attr('disabled', 'disabled');";
193
                    $js .= "$('#id_customfield_courseeventscheckgroupavailability').attr('disabled', 'disabled');";
194
                    $js .= "$('#id_customfield_courseeventsnotification').attr('disabled', 'disabled');";
195
                    foreach ($configvars as $configvar) {
196
                        $name = 'id_customfield_' . $configvar;
197
                        $js .= "$('#$name').attr('disabled', 'disabled');";
198
                    }
199
                }
200
            }
201
            if (is_null($courseenrollmentstime)) {
202
                $js .= "$('#id_customfield_courseenrollmentstime').val($coursesenrollmentstime);";
203
            }
204
            if (is_null($courseaccesstime)) {
205
                $js .= "$('#id_customfield_courseaccesstime').val($coursesaccesstime);";
206
            }
207
 
208
            $configvars[] = 'courseenrollmentstime';
209
            foreach ($configvars as $configvar) {
210
                $name = 'id_customfield_' . $configvar;
211
                $msg = get_string('notanumber', 'local_moofactory_notification');
212
                $js .= "$('#$name').blur(function(){";
213
                $js .= "    if(isNaN($('#$name').val()) || parseInt($('#$name').val()) < 0){";
214
                $js .= "        $('#id_saveanddisplay').attr('disabled', 'disabled');";
215
                $js .= "        $('#$name').addClass('is-invalid');";
216
                $js .= "        $('#id_error_customfield_$configvar').html('$msg');";
217
                $js .= "    }";
218
                $js .= "    else{";
219
                $js .= "        $('#$name').removeClass('is-invalid');";
220
                $js .= "        $('#id_error_customfield_$configvar').html('');";
221
                $js .= "        ret = checkValues();";
222
                $js .= "        if(ret){";
223
                $js .= "            $('#id_saveanddisplay').removeAttr('disabled');";
224
                $js .= "        }";
225
                $js .= "    }";
226
                $js .= "});";
227
            }
228
 
229
            $configvar = 'courseaccesstime';
230
            $name = 'id_customfield_' . $configvar;
231
            $msg = get_string('notanullnumber', 'local_moofactory_notification');
232
            $js .= "$('#$name').blur(function(){";
233
            $js .= "    if(isNaN($('#$name').val()) || Number($('#$name').val()) <= 0){";
234
            $js .= "        $('#id_saveanddisplay').attr('disabled', 'disabled');";
235
            $js .= "        $('#$name').addClass('is-invalid');";
236
            $js .= "        $('#id_error_customfield_$configvar').html('$msg');";
237
            $js .= "    }";
238
            $js .= "    else{";
239
            $js .= "        $('#$name').removeClass('is-invalid');";
240
            $js .= "        $('#id_error_customfield_$configvar').html('');";
241
            $js .= "        ret = checkValues();";
242
            $js .= "        if(ret){";
243
            $js .= "            $('#id_saveanddisplay').removeAttr('disabled');";
244
            $js .= "        }";
245
            $js .= "    }";
246
            $js .= "});";
247
 
248
            $js .= "function checkValues(){";
249
            $js .= "    var configvars = ['courseenrollmentstime', 'courseaccesstime', 'daysbeforeevents1', 'hoursbeforeevents1', 'daysbeforeevents2', 'hoursbeforeevents2', 'daysbeforeevents3', 'hoursbeforeevents3'];";
250
            $js .= "    var ret = true;";
251
            $js .= "    for(i=0;i<configvars.length;i++){";
252
            $js .= "        if(isNaN($('#id_customfield_'+configvars[i]).val())){";
253
            $js .= "            ret &= false;";
254
            $js .= "        }";
255
            $js .= "    }";
256
            $js .= "    return ret;";
257
            $js .= "}";
258
 
259
            $js .= "initCheckAvailability($('#id_customfield_courseeventscheckavailability').is(':checked'));";
260
        }
261
 
262
        // Ajout de l'item "Activation des notifications" dans le menu "Modifier"" des activités.
263
        if ($path == "/course/view.php") {
264
            if ($enabled && $coursesevents) {
265
                $courseid = $PAGE->url->get_param("id");
266
                $activities = local_moofactory_notification_get_all_activities($courseid);
267
                $courseevents = local_moofactory_notification_getCustomfield($courseid, 'courseevents', 'checkbox');
268
 
269
                // Affichage d'un picto pour indiquer que les notification sont activées.
270
                foreach ($activities as $activity) {
271
                    $moduleid = $activity["id"];
272
                    $moduleevents = get_config('local_moofactory_notification', 'moduleevents_' . $courseid . '_' . $moduleid . '');
273
                    $modulelevee = get_config('local_moofactory_notification', 'modulelevee_' . $courseid . '_' . $moduleid . '');
274
                    if (!empty($moduleevents) || !empty($modulelevee)) {
275
                        $js .= "$(\"[data-owner='#module-" . $moduleid . "']  .dropdown a.dropdown-toggle[data-toggle='dropdown']\").prepend('<span class=\"icon fa fa-envelope-o fa-fw\"></span>');";
276
                    }
277
                }
278
 
279
                if (empty($courseevents) && $coursesevents) {
280
                    $menuitem = '<a class="dropdown-item editing_mfnotification menu-action cm-edit-action"';
281
                    $menuitem .= ' data-action="mfnotification" role="menuitem"';
282
                    $menuitem .= ' href="' . new moodle_url('/local/moofactory_notification/module.php', array('courseid' => $courseid, 'id' => 'moduleid')) . '"';
283
                    $menuitem .= ' title="' . get_string('menuitem', 'local_moofactory_notification') . '">';
284
                    $menuitem .= $OUTPUT->pix_icon('t/email', get_string('menuitem', 'local_moofactory_notification'));
285
                    $menuitem .= '<span class="menu-action-text">' . get_string('menuitem', 'local_moofactory_notification') . '</span>';
286
                    $menuitem .= '</a>';
287
 
288
                    $js .= "gmenuitem = '$menuitem';";
289
                    $js .= "$('.activity .activity-actions .dropdown-menu.dropdown-menu-right').each(function(index, element ){";
290
                    $js .= "    $(element).parents().each(function(index, element){";
291
                    $js .= "        if($(element).attr('data-owner') != undefined){";
292
                    $js .= "            owner = $(element).attr('data-owner');";
293
                    $js .= "            owner = owner.replace('#module-', '');";
294
                    $js .= "            menuitem = gmenuitem.replace('moduleid', owner);";
295
                    $js .= "        }";
296
                    $js .= "    });";
297
                    $js .= "    $(element).append(menuitem);";
298
                    $js .= "});";
299
                }
300
            }
301
        }
302
        $PAGE->requires->jquery();
303
        $PAGE->requires->js('/local/moofactory_notification/util.js');
304
        $PAGE->requires->js_init_code($js, true);
305
    }
306
}
307
 
308
// Events callback
309
function local_moofactory_notification_user_enrolment_created($event): bool
310
{
311
    global $DB;
312
 
313
    if (!empty($event)) {
314
        $courseid = $event->courseid;
315
        $userid = $event->relateduserid;
316
    } else {
317
        $courseid = get_config('local_moofactory_notification', 'enrollcourseid');
318
        $userid = get_config('local_moofactory_notification', 'enrolluserid');
319
    }
320
    $user = $DB->get_record('user', array('id' => $userid));
321
 
322
    // Le user a-t-il un statut actif ?
323
    $context = context_course::instance($courseid, IGNORE_MISSING);
324
 
325
    $is_enrolled = is_enrolled($context, $userid, '', true);
326
 
327
    if (!$is_enrolled) {
328
        // Sinon, mise en liste d'attente dans la table 'local_mf_enrollnotif'
329
        $notificationtime = 0;
330
        $record = new stdclass();
331
        $record->userid = $userid;
332
        $record->courseid = $courseid;
333
        $record->notificationtime = $notificationtime + time();
334
 
335
        $id = $DB->insert_record('local_mf_enrollnotif', $record);
336
        return false;
337
    }
338
 
339
    // Activation des notifications
340
    $enabled = get_config('local_moofactory_notification', 'enabled');
341
    // Activation des inscriptions aux cours
342
    $coursesenrollments = get_config('local_moofactory_notification', 'coursesenrollments');
343
 
344
    // si les notifications sont activées
345
    if (!empty($enabled)) {
346
        // si les notifications d'inscriptions aux cours sont activées
347
        if (!empty($coursesenrollments)) {
348
            $courseenrollments = local_moofactory_notification_getCustomfield($courseid, 'courseenrollments', 'checkbox');
349
            // si les notifications d'inscriptions au cours courant sont activées
350
            if (!empty($courseenrollments)) {
351
                $courseenrollmentstime = local_moofactory_notification_getCustomfield($courseid, 'courseenrollmentstime', 'text');
352
 
353
                $notificationtime = empty($courseenrollmentstime) ? 10 : $courseenrollmentstime * 60;
354
                $record = new stdclass();
355
                $record->userid = $userid;
356
                $record->courseid = $courseid;
357
                $record->notificationtime = $notificationtime + time();
358
 
359
                $id = $DB->insert_record('local_mf_enrollnotif', $record);
360
            }
361
        }
362
    }
363
    return true;
364
}
365
 
366
function local_moofactory_notification_user_enrolment_updated($event): bool
367
{
368
    global $DB;
369
 
370
    $courseid = $event->courseid;
371
    $userid = $event->relateduserid;
372
 
373
    $coursecontext = \context_course::instance($courseid);
374
    $is_enrolled = is_enrolled($coursecontext, $userid, 'moodle/course:isincompletionreports', true);
375
    if (empty($is_enrolled)) {
376
        // L'inscription de l'utilisateur n'est plus active...
377
        // Il faut supprimer la ligne correspondante dans la table local_mf_accessnotif et local_mf_modaccessnotif
378
        $DB->delete_records('local_mf_accessnotif', array('userid' => $userid, 'courseid' => $courseid));
379
        delete_mf_modaccessnotif_records($courseid, $userid);
380
    }
381
    return true;
382
}
383
function local_moofactory_notification_user_enrolment_deleted($event): bool
384
{
385
    global $DB;
386
 
387
    $courseid = $event->courseid;
388
    $userid = $event->relateduserid;
389
 
390
    // L'utilisateur désinscrit n'est plus dans le cours...
391
    // Il faut supprimer la ligne correspondante dans la table local_mf_accessnotif, local_mf_modaccessnotif et local_mf_enrollnotif
392
    $DB->delete_records('local_mf_accessnotif', array('userid' => $userid, 'courseid' => $courseid));
393
    $DB->delete_records('local_mf_enrollnotif', array('userid' => $userid, 'courseid' => $courseid));
394
    delete_mf_modaccessnotif_records($courseid, $userid);
395
 
396
    return true;
397
}
398
 
399
function delete_mf_modaccessnotif_records($courseid, $userid)
400
{
401
    global $DB;
402
    // Récupérer les moduleid du cours
403
    $sql = "SELECT cm.id
404
        FROM {course_modules} cm
405
        JOIN {modules} m ON cm.module = m.id
406
        WHERE cm.course = :courseid";
407
    $moduleids = $DB->get_fieldset_sql($sql, array('courseid' => $courseid));
408
 
409
    if (!empty($moduleids)) {
410
        list($insql, $params) = $DB->get_in_or_equal($moduleids, SQL_PARAMS_NAMED);
411
        $params['userid'] = $userid;
412
 
413
        // Suppression des enregistrements dans local_mf_modaccessnotif pour les modules du cours
414
        $DB->delete_records_select('local_mf_modaccessnotif', "userid = :userid AND moduleid $insql", $params);
415
    }
416
}
417
 
418
function local_moofactory_notification_course_viewed($event): bool
419
{
420
    global $DB;
421
 
422
    $courseid = $event->courseid;
423
    $userid = $event->userid;
424
 
425
    // Il faut supprimer la ligne correspondante dans la table local_mf_accessnotif pour réinitialiser l'envoi des notif
426
    $DB->delete_records('local_mf_accessnotif', array('userid' => $userid, 'courseid' => $courseid));
427
    return true;
428
}
429
 
430
function local_moofactory_notification_course_updated($event): bool
431
{
432
    global $DB;
433
 
434
    $courseid = $event->courseid;
435
 
436
    // Activation des non accès à ce cours
437
    $courseaccess = local_moofactory_notification_getCustomfield($courseid, 'courseaccess', 'checkbox');
438
 
439
    if (empty($courseaccess)) {
440
        // Plus d'envoi de notifications pour ce cours
441
        // Il faut supprimer les lignes correspondantes dans la table local_mf_accessnotif
442
        $DB->delete_records('local_mf_accessnotif', array('courseid' => $courseid));
443
    }
444
    return true;
445
}
446
function local_moofactory_notification_module_deleted($event)
447
{
448
    global $DB;
449
 
450
    $moduleid = $event->objectid;
451
 
452
    // Supprimez les données de notifs local_mf_modaccessnotif liées au module supprimé
453
    $DB->delete_records('local_mf_modaccessnotif', array('moduleid' => $moduleid));
454
 
455
    return true;
456
}
457
 
458
// Evènements de type site
459
function local_moofactory_notification_send_siteevents_notification()
460
{
461
    global $CFG, $DB, $SITE;
462
 
463
    require_once($CFG->dirroot . '/calendar/lib.php');
464
 
465
    // Nombre de notifications envoyées
466
    $nbnotif = 0;
467
    // Activation des notifications
468
    $enabled = get_config('local_moofactory_notification', 'enabled');
469
    // Activation évènements de type cours
470
    $siteevents = get_config('local_moofactory_notification', 'siteevents');
471
    // Tableau des notification de type courseevent
472
    $siteeventsnotifications = $DB->get_records('local_mf_notification', array('type' => 'siteevent'), 'base DESC, name ASC');
473
 
474
    // Maintenant
475
    $time = time();
476
 
477
    // La dernière fois que la tâche s'est exécutée
478
    $previoussiteeventstasktime = get_config('local_moofactory_notification', 'previoussiteeventstasktime');
479
    if (empty($previoussiteeventstasktime)) {
480
        set_config('previoussiteeventstasktime', $time, 'local_moofactory_notification');
481
        return;
482
    } else {
483
        set_config('previoussiteeventstasktime', $time, 'local_moofactory_notification');
484
    }
485
 
486
 
487
    // Si les notifications sont activées
488
    if (!empty($enabled)) {
489
        // Si les évènements de type site sont activées
490
        if (!empty($siteevents)) {
491
            // Délai pour l'envoi des notifications
492
            $daysvalue = get_config('local_moofactory_notification', 'daysbeforesiteevent');
493
            $hoursvalue = get_config('local_moofactory_notification', 'hoursbeforesiteevent');
494
            $delay = (int)$daysvalue * 60 * 60 * 24 + (int)$hoursvalue * 60 * 60;
495
            if (!empty($delay)) {
496
                // Tous les évènements à venir
497
                $events = calendar_get_legacy_events($previoussiteeventstasktime + $delay, $time + $delay, false, false, true, true, false);
498
 
499
                foreach ($events as $event) {
500
                    if ($event->eventtype == "site") {
501
                        //$targetedevents = calendar_get_legacy_events($previoussiteeventstasktime + $delay, $time + $delay, false, false, true, true, false);
502
                        //foreach($targetedevents as $targetedevent) {
503
                        //if($targetedevent->id == $event->id){
504
 
505
                        // Vérifier si la notification a déjà été envoyée pour cet événement
506
                        $existingNotification = $DB->get_record('local_mf_event_notifications', array('eventid' => $event->id, 'notified' => 1));
507
                        if (!$existingNotification) {
508
                            // message
509
                            $notifvalue = get_config('local_moofactory_notification', 'siteeventsnotification');
510
                            $notif = $siteeventsnotifications[$notifvalue];
511
                            $bodyhtml = urldecode($notif->bodyhtml);
512
 
513
                            $variables = local_moofactory_notification_fetch_variables($bodyhtml);
514
 
515
                            $users = get_users_listing('id');
516
                            //$users = [$DB->get_record('user', array('id' => 84))];
517
 
518
                            if (!empty($notif)) {
519
                                foreach ($users as $user) {
520
                                    if (!is_siteadmin($user)) {
521
                                        if (!$user->suspended) {
522
                                            $data = new stdClass();
523
                                            $data->firstname = $user->firstname;
524
                                            $data->lastname = $user->lastname;
525
                                            $data->username = $user->username;
526
                                            $data->usergroup = "";
527
                                            $data->eventdate = date("d/m/Y à H:i", $event->timestart);
528
                                            $data->eventname = $event->name;
529
                                            $data->coursename = "";
530
                                            $data->coursestartdate = "";
531
                                            $data->courseenddate = "";
532
                                            $data->courseenrolstartdate = "";
533
                                            $data->courseenrolenddate = "";
534
                                            $data->courseurl = "";
535
                                            $data->activityname = "";
536
                                            $data->lmsurl = $CFG->wwwroot;
537
                                            $data->lmsname = $SITE->fullname;
538
                                            $data->interval = "";
539
 
540
                                            $msgbodyhtml = local_moofactory_notification_replace_variables($variables, $bodyhtml, $data);
541
 
542
                                            $msg = new stdClass();
543
                                            $msg->subject = $notif->subject;
544
                                            $msg->from = "moofactory";
545
                                            $msg->bodytext = "";
546
                                            $msg->bodyhtml = $msgbodyhtml;
547
 
548
                                            $ret = local_moofactory_notification_send_email($user, $msg, $courseid, 'siteevents_notification');
549
 
550
                                            $dateEnvoi = date("d/m/Y H:i:s", time());
551
                                            mtrace("\n" . 'Envoyé le : ' . $dateEnvoi . ' à ' . $data->firstname . ' ' . $data->lastname . ' (Evènement le ' . $data->eventdate . ")");
552
                                            mtrace('Objet du mail : ' . $msg->subject);
553
                                            $nbnotif++;
554
 
555
                                            // Marquer l'événement comme notifié
556
                                            $notification = new stdClass();
557
                                            $notification->eventid = $event->id;
558
                                            $notification->notificationtime = time();
559
                                            $notification->notified = 1;
560
                                            $DB->insert_record('local_mf_event_notifications', $notification);
561
                                        }
562
                                    }
563
                                }
564
                            } else {
565
                                mtrace("Pas d'envoi : la notification est inexistante.");
566
                            }
567
                            //}
568
                            //}
569
                        }
570
                    }
571
                }
572
            }
573
        }
574
    }
575
    mtrace("\n" . $nbnotif . ' notification(s) envoyée(s).' . "\n");
576
}
577
 
578
// Inscriptions aux cours
579
function local_moofactory_notification_send_coursesenroll_notification()
580
{
581
    global $DB;
582
 
583
    // Nombre de notifications envoyées
584
    $nbnotif = 0;
585
    // Maintenant
586
    $time = time();
587
 
588
    // La dernière fois que la tâche s'est exécutée
589
    $previouscourseenrolltasktime = get_config('local_moofactory_notification', 'previouscourseenrolltasktime');
590
    if (empty($previouscourseenrolltasktime)) {
591
        set_config('previouscourseenrolltasktime', $time, 'local_moofactory_notification');
592
        return;
593
    } else {
594
        set_config('previouscourseenrolltasktime', $time, 'local_moofactory_notification');
595
    }
596
 
597
    $sql = "SELECT * FROM {local_mf_enrollnotif} ";
598
    $sql .= "WHERE notificationtime > ? AND notificationtime <= ?";
599
    $records = $DB->get_records_sql(
600
        $sql,
601
        array($previouscourseenrolltasktime, $time)
602
    );
603
 
604
    if (!empty($records)) {
605
        foreach ($records as $record) {
606
            $courseid = $record->courseid;
607
            $userid = $record->userid;
608
 
609
            // Vérification de la visibilité du cours
610
            $course = $DB->get_record('course', array('id' => $courseid), 'id, visible');
611
            if (!$course || $course->visible == 0) {
612
                // Si le cours n'existe pas ou est masqué, ignorer
613
                continue;
614
            }
615
 
616
            $enrolled = is_enrolled(context_course::instance($courseid), $userid);
617
            $active = is_enrolled(context_course::instance($courseid), $userid, '', true);
618
 
619
            // Si le user courant est bien inscrit au cours correspondant
620
            if ($enrolled) {
621
 
622
                // S'il est actif
623
                if ($active) {
624
                    $context = context_course::instance($courseid);
625
                    if (has_capability('local/moofactory_notification:coursesenrollments', $context, $userid)) {
626
                        $user = $DB->get_record('user', array('id' => $userid));
627
                        // Activation des notifications
628
                        $enabled = get_config('local_moofactory_notification', 'enabled');
629
                        // Activation des inscriptions aux cours
630
                        $coursesenrollments = get_config('local_moofactory_notification', 'coursesenrollments');
631
                        // Tableau des notification de type courseenroll
632
                        $courseenrollmentsnotifications = $DB->get_records('local_mf_notification', array('type' => 'courseenroll'), 'base DESC, name ASC');
633
 
634
                        // Si les notifications sont activées
635
                        if (!empty($enabled)) {
636
                            // si les notifications d'inscriptions aux cours sont activées
637
                            if (!empty($coursesenrollments)) {
638
                                $courseenrollments = local_moofactory_notification_getCustomfield($courseid, 'courseenrollments', 'checkbox');
639
                                // si les notifications d'inscriptions au cours courant sont activées
640
                                if (!empty($courseenrollments)) {
641
                                    // message
642
                                    local_moofactory_notification_prepare_enrollments_email($user, $courseid, $courseenrollmentsnotifications);
643
                                    $nbnotif++;
644
                                }
645
                            }
646
                        }
647
                    }
648
                    // Suppression de la ligne correspondant à l'envoi ou non(cas si le user n'a pas la capacité à recevoir) qui vient d'être effectué dans la table 'local_mf_enrollnotif'
649
                    $DB->delete_records('local_mf_enrollnotif', array('userid' => $userid, 'courseid' => $courseid, 'notificationtime' => $record->notificationtime));
650
                }
651
                // Update de notificationtime dans la table 'local_mf_enrollnotif' avec l'heure courante
652
                else {
653
                    $data = new stdclass();
654
                    $data->id = $record->id;
655
                    $data->notificationtime = $time + 1;
656
                    $res = $DB->update_record('local_mf_enrollnotif', $data);
657
                }
658
            }
659
        }
660
    }
661
    mtrace("\n" . $nbnotif . ' notification(s) envoyée(s).' . "\n");
662
}
663
 
664
// Non accès aux cours
665
function local_moofactory_notification_send_coursesaccess_notification()
666
{
667
    global $DB;
668
 
669
    // Nombre de notifications envoyées
670
    $nbnotif = 0;
671
    // Activation des notifications
672
    $enabled = get_config('local_moofactory_notification', 'enabled');
673
    // Activation des non accès aux cours
674
    $coursesaccess = get_config('local_moofactory_notification', 'coursesaccess');
675
    // Tableau des notification de type courseaccess
676
    $courseaccessnotifications = $DB->get_records('local_mf_notification', array('type' => 'courseaccess'), 'base DESC, name ASC');
677
    // Nombre max de notifications à envoyer entre deux accès
678
    $coursesaccessnotifnumber = get_config('local_moofactory_notification', 'coursesaccessnotifnumber');
679
    // Valeur par défaut
680
    $coursesaccessnotifdefaultnumber = get_config('local_moofactory_notification', 'coursesaccessnotifdefaultnumber');
681
    if (empty($coursesaccessnotifnumber)) {
682
        // Si 0, on force la valeur par défaut
683
        set_config('coursesaccessnotifnumber', $coursesaccessnotifdefaultnumber, 'local_moofactory_notification'); // Valeur par défaut
684
        $coursesaccessnotifnumber = $coursesaccessnotifdefaultnumber;
685
    }
686
 
687
    // Maintenant
688
    $time = time();
689
 
690
    // Si l'envoi des notifications est désactivé au niveau plugin, on vide la table local_mf_accessnotif
691
    if (empty($enabled) || empty($coursesaccess)) {
692
        $DB->delete_records('local_mf_accessnotif');
693
    }
694
 
695
    // si les notifications sont activées
696
    if (!empty($enabled)) {
697
        // si les notifications des non accès aux cours sont activées
698
        if (!empty($coursesaccess)) {
699
            // Recherche de tous les cours visibles dont la date de début est antérieure à la date courante
700
            // et la date de fin est inactive ou postérieure à la date courante.
701
            $sql = "SELECT id, fullname FROM {course} WHERE id <> 1 AND (startdate <= ?) AND (enddate = 0 OR enddate > ?) AND visible = 1";
702
            $params = array($time, $time);
703
            $courses = $DB->get_records_sql($sql, $params);
704
 
705
            foreach ($courses as $course) {
706
                $courseid = $course->id;
707
                $courseaccess = local_moofactory_notification_getCustomfield($courseid, 'courseaccess', 'checkbox');
708
                // si les notifications des non accès au cours courant sont activées
709
                if (!empty($courseaccess)) {
710
                    $coursecontext = \context_course::instance($courseid);
711
                    // 'moodle/course:isincompletionreports' - this capability is allowed to only students
712
                    // Seulement les inscriptions actives
713
                    $enrolledusers = get_enrolled_users($coursecontext, 'moodle/course:isincompletionreports', 0, 'u.*', null, 0, 0, true);
714
 
715
                    foreach ($enrolledusers as $user) {
716
                        if (!is_siteadmin($user)) {
717
                            $userid = $user->id;
718
 
719
                            // Vérification de la capacité avant de continuer.
720
                            if (!has_capability('local/moofactory_notification:coursesaccess', $coursecontext, $userid)) {
721
                                mtrace("Utilisateur {$userid} ignoré : capacité 'local/moofactory_notification:coursesaccess' non satisfaite.");
722
                                continue;
723
                            }
724
 
725
                            $progress = local_moofactory_notification_get_progress($courseid, $userid);
726
                            $completion = new completion_info($course);
727
                            $is_complete = $completion->is_course_complete($userid);
728
 
729
                            // On envoie un notification uniquement si le cours n'est pas achevé
730
                            if ($progress < 100 && !$is_complete) {
731
                                // Calcul de l'intervalle
732
                                $courseaccesstime = local_moofactory_notification_getCustomfield($courseid, 'courseaccesstime', 'text');
733
                                $interval = (int)$courseaccesstime * 60 * 60 * 24; // jours
734
                                // $interval = (int)$courseaccesstime * 60 * 60; // heures pour tests
735
                                // $interval = (int)$courseaccesstime * 60; // minutes pour tests
736
 
737
                                // On envoie une notification si le délai de non accès a été atteint depuis la dernière fois que la tâche s'est exécutée
738
 
739
                                // On regarde si une notif a déja été envoyée et depuis combien de temps
740
                                $recordaccessnotif = $DB->get_record('local_mf_accessnotif', array('userid' => $userid, 'courseid' => $courseid), 'id, notificationtime, notificationnumber');
741
 
742
                                if (!empty($recordaccessnotif)) {
743
                                    $notificationtime = $recordaccessnotif->notificationtime;
744
                                    $idaccessnotif = $recordaccessnotif->id;
745
                                    $notificationnumber = $recordaccessnotif->notificationnumber;
746
 
747
                                    if ($notificationtime + $interval <= $time) {
748
                                        // Est-ce qu'on est en dessous du nombre max de notif à envoyer ?
749
                                        if ($notificationnumber < $coursesaccessnotifnumber) {
750
                                            // update de local_mf_accessnotif
751
                                            $data = new stdclass();
752
                                            $data->userid = $userid;
753
                                            $data->courseid = $courseid;
754
                                            // Offset d'une minute pour rattraper le décalage entre l'heure de l'exécution théorique de la tâche et l'heure réelle
755
                                            $data->notificationtime = $time - 60;
756
                                            $data->id = $idaccessnotif;
757
                                            $data->notificationnumber = $notificationnumber + 1;
758
                                            $res = $DB->update_record('local_mf_accessnotif', $data);
759
 
760
                                            // Envoi de la notification
761
                                            local_moofactory_notification_prepare_access_email($user, $courseid, $courseaccesstime, $courseaccessnotifications);
762
                                            $nbnotif++;
763
                                        }
764
                                    }
765
                                }
766
 
767
                                // Si aucune notif n'a été envoyée, on regarde depuis combien de temps il n'y a pas eu d'accès
768
                                else {
769
                                    $recordlastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $userid, 'courseid' => $courseid), IGNORE_MISSING);
770
                                    // SI le user est déja allé sur le cours, on récupère la date de son dernier accès
771
                                    if (!empty($recordlastaccess)) {
772
                                        $lastaccesstime = $recordlastaccess;
773
                                    }
774
                                    // Sinon on récupère la date de son inscription la plus ancienne
775
                                    else {
776
                                        $enrolments = local_moofactory_notification_get_user_enrolments($courseid, $userid);
777
                                        $times = array();
778
                                        foreach ($enrolments as $enrolment) {
779
                                            $times[] = !empty($enrolment->timestart) ? $enrolment->timestart : $enrolment->timecreated;
780
                                        }
781
                                        $timestart = min($times);
782
                                        $lastaccesstime = $timestart;
783
                                    }
784
 
785
                                    if ($lastaccesstime + $interval <= $time) {
786
                                        // Insert dans la table accessnotif de la ligne correspondant au cours et au user
787
                                        $record = new stdclass();
788
                                        $record->userid = $userid;
789
                                        $record->courseid = $courseid;
790
                                        // Offset d'une minute pour rattraper le décalage entre l'heure de l'exécution théorique de la tâche et l'heure réelle
791
                                        $record->notificationtime = $time - 60;
792
                                        $record->notificationnumber = 1;
793
                                        $DB->insert_record('local_mf_accessnotif', $record);
794
 
795
                                        // Envoi de la notification
796
                                        local_moofactory_notification_prepare_access_email($user, $courseid, $courseaccesstime, $courseaccessnotifications);
797
                                        $nbnotif++;
798
                                    }
799
                                }
800
                            }
801
                        }
802
                    }
803
                }
804
            }
805
        }
806
    }
807
    mtrace("\n" . $nbnotif . ' notification(s) envoyée(s).' . "\n");
808
}
809
 
810
function local_moofactory_notification_get_progress($courseid, $userid)
811
{
812
    global $DB;
813
 
814
    $params = array('id' => $courseid);
815
    $course = $DB->get_record('course', $params, '*', MUST_EXIST);
816
 
817
    $activities = local_moofactory_notification_get_activities($courseid);
818
    $exclusions = local_moofactory_notification_exclusions($courseid);
819
    $useractivities = local_moofactory_notification_filter_visibility($activities, $userid, $courseid, $exclusions);
820
    if (!empty($useractivities)) {
821
        $completions = local_moofactory_notification_completions($useractivities, $userid, $course, null);
822
        $progressvalue = local_moofactory_notification_percentage($useractivities, $completions, $course, $userid);
823
    } else {
824
        $progressvalue = 0;
825
    }
826
    return $progressvalue;
827
}
828
 
829
/**
830
 * Returns the activities with completion set in current course
831
 *
832
 * @param int    courseid   ID of the course
833
 * @param int    config     The block instance configuration
834
 * @param string forceorder An override for the course order setting
835
 * @return array Activities with completion settings in the course
836
 */
837
function local_moofactory_notification_get_activities($courseid, $config = null, $forceorder = null)
838
{
839
    $modinfo = get_fast_modinfo($courseid, -1);
840
 
841
    $sections = $modinfo->get_sections();
842
    $activities = array();
843
    foreach ($modinfo->instances as $module => $instances) {
844
        $modulename = get_string('pluginname', $module);
845
        foreach ($instances as $index => $cm) {
846
            if (
847
                $cm->completion != COMPLETION_TRACKING_NONE && (
848
                    $config == null || (
849
                        !isset($config->activitiesincluded) || (
850
                            $config->activitiesincluded != 'selectedactivities' ||
851
                            !empty($config->selectactivities) &&
852
                            in_array($module . '-' . $cm->instance, $config->selectactivities))))
853
            ) {
854
                $activities[] = array(
855
                    'type'       => $module,
856
                    'modulename' => $modulename,
857
                    'id'         => $cm->id,
858
                    'instance'   => $cm->instance,
859
                    'name'       => format_string($cm->name),
860
                    'expected'   => $cm->completionexpected,
861
                    'section'    => $cm->sectionnum,
862
                    'position'   => array_search($cm->id, $sections[$cm->sectionnum]),
863
                    // 'url'        => method_exists($cm->url, 'out') ? $cm->url->out() : '',
864
                    'context'    => $cm->context,
865
                    'icon'       => $cm->get_icon_url(),
866
                    'available'  => $cm->available,
867
                    'deletioninprogress' => $cm->deletioninprogress,
868
                );
869
            }
870
        }
871
    }
872
 
873
    // Sort by first value in each element, which is time due.
874
    if ($forceorder == 'orderbycourse' || ($config && $config->orderby == 'orderbycourse')) {
875
        usort($activities, 'format_moofactory_compare_events');
876
    } else {
877
        usort($activities, 'format_moofactory_compare_times');
878
    }
879
 
880
    return $activities;
881
}
882
 
883
function local_moofactory_notification_get_all_activities($courseid, $config = null, $forceorder = null)
884
{
885
    $modinfo = get_fast_modinfo($courseid, -1);
886
 
887
    $sections = $modinfo->get_sections();
888
    $activities = array();
889
    foreach ($modinfo->instances as $module => $instances) {
890
        $modulename = get_string('pluginname', $module);
891
        foreach ($instances as $index => $cm) {
892
            $activities[] = array(
893
                'type'       => $module,
894
                'modulename' => $modulename,
895
                'id'         => $cm->id,
896
                'instance'   => $cm->instance,
897
                'name'       => format_string($cm->name),
898
                'expected'   => $cm->completionexpected,
899
                'section'    => $cm->sectionnum,
900
                'position'   => array_search($cm->id, $sections[$cm->sectionnum]),
901
                // 'url'        => method_exists($cm->url, 'out') ? $cm->url->out() : '',
902
                'context'    => $cm->context,
903
                'icon'       => $cm->get_icon_url(),
904
                'available'  => $cm->available,
905
                'deletioninprogress' => $cm->deletioninprogress,
906
            );
907
        }
908
    }
909
 
910
    return $activities;
911
}
912
 
913
/**
914
 * Finds gradebook exclusions for students in a course
915
 *
916
 * @param int $courseid The ID of the course containing grade items
917
 * @ array of exclusions as activity-user pairs
918
 */
919
function local_moofactory_notification_exclusions($courseid)
920
{
921
    global $DB;
922
 
923
    $query = "SELECT g.id, " . $DB->sql_concat('i.itemmodule', "'-'", 'i.iteminstance', "'-'", 'g.userid') . " as exclusion
924
               FROM {grade_grades} g, {grade_items} i
925
              WHERE i.courseid = :courseid
926
                AND i.id = g.itemid
927
                AND g.excluded <> 0";
928
    $params = array('courseid' => $courseid);
929
    $results = $DB->get_records_sql($query, $params);
930
    $exclusions = array();
931
    foreach ($results as $key => $value) {
932
        $exclusions[] = $value->exclusion;
933
    }
934
    return $exclusions;
935
}
936
 
937
/**
938
 * Filters activities that a user cannot see due to grouping constraints
939
 *
940
 * @param array  $activities The possible activities that can occur for modules
941
 * @param array  $userid The user's id
942
 * @param string $courseid the course for filtering visibility
943
 * @param array  $exclusions Assignment exemptions for students in the course
944
 * @ array The array with restricted activities removed
945
 */
946
function local_moofactory_notification_filter_visibility($activities, $userid, $courseid, $exclusions)
947
{
948
    global $CFG;
949
    $filteredactivities = array();
950
    $modinfo = get_fast_modinfo($courseid, $userid);
951
    $coursecontext = CONTEXT_COURSE::instance($courseid);
952
 
953
    // Keep only activities that are visible.
954
    foreach ($activities as $index => $activity) {
955
 
956
        $coursemodule = $modinfo->cms[$activity['id']];
957
 
958
        // Check visibility in course.
959
        if (!$coursemodule->visible && !has_capability('moodle/course:viewhiddenactivities', $coursecontext, $userid)) {
960
            continue;
961
        }
962
 
963
        // Check availability, allowing for visible, but not accessible items.
964
        if (!empty($CFG->enableavailability)) {
965
            if (has_capability('moodle/course:viewhiddenactivities', $coursecontext, $userid)) {
966
                $activity['available'] = true;
967
            } else {
968
                if (isset($coursemodule->available) && !$coursemodule->available && empty($coursemodule->availableinfo)) {
969
                    continue;
970
                }
971
                $activity['available'] = $coursemodule->available;
972
            }
973
        }
974
 
975
        // Check visibility by grouping constraints (includes capability check).
976
        if (!empty($CFG->enablegroupmembersonly)) {
977
            if (isset($coursemodule->uservisible)) {
978
                if ($coursemodule->uservisible != 1 && empty($coursemodule->availableinfo)) {
979
                    continue;
980
                }
981
            } else if (!groups_course_module_visible($coursemodule, $userid)) {
982
                continue;
983
            }
984
        }
985
 
986
        // Check for exclusions.
987
        if (in_array($activity['type'] . '-' . $activity['instance'] . '-' . $userid, $exclusions)) {
988
            continue;
989
        }
990
 
991
        // Save the visible event.
992
        $filteredactivities[] = $activity;
993
    }
994
    return $filteredactivities;
995
}
996
 
997
/**
998
 * Checked if a user has completed an activity/resource
999
 *
1000
 * @param array $activities  The activities with completion in the course
1001
 * @param int   $userid      The user's id
1002
 * @param int   $course      The course instance
1003
 * @param array $submissions Submissions by the user
1004
 * @ array   an describing the user's attempts based on module+instance identifiers
1005
 */
1006
function local_moofactory_notification_completions($activities, $userid, $course, $submissions)
1007
{
1008
    $completions = array();
1009
    $completion = new completion_info($course);
1010
    $cm = new stdClass();
1011
 
1012
    foreach ($activities as $activity) {
1013
        $cm->id = $activity['id'];
1014
        $activitycompletion = $completion->get_data($cm, true, $userid);
1015
        $completions[$activity['id']] = $activitycompletion->completionstate;
1016
    }
1017
 
1018
    return $completions;
1019
}
1020
 
1021
/**
1022
 * Calculates an overall percentage of progress
1023
 *
1024
 * @param array $activities   The possible events that can occur for modules
1025
 * @param array $completions The user's attempts on course activities
1026
 * @ int  Progress value as a percentage
1027
 */
1028
function local_moofactory_notification_percentage($activities, $completions, $course, $userid)
1029
{
1030
    global $DB;
1031
 
1032
    $completecount = 0;
1033
    $numactivities = 0;
1034
 
1035
    $notavailablecount = 0;
1036
 
1037
    $sql = "SELECT cd.intvalue FROM {customfield_data} cd ";
1038
    $sql .= "LEFT JOIN {customfield_field} cf ON cf.id = cd.fieldid ";
1039
    $sql .= "WHERE cd.instanceid = ? AND cf.shortname = ?";
1040
    $record = $DB->get_record_sql(
1041
        $sql,
1042
        array($course->id, 'checkavailability')
1043
    );
1044
    $checkavailability = $record->intvalue;
1045
 
1046
    $modinfo = get_fast_modinfo($course, $userid);
1047
 
1048
    foreach ($activities as $activity) {
1049
        if (!empty($checkavailability)) {
1050
            $mod = $modinfo->cms[$activity['id']];
1051
            if ($mod->available) {
1052
                if (
1053
                    $completions[$activity['id']] == COMPLETION_COMPLETE ||
1054
                    $completions[$activity['id']] == COMPLETION_COMPLETE_PASS
1055
                ) {
1056
                    $completecount++;
1057
                }
1058
                if (empty($activity['deletioninprogress'])) {
1059
                    $numactivities++;
1060
                }
1061
            }
1062
        } else {
1063
            if (
1064
                $completions[$activity['id']] == COMPLETION_COMPLETE ||
1065
                $completions[$activity['id']] == COMPLETION_COMPLETE_PASS
1066
            ) {
1067
                $completecount++;
1068
            }
1069
            if (empty($activity['deletioninprogress'])) {
1070
                $numactivities++;
1071
            }
1072
        }
1073
    }
1074
 
1075
    $progressvalue = $completecount == 0 ? 0 : $completecount / $numactivities;
1076
 
1077
    return (int)round($progressvalue * 100);
1078
}
1079
 
1080
function local_moofactory_notification_get_user_enrolments($courseid, $userid)
1081
{
1082
    global $DB;
1083
 
1084
    $sql = "SELECT ue.*
1085
              FROM {user_enrolments} ue
1086
              JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1087
              JOIN {user} u ON u.id = ue.userid
1088
             WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1089
    $params = array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'userid' => $userid, 'courseid' => $courseid);
1090
 
1091
    if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1092
        false;
1093
    }
1094
 
1095
    return $enrolments;
1096
}
1097
 
1098
function local_moofactory_notification_get_user_enrolment_dates($courseid, $userid)
1099
{
1100
    $enrolments = local_moofactory_notification_get_user_enrolments($courseid, $userid);
1101
    $starttimes = array();
1102
    $endtimes = array();
1103
    foreach ($enrolments as $enrolment) {
1104
        $starttimes[] = $enrolment->timestart;
1105
        $endtimes[] = $enrolment->timeend;
1106
    }
1107
    // On récupère la date de début d'inscription la plus ancienne et la date de fin la plus éloignée.
1108
    $timestart = min($starttimes);
1109
    $timeend = max($endtimes);
1110
    return [$timestart, $timeend];
1111
}
1112
 
1113
// Evènements de type cours.
1114
function local_moofactory_notification_send_coursesevents_notification()
1115
{
1116
    global $CFG, $DB, $SITE;
1117
 
1118
    require_once($CFG->dirroot . '/calendar/lib.php');
1119
 
1120
    // Nombre de notifications envoyées
1121
    $nbnotif = 0;
1122
    // Activation des notifications.
1123
    $enabled = get_config('local_moofactory_notification', 'enabled');
1124
    // Activation évènements de type cours.
1125
    $coursesevents = get_config('local_moofactory_notification', 'coursesevents');
1126
    // Tableau des notification de type courseevent.
1127
    $courseeventsnotifications = $DB->get_records('local_mf_notification', array('type' => 'courseevent'), 'base DESC, name ASC');
1128
 
1129
    // Maintenant.
1130
    $time = time();
1131
 
1132
    // La dernière fois que la tâche s'est exécutée.
1133
    $previouscourseeventstasktime = get_config('local_moofactory_notification', 'previouscourseeventstasktime');
1134
    if (empty($previouscourseeventstasktime)) {
1135
        set_config('previouscourseeventstasktime', $time, 'local_moofactory_notification');
1136
        return;
1137
    } else {
1138
        set_config('previouscourseeventstasktime', $time, 'local_moofactory_notification');
1139
    }
1140
 
1141
    // Si les notifications sont activées.
1142
    if (!empty($enabled)) {
1143
        // Si les évènements de type cours sont activées.
1144
        if (!empty($coursesevents)) {
1145
            // Tous les évènements à venir.
1146
            // $events = calendar_get_legacy_events($previouscourseeventstasktime, 0, false, false, true, false, false);
1147
            $eventssql = $DB->get_records_select('event', "timestart>=?", array($previouscourseeventstasktime));
1148
 
1149
            // Pour les rendez-vous.
1150
            $events2 = calendar_get_legacy_events($previouscourseeventstasktime, 0, false, false, 0, false, false);
1151
 
1152
            $events = array_merge($eventssql, $events2);
1153
 
1154
            foreach ($events as $event) {
1155
                if (!empty($event->courseid) && !empty($event->modulename)) {
1156
                    $courseid = $event->courseid;
1157
                    $coursecontext = \context_course::instance($courseid);
1158
 
1159
                    // Vérification si le cours est visible
1160
                    $course = $DB->get_record('course', array('id' => $courseid, 'visible' => 1), '*', IGNORE_MISSING);
1161
                    if (empty($course)) {
1162
                        //mtrace("Le cours ID {$courseid} n'est pas visible. Notifications ignorées pour ce cours.");
1163
                        continue;
1164
                    }
1165
 
1166
                    if ($event->eventtype == 'gradingdue') {
1167
                        continue; //On ignore ce genre de notif de devoirs
1168
                    }
1169
                    // Seulement les inscriptions actives.
1170
                    $enrolledusers = get_enrolled_users($coursecontext, '', 0, 'u.*', null, 0, 0, true);
1171
 
1172
                    $instances = get_fast_modinfo($event->courseid, $event->userid)->get_instances_of($event->modulename);
1173
                    if (array_key_exists($event->instance, $instances)) {
1174
                        $module = $instances[$event->instance];
1175
 
1176
                        $moduleid = $module->id;
1177
                        $modulename = $module->name;
1178
 
1179
                        if (!$module->visible) {
1180
                            continue; // Si l'activité est cachée, on ignore
1181
                        }
1182
                        // Activation évènements au niveau du cours.
1183
                        $courseevents = local_moofactory_notification_getCustomfield($courseid, 'courseevents', 'checkbox');
1184
 
1185
                        // Si les évènements sont activés au niveau du cours.
1186
                        if (!empty($courseevents)) {
1187
                            // Restriction
1188
                            $modulecheckavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckavailability', 'checkbox');
1189
                            // Date
1190
                            $modulecheckdateavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckdateavailability', 'checkbox');
1191
                            // Groupe
1192
                            $modulecheckgroupavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckgroupavailability', 'checkbox');
1193
                        }
1194
                        // Sinon on prend le paramétrage de l'activité.
1195
                        else {
1196
                            // Restriction
1197
                            $modulecheckavailabilityname = 'modulecheckavailability_' . $courseid . '_' . $moduleid;
1198
                            $modulecheckavailabilityvalue = get_config('local_moofactory_notification', $modulecheckavailabilityname);
1199
                            // Date
1200
                            $modulecheckdateavailabilityname = 'modulecheckdateavailability_' . $courseid . '_' . $moduleid;
1201
                            $modulecheckdateavailabilityvalue = get_config('local_moofactory_notification', $modulecheckdateavailabilityname);
1202
                            // Groupe
1203
                            $modulecheckgroupavailabilityname = 'modulecheckgroupavailability_' . $courseid . '_' . $moduleid;
1204
                            $modulecheckgroupavailabilityvalue = get_config('local_moofactory_notification', $modulecheckgroupavailabilityname);
1205
 
1206
                            // Si les notifications de l'activité n'ont jamais été paramétrées et enregistrées on prend les réglages du cours
1207
                            if ($modulecheckavailabilityvalue === false) {
1208
                                $modulecheckavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckavailability', 'checkbox');
1209
                            }
1210
                            // Date
1211
                            if ($modulecheckdateavailabilityvalue === false) {
1212
                                $modulecheckdateavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckdateavailability', 'checkbox');
1213
                            }
1214
                            // Groupe
1215
                            if ($modulecheckgroupavailabilityvalue === false) {
1216
                                $modulecheckgroupavailabilityvalue = local_moofactory_notification_getCustomfield($courseid, 'courseeventscheckgroupavailability', 'checkbox');
1217
                            }
1218
                        }
1219
                    }
1220
                }
1221
 
1222
                // Pour l'évènement courant, on cherche les delais des trois rappels (cours ou activité)
1223
                // Evènements liés au cours $courseid
1224
                if (!empty($courseevents)) {
1225
                    // Valeurs des rappels liés au cours $courseid
1226
                    $delays = local_moofactory_notification_get_delays('course', $courseid);
1227
                } else {
1228
                    // Evènements liés à l'activité $moduleid
1229
                    $moduleevents = get_config('local_moofactory_notification', 'moduleevents_' . $courseid . '_' . $moduleid . '');
1230
                    if (!empty($moduleevents)) {
1231
                        // Valeurs des rappels liés à l'activité $moduleid
1232
                        $delays = local_moofactory_notification_get_delays('module', $courseid, $moduleid);
1233
                    }
1234
                }
1235
 
1236
                // Envoi des notifications si l'évènement est prévu à l'issue d'un des délais, au moment de la tâche courante.
1237
                if (!empty($delays)) {
1238
                    foreach ($delays as $delay) {
1239
                        // $targetedevents = calendar_get_legacy_events($previouscourseeventstasktime + $delay, $time + $delay, false, false, $courseid, false, false);
1240
                        $targeteventssql = $DB->get_records_select('event', "timestart>? AND timestart<=? AND courseid=?", array($previouscourseeventstasktime + $delay, $time + $delay, $courseid));
1241
 
1242
                        // Pour les rendez-vous
1243
                        $targetedevents2 = calendar_get_legacy_events($previouscourseeventstasktime + $delay, $time + $delay, false, false, 0, false, false);
1244
 
1245
                        // $targetedevents = array_merge($targetedevents, $targetedevents2);
1246
                        $targetedevents = array_merge($targeteventssql, $targetedevents2);
1247
 
1248
                        foreach ($targetedevents as $targetedevent) {
1249
                            if ($targetedevent->id == $event->id) {
1250
                                // message
1251
                                if (!empty($courseevents)) {
1252
                                    // Notification du cours $courseid
1253
                                    $notifvalue = (int)local_moofactory_notification_getCustomfield($courseid, 'courseeventsnotification', 'select');
1254
                                    if (!empty($notifvalue)) {
1255
                                        $courseeventsnotifications = array_values($courseeventsnotifications);
1256
                                        $notifvalue--;
1257
                                    } else {
1258
                                        $notifvalue = get_config('local_moofactory_notification', 'courseseventsnotification');
1259
                                    }
1260
                                } else {
1261
                                    // Notification de l'activité $moduleid
1262
                                    $moduleevents = get_config('local_moofactory_notification', 'moduleevents_' . $courseid . '_' . $moduleid . '');
1263
                                    if (!empty($moduleevents)) {
1264
                                        $configvarid = 'modulenotification' . '_' . $courseid . '_' . $moduleid;
1265
                                        $notifvalue = get_config('local_moofactory_notification', $configvarid);
1266
                                    }
1267
                                }
1268
 
1269
                                $notif = $courseeventsnotifications[$notifvalue];
1270
                                $bodyhtml = urldecode($notif->bodyhtml);
1271
 
1272
                                $variables = local_moofactory_notification_fetch_variables($bodyhtml);
1273
 
1274
                                if (!empty($notif)) {
1275
                                    foreach ($enrolledusers as $user) {
1276
 
1277
                                        // Vérification de la capacité avant de continuer.
1278
                                        if (!has_capability('local/moofactory_notification:coursesevents', $coursecontext, $user->id)) {
1279
                                            mtrace("Utilisateur {$user->id} ignoré : capacité 'local/moofactory_notification:coursesevents' non satisfaite.");
1280
                                            continue;
1281
                                        }
1282
                                        $instances = get_fast_modinfo($event->courseid, $user->id)->get_instances_of($event->modulename);
1283
 
1284
                                        // echo($user->firstname." ".$user->lastname."<br>");
1285
 
1286
                                        if (array_key_exists($event->instance, $instances)) {
1287
                                            $module = $instances[$event->instance];
1288
                                        }
1289
 
1290
                                        // Vérification section availability
1291
                                        $sectionavailable = true;
1292
                                        $section = $DB->get_record('course_sections', array('id' => $module->section), '*', IGNORE_MISSING);
1293
                                        if (!empty($section->availability)) {
1294
                                            $modinfo = get_fast_modinfo($event->courseid, $user->id);
1295
                                            $section_info = $modinfo->get_section_info((int)$section->section);
1296
                                            $si = new \core_availability\info_section($section_info);
1297
                                            $sectionavailable = local_moofactory_check_availability($si, $user->id, $modulecheckdateavailabilityvalue, $modulecheckgroupavailabilityvalue);
1298
                                            if(!$sectionavailable){
1299
                                                mtrace("Utilisateur {$user->id} ignoré : section {$module->section} non disponible.");
1300
                                                continue;
1301
                                            }
1302
                                        }
1303
 
1304
                                        // Vérification module availability
1305
                                        $moduleavailable = true;
1306
                                        if (!empty($modulecheckavailabilityvalue) && !empty($module->availability)) {
1307
                                            // On tient compte des restrictions s'il y en a.
1308
                                            // Get availability information.
1309
                                            $ci = new \core_availability\info_moofactory_notification($module);
1310
                                            $ci->set_modinfo($event->courseid, $user->id);
1311
                                            $moduleavailable = local_moofactory_check_availability($ci, $user->id, $modulecheckdateavailabilityvalue, $modulecheckgroupavailabilityvalue);
1312
                                        }
1313
 
1314
                                        // Pas de notification si l'activité est achevée.
1315
                                        $result = $DB->get_record('course_modules_completion', array('coursemoduleid' => $moduleid, 'userid' => $user->id), 'completionstate');
1316
                                        $completionstate = $result->completionstate;
1317
 
1318
                                        if (!is_siteadmin($user) && $moduleavailable && !$completionstate) {
1319
                                            // Pour les activités rendez-vous, on tient compte du user concerné
1320
                                            if ($targetedevent->modulename != "scheduler" || $targetedevent->userid == $user->id) {
1321
                                                $data = new stdClass();
1322
                                                $data->firstname = $user->firstname;
1323
                                                $data->lastname = $user->lastname;
1324
                                                $data->username = $user->username;
1325
                                                $data->usergroup = local_moofactory_notification_get_group($courseid, $user->id);
1326
                                                $data->eventdate = date("d/m/Y à H:i", $targetedevent->timestart);
1327
                                                $data->eventname = $targetedevent->name;
1328
                                                $course = $DB->get_record('course', array('id' => $courseid), 'fullname,startdate,enddate');
1329
                                                $data->coursename = $course->fullname;
1330
                                                $data->coursestartdate = $course->startdate == "0" ? "" : date("d/m/Y à H:i", $course->startdate);
1331
                                                $data->courseenddate = $course->enddate == "0" ? "" : date("d/m/Y à H:i", $course->enddate);
1332
                                                list($courseenrolstartdate, $courseenrolenddate) = local_moofactory_notification_get_user_enrolment_dates($courseid, $user->id);
1333
                                                $data->courseenrolstartdate = $courseenrolstartdate == "0" ? "" : date("d/m/Y à H:i", $courseenrolstartdate);
1334
                                                $data->courseenrolenddate = $courseenrolenddate == "0" ? "" : date("d/m/Y à H:i", $courseenrolenddate);
1335
                                                $data->courseurl = $CFG->wwwroot . '/course/view.php?id=' . $courseid;
1336
                                                $data->activityname = $modulename;
1337
                                                $data->lmsurl = $CFG->wwwroot;
1338
                                                $data->lmsname = $SITE->fullname;
1339
                                                $data->interval = "";
1340
 
1341
                                                $msgbodyhtml = local_moofactory_notification_replace_variables($variables, $bodyhtml, $data);
1342
 
1343
                                                $msg = new stdClass();
1344
                                                $msg->subject = $notif->subject;
1345
                                                $msg->from = "moofactory";
1346
                                                $msg->bodytext = "";
1347
                                                $msg->bodyhtml = $msgbodyhtml;
1348
 
1349
                                                $ret = local_moofactory_notification_send_email($user, $msg, $courseid, 'coursesevents_notification');
1350
 
1351
                                                $dateEnvoi = date("d/m/Y H:i:s", time());
1352
                                                mtrace("\n" . 'Envoyé le : ' . $dateEnvoi . ' à ' . $data->firstname . ' ' . $data->lastname . ' - Cours : ' . $data->coursename . ' - Activité : ' . $data->activityname . ' (Evènement le ' . $data->eventdate . ")");
1353
                                                mtrace('Objet du mail : ' . $msg->subject);
1354
                                                $nbnotif++;
1355
                                            }
1356
                                        }
1357
                                    }
1358
                                } else {
1359
                                    mtrace("Pas d'envoi : la notification est inexistante.");
1360
                                }
1361
                            }
1362
                        }
1363
                    }
1364
                }
1365
            }
1366
        }
1367
    }
1368
    mtrace("\n" . $nbnotif . ' notification(s) envoyée(s).' . "\n");
1369
}
1370
 
1371
function local_moofactory_check_availability($info, $userid,$modulecheckdateavailabilityvalue,$modulecheckgroupavailabilityvalue){
1372
    $avalaible=true;
1373
    $tree = $info->get_availability_tree();
1374
    list($innernot, $andoperator) = $tree->get_logic_flags(false);
1375
    $children = $tree->get_all_children('core_availability\condition');
1376
 
1377
    // Il faut traiter chaque restriction pour en déduire la disponibilité du module.
1378
    foreach ($children as $index => $child) {
1379
        $childresult = $child->is_available($innernot, $info, true, $userid);
1380
        $type = preg_replace('~^availability_(.*?)\\\\condition$~', '$1', get_class($child));
1381
 
1382
        //On ne limite les restrictions que pour les modules
1383
        if ($type != "date" && $type != "group") {
1384
            $avalaible &= $childresult;
1385
        } elseif ($type == "date") {
1386
            if (!empty($modulecheckdateavailabilityvalue)) {
1387
                $avalaible &= true;
1388
            } else {
1389
                $avalaible &= $childresult;
1390
            }
1391
        } elseif ($type == "group") {
1392
            if (!empty($modulecheckgroupavailabilityvalue)) {
1393
                $avalaible &= true;
1394
            } else {
1395
                $avalaible &= $childresult;
1396
            }
1397
        }
1398
    }
1399
 
1400
    return $avalaible;
1401
}
1402
function local_moofactory_notification_getCustomfield($courseid, $name, $type)
1403
{
1404
    global $DB;
1405
 
1406
    switch ($type) {
1407
        case "select":
1408
        case "checkbox":
1409
            $fieldvalue = "intvalue";
1410
            break;
1411
        case "text":
1412
            $fieldvalue = "charvalue";
1413
            break;
1414
    }
1415
    $sql = "SELECT cd.$fieldvalue FROM {customfield_data} cd ";
1416
    $sql .= "LEFT JOIN {customfield_field} cf ON cf.id = cd.fieldid ";
1417
    $sql .= "WHERE cd.instanceid = ? AND cf.shortname = ?";
1418
    $record = $DB->get_record_sql(
1419
        $sql,
1420
        array($courseid, $name)
1421
    );
1422
 
1423
    if (!empty($record)) {
1424
        $value = $record->$fieldvalue;
1425
    } else {
1426
        $value = "0";
1427
    }
1428
    return $value;
1429
}
1430
 
1431
function local_moofactory_notification_setCustomfield($courseid, $name, $type, $value)
1432
{
1433
    global $DB;
1434
 
1435
    switch ($type) {
1436
        case "select":
1437
        case "checkbox":
1438
            $fieldvalue = "intvalue";
1439
            break;
1440
        case "text":
1441
            $fieldvalue = "charvalue";
1442
            break;
1443
    }
1444
    $sql = "UPDATE {customfield_data} cd ";
1445
    $sql .= "LEFT JOIN {customfield_field} cf ON cf.id = cd.fieldid ";
1446
    $sql .= "SET cd.$fieldvalue = $value, cd.value = $value ";
1447
    $sql .= "WHERE cd.instanceid = ? AND cf.shortname = ?";
1448
    $DB->execute($sql, array($courseid, $name));
1449
}
1450
 
1451
function local_moofactory_notification_get_group($courseid, $userid)
1452
{
1453
    global $DB;
1454
 
1455
    $sql = "SELECT g.name FROM {groups} g ";
1456
    $sql .= "LEFT JOIN {groups_members} gm ON g.id = gm.groupid ";
1457
    $sql .= "WHERE g.courseid = ? AND gm.userid = ?";
1458
 
1459
    $records = $DB->get_records_sql(
1460
        $sql,
1461
        array($courseid, $userid)
1462
    );
1463
 
1464
    $groups = implode(", ", array_keys($records));
1465
 
1466
    if (!empty($groups)) {
1467
        $return = $groups;
1468
    } else {
1469
        $return = get_string('nogroup', 'local_moofactory_notification');
1470
    }
1471
    return $return;
1472
}
1473
 
1474
function local_moofactory_notification_replace_variables($variables, $html, $data)
1475
{
1476
 
1477
    foreach ($variables as $variable) {
1478
        $find = "{{" . $variable . "}}";
1479
        switch ($variable) {
1480
            case "firstname":
1481
                $html = str_replace($find, $data->firstname, $html);
1482
                break;
1483
            case "lastname":
1484
                $html = str_replace($find, $data->lastname, $html);
1485
                break;
1486
            case "username":
1487
                $html = str_replace($find, $data->username, $html);
1488
                break;
1489
            case "usergroup":
1490
                $html = str_replace($find, $data->usergroup, $html);
1491
                break;
1492
            case "eventdate":
1493
                $html = str_replace($find, $data->eventdate, $html);
1494
                break;
1495
            case "eventname":
1496
                $html = str_replace($find, $data->eventname, $html);
1497
                break;
1498
            case "coursename":
1499
                $html = str_replace($find, $data->coursename, $html);
1500
                break;
1501
            case "coursestartdate":
1502
                $html = str_replace($find, $data->coursestartdate, $html);
1503
                break;
1504
            case "courseenddate":
1505
                $html = str_replace($find, $data->courseenddate, $html);
1506
                break;
1507
            case "courseenrolstartdate":
1508
                $html = str_replace($find, $data->courseenrolstartdate, $html);
1509
                break;
1510
            case "courseenrolenddate":
1511
                $html = str_replace($find, $data->courseenrolenddate, $html);
1512
                break;
1513
            case "courseurl":
1514
                $html = str_replace($find, $data->courseurl, $html);
1515
                break;
1516
            case "activityname":
1517
                $html = str_replace($find, $data->activityname, $html);
1518
                break;
1519
            case "lmsurl":
1520
                $html = str_replace($find, $data->lmsurl, $html);
1521
                break;
1522
            case "lmsname":
1523
                $html = str_replace($find, $data->lmsname, $html);
1524
                break;
1525
            case "interval":
1526
                $html = str_replace($find, $data->interval, $html);
1527
                break;
1528
        }
1529
    }
1530
    return $html;
1531
}
1532
 
1533
function local_moofactory_notification_prepare_access_email($user, $courseid, $courseaccesstime, $courseaccessnotifications)
1534
{
1535
    global $DB, $CFG, $SITE;
1536
 
1537
    $notifvalue = (int)local_moofactory_notification_getCustomfield($courseid, 'courseaccessnotification', 'select');
1538
    if (!empty($notifvalue)) {
1539
        $courseaccessnotifications = array_values($courseaccessnotifications);
1540
        $notifvalue--;
1541
    } else {
1542
        $notifvalue = get_config('local_moofactory_notification', 'coursesaccessnotification');
1543
    }
1544
 
1545
    $notif = $courseaccessnotifications[$notifvalue];
1546
    $bodyhtml = urldecode($notif->bodyhtml);
1547
 
1548
    $variables = local_moofactory_notification_fetch_variables($bodyhtml);
1549
 
1550
    if (!empty($notif)) {
1551
        $data = new stdClass();
1552
        $data->firstname = $user->firstname;
1553
        $data->lastname = $user->lastname;
1554
        $data->username = $user->username;
1555
        $data->usergroup = local_moofactory_notification_get_group($courseid, $user->id);
1556
        $data->eventdate = "";
1557
        $data->eventname = "";
1558
        $course = $DB->get_record('course', array('id' => $courseid), 'fullname,startdate,enddate');
1559
        $data->coursename = $course->fullname;
1560
        $data->coursestartdate = $course->startdate == "0" ? "" : date("d/m/Y à H:i", $course->startdate);
1561
        $data->courseenddate = $course->enddate == "0" ? "" : date("d/m/Y à H:i", $course->enddate);
1562
        list($courseenrolstartdate, $courseenrolenddate) = local_moofactory_notification_get_user_enrolment_dates($courseid, $user->id);
1563
        $data->courseenrolstartdate = $courseenrolstartdate == "0" ? "" : date("d/m/Y à H:i", $courseenrolstartdate);
1564
        $data->courseenrolenddate = $courseenrolenddate == "0" ? "" : date("d/m/Y à H:i", $courseenrolenddate);
1565
        $data->courseurl = $CFG->wwwroot . '/course/view.php?id=' . $courseid;
1566
        $data->activityname = "";
1567
        $data->lmsurl = $CFG->wwwroot;
1568
        $data->lmsname = $SITE->fullname;
1569
        if ((int)$courseaccesstime < 2) {
1570
            $data->interval = $courseaccesstime . " jour";
1571
        } else {
1572
            $data->interval = $courseaccesstime . " jours";
1573
        }
1574
 
1575
        $msgbodyhtml = local_moofactory_notification_replace_variables($variables, $bodyhtml, $data);
1576
 
1577
        $msg = new stdClass();
1578
        $msg->subject = $notif->subject;
1579
        $msg->from = "moofactory";
1580
        $msg->bodytext = "";
1581
        $msg->bodyhtml = $msgbodyhtml;
1582
        $ret = local_moofactory_notification_send_email($user, $msg, $courseid, 'coursesaccess_notification');
1583
    } else {
1584
        mtrace("Pas d'envoi : la notification est inexistante.");
1585
    }
1586
}
1587
 
1588
function local_moofactory_notification_prepare_enrollments_email($user, $courseid, $courseenrollmentsnotifications)
1589
{
1590
    global $DB, $CFG, $SITE;
1591
 
1592
    // Récupération des champs personnalisés pour le cours
1593
    $defaultNotificationValue = (int)local_moofactory_notification_getCustomfield($courseid, 'courseenrollmentsnotification', 'select');
1594
    $roleSpecificNotificationValue = (int)local_moofactory_notification_getCustomfield($courseid, 'courseenrollmentsnotification2', 'select');
1595
    $roleToMatch = local_moofactory_notification_getCustomfield($courseid, 'courseenrollmentsrole', 'select');
1596
 
1597
    // Détermination de la notification à utiliser
1598
    $notifvalue = $defaultNotificationValue; // Valeur par défaut
1599
    if (!empty($roleToMatch) && !empty($roleSpecificNotificationValue)) {
1600
        $coursecontext = \context_course::instance($courseid);
1601
        $userRoles = get_user_roles($coursecontext, $user->id);
1602
        $roles = $DB->get_records('role', null, '', 'id, name, shortname');
1603
        $roles = array_values($roles);
1604
        foreach ($userRoles as $userRole) {
1605
            if ($userRole->shortname === $roles[$roleToMatch - 1]->shortname) {
1606
                $notifvalue = $roleSpecificNotificationValue; // Si le rôle correspond, utiliser la notification spécifique
1607
                break;
1608
            }
1609
        }
1610
    }
1611
    $courseenrollmentsnotifications = array_values($courseenrollmentsnotifications);
1612
    // Validation de la notification sélectionnée
1613
    if (!isset($courseenrollmentsnotifications[$notifvalue - 1])) {
1614
        mtrace("Notification invalide ou inexistante pour le cours {$courseid}.");
1615
        return;
1616
    }
1617
 
1618
    $notif = $courseenrollmentsnotifications[$notifvalue - 1];
1619
 
1620
    $bodyhtml = urldecode($notif->bodyhtml);
1621
 
1622
    $variables = local_moofactory_notification_fetch_variables($bodyhtml);
1623
 
1624
    if (!empty($notif)) {
1625
        $data = new stdClass();
1626
        $data->firstname = $user->firstname;
1627
        $data->lastname = $user->lastname;
1628
        $data->username = $user->username;
1629
        $data->usergroup = local_moofactory_notification_get_group($courseid, $user->id);
1630
        $data->eventdate = "";
1631
        $data->eventname = "";
1632
        $course = $DB->get_record('course', array('id' => $courseid), 'fullname,startdate,enddate');
1633
        $data->coursename = $course->fullname;
1634
        $data->coursestartdate = $course->startdate == "0" ? "" : date("d/m/Y à H:i", $course->startdate);
1635
        $data->courseenddate = $course->enddate == "0" ? "" : date("d/m/Y à H:i", $course->enddate);
1636
        list($courseenrolstartdate, $courseenrolenddate) = local_moofactory_notification_get_user_enrolment_dates($courseid, $user->id);
1637
        $data->courseenrolstartdate = $courseenrolstartdate == "0" ? "" : date("d/m/Y à H:i", $courseenrolstartdate);
1638
        $data->courseenrolenddate = $courseenrolenddate == "0" ? "" : date("d/m/Y à H:i", $courseenrolenddate);
1639
        $data->courseurl = $CFG->wwwroot . '/course/view.php?id=' . $courseid;
1640
        $data->activityname = "";
1641
        $data->lmsurl = $CFG->wwwroot;
1642
        $data->lmsname = $SITE->fullname;
1643
        $data->interval = "";
1644
 
1645
        $msgbodyhtml = local_moofactory_notification_replace_variables($variables, $bodyhtml, $data);
1646
 
1647
        $msg = new stdClass();
1648
        $msg->subject = $notif->subject;
1649
        $msg->from = "moofactory";
1650
        $msg->bodytext = "";
1651
        $msg->bodyhtml = $msgbodyhtml;
1652
        $ret = local_moofactory_notification_send_email($user, $msg, $courseid, 'coursesenrollments_notification');
1653
 
1654
        $dateEnvoi = date("d/m/Y H:i:s", time());
1655
        mtrace("\n" . 'Envoyé le : ' . $dateEnvoi . ' à ' . $data->firstname . ' ' . $data->lastname . ' - Cours : ' . $data->coursename . ' - Date d\'inscription : ' . $data->courseenrolstartdate . ")");
1656
        mtrace('Objet du mail : ' . $msg->subject);
1657
    } else {
1658
        mtrace("Pas d'envoi : la notification est inexistante.");
1659
        throw new moodle_exception("Pas d'envoi : la notification est inexistante.");
1660
    }
1661
}
1662
 
1663
function local_moofactory_notification_send_email_with_cc($user, $msg)
1664
{
1665
 
1666
    if (empty($user->email)) {
1667
        return false;
1668
    }
1669
 
1670
    $bodytext = !empty($msg->bodytext) ? $msg->bodytext : $msg->bodyhtml;
1671
 
1672
    // Envoi de l'email principal
1673
    $success = email_to_user(
1674
        $user,                         // Utilisateur destinataire
1675
        core_user::get_noreply_user(), // Utilisateur expéditeur (noreply)
1676
        $msg->subject,
1677
        $bodytext,
1678
        $msg->bodyhtml
1679
    );
1680
 
1681
    // Vérification et gestion des emails en copie
1682
    if (!empty($msg->cc)) {
1683
        foreach ($msg->cc as $ccEmail) {
1684
            // Création d'un utilisateur factice pour l'email en copie
1685
            $ccUser = (object)[
1686
                'email' => $ccEmail,
1687
                'id' => -99, // ID factice pour les utilisateurs non-enregistrés
1688
                'firstname' => 'Copie',
1689
                'lastname' => 'Notification',
1690
            ];
1691
 
1692
            email_to_user(
1693
                $ccUser,
1694
                core_user::get_noreply_user(),
1695
                "[COPIE MAIL] [USER] [" . $user->username . "] " .  $msg->subject,
1696
                "[COPIE MAIL] [USER] [" . $user->username . "]\n\n" . $bodytext,
1697
                $msg->bodyhtml
1698
            );
1699
        }
1700
    }
1701
 
1702
    return $success;
1703
}
1704
 
1705
function local_moofactory_notification_send_email($user, $msg, $courseid, $name)
1706
{
1707
    if (!isset($user->email) && empty($user->email)) {
1708
        return false;
1709
    }
1710
 
1711
    $message = new \core\message\message();
1712
    $message->courseid  = empty($courseid) ? SITEID : $courseid; // This is required in recent versions, use it from 3.2 on https://tracker.moodle.org/browse/MDL-47162
1713
    $message->component = 'local_moofactory_notification';
1714
    $message->name = $name;
1715
    $message->userfrom = core_user::get_noreply_user();
1716
    $message->userto = $user;
1717
    $message->subject = $msg->subject;
1718
    $message->fullmessage = $msg->bodytext;
1719
    $message->fullmessagehtml = $msg->bodyhtml;
1720
    // With FORMAT_HTML, most outputs will use fullmessagehtml, and convert it to plain text if necessary.
1721
    // but some output plugins will behave differently (airnotifier only uses fullmessage)
1722
    $message->fullmessageformat = FORMAT_HTML;
1723
    // If smallmessage is not empty,
1724
    // it will have priority over the 2 other fields, with a hard coded FORMAT_PLAIN.
1725
    // But some output plugins may need it, as jabber currently does.
1726
    $message->smallmessage = '';
1727
    $message->notification = '1';
1728
    if (!empty($courseid)) {
1729
        $message->contexturl = new moodle_url('/course/view.php', array('id' => $courseid));
1730
        $message->contexturlname = 'Your course';
1731
    }
1732
 
1733
    $messageid = message_send($message);
1734
    return $messageid;
1735
}
1736
 
1737
function local_moofactory_notification_get_delays($type, $courseid, $moduleid = 0, $configvarstarget = 'events')
1738
{
1739
    $configvars = ['daysbefore' . $configvarstarget . '1', 'hoursbefore' . $configvarstarget . '1', 'daysbefore' . $configvarstarget . '2', 'hoursbefore' . $configvarstarget . '2', 'daysbefore' . $configvarstarget . '3', 'hoursbefore' . $configvarstarget . '3'];
1740
 
1741
    foreach ($configvars as $configvar) {
1742
        if ($type == 'course') {
1743
            $value = local_moofactory_notification_getCustomfield($courseid, $configvar, 'text');
1744
        } else {
1745
            $configvarid = 'module' . $configvar . '_' . $courseid . '_' . $moduleid;
1746
            $value = get_config('local_moofactory_notification', $configvarid);
1747
        }
1748
 
1749
        $idrappel = (int)substr($configvar, -1);
1750
        switch ($idrappel) {
1751
            case 1:
1752
                if (strpos($configvar, 'days') !== false) {
1753
                    $daysvalue1 = $value;
1754
                }
1755
                if (strpos($configvar, 'hours') !== false) {
1756
                    $hoursvalue1 = $value;
1757
                }
1758
                break;
1759
            case 2:
1760
                if (strpos($configvar, 'days') !== false) {
1761
                    $daysvalue2 = $value;
1762
                }
1763
                if (strpos($configvar, 'hours') !== false) {
1764
                    $hoursvalue2 = $value;
1765
                }
1766
                break;
1767
            case 3:
1768
                if (strpos($configvar, 'days') !== false) {
1769
                    $daysvalue3 = $value;
1770
                }
1771
                if (strpos($configvar, 'hours') !== false) {
1772
                    $hoursvalue3 = $value;
1773
                }
1774
                break;
1775
        }
1776
    }
1777
 
1778
    $delays = array();
1779
    if (!($daysvalue1 == "") || !($hoursvalue1 == "")) {
1780
        $delay1 = (int)$daysvalue1 * 60 * 60 * 24 + (int)$hoursvalue1 * 60 * 60;
1781
        if ($configvarstarget == 'levee') {
1782
            $delays['first'] = $delay1;
1783
        } else {
1784
            $delays[] = $delay1;
1785
        }
1786
    }
1787
    if (!($daysvalue2 == "") || !($hoursvalue2 == "")) {
1788
        $delay2 = (int)$daysvalue2 * 60 * 60 * 24 + (int)$hoursvalue2 * 60 * 60;
1789
        if ($configvarstarget == 'levee') {
1790
            $delays['second'] = $delay2;
1791
        } else {
1792
            $delays[] = $delay2;
1793
        }
1794
    }
1795
    if (!($daysvalue3 == "") || !($hoursvalue3 == "")) {
1796
        $delay3 = (int)$daysvalue3 * 60 * 60 * 24 + (int)$hoursvalue3 * 60 * 60;
1797
        if ($configvarstarget == 'levee') {
1798
            $delays['third'] = $delay3;
1799
        } else {
1800
            $delays[] = $delay3;
1801
        }
1802
    }
1803
    return $delays;
1804
}
1805
 
1806
/**
1807
 *  an array of variable names
1808
 * @param string template containing {{variable}} variables
1809
 * @ array of variable names parsed from template string
1810
 */
1811
function local_moofactory_notification_fetch_variables($html)
1812
{
1813
    $matches = array();
1814
    $t = preg_match_all('/{{(.*?)}}/', $html, $matches);
1815
    if (count($matches) > 1) {
1816
        $uniquearray = array_unique($matches[1]);
1817
        return array_values($uniquearray);
1818
    } else {
1819
        return array();
1820
    }
1821
}
1822
 
1823
function local_moofactory_notification_send_modulesaccess_notification()
1824
{
1825
    global $DB;
1826
 
1827
    // Nombre de notifications envoyées
1828
    $nbnotif = 0;
1829
 
1830
    $enabled = get_config('local_moofactory_notification', 'enabled');
1831
    // Activation évènements de type cours.
1832
    $moduleaccessnotif = get_config('local_moofactory_notification', 'modulesaccess');
1833
 
1834
    // si les notifications sont désactivées
1835
    if (empty($enabled) || empty($moduleaccessnotif)) {
1836
        return;
1837
    }
1838
 
1839
    // Tableau des notification de type levee
1840
    $leveenotifications = $DB->get_records('local_mf_notification', array('type' => 'moduleaccess'), 'base DESC, name ASC');
1841
 
1842
    // Obtenir tous les modules avec des restrictions d'accès
1843
    $sql = "SELECT cm.id, cm.course, cm.availability, cm.completion
1844
            FROM {course_modules} cm
1845
            WHERE cm.deletioninprogress = 0 AND cm.availability IS NOT NULL"; //and cm.id=522 for tests
1846
    $modules = $DB->get_records_sql($sql);
1847
 
1848
    $time = time();
1849
    foreach ($modules as $module) {
1850
 
1851
        // Vérifie si les notifications pour la levée sont activées pour ce module
1852
        $moduleleveename = 'modulelevee_' . $module->course . '_' . $module->id;
1853
        $moduleleveevalue = get_config('local_moofactory_notification', $moduleleveename);
1854
 
1855
        // Si les notifications pour la levée sont désactivées pour ce module
1856
        if (!$moduleleveevalue) {
1857
            continue;
1858
        }
1859
 
1860
        // Récupérer tous les utilisateurs inscrits au cours
1861
        $course = $DB->get_record('course', ['id' => $module->course], '*', MUST_EXIST);
1862
 
1863
        // Vérifier si le cours est visible
1864
        if ($course->visible == 0) {
1865
            continue; // Passer au module suivant
1866
        }
1867
 
1868
        $context = \context_course::instance($course->id);
1869
        $users = get_enrolled_users($context);
1870
        foreach ($users as $user) {
1871
 
1872
            // Vérification de la capacité avant de continuer.
1873
            if (!has_capability('local/moofactory_notification:modulesaccess', $context, $user->id)) {
1874
                mtrace("Utilisateur {$user->id} ignoré : capacité 'local/moofactory_notification:modulesaccess' non satisfaite.");
1875
                continue;
1876
            }
1877
 
1878
            // Vérifier si l'activité est visible pour cet utilisateur
1879
            $modinfo = get_fast_modinfo($course, $user->id);
1880
            $cm = $modinfo->get_cm($module->id);
1881
 
1882
            // Vérifier si l'utilisateur a déjà été notifié
1883
            $recordaccessnotif = $DB->get_record('local_mf_modaccessnotif', [
1884
                'moduleid' => $module->id,
1885
                'userid' => $user->id
1886
            ], 'id, notificationtime, notificationnumber');
1887
 
1888
            if (!$cm->uservisible) {
1889
                $record = new stdclass();
1890
                $record->moduleid = $module->id;
1891
                $record->userid = $user->id;
1892
                $record->notificationtime = $time;
1893
                $record->notificationnumber = 0;
1894
                if (empty($recordaccessnotif)) {
1895
                    //1er traçage de cette restriction d'accès
1896
                    $DB->insert_record('local_mf_modaccessnotif', $record);
1897
                } else {
1898
                    //on met à jour le traçage
1899
                    $record->id = $recordaccessnotif->id;
1900
                    $DB->update_record('local_mf_modaccessnotif', $record);
1901
                }
1902
                continue; // Non visible pour cet utilisateur
1903
            }
1904
 
1905
            // Vérifier si l'utilisateur a terminé l'activité
1906
            $completion = $DB->get_record('course_modules_completion', [
1907
                'coursemoduleid' => $module->id,
1908
                'userid' => $user->id
1909
            ]);
1910
 
1911
            if ($completion && $completion->completionstate == 1) {
1912
                continue; // Déjà complété, passer
1913
            }
1914
 
1915
            $notificationnumber = $recordaccessnotif->notificationnumber;
1916
 
1917
            $moduleleveedelay = get_config('local_moofactory_notification', 'moduleleveedelai_' . $course->id . '_' . $module->id);
1918
            //$module_enabled_date = get_config('local_moofactory_notification', $moduleleveename . '_date'); // Date d'activation spécifique
1919
 
1920
            $update_record = false;
1921
            if (!empty($recordaccessnotif)) {
1922
                if ($recordaccessnotif->notificationnumber == 0) {
1923
                    // 1ère notification sans délai
1924
                    if (empty($moduleleveedelay)) {
1925
                        // message sans délai
1926
                        local_moofactory_notification_prepare_levee_email($user, $course->id, $leveenotifications, $cm);
1927
                        $nbnotif++;
1928
                        $notificationnumber = 1;
1929
                        $update_record = true;
1930
                    }
1931
                    // Gestion du délai si un délai est configuré
1932
                    elseif ($moduleleveedelay * 60 + $recordaccessnotif->notificationtime <= $time) {
1933
                        local_moofactory_notification_prepare_levee_email($user, $course->id, $leveenotifications, $cm);
1934
                        $nbnotif++;
1935
                        $notificationnumber = 1;
1936
                        $update_record = true;
1937
                    }
1938
                } else {
1939
                    // Gestion des rappels pour les notifications suivantes
1940
                    $delays = local_moofactory_notification_get_delays('module', $course->id, $module->id, 'levee');
1941
 
1942
                    if (!empty($delays)) {
1943
                        if ($notificationnumber == 1 && array_key_exists('first', $delays)) {
1944
                            if ($recordaccessnotif->notificationtime + $delays['first'] <= $time) {
1945
                                local_moofactory_notification_prepare_levee_email($user, $course->id, $leveenotifications, $cm);
1946
                                $nbnotif++;
1947
                                $notificationnumber = 2;
1948
                                $update_record = true;
1949
                            }
1950
                        } elseif ($notificationnumber == 2 && array_key_exists('second', $delays)) {
1951
                            if ($recordaccessnotif->notificationtime + $delays['second'] <= $time) {
1952
                                local_moofactory_notification_prepare_levee_email($user, $course->id, $leveenotifications, $cm);
1953
                                $nbnotif++;
1954
                                $notificationnumber = 3;
1955
                                $update_record = true;
1956
                            }
1957
                        } elseif ($notificationnumber == 3 && array_key_exists('third', $delays)) {
1958
                            if ($recordaccessnotif->notificationtime + $delays['third'] <= $time) {
1959
                                local_moofactory_notification_prepare_levee_email($user, $course->id, $leveenotifications, $cm);
1960
                                $nbnotif++;
1961
                                $notificationnumber = 4;
1962
                                $update_record = true;
1963
                            }
1964
                        }
1965
                    }
1966
                }
1967
                // Mettre à jour les données de notification
1968
                if ($update_record === true) {
1969
                    $record = new stdclass();
1970
                    $record->id = $recordaccessnotif->id;
1971
                    $record->moduleid = $module->id;
1972
                    $record->userid = $user->id;
1973
                    $record->notificationtime = $time;
1974
                    $record->notificationnumber = $notificationnumber;
1975
 
1976
                    $DB->update_record('local_mf_modaccessnotif', $record);
1977
                }
1978
            }
1979
        }
1980
    }
1981
    mtrace("\n" . $nbnotif . ' notification(s) envoyée(s).' . "\n");
1982
}
1983
 
1984
 
1985
function local_moofactory_notification_prepare_levee_email($user, $courseid, $leveenotifications, $cm)
1986
{
1987
    global $DB, $CFG, $SITE;
1988
 
1989
    // Notification de l'activité $moduleid
1990
    $modulelevee = get_config('local_moofactory_notification', 'modulelevee_' . $courseid . '_' . $cm->id . '');
1991
    if (!empty($modulelevee)) {
1992
        $configvarid = 'moduleleveenotification_' . $courseid . '_' . $cm->id;
1993
        $notifvalue = get_config('local_moofactory_notification', $configvarid);
1994
    } else {
1995
        $notifvalue = get_config('local_moofactory_notification', 'modulesaccessnotification');
1996
    }
1997
 
1998
    $notif = $leveenotifications[$notifvalue];
1999
 
2000
 
2001
    $bodyhtml = urldecode($notif->bodyhtml);
2002
 
2003
    $variables = local_moofactory_notification_fetch_variables($bodyhtml);
2004
 
2005
    if (!empty($notif)) {
2006
        $data = new stdClass();
2007
        $data->firstname = $user->firstname;
2008
        $data->lastname = $user->lastname;
2009
        $data->username = $user->username;
2010
        $data->usergroup = local_moofactory_notification_get_group($courseid, $user->id);
2011
        $data->eventdate = "";
2012
        $data->eventname = "";
2013
        $course = $DB->get_record('course', array('id' => $courseid), 'fullname,startdate,enddate');
2014
        $data->coursename = $course->fullname;
2015
        $data->coursestartdate = $course->startdate == "0" ? "" : date("d/m/Y à H:i", $course->startdate);
2016
        $data->courseenddate = $course->enddate == "0" ? "" : date("d/m/Y à H:i", $course->enddate);
2017
        list($courseenrolstartdate, $courseenrolenddate) = local_moofactory_notification_get_user_enrolment_dates($courseid, $user->id);
2018
        $data->courseenrolstartdate = $courseenrolstartdate == "0" ? "" : date("d/m/Y à H:i", $courseenrolstartdate);
2019
        $data->courseenrolenddate = $courseenrolenddate == "0" ? "" : date("d/m/Y à H:i", $courseenrolenddate);
2020
        $data->courseurl = $CFG->wwwroot . '/course/view.php?id=' . $courseid;
2021
        $data->activityname = $cm->name;
2022
        $data->lmsurl = $CFG->wwwroot;
2023
        $data->lmsname = $SITE->fullname;
2024
        $data->interval = "";
2025
 
2026
        $msgbodyhtml = local_moofactory_notification_replace_variables($variables, $bodyhtml, $data);
2027
 
2028
        // Gestion des emails en copie
2029
        $copiedEmails = get_config('local_moofactory_notification', 'copiemaillevee_' . $courseid . '_' . $cm->id . '');
2030
 
2031
        $copiedEmails = str_replace(';', ',', $copiedEmails);
2032
        $copiedEmails = array_map('trim', explode(',', $copiedEmails)); // Supprimer les espaces inutiles
2033
        $copiedEmails = array_filter($copiedEmails, function ($email) {
2034
            return filter_var($email, FILTER_VALIDATE_EMAIL); // Valider chaque email
2035
        });
2036
 
2037
        $msg = new stdClass();
2038
        $msg->subject = $notif->subject;
2039
        $msg->from = "moofactory";
2040
        $msg->bodytext = "";
2041
        $msg->bodyhtml = $msgbodyhtml;
2042
        $msg->cc = $copiedEmails;
2043
 
2044
        //local_moofactory_notification_send_email($user, $msg, $courseid, 'levee_notification');
2045
        local_moofactory_notification_send_email_with_cc($user, $msg);
2046
        mtrace('Notification de levée de restriction envoyée.');
2047
    } else {
2048
        mtrace("Pas d'envoi : la notification est inexistante.");
2049
    }
2050
}