Proyectos de Subversion Moodle

Rev

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