-
Notifications
You must be signed in to change notification settings - Fork 14
/
lib.php
430 lines (387 loc) · 16.4 KB
/
lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Auto-cohort local plugin for Moodle 3.5+
* @package local_cohortauto
* @copyright 2019 Catalyst IT
* @author David Thompson <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->dirroot . '/user/profile/lib.php');
require_once($CFG->dirroot . '/cohort/lib.php');
/**
* This function prepares complete $USER object for manipulation.
* Strip long strings and reject some keys.
*
* @author 2011 Andrew "Kama" ([email protected]) in auth_mcae
* @param array $data Complete $USER object with custom profile fields loaded
* @param string $replaceempty Placeholder value to use for empty entries.
* @return array Cleaned array created from $data
*/
function cohortauto_prepare_profile_data($data, $replaceempty = 'EMPTY') {
$reject = array('ajax_updatable_user_prefs', 'sesskey', 'preference', 'editing', 'access', 'message_lastpopup', 'enrol');
if (is_array($data) || is_object($data)) {
$newdata = array();
foreach ($data as $key => $val) {
if (!in_array($key, $reject)) {
if (is_array($val) || is_object($val)) {
$newdata[$key] = cohortauto_prepare_profile_data($val, $replaceempty);
} else {
if ($val === '' || $val === ' ' || $val === null) {
$str = ($val === false) ? 'false' : $replaceempty;
} else {
$str = ($val === true) ? 'true' : strip_tags("$val");
}
$newdata[$key] = substr($str, 0, 2048);
}
}
}
} else {
if ($data === '' || $data === ' ' || $data === null) {
$str = ($data === false) ? 'false' : $replaceempty;
} else {
$str = ($data === true) ? 'true' : strip_tags("$data");
}
$newdata = substr($str, 0, 100);
}
if (empty($newdata)) {
return $replaceempty;
} else {
return $newdata;
}
}
/**
* This function prepares help section for settings page.
*
* @author 2011 Andrew "Kama" ([email protected]) in auth_mcae
* @param array $data Result of cohortauto_prepare_profile_data function
* @param string $prefix String prefix
* @param array $result Variable to store result
*/
function cohortauto_print_profile_data($data, $prefix, &$result) {
if (is_array($data)) {
foreach ($data as $key => $val) {
if (is_array($val)) {
$field = ($prefix == '') ? "$key" : "$prefix.$key";
cohortauto_print_profile_data($val, $field, $result);
} else {
$field = ($prefix == '') ? "$key" : "$prefix.$key";
$title = format_string($val);
$result[] = "<span title=\"$title\">{{ $field }}</span>";
}
}
} else {
$title = format_string($data);
$result[] = "<span title=\"$title\">{{ $prefix }}</span>";
}
}
/**
* Event handler class for user profile information changes.
*
* This is usually triggered by user profile update events, but can also be
* triggered by CLI scripts.
*
* @copyright 2019 Catalyst IT
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class local_cohortauto_handler {
/**
* The component name of the plugin.
*
* Used in setting config, and in the cohort table to specify the
* managing component.
*/
const COMPONENT_NAME = 'local_cohortauto';
/**
* Constructor.
*/
public function __construct() {
global $CFG;
require_once($CFG->dirroot . '/lib/mustache/src/Mustache/Autoloader.php');
$this->config = get_config(self::COMPONENT_NAME);
Mustache_Autoloader::register();
$this->mustache = new Mustache_Engine;
}
/**
* Processes and stores configuration data for this plugin.
* $this->config->somefield
*
* @author 2011 Andrew "Kama" ([email protected]) in auth_mcae
* @param object $config The configuration object.
*/
public function process_config($config) {
// Set to defaults if undefined.
if (!isset($config->mainrule_fld)) {
$config->mainrule_fld = '';
}
if (!isset($config->secondrule_fld)) {
$config->secondrule_fld = 'n/a';
}
if (!isset($config->replace_arr)) {
$config->replace_arr = '';
}
if (!isset($config->delim)) {
$config->delim = 'CR+LF';
}
if (!isset($config->donttouchusers)) {
$config->donttouchusers = '';
}
if (!isset($config->enableunenrol)) {
$config->enableunenrol = 0;
}
if (!isset($config->allowedemaildomains)) {
$config->allowedemaildomains = '';
}
// Save settings.
set_config('mainrule_fld', $config->mainrule_fld, self::COMPONENT_NAME);
set_config('secondrule_fld', $config->secondrule_fld, self::COMPONENT_NAME);
set_config('replace_arr', $config->replace_arr, self::COMPONENT_NAME);
set_config('delim', $config->delim, self::COMPONENT_NAME);
set_config('donttouchusers', $config->donttouchusers, self::COMPONENT_NAME);
set_config('enableunenrol', $config->enableunenrol, self::COMPONENT_NAME);
set_config('allowedemaildomains', $config->allowedemaildomains, self::COMPONENT_NAME);
return true;
}
/**
* Check to see if a user's email address is included in the allow list.
*
* @param object $user The user object for the user sending emails.
* @return bool returns true if the user is included in the allow list.
*/
protected function included_in_allow_list($user) {
$alloweddomains = $this->config->allowedemaildomains;
$usersemaildomain = '';
if (!isset($alloweddomains) || empty(trim($alloweddomains))) {
// Allowed domains is empty / not configured - allow everyone.
return true;
}
$alloweddomains = array_map('trim', explode("\n", $alloweddomains));
if (isset($user->email)) {
$usersemaildomain = substr(strtolower($user->email), strpos($user->email, '@') + 1);
}
// Email is in the list of allowed domains for sending email.
if (in_array($usersemaildomain, $alloweddomains)) {
return true;
}
return false;
}
/**
* Hook for processing user profile changes.
*
* This method is called on user_created and user_updated events, where
* changes to user profiles may effect changes in cohort membership.
*
* Derived from auth.php in auth_mcae.
*
* @author David Thompson <[email protected]>
* @param object $user The user whose profile needs to be inspected
*/
public function user_profile_hook(&$user) {
global $DB;
$context = context_system::instance();
$uid = $user->id;
// Ignore users from don't_touch list.
$ignore = explode(",", $this->config->donttouchusers);
// Skip explicitly ignored users.
if (!empty($ignore) && array_search($user->username, $ignore) !== false) {
return;
};
// Ignore guests.
if (isguestuser($user)) {
return;
};
// Ignore users with no email address (probably UNIT tests.
if (empty($user->email)) {
return;
}
// Users email domain must be included in the allow list.
if (!$this->included_in_allow_list($user)) {
return;
}
// Get cohorts.
$params = array(
'contextid' => $context->id,
);
if ($this->config->enableunenrol == 1) {
$params['component'] = self::COMPONENT_NAME;
};
$cohorts = $DB->get_records('cohort', $params);
$cohortslist = array();
foreach ($cohorts as $cohort) {
$cohortslist[$cohort->id] = strip_tags("$cohort->name");
}
// Get advanced user data.
profile_load_data($user);
profile_load_custom_fields($user);
$userprofiledata = cohortauto_prepare_profile_data($user, $this->config->secondrule_fld);
if (empty($userprofiledata['email'])) {
$userprofiledata['email'] = array(
'full' => '',
'username' => '',
'domain' => '',
'rootdomain' => '',
);
} else {
// Additional values for email.
list($emailusername, $emaildomain) = explode("@", $userprofiledata['email']);
// Email root domain.
$emaildomainarray = explode('.', $emaildomain);
if (count($emaildomainarray) > 2) {
$emailrootdomain = $emaildomainarray[count($emaildomainarray) - 2] . '.' .
$emaildomainarray[count($emaildomainarray) - 1];
} else {
$emailrootdomain = $emaildomain;
}
$userprofiledata['email'] = array(
'full' => $userprofiledata['email'],
'username' => $emailusername,
'domain' => $emaildomain,
'rootdomain' => $emailrootdomain
);
}
// Set delimiter in use.
$delimiter = $this->config->delim;
$delim = strtr($delimiter, array('CR+LF' => chr(13).chr(10), 'CR' => chr(13), 'LF' => chr(10)));
// Calculate cohort names for user.
$replacementstemplate = $this->config->replace_arr;
$replacements = array();
if (!empty($replacementstemplate)) {
$replacementsarray = explode($delim, $replacementstemplate);
foreach ($replacementsarray as $replacement) {
list($key, $val) = explode("|", $replacement);
$replacements[$key] = $val;
};
};
// Generate cohort array.
$mainrule = $this->config->mainrule_fld;
$mainrulearray = array();
$templates = array();
if (!empty($mainrule)) {
$mainrulearray = explode($delim, $mainrule);
} else {
return; // Empty mainrule; no further processing to do.
};
// Find %split function.
foreach ($mainrulearray as $item) {
if (preg_match('/(?<full>%split\((?<fld>.*)\|(?<delim>.{1,5})\))/', $item, $splitparams)) {
// Split!
$splitparams['fldkey'] = sha1($splitparams['fld']);
$withruleinternalreplacement = preg_match(
'/(?<fld>.*)#(?<pattern>.*)#(?<replacement>\$\d{1,2})/',
$splitparams['fld'],
$ruleinternalreplacement
);
if ($withruleinternalreplacement) {
$splitparams['fld'] = $ruleinternalreplacement['fld'];
}
// Supporting . notation in fld definition.
$fieldvalue = '';
$userprofileaccessors = preg_split('/\./', $splitparams['fld'], -1, PREG_SPLIT_NO_EMPTY);
if (count($userprofileaccessors) > 1) {
$userprofiledataaccessed = $userprofiledata;
foreach ($userprofileaccessors as $accessor) {
if (!isset($userprofiledataaccessed[$accessor])) {
$fieldvalue = '';
break;
}
$userprofiledataaccessed = $userprofiledataaccessed[$accessor];
$fieldvalue = $userprofiledataaccessed;
}
} else {
$fieldvalue = $userprofiledata[$splitparams['fld']];
}
$parts = preg_split('/' . $splitparams['delim'] . '/', $fieldvalue, -1, PREG_SPLIT_NO_EMPTY);
foreach ($parts as $key => $val) {
$val = trim($val);
if ($withruleinternalreplacement) {
$val = preg_replace(
'/' . $ruleinternalreplacement['pattern'] . '/i',
$ruleinternalreplacement['replacement'],
$val
);
}
$userprofiledata[$splitparams['fldkey'] . "_$key"] = $val;
$templates[] = strtr($item, array("{$splitparams['full']}" => "{{ " . $splitparams['fldkey'] . "_$key }}"));
}
} else {
$templates[] = $item;
}
}
$processed = array();
$defaultvisibility = $this->config->visible;
// Moved here for performance.
$tolowercase = isset($this->config->lowercase) && !empty($this->config->lowercase);
// Apply templates and process the user's cohort memberships.
foreach ($templates as $cohort) {
// Transform templates into cohort names with Mustache.
$cohortname = $this->mustache->render($cohort, $userprofiledata);
// Apply symbol replacements as necessary.
$cohortname = (!empty($replacements)) ? strtr($cohortname, $replacements) : $cohortname;
// Skip empty cohort names. Users with no cohort name should not be assigned.
if ($cohortname == '') {
continue;
};
if ($tolowercase) {
$cohortname = strtolower($cohortname);
}
if ($user->suspended != 1) {
$cid = array_search($cohortname, $cohortslist);
if ($cid !== false) {
if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) {
cohort_add_member($cid, $user->id);
};
} else {
// Cohort with this name does not exist, so create a new one.
$newcohort = new stdClass();
$newcohort->name = $cohortname;
$newcohort->description = "created ".date("d-m-Y");
$newcohort->contextid = $context->id;
$newcohort->idnumber = '';
$newcohort->visible = $defaultvisibility;
if ($this->config->enableunenrol == 1) {
$newcohort->component = self::COMPONENT_NAME;
};
$cid = cohort_add_cohort($newcohort);
// Add new cohort into the list to avoid creating new ones with same name.
$cohortslist[$cid] = $cohortname;
// Add user to the new cohort.
cohort_add_member($cid, $user->id);
};
$processed[] = $cid;
};
};
// Remove users from cohorts if necessary.
if ($this->config->enableunenrol == 1) {
// List of cohorts, managed by this plugin, where the user is a member.
$sql = "SELECT DISTINCT c.id AS cid
FROM {cohort} c
JOIN {cohort_members} cm ON cm.cohortid = c.id
WHERE c.component = :component AND cm.userid = :userid";
$params = array(
'component' => self::COMPONENT_NAME,
'userid' => $uid,
);
$incohorts = $DB->get_records_sql($sql, $params);
foreach ($incohorts as $target) {
// Remove membership if it no longer matches a processed cohort.
if (array_search($target->cid, $processed) === false) {
cohort_remove_member($target->cid, $uid);
};
};
};
}
}