MDL-45678 cache: renamed new cache and better comments
[moodle.git] / lib / enrollib.php
CommitLineData
df997f84
PS
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This library includes the basic parts of enrol api.
20 * It is available on each page.
21 *
78bfb562
PS
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Petr Skoda {@link http://skodak.org}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
26 */
27
78bfb562 28defined('MOODLE_INTERNAL') || die();
df997f84
PS
29
30/** Course enrol instance enabled. (used in enrol->status) */
31define('ENROL_INSTANCE_ENABLED', 0);
32
33/** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/
34define('ENROL_INSTANCE_DISABLED', 1);
35
36/** User is active participant (used in user_enrolments->status)*/
37define('ENROL_USER_ACTIVE', 0);
38
39/** User participation in course is suspended (used in user_enrolments->status) */
40define('ENROL_USER_SUSPENDED', 1);
41
bbfdff34 42/** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */
df997f84
PS
43define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
44
bbfdff34
PS
45/** The timestamp indicating forever */
46define('ENROL_MAX_TIMESTAMP', 2147483647);
47
34121765
PS
48/** When user disappears from external source, the enrolment is completely removed */
49define('ENROL_EXT_REMOVED_UNENROL', 0);
50
51/** When user disappears from external source, the enrolment is kept as is - one way sync */
52define('ENROL_EXT_REMOVED_KEEP', 1);
53
7a7b8a1f 54/** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */
f2a9be5f 55define('ENROL_RESTORE_TYPE', 'enrolrestore');
f2a9be5f 56
34121765
PS
57/**
58 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
59 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
60 * assignments, etc.
61 */
62define('ENROL_EXT_REMOVED_SUSPEND', 2);
63
64/**
65 * When user disappears from external source, the enrolment is suspended and roles assigned
66 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
67 * */
68define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
69
df997f84
PS
70/**
71 * Returns instances of enrol plugins
bbfdff34 72 * @param bool $enabled return enabled only
df997f84
PS
73 * @return array of enrol plugins name=>instance
74 */
75function enrol_get_plugins($enabled) {
76 global $CFG;
77
78 $result = array();
79
80 if ($enabled) {
81 // sorted by enabled plugin order
82 $enabled = explode(',', $CFG->enrol_plugins_enabled);
83 $plugins = array();
84 foreach ($enabled as $plugin) {
85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
86 }
87 } else {
88 // sorted alphabetically
bd3b3bba 89 $plugins = core_component::get_plugin_list('enrol');
df997f84
PS
90 ksort($plugins);
91 }
92
93 foreach ($plugins as $plugin=>$location) {
df997f84
PS
94 $class = "enrol_{$plugin}_plugin";
95 if (!class_exists($class)) {
d432e0f7
MA
96 if (!file_exists("$location/lib.php")) {
97 continue;
98 }
99 include_once("$location/lib.php");
100 if (!class_exists($class)) {
101 continue;
102 }
df997f84
PS
103 }
104
105 $result[$plugin] = new $class();
106 }
107
108 return $result;
109}
110
111/**
112 * Returns instance of enrol plugin
113 * @param string $name name of enrol plugin ('manual', 'guest', ...)
114 * @return enrol_plugin
115 */
116function enrol_get_plugin($name) {
117 global $CFG;
118
aff24313
PS
119 $name = clean_param($name, PARAM_PLUGIN);
120
121 if (empty($name)) {
122 // ignore malformed or missing plugin names completely
df997f84
PS
123 return null;
124 }
125
126 $location = "$CFG->dirroot/enrol/$name";
127
128 if (!file_exists("$location/lib.php")) {
129 return null;
130 }
131 include_once("$location/lib.php");
132 $class = "enrol_{$name}_plugin";
133 if (!class_exists($class)) {
134 return null;
135 }
136
137 return new $class();
138}
139
140/**
141 * Returns enrolment instances in given course.
142 * @param int $courseid
143 * @param bool $enabled
144 * @return array of enrol instances
145 */
146function enrol_get_instances($courseid, $enabled) {
147 global $DB, $CFG;
148
149 if (!$enabled) {
150 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
151 }
152
153 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
154
79721bd3 155 $enabled = explode(',', $CFG->enrol_plugins_enabled);
df997f84
PS
156 foreach ($result as $key=>$instance) {
157 if (!in_array($instance->enrol, $enabled)) {
158 unset($result[$key]);
159 continue;
160 }
161 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
162 // broken plugin
163 unset($result[$key]);
164 continue;
165 }
166 }
167
168 return $result;
169}
170
171/**
172 * Checks if a given plugin is in the list of enabled enrolment plugins.
173 *
174 * @param string $enrol Enrolment plugin name
175 * @return boolean Whether the plugin is enabled
176 */
177function enrol_is_enabled($enrol) {
178 global $CFG;
179
180 if (empty($CFG->enrol_plugins_enabled)) {
181 return false;
182 }
183 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
184}
185
186/**
187 * Check all the login enrolment information for the given user object
188 * by querying the enrolment plugins
189 *
e922fe23
PS
190 * This function may be very slow, use only once after log-in or login-as.
191 *
192 * @param stdClass $user
df997f84
PS
193 * @return void
194 */
195function enrol_check_plugins($user) {
196 global $CFG;
197
198 if (empty($user->id) or isguestuser($user)) {
199 // shortcut - there is no enrolment work for guests and not-logged-in users
200 return;
201 }
202
bcb368d9
PS
203 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
204 // which proved it was actually not necessary.
e384d2dc 205
df997f84
PS
206 static $inprogress = array(); // To prevent this function being called more than once in an invocation
207
208 if (!empty($inprogress[$user->id])) {
209 return;
210 }
211
212 $inprogress[$user->id] = true; // Set the flag
213
214 $enabled = enrol_get_plugins(true);
215
216 foreach($enabled as $enrol) {
217 $enrol->sync_user_enrolments($user);
218 }
219
220 unset($inprogress[$user->id]); // Unset the flag
221}
222
181991e7
PS
223/**
224 * Do these two students share any course?
225 *
226 * The courses has to be visible and enrolments has to be active,
227 * timestart and timeend restrictions are ignored.
228 *
61ab8f07
SH
229 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
230 * to true.
231 *
181991e7
PS
232 * @param stdClass|int $user1
233 * @param stdClass|int $user2
234 * @return bool
235 */
236function enrol_sharing_course($user1, $user2) {
61ab8f07 237 return enrol_get_shared_courses($user1, $user2, false, true);
181991e7
PS
238}
239
4b715423
SH
240/**
241 * Returns any courses shared by the two users
242 *
243 * The courses has to be visible and enrolments has to be active,
244 * timestart and timeend restrictions are ignored.
245 *
61ab8f07 246 * @global moodle_database $DB
4b715423
SH
247 * @param stdClass|int $user1
248 * @param stdClass|int $user2
61ab8f07
SH
249 * @param bool $preloadcontexts If set to true contexts for the returned courses
250 * will be preloaded.
251 * @param bool $checkexistsonly If set to true then this function will return true
252 * if the users share any courses and false if not.
253 * @return array|bool An array of courses that both users are enrolled in OR if
254 * $checkexistsonly set returns true if the users share any courses
255 * and false if not.
4b715423 256 */
61ab8f07 257function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
4b715423
SH
258 global $DB, $CFG;
259
5b244e2b
HD
260 $user1 = isset($user1->id) ? $user1->id : $user1;
261 $user2 = isset($user2->id) ? $user2->id : $user2;
4b715423
SH
262
263 if (empty($user1) or empty($user2)) {
264 return false;
265 }
266
267 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
268 return false;
269 }
270
271 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
272 $params['enabled'] = ENROL_INSTANCE_ENABLED;
273 $params['active1'] = ENROL_USER_ACTIVE;
274 $params['active2'] = ENROL_USER_ACTIVE;
275 $params['user1'] = $user1;
276 $params['user2'] = $user2;
277
278 $ctxselect = '';
279 $ctxjoin = '';
280 if ($preloadcontexts) {
2e4c0c91
FM
281 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
282 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
283 $params['contextlevel'] = CONTEXT_COURSE;
4b715423
SH
284 }
285
286 $sql = "SELECT c.* $ctxselect
287 FROM {course} c
288 JOIN (
289 SELECT DISTINCT c.id
290 FROM {enrol} e
291 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
292 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
293 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
294 WHERE e.status = :enabled AND e.enrol $plugins
295 ) ec ON ec.id = c.id
296 $ctxjoin";
4b715423 297
61ab8f07
SH
298 if ($checkexistsonly) {
299 return $DB->record_exists_sql($sql, $params);
300 } else {
301 $courses = $DB->get_records_sql($sql, $params);
302 if ($preloadcontexts) {
a55ad8f8 303 array_map('context_helper::preload_from_record', $courses);
61ab8f07
SH
304 }
305 return $courses;
306 }
4b715423
SH
307}
308
df997f84
PS
309/**
310 * This function adds necessary enrol plugins UI into the course edit form.
311 *
312 * @param MoodleQuickForm $mform
313 * @param object $data course edit form data
314 * @param object $context context of existing course or parent category if course does not exist
315 * @return void
316 */
317function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
318 $plugins = enrol_get_plugins(true);
319 if (!empty($data->id)) {
320 $instances = enrol_get_instances($data->id, false);
321 foreach ($instances as $instance) {
322 if (!isset($plugins[$instance->enrol])) {
323 continue;
324 }
325 $plugin = $plugins[$instance->enrol];
326 $plugin->course_edit_form($instance, $mform, $data, $context);
327 }
328 } else {
329 foreach ($plugins as $plugin) {
330 $plugin->course_edit_form(NULL, $mform, $data, $context);
331 }
332 }
333}
334
335/**
336 * Validate course edit form data
337 *
338 * @param array $data raw form data
339 * @param object $context context of existing course or parent category if course does not exist
340 * @return array errors array
341 */
342function enrol_course_edit_validation(array $data, $context) {
343 $errors = array();
344 $plugins = enrol_get_plugins(true);
345
346 if (!empty($data['id'])) {
347 $instances = enrol_get_instances($data['id'], false);
348 foreach ($instances as $instance) {
349 if (!isset($plugins[$instance->enrol])) {
350 continue;
351 }
352 $plugin = $plugins[$instance->enrol];
353 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
354 }
355 } else {
356 foreach ($plugins as $plugin) {
357 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
358 }
359 }
360
361 return $errors;
362}
363
364/**
365 * Update enrol instances after course edit form submission
366 * @param bool $inserted true means new course added, false course already existed
367 * @param object $course
368 * @param object $data form data
369 * @return void
370 */
371function enrol_course_updated($inserted, $course, $data) {
372 global $DB, $CFG;
373
374 $plugins = enrol_get_plugins(true);
375
376 foreach ($plugins as $plugin) {
377 $plugin->course_updated($inserted, $course, $data);
378 }
379}
380
381/**
382 * Add navigation nodes
383 * @param navigation_node $coursenode
384 * @param object $course
385 * @return void
386 */
387function enrol_add_course_navigation(navigation_node $coursenode, $course) {
6e4c374d 388 global $CFG;
df997f84 389
b0c6dc1c 390 $coursecontext = context_course::instance($course->id);
df997f84
PS
391
392 $instances = enrol_get_instances($course->id, true);
393 $plugins = enrol_get_plugins(true);
394
395 // we do not want to break all course pages if there is some borked enrol plugin, right?
396 foreach ($instances as $k=>$instance) {
397 if (!isset($plugins[$instance->enrol])) {
398 unset($instances[$k]);
399 }
400 }
401
f5ce6b71 402 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
df997f84
PS
403
404 if ($course->id != SITEID) {
f5ce6b71 405 // list all participants - allows assigning roles, groups, etc.
df997f84
PS
406 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
407 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
c42651d6 408 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
df997f84
PS
409 }
410
411 // manage enrol plugin instances
412 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
413 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
414 } else {
415 $url = NULL;
416 }
f5ce6b71 417 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
df997f84
PS
418
419 // each instance decides how to configure itself or how many other nav items are exposed
420 foreach ($instances as $instance) {
421 if (!isset($plugins[$instance->enrol])) {
422 continue;
423 }
424 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
425 }
426
427 if (!$url) {
428 $instancesnode->trim_if_empty();
429 }
430 }
431
432 // Manage groups in this course or even frontpage
433 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
434 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
435 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
436 }
437
438 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
439 // Override roles
440 if (has_capability('moodle/role:review', $coursecontext)) {
441 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
442 } else {
443 $url = NULL;
444 }
f5ce6b71 445 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
df997f84
PS
446
447 // Add assign or override roles if allowed
448 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
449 if (has_capability('moodle/role:assign', $coursecontext)) {
450 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
fbb207c5 451 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
df997f84
PS
452 }
453 }
454 // Check role permissions
455 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
456 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
f5ce6b71 457 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
df997f84
PS
458 }
459 }
460
461 // Deal somehow with users that are not enrolled but still got a role somehow
462 if ($course->id != SITEID) {
463 //TODO, create some new UI for role assignments at course level
288e7b09 464 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
df997f84 465 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
fbb207c5 466 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
df997f84
PS
467 }
468 }
469
470 // just in case nothing was actually added
471 $usersnode->trim_if_empty();
472
473 if ($course->id != SITEID) {
6813cdf7 474 if (isguestuser() or !isloggedin()) {
39ec18db 475 // guest account can not be enrolled - no links for them
6813cdf7 476 } else if (is_enrolled($coursecontext)) {
39ec18db 477 // unenrol link if possible
217d0397
PS
478 foreach ($instances as $instance) {
479 if (!isset($plugins[$instance->enrol])) {
480 continue;
481 }
482 $plugin = $plugins[$instance->enrol];
483 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
8ebbb06a
SH
484 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
485 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
217d0397
PS
486 break;
487 //TODO. deal with multiple unenrol links - not likely case, but still...
488 }
df997f84 489 }
217d0397 490 } else {
39ec18db 491 // enrol link if possible
217d0397
PS
492 if (is_viewing($coursecontext)) {
493 // better not show any enrol link, this is intended for managers and inspectors
494 } else {
495 foreach ($instances as $instance) {
496 if (!isset($plugins[$instance->enrol])) {
497 continue;
498 }
499 $plugin = $plugins[$instance->enrol];
500 if ($plugin->show_enrolme_link($instance)) {
501 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
8ebbb06a
SH
502 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
503 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
217d0397
PS
504 break;
505 }
506 }
df997f84
PS
507 }
508 }
df997f84
PS
509 }
510}
511
512/**
513 * Returns list of courses current $USER is enrolled in and can access
514 *
515 * - $fields is an array of field names to ADD
516 * so name the fields you really need, which will
517 * be added and uniq'd
518 *
eb6f592a 519 * @param string|array $fields
df997f84
PS
520 * @param string $sort
521 * @param int $limit max number of courses
522 * @return array
523 */
524function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
525 global $DB, $USER;
526
527 // Guest account does not have any courses
528 if (isguestuser() or !isloggedin()) {
529 return(array());
530 }
531
532 $basefields = array('id', 'category', 'sortorder',
533 'shortname', 'fullname', 'idnumber',
534 'startdate', 'visible',
4a3fb71c 535 'groupmode', 'groupmodeforce', 'cacherev');
df997f84
PS
536
537 if (empty($fields)) {
538 $fields = $basefields;
539 } else if (is_string($fields)) {
540 // turn the fields from a string to an array
541 $fields = explode(',', $fields);
542 $fields = array_map('trim', $fields);
543 $fields = array_unique(array_merge($basefields, $fields));
544 } else if (is_array($fields)) {
545 $fields = array_unique(array_merge($basefields, $fields));
546 } else {
547 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
548 }
549 if (in_array('*', $fields)) {
550 $fields = array('*');
551 }
552
553 $orderby = "";
554 $sort = trim($sort);
555 if (!empty($sort)) {
556 $rawsorts = explode(',', $sort);
557 $sorts = array();
558 foreach ($rawsorts as $rawsort) {
559 $rawsort = trim($rawsort);
560 if (strpos($rawsort, 'c.') === 0) {
561 $rawsort = substr($rawsort, 2);
562 }
563 $sorts[] = trim($rawsort);
564 }
565 $sort = 'c.'.implode(',c.', $sorts);
566 $orderby = "ORDER BY $sort";
567 }
568
569 $wheres = array("c.id <> :siteid");
570 $params = array('siteid'=>SITEID);
571
572 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
573 // list _only_ this course - anything else is asking for trouble...
574 $wheres[] = "courseid = :loginas";
575 $params['loginas'] = $USER->loginascontext->instanceid;
576 }
577
578 $coursefields = 'c.' .join(',c.', $fields);
2e4c0c91
FM
579 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
581 $params['contextlevel'] = CONTEXT_COURSE;
4129338c 582 $wheres = implode(" AND ", $wheres);
df997f84 583
4129338c
PS
584 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
585 $sql = "SELECT $coursefields $ccselect
df997f84 586 FROM {course} c
4129338c
PS
587 JOIN (SELECT DISTINCT e.courseid
588 FROM {enrol} e
589 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
590 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
591 ) en ON (en.courseid = c.id)
df997f84 592 $ccjoin
4129338c 593 WHERE $wheres
df997f84
PS
594 $orderby";
595 $params['userid'] = $USER->id;
596 $params['active'] = ENROL_USER_ACTIVE;
597 $params['enabled'] = ENROL_INSTANCE_ENABLED;
598 $params['now1'] = round(time(), -2); // improves db caching
599 $params['now2'] = $params['now1'];
600
601 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
602
603 // preload contexts and check visibility
604 foreach ($courses as $id=>$course) {
db314f34 605 context_helper::preload_from_record($course);
df997f84 606 if (!$course->visible) {
b0c6dc1c 607 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
55880bdd 608 unset($courses[$id]);
df997f84
PS
609 continue;
610 }
611 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
55880bdd 612 unset($courses[$id]);
df997f84
PS
613 continue;
614 }
615 }
616 $courses[$id] = $course;
617 }
618
619 //wow! Is that really all? :-D
620
621 return $courses;
622}
623
bf423bb1
PS
624/**
625 * Returns course enrolment information icons.
626 *
627 * @param object $course
628 * @param array $instances enrol instances of this course, improves performance
629 * @return array of pix_icon
630 */
631function enrol_get_course_info_icons($course, array $instances = NULL) {
632 $icons = array();
633 if (is_null($instances)) {
634 $instances = enrol_get_instances($course->id, true);
635 }
636 $plugins = enrol_get_plugins(true);
637 foreach ($plugins as $name => $plugin) {
638 $pis = array();
639 foreach ($instances as $instance) {
640 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
641 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
642 continue;
643 }
644 if ($instance->enrol == $name) {
645 $pis[$instance->id] = $instance;
646 }
647 }
648 if ($pis) {
649 $icons = array_merge($icons, $plugin->get_info_icons($pis));
650 }
651 }
652 return $icons;
653}
654
655/**
656 * Returns course enrolment detailed information.
657 *
658 * @param object $course
659 * @return array of html fragments - can be used to construct lists
660 */
661function enrol_get_course_description_texts($course) {
662 $lines = array();
663 $instances = enrol_get_instances($course->id, true);
664 $plugins = enrol_get_plugins(true);
665 foreach ($instances as $instance) {
64942a9d 666 if (!isset($plugins[$instance->enrol])) {
bf423bb1
PS
667 //weird
668 continue;
669 }
64942a9d 670 $plugin = $plugins[$instance->enrol];
bf423bb1
PS
671 $text = $plugin->get_description_text($instance);
672 if ($text !== NULL) {
673 $lines[] = $text;
674 }
675 }
676 return $lines;
677}
678
df997f84
PS
679/**
680 * Returns list of courses user is enrolled into.
9ffd29ce 681 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
df997f84
PS
682 *
683 * - $fields is an array of fieldnames to ADD
684 * so name the fields you really need, which will
685 * be added and uniq'd
686 *
687 * @param int $userid
688 * @param bool $onlyactive return only active enrolments in courses user may see
eb6f592a 689 * @param string|array $fields
df997f84
PS
690 * @param string $sort
691 * @return array
692 */
693function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
694 global $DB;
695
9ffd29ce
AA
696 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
697
698 // preload contexts and check visibility
699 if ($onlyactive) {
700 foreach ($courses as $id=>$course) {
db314f34 701 context_helper::preload_from_record($course);
9ffd29ce
AA
702 if (!$course->visible) {
703 if (!$context = context_course::instance($id)) {
704 unset($courses[$id]);
705 continue;
706 }
707 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
708 unset($courses[$id]);
709 continue;
710 }
711 }
712 }
713 }
714
715 return $courses;
716
717}
718
05f6da14
719/**
720 * Can user access at least one enrolled course?
721 *
722 * Cheat if necessary, but find out as fast as possible!
723 *
724 * @param int|stdClass $user null means use current user
725 * @return bool
726 */
727function enrol_user_sees_own_courses($user = null) {
728 global $USER;
729
730 if ($user === null) {
731 $user = $USER;
732 }
733 $userid = is_object($user) ? $user->id : $user;
734
735 // Guest account does not have any courses
736 if (isguestuser($userid) or empty($userid)) {
737 return false;
738 }
739
740 // Let's cheat here if this is the current user,
741 // if user accessed any course recently, then most probably
742 // we do not need to query the database at all.
743 if ($USER->id == $userid) {
744 if (!empty($USER->enrol['enrolled'])) {
745 foreach ($USER->enrol['enrolled'] as $until) {
746 if ($until > time()) {
747 return true;
748 }
749 }
750 }
751 }
752
753 // Now the slow way.
754 $courses = enrol_get_all_users_courses($userid, true);
755 foreach($courses as $course) {
756 if ($course->visible) {
757 return true;
758 }
759 context_helper::preload_from_record($course);
760 $context = context_course::instance($course->id);
761 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
762 return true;
763 }
764 }
765
766 return false;
767}
768
9ffd29ce
AA
769/**
770 * Returns list of courses user is enrolled into without any capability checks
771 * - $fields is an array of fieldnames to ADD
772 * so name the fields you really need, which will
773 * be added and uniq'd
774 *
775 * @param int $userid
776 * @param bool $onlyactive return only active enrolments in courses user may see
777 * @param string|array $fields
778 * @param string $sort
779 * @return array
780 */
781function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
782 global $DB;
783
df997f84 784 // Guest account does not have any courses
87163782 785 if (isguestuser($userid) or empty($userid)) {
df997f84
PS
786 return(array());
787 }
788
789 $basefields = array('id', 'category', 'sortorder',
9ffd29ce
AA
790 'shortname', 'fullname', 'idnumber',
791 'startdate', 'visible',
792 'groupmode', 'groupmodeforce');
df997f84
PS
793
794 if (empty($fields)) {
795 $fields = $basefields;
796 } else if (is_string($fields)) {
797 // turn the fields from a string to an array
798 $fields = explode(',', $fields);
799 $fields = array_map('trim', $fields);
800 $fields = array_unique(array_merge($basefields, $fields));
801 } else if (is_array($fields)) {
802 $fields = array_unique(array_merge($basefields, $fields));
803 } else {
804 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
805 }
806 if (in_array('*', $fields)) {
807 $fields = array('*');
808 }
809
810 $orderby = "";
811 $sort = trim($sort);
812 if (!empty($sort)) {
813 $rawsorts = explode(',', $sort);
814 $sorts = array();
815 foreach ($rawsorts as $rawsort) {
816 $rawsort = trim($rawsort);
817 if (strpos($rawsort, 'c.') === 0) {
818 $rawsort = substr($rawsort, 2);
819 }
820 $sorts[] = trim($rawsort);
821 }
822 $sort = 'c.'.implode(',c.', $sorts);
823 $orderby = "ORDER BY $sort";
824 }
825
df997f84
PS
826 $params = array('siteid'=>SITEID);
827
828 if ($onlyactive) {
4129338c 829 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
df997f84
PS
830 $params['now1'] = round(time(), -2); // improves db caching
831 $params['now2'] = $params['now1'];
832 $params['active'] = ENROL_USER_ACTIVE;
833 $params['enabled'] = ENROL_INSTANCE_ENABLED;
4129338c
PS
834 } else {
835 $subwhere = "";
df997f84
PS
836 }
837
838 $coursefields = 'c.' .join(',c.', $fields);
2e4c0c91
FM
839 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
840 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
841 $params['contextlevel'] = CONTEXT_COURSE;
df997f84 842
4129338c
PS
843 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
844 $sql = "SELECT $coursefields $ccselect
df997f84 845 FROM {course} c
4129338c
PS
846 JOIN (SELECT DISTINCT e.courseid
847 FROM {enrol} e
848 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
849 $subwhere
850 ) en ON (en.courseid = c.id)
df997f84 851 $ccjoin
4129338c 852 WHERE c.id <> :siteid
df997f84 853 $orderby";
87163782 854 $params['userid'] = $userid;
df997f84
PS
855
856 $courses = $DB->get_records_sql($sql, $params);
857
df997f84 858 return $courses;
df997f84
PS
859}
860
9ffd29ce
AA
861
862
df997f84
PS
863/**
864 * Called when user is about to be deleted.
865 * @param object $user
866 * @return void
867 */
868function enrol_user_delete($user) {
869 global $DB;
870
871 $plugins = enrol_get_plugins(true);
872 foreach ($plugins as $plugin) {
873 $plugin->user_delete($user);
874 }
875
876 // force cleanup of all broken enrolments
877 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
878}
879
582bae08
PS
880/**
881 * Called when course is about to be deleted.
bbfdff34 882 * @param stdClass $course
582bae08
PS
883 * @return void
884 */
885function enrol_course_delete($course) {
886 global $DB;
887
888 $instances = enrol_get_instances($course->id, false);
889 $plugins = enrol_get_plugins(true);
890 foreach ($instances as $instance) {
891 if (isset($plugins[$instance->enrol])) {
892 $plugins[$instance->enrol]->delete_instance($instance);
893 }
894 // low level delete in case plugin did not do it
895 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
896 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
897 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
898 $DB->delete_records('enrol', array('id'=>$instance->id));
899 }
900}
901
df997f84
PS
902/**
903 * Try to enrol user via default internal auth plugin.
904 *
905 * For now this is always using the manual enrol plugin...
906 *
907 * @param $courseid
908 * @param $userid
909 * @param $roleid
910 * @param $timestart
911 * @param $timeend
912 * @return bool success
913 */
914function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
915 global $DB;
916
917 //note: this is hardcoded to manual plugin for now
918
919 if (!enrol_is_enabled('manual')) {
920 return false;
921 }
922
923 if (!$enrol = enrol_get_plugin('manual')) {
924 return false;
925 }
926 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
927 return false;
928 }
929 $instance = reset($instances);
930
931 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
932
933 return true;
934}
935
45ff8a80
PS
936/**
937 * Is there a chance users might self enrol
938 * @param int $courseid
939 * @return bool
940 */
941function enrol_selfenrol_available($courseid) {
942 $result = false;
943
944 $plugins = enrol_get_plugins(true);
945 $enrolinstances = enrol_get_instances($courseid, true);
946 foreach($enrolinstances as $instance) {
947 if (!isset($plugins[$instance->enrol])) {
948 continue;
949 }
950 if ($instance->enrol === 'guest') {
951 // blacklist known temporary guest plugins
952 continue;
953 }
954 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
955 $result = true;
956 break;
957 }
958 }
959
960 return $result;
961}
962
bbfdff34
PS
963/**
964 * This function returns the end of current active user enrolment.
965 *
966 * It deals correctly with multiple overlapping user enrolments.
967 *
968 * @param int $courseid
969 * @param int $userid
970 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
971 */
972function enrol_get_enrolment_end($courseid, $userid) {
973 global $DB;
974
975 $sql = "SELECT ue.*
976 FROM {user_enrolments} ue
977 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
978 JOIN {user} u ON u.id = ue.userid
979 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
980 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
981
982 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
983 return false;
984 }
985
986 $changes = array();
987
988 foreach ($enrolments as $ue) {
989 $start = (int)$ue->timestart;
990 $end = (int)$ue->timeend;
991 if ($end != 0 and $end < $start) {
992 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
993 continue;
994 }
995 if (isset($changes[$start])) {
996 $changes[$start] = $changes[$start] + 1;
997 } else {
998 $changes[$start] = 1;
999 }
1000 if ($end === 0) {
1001 // no end
1002 } else if (isset($changes[$end])) {
1003 $changes[$end] = $changes[$end] - 1;
1004 } else {
1005 $changes[$end] = -1;
1006 }
1007 }
1008
1009 // let's sort then enrolment starts&ends and go through them chronologically,
1010 // looking for current status and the next future end of enrolment
1011 ksort($changes);
1012
1013 $now = time();
1014 $current = 0;
1015 $present = null;
1016
1017 foreach ($changes as $time => $change) {
1018 if ($time > $now) {
1019 if ($present === null) {
1020 // we have just went past current time
1021 $present = $current;
1022 if ($present < 1) {
1023 // no enrolment active
1024 return false;
1025 }
1026 }
1027 if ($present !== null) {
1028 // we are already in the future - look for possible end
1029 if ($current + $change < 1) {
1030 return $time;
1031 }
1032 }
1033 }
1034 $current += $change;
1035 }
1036
1037 if ($current > 0) {
1038 return 0;
1039 } else {
1040 return false;
1041 }
1042}
1043
12c92bca
PS
1044/**
1045 * Is current user accessing course via this enrolment method?
1046 *
1047 * This is intended for operations that are going to affect enrol instances.
1048 *
1049 * @param stdClass $instance enrol instance
1050 * @return bool
1051 */
1052function enrol_accessing_via_instance(stdClass $instance) {
1053 global $DB, $USER;
1054
1055 if (empty($instance->id)) {
1056 return false;
1057 }
1058
1059 if (is_siteadmin()) {
1060 // Admins may go anywhere.
1061 return false;
1062 }
1063
1064 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1065}
1066
bbfdff34 1067
df997f84
PS
1068/**
1069 * All enrol plugins should be based on this class,
1070 * this is also the main source of documentation.
1071 */
1072abstract class enrol_plugin {
1073 protected $config = null;
1074
1075 /**
1076 * Returns name of this enrol plugin
1077 * @return string
1078 */
1079 public function get_name() {
bf423bb1 1080 // second word in class is always enrol name, sorry, no fancy plugin names with _
df997f84
PS
1081 $words = explode('_', get_class($this));
1082 return $words[1];
1083 }
1084
1085 /**
1086 * Returns localised name of enrol instance
1087 *
1088 * @param object $instance (null is accepted too)
1089 * @return string
1090 */
1091 public function get_instance_name($instance) {
1092 if (empty($instance->name)) {
1093 $enrol = $this->get_name();
1094 return get_string('pluginname', 'enrol_'.$enrol);
1095 } else {
b0c6dc1c 1096 $context = context_course::instance($instance->courseid);
54475ccb 1097 return format_string($instance->name, true, array('context'=>$context));
df997f84
PS
1098 }
1099 }
1100
bf423bb1
PS
1101 /**
1102 * Returns optional enrolment information icons.
1103 *
1104 * This is used in course list for quick overview of enrolment options.
1105 *
1106 * We are not using single instance parameter because sometimes
1107 * we might want to prevent icon repetition when multiple instances
1108 * of one type exist. One instance may also produce several icons.
1109 *
1110 * @param array $instances all enrol instances of this type in one course
1111 * @return array of pix_icon
1112 */
1113 public function get_info_icons(array $instances) {
1114 return array();
1115 }
1116
1117 /**
1118 * Returns optional enrolment instance description text.
1119 *
1120 * This is used in detailed course information.
1121 *
1122 *
1123 * @param object $instance
1124 * @return string short html text
1125 */
1126 public function get_description_text($instance) {
1127 return null;
1128 }
1129
df997f84
PS
1130 /**
1131 * Makes sure config is loaded and cached.
1132 * @return void
1133 */
1134 protected function load_config() {
1135 if (!isset($this->config)) {
1136 $name = $this->get_name();
820a8188 1137 $this->config = get_config("enrol_$name");
df997f84
PS
1138 }
1139 }
1140
1141 /**
1142 * Returns plugin config value
1143 * @param string $name
1144 * @param string $default value if config does not exist yet
1145 * @return string value or default
1146 */
1147 public function get_config($name, $default = NULL) {
1148 $this->load_config();
1149 return isset($this->config->$name) ? $this->config->$name : $default;
1150 }
1151
1152 /**
1153 * Sets plugin config value
1154 * @param string $name name of config
1155 * @param string $value string config value, null means delete
1156 * @return string value
1157 */
1158 public function set_config($name, $value) {
47811589 1159 $pluginname = $this->get_name();
df997f84
PS
1160 $this->load_config();
1161 if ($value === NULL) {
1162 unset($this->config->$name);
1163 } else {
1164 $this->config->$name = $value;
1165 }
47811589 1166 set_config($name, $value, "enrol_$pluginname");
df997f84
PS
1167 }
1168
1169 /**
1170 * Does this plugin assign protected roles are can they be manually removed?
1171 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1172 */
1173 public function roles_protected() {
1174 return true;
1175 }
1176
91b99e80
PS
1177 /**
1178 * Does this plugin allow manual enrolments?
1179 *
1180 * @param stdClass $instance course enrol instance
1181 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1182 *
282b5cc7 1183 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
91b99e80
PS
1184 */
1185 public function allow_enrol(stdClass $instance) {
1186 return false;
1187 }
1188
df997f84 1189 /**
282b5cc7 1190 * Does this plugin allow manual unenrolment of all users?
91b99e80 1191 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
df997f84 1192 *
282b5cc7
PS
1193 * @param stdClass $instance course enrol instance
1194 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
df997f84
PS
1195 */
1196 public function allow_unenrol(stdClass $instance) {
1197 return false;
1198 }
1199
282b5cc7
PS
1200 /**
1201 * Does this plugin allow manual unenrolment of a specific user?
1202 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1203 *
1204 * This is useful especially for synchronisation plugins that
1205 * do suspend instead of full unenrolment.
1206 *
1207 * @param stdClass $instance course enrol instance
1208 * @param stdClass $ue record from user_enrolments table, specifies user
1209 *
1210 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1211 */
1212 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1213 return $this->allow_unenrol($instance);
1214 }
1215
df997f84
PS
1216 /**
1217 * Does this plugin allow manual changes in user_enrolments table?
1218 *
91b99e80 1219 * All plugins allowing this must implement 'enrol/xxx:manage' capability
df997f84
PS
1220 *
1221 * @param stdClass $instance course enrol instance
1222 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1223 */
1224 public function allow_manage(stdClass $instance) {
1225 return false;
1226 }
1227
217d0397
PS
1228 /**
1229 * Does this plugin support some way to user to self enrol?
1230 *
1231 * @param stdClass $instance course enrol instance
1232 *
1233 * @return bool - true means show "Enrol me in this course" link in course UI
1234 */
1235 public function show_enrolme_link(stdClass $instance) {
1236 return false;
1237 }
1238
df997f84
PS
1239 /**
1240 * Attempt to automatically enrol current user in course without any interaction,
1241 * calling code has to make sure the plugin and instance are active.
1242 *
ed1d72ea
SH
1243 * This should return either a timestamp in the future or false.
1244 *
df997f84 1245 * @param stdClass $instance course enrol instance
df997f84
PS
1246 * @return bool|int false means not enrolled, integer means timeend
1247 */
1248 public function try_autoenrol(stdClass $instance) {
1249 global $USER;
1250
1251 return false;
1252 }
1253
1254 /**
1255 * Attempt to automatically gain temporary guest access to course,
1256 * calling code has to make sure the plugin and instance are active.
1257 *
ed1d72ea
SH
1258 * This should return either a timestamp in the future or false.
1259 *
df997f84 1260 * @param stdClass $instance course enrol instance
df997f84
PS
1261 * @return bool|int false means no guest access, integer means timeend
1262 */
1263 public function try_guestaccess(stdClass $instance) {
1264 global $USER;
1265
1266 return false;
1267 }
1268
1269 /**
1270 * Enrol user into course via enrol instance.
1271 *
1272 * @param stdClass $instance
1273 * @param int $userid
1274 * @param int $roleid optional role id
2a6dcb72
PS
1275 * @param int $timestart 0 means unknown
1276 * @param int $timeend 0 means forever
f2a9be5f 1277 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
ef8a733a 1278 * @param bool $recovergrades restore grade history
df997f84
PS
1279 * @return void
1280 */
ef8a733a 1281 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
df997f84
PS
1282 global $DB, $USER, $CFG; // CFG necessary!!!
1283
1284 if ($instance->courseid == SITEID) {
1285 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1286 }
1287
1288 $name = $this->get_name();
1289 $courseid = $instance->courseid;
1290
1291 if ($instance->enrol !== $name) {
1292 throw new coding_exception('invalid enrol instance!');
1293 }
b0c6dc1c 1294 $context = context_course::instance($instance->courseid, MUST_EXIST);
ef8a733a
CF
1295 if (!isset($recovergrades)) {
1296 $recovergrades = $CFG->recovergradesdefault;
1297 }
df997f84
PS
1298
1299 $inserted = false;
358fb4dc 1300 $updated = false;
df997f84 1301 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
d587f077 1302 //only update if timestart or timeend or status are different.
ae8c1f3d 1303 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
bb78e249 1304 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
df997f84
PS
1305 }
1306 } else {
365a5941 1307 $ue = new stdClass();
df997f84 1308 $ue->enrolid = $instance->id;
ae8c1f3d 1309 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
df997f84
PS
1310 $ue->userid = $userid;
1311 $ue->timestart = $timestart;
1312 $ue->timeend = $timeend;
6006774c 1313 $ue->modifierid = $USER->id;
2a6dcb72
PS
1314 $ue->timecreated = time();
1315 $ue->timemodified = $ue->timecreated;
df997f84
PS
1316 $ue->id = $DB->insert_record('user_enrolments', $ue);
1317
1318 $inserted = true;
1319 }
1320
df997f84 1321 if ($inserted) {
bb78e249
RT
1322 // Trigger event.
1323 $event = \core\event\user_enrolment_created::create(
1324 array(
1325 'objectid' => $ue->id,
1326 'courseid' => $courseid,
1327 'context' => $context,
1328 'relateduserid' => $ue->userid,
1329 'other' => array('enrol' => $name)
1330 )
1331 );
1332 $event->trigger();
df997f84
PS
1333 }
1334
0c2701fd 1335 if ($roleid) {
bbfdff34 1336 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
0c2701fd
PS
1337 if ($this->roles_protected()) {
1338 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1339 } else {
1340 role_assign($roleid, $userid, $context->id);
1341 }
1342 }
1343
ef8a733a
CF
1344 // Recover old grades if present.
1345 if ($recovergrades) {
1346 require_once("$CFG->libdir/gradelib.php");
1347 grade_recover_history_grades($userid, $courseid);
1348 }
1349
bbfdff34 1350 // reset current user enrolment caching
df997f84
PS
1351 if ($userid == $USER->id) {
1352 if (isset($USER->enrol['enrolled'][$courseid])) {
1353 unset($USER->enrol['enrolled'][$courseid]);
1354 }
1355 if (isset($USER->enrol['tempguest'][$courseid])) {
1356 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1357 remove_temp_course_roles($context);
df997f84
PS
1358 }
1359 }
1360 }
1361
1362 /**
1363 * Store user_enrolments changes and trigger event.
1364 *
358fb4dc
PS
1365 * @param stdClass $instance
1366 * @param int $userid
df997f84
PS
1367 * @param int $status
1368 * @param int $timestart
1369 * @param int $timeend
1370 * @return void
1371 */
1372 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1373 global $DB, $USER;
1374
1375 $name = $this->get_name();
1376
1377 if ($instance->enrol !== $name) {
1378 throw new coding_exception('invalid enrol instance!');
1379 }
1380
1381 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1382 // weird, user not enrolled
1383 return;
1384 }
1385
1386 $modified = false;
1387 if (isset($status) and $ue->status != $status) {
1388 $ue->status = $status;
1389 $modified = true;
1390 }
1391 if (isset($timestart) and $ue->timestart != $timestart) {
1392 $ue->timestart = $timestart;
1393 $modified = true;
1394 }
1395 if (isset($timeend) and $ue->timeend != $timeend) {
1396 $ue->timeend = $timeend;
1397 $modified = true;
1398 }
1399
1400 if (!$modified) {
1401 // no change
1402 return;
1403 }
1404
1405 $ue->modifierid = $USER->id;
1406 $DB->update_record('user_enrolments', $ue);
bbfdff34 1407 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
df997f84 1408
eeb9ee8e 1409 // Invalidate core_access cache for get_suspended_userids.
03ecddb4 1410 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
eeb9ee8e 1411
bb78e249
RT
1412 // Trigger event.
1413 $event = \core\event\user_enrolment_updated::create(
1414 array(
1415 'objectid' => $ue->id,
1416 'courseid' => $instance->courseid,
1417 'context' => context_course::instance($instance->courseid),
1418 'relateduserid' => $ue->userid,
1419 'other' => array('enrol' => $name)
1420 )
1421 );
1422 $event->trigger();
df997f84
PS
1423 }
1424
1425 /**
1426 * Unenrol user from course,
1427 * the last unenrolment removes all remaining roles.
1428 *
1429 * @param stdClass $instance
1430 * @param int $userid
1431 * @return void
1432 */
1433 public function unenrol_user(stdClass $instance, $userid) {
1434 global $CFG, $USER, $DB;
7881024e 1435 require_once("$CFG->dirroot/group/lib.php");
df997f84
PS
1436
1437 $name = $this->get_name();
1438 $courseid = $instance->courseid;
1439
1440 if ($instance->enrol !== $name) {
1441 throw new coding_exception('invalid enrol instance!');
1442 }
b0c6dc1c 1443 $context = context_course::instance($instance->courseid, MUST_EXIST);
df997f84
PS
1444
1445 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1446 // weird, user not enrolled
1447 return;
1448 }
1449
7881024e
PS
1450 // Remove all users groups linked to this enrolment instance.
1451 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
1452 foreach ($gms as $gm) {
1453 groups_remove_member($gm->groupid, $gm->userid);
1454 }
1455 }
1456
df997f84
PS
1457 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1458 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1459
1460 // add extra info and trigger event
1461 $ue->courseid = $courseid;
1462 $ue->enrol = $name;
1463
1464 $sql = "SELECT 'x'
1465 FROM {user_enrolments} ue
1466 JOIN {enrol} e ON (e.id = ue.enrolid)
7881024e 1467 WHERE ue.userid = :userid AND e.courseid = :courseid";
df997f84
PS
1468 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1469 $ue->lastenrol = false;
7881024e 1470
df997f84
PS
1471 } else {
1472 // the big cleanup IS necessary!
df997f84
PS
1473 require_once("$CFG->libdir/gradelib.php");
1474
1475 // remove all remaining roles
1476 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1477
1478 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1479 groups_delete_group_members($courseid, $userid);
1480
1481 grade_user_unenrol($courseid, $userid);
1482
1483 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1484
7d2800fb 1485 $ue->lastenrol = true; // means user not enrolled any more
df997f84 1486 }
bb78e249
RT
1487 // Trigger event.
1488 $event = \core\event\user_enrolment_deleted::create(
1489 array(
1490 'courseid' => $courseid,
1491 'context' => $context,
1492 'relateduserid' => $ue->userid,
4fb6600e 1493 'objectid' => $ue->id,
bb78e249
RT
1494 'other' => array(
1495 'userenrolment' => (array)$ue,
1496 'enrol' => $name
1497 )
1498 )
1499 );
1500 $event->trigger();
bbfdff34
PS
1501 // reset all enrol caches
1502 $context->mark_dirty();
1503
1504 // reset current user enrolment caching
df997f84
PS
1505 if ($userid == $USER->id) {
1506 if (isset($USER->enrol['enrolled'][$courseid])) {
1507 unset($USER->enrol['enrolled'][$courseid]);
1508 }
1509 if (isset($USER->enrol['tempguest'][$courseid])) {
1510 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1511 remove_temp_course_roles($context);
df997f84
PS
1512 }
1513 }
1514 }
1515
1516 /**
1517 * Forces synchronisation of user enrolments.
1518 *
1519 * This is important especially for external enrol plugins,
1520 * this function is called for all enabled enrol plugins
1521 * right after every user login.
1522 *
1523 * @param object $user user record
1524 * @return void
1525 */
1526 public function sync_user_enrolments($user) {
1527 // override if necessary
1528 }
1529
1530 /**
1531 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1532 * @param int $courseid
1533 * @return moodle_url page url
1534 */
e25f2466 1535 public function get_newinstance_link($courseid) {
df997f84
PS
1536 // override for most plugins, check if instance already exists in cases only one instance is supported
1537 return NULL;
1538 }
1539
1540 /**
1541 * Is it possible to delete enrol instance via standard UI?
1542 *
1543 * @param object $instance
1544 * @return bool
1545 */
1546 public function instance_deleteable($instance) {
1547 return true;
1548 }
1549
1550 /**
1551 * Returns link to manual enrol UI if exists.
1552 * Does the access control tests automatically.
1553 *
1554 * @param object $instance
1555 * @return moodle_url
1556 */
1557 public function get_manual_enrol_link($instance) {
1558 return NULL;
1559 }
1560
1561 /**
1562 * Returns list of unenrol links for all enrol instances in course.
1563 *
217d0397 1564 * @param int $instance
bf423bb1 1565 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1566 */
1567 public function get_unenrolself_link($instance) {
1568 global $USER, $CFG, $DB;
1569
1570 $name = $this->get_name();
1571 if ($instance->enrol !== $name) {
1572 throw new coding_exception('invalid enrol instance!');
1573 }
1574
1575 if ($instance->courseid == SITEID) {
1576 return NULL;
1577 }
1578
1579 if (!enrol_is_enabled($name)) {
1580 return NULL;
1581 }
1582
1583 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1584 return NULL;
1585 }
1586
df997f84
PS
1587 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1588 return NULL;
1589 }
1590
b0c6dc1c 1591 $context = context_course::instance($instance->courseid, MUST_EXIST);
217d0397 1592
df997f84
PS
1593 if (!has_capability("enrol/$name:unenrolself", $context)) {
1594 return NULL;
1595 }
1596
1597 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1598 return NULL;
1599 }
1600
0e35ba6f 1601 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
df997f84
PS
1602 }
1603
1604 /**
1605 * Adds enrol instance UI to course edit form
1606 *
1607 * @param object $instance enrol instance or null if does not exist yet
1608 * @param MoodleQuickForm $mform
1609 * @param object $data
1610 * @param object $context context of existing course or parent category if course does not exist
1611 * @return void
1612 */
1613 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1614 // override - usually at least enable/disable switch, has to add own form header
1615 }
1616
1617 /**
1618 * Validates course edit form data
1619 *
1620 * @param object $instance enrol instance or null if does not exist yet
1621 * @param array $data
1622 * @param object $context context of existing course or parent category if course does not exist
1623 * @return array errors array
1624 */
1625 public function course_edit_validation($instance, array $data, $context) {
1626 return array();
1627 }
1628
1629 /**
1630 * Called after updating/inserting course.
1631 *
1632 * @param bool $inserted true if course just inserted
1633 * @param object $course
1634 * @param object $data form data
1635 * @return void
1636 */
1637 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
1638 if ($inserted) {
1639 if ($this->get_config('defaultenrol')) {
1640 $this->add_default_instance($course);
1641 }
1642 }
df997f84
PS
1643 }
1644
1645 /**
eafb7a72 1646 * Add new instance of enrol plugin.
df997f84
PS
1647 * @param object $course
1648 * @param array instance fields
0848a196 1649 * @return int id of new instance, null if can not be created
df997f84
PS
1650 */
1651 public function add_instance($course, array $fields = NULL) {
1652 global $DB;
1653
1654 if ($course->id == SITEID) {
1655 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1656 }
1657
365a5941 1658 $instance = new stdClass();
df997f84
PS
1659 $instance->enrol = $this->get_name();
1660 $instance->status = ENROL_INSTANCE_ENABLED;
1661 $instance->courseid = $course->id;
1662 $instance->enrolstartdate = 0;
1663 $instance->enrolenddate = 0;
1664 $instance->timemodified = time();
1665 $instance->timecreated = $instance->timemodified;
1666 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1667
1668 $fields = (array)$fields;
1669 unset($fields['enrol']);
1670 unset($fields['courseid']);
1671 unset($fields['sortorder']);
1672 foreach($fields as $field=>$value) {
1673 $instance->$field = $value;
1674 }
1675
1676 return $DB->insert_record('enrol', $instance);
1677 }
1678
1679 /**
1680 * Add new instance of enrol plugin with default settings,
1681 * called when adding new instance manually or when adding new course.
1682 *
1683 * Not all plugins support this.
1684 *
1685 * @param object $course
1686 * @return int id of new instance or null if no default supported
1687 */
1688 public function add_default_instance($course) {
1689 return null;
1690 }
1691
af7177db
PS
1692 /**
1693 * Update instance status
1694 *
1695 * Override when plugin needs to do some action when enabled or disabled.
1696 *
1697 * @param stdClass $instance
1698 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1699 * @return void
1700 */
1701 public function update_status($instance, $newstatus) {
1702 global $DB;
1703
1704 $instance->status = $newstatus;
1705 $DB->update_record('enrol', $instance);
1706
1707 // invalidate all enrol caches
1708 $context = context_course::instance($instance->courseid);
1709 $context->mark_dirty();
1710 }
1711
df997f84
PS
1712 /**
1713 * Delete course enrol plugin instance, unenrol all users.
1714 * @param object $instance
1715 * @return void
1716 */
1717 public function delete_instance($instance) {
1718 global $DB;
1719
1720 $name = $this->get_name();
1721 if ($instance->enrol !== $name) {
1722 throw new coding_exception('invalid enrol instance!');
1723 }
1724
1725 //first unenrol all users
1726 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1727 foreach ($participants as $participant) {
1728 $this->unenrol_user($instance, $participant->userid);
1729 }
1730 $participants->close();
1731
1732 // now clean up all remainders that were not removed correctly
a1cedcc9
PS
1733 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
1734 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
df997f84
PS
1735 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1736
1737 // finally drop the enrol row
1738 $DB->delete_records('enrol', array('id'=>$instance->id));
af7177db
PS
1739
1740 // invalidate all enrol caches
1741 $context = context_course::instance($instance->courseid);
1742 $context->mark_dirty();
df997f84
PS
1743 }
1744
1745 /**
1746 * Creates course enrol form, checks if form submitted
1747 * and enrols user if necessary. It can also redirect.
1748 *
1749 * @param stdClass $instance
1750 * @return string html text, usually a form in a text box
1751 */
1752 public function enrol_page_hook(stdClass $instance) {
1753 return null;
1754 }
1755
85d1c53a
RT
1756 /**
1757 * Checks if user can self enrol.
1758 *
1759 * @param stdClass $instance enrolment instance
cc1b5015
RT
1760 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
1761 * used by navigation to improve performance.
1762 * @return bool|string true if successful, else error message or false
85d1c53a 1763 */
cc1b5015 1764 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
85d1c53a
RT
1765 return false;
1766 }
1767
1768 /**
1769 * Return information for enrolment instance containing list of parameters required
1770 * for enrolment, name of enrolment plugin etc.
1771 *
1772 * @param stdClass $instance enrolment instance
1773 * @return array instance info.
1774 */
1775 public function get_enrol_info(stdClass $instance) {
1776 return null;
1777 }
1778
df997f84
PS
1779 /**
1780 * Adds navigation links into course admin block.
1781 *
1782 * By defaults looks for manage links only.
1783 *
1784 * @param navigation_node $instancesnode
bbfdff34 1785 * @param stdClass $instance
2d4b1f3e 1786 * @return void
df997f84
PS
1787 */
1788 public function add_course_navigation($instancesnode, stdClass $instance) {
2d4b1f3e 1789 // usually adds manage users
df997f84
PS
1790 }
1791
1792 /**
2d4b1f3e
PS
1793 * Returns edit icons for the page with list of instances
1794 * @param stdClass $instance
1795 * @return array
df997f84 1796 */
2d4b1f3e
PS
1797 public function get_action_icons(stdClass $instance) {
1798 return array();
df997f84
PS
1799 }
1800
1801 /**
1802 * Reads version.php and determines if it is necessary
1803 * to execute the cron job now.
1804 * @return bool
1805 */
1806 public function is_cron_required() {
1807 global $CFG;
1808
1809 $name = $this->get_name();
1810 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 1811 $plugin = new stdClass();
df997f84
PS
1812 include($versionfile);
1813 if (empty($plugin->cron)) {
1814 return false;
1815 }
1816 $lastexecuted = $this->get_config('lastcron', 0);
1817 if ($lastexecuted + $plugin->cron < time()) {
1818 return true;
1819 } else {
1820 return false;
1821 }
1822 }
1823
1824 /**
1825 * Called for all enabled enrol plugins that returned true from is_cron_required().
1826 * @return void
1827 */
1828 public function cron() {
1829 }
1830
1831 /**
1832 * Called when user is about to be deleted
1833 * @param object $user
1834 * @return void
1835 */
1836 public function user_delete($user) {
1837 global $DB;
1838
1839 $sql = "SELECT e.*
1840 FROM {enrol} e
45fb2cf8
PS
1841 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1842 WHERE e.enrol = :name AND ue.userid = :userid";
df997f84
PS
1843 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1844
45fb2cf8 1845 $rs = $DB->get_recordset_sql($sql, $params);
df997f84
PS
1846 foreach($rs as $instance) {
1847 $this->unenrol_user($instance, $user->id);
1848 }
1849 $rs->close();
1850 }
df997f84 1851
b69ca6be
SH
1852 /**
1853 * Returns an enrol_user_button that takes the user to a page where they are able to
1854 * enrol users into the managers course through this plugin.
1855 *
1856 * Optional: If the plugin supports manual enrolments it can choose to override this
1857 * otherwise it shouldn't
1858 *
1859 * @param course_enrolment_manager $manager
1860 * @return enrol_user_button|false
1861 */
1862 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1863 return false;
1864 }
291215f4
SH
1865
1866 /**
1867 * Gets an array of the user enrolment actions
1868 *
1869 * @param course_enrolment_manager $manager
1870 * @param stdClass $ue
1871 * @return array An array of user_enrolment_actions
1872 */
1873 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
12a52d7c 1874 return array();
291215f4 1875 }
75ee207b
SH
1876
1877 /**
1878 * Returns true if the plugin has one or more bulk operations that can be performed on
1879 * user enrolments.
1880 *
f20edd52 1881 * @param course_enrolment_manager $manager
75ee207b
SH
1882 * @return bool
1883 */
f20edd52 1884 public function has_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
1885 return false;
1886 }
1887
1888 /**
1889 * Return an array of enrol_bulk_enrolment_operation objects that define
1890 * the bulk actions that can be performed on user enrolments by the plugin.
1891 *
f20edd52 1892 * @param course_enrolment_manager $manager
75ee207b
SH
1893 * @return array
1894 */
f20edd52 1895 public function get_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
1896 return array();
1897 }
7a7b8a1f 1898
d8f22c49
PS
1899 /**
1900 * Do any enrolments need expiration processing.
1901 *
1902 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
1903 *
1904 * @param progress_trace $trace
1905 * @param int $courseid one course, empty mean all
1906 * @return bool true if any data processed, false if not
1907 */
1908 public function process_expirations(progress_trace $trace, $courseid = null) {
1909 global $DB;
1910
1911 $name = $this->get_name();
1912 if (!enrol_is_enabled($name)) {
1913 $trace->finished();
1914 return false;
1915 }
1916
1917 $processed = false;
1918 $params = array();
1919 $coursesql = "";
1920 if ($courseid) {
1921 $coursesql = "AND e.courseid = :courseid";
1922 }
1923
1924 // Deal with expired accounts.
1925 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
1926
1927 if ($action == ENROL_EXT_REMOVED_UNENROL) {
1928 $instances = array();
1929 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
1930 FROM {user_enrolments} ue
1931 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
1932 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
1933 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
1934 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
1935
1936 $rs = $DB->get_recordset_sql($sql, $params);
1937 foreach ($rs as $ue) {
1938 if (!$processed) {
1939 $trace->output("Starting processing of enrol_$name expirations...");
1940 $processed = true;
1941 }
1942 if (empty($instances[$ue->enrolid])) {
1943 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
1944 }
1945 $instance = $instances[$ue->enrolid];
1946 if (!$this->roles_protected()) {
1947 // Let's just guess what extra roles are supposed to be removed.
1948 if ($instance->roleid) {
1949 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
1950 }
1951 }
1952 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
1953 $this->unenrol_user($instance, $ue->userid);
1954 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
1955 }
1956 $rs->close();
1957 unset($instances);
1958
1959 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
1960 $instances = array();
1961 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
1962 FROM {user_enrolments} ue
1963 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
1964 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
1965 WHERE ue.timeend > 0 AND ue.timeend < :now
1966 AND ue.status = :useractive $coursesql";
1967 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
1968 $rs = $DB->get_recordset_sql($sql, $params);
1969 foreach ($rs as $ue) {
1970 if (!$processed) {
1971 $trace->output("Starting processing of enrol_$name expirations...");
1972 $processed = true;
1973 }
1974 if (empty($instances[$ue->enrolid])) {
1975 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
1976 }
1977 $instance = $instances[$ue->enrolid];
1978
1979 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
1980 if (!$this->roles_protected()) {
1981 // Let's just guess what roles should be removed.
1982 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
1983 if ($count == 1) {
1984 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
1985
1986 } else if ($count > 1 and $instance->roleid) {
1987 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
1988 }
1989 }
1990 // In any case remove all roles that belong to this instance and user.
1991 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
1992 // Final cleanup of subcontexts if there are no more course roles.
1993 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
1994 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
1995 }
1996 }
1997
1998 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
1999 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2000 }
2001 $rs->close();
2002 unset($instances);
2003
2004 } else {
2005 // ENROL_EXT_REMOVED_KEEP means no changes.
2006 }
2007
2008 if ($processed) {
2009 $trace->output("...finished processing of enrol_$name expirations");
2010 } else {
2011 $trace->output("No expired enrol_$name enrolments detected");
2012 }
2013 $trace->finished();
2014
2015 return $processed;
2016 }
2017
8c04252c
PS
2018 /**
2019 * Send expiry notifications.
2020 *
2021 * Plugin that wants to have expiry notification MUST implement following:
2022 * - expirynotifyhour plugin setting,
2023 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2024 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2025 * expirymessageenrolledsubject and expirymessageenrolledbody),
2026 * - expiry_notification provider in db/messages.php,
2027 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2028 * - something that calls this method, such as cron.
2029 *
5d549ffc 2030 * @param progress_trace $trace (accepts bool for backwards compatibility only)
8c04252c 2031 */
5d549ffc 2032 public function send_expiry_notifications($trace) {
8c04252c
PS
2033 global $DB, $CFG;
2034
d8f22c49
PS
2035 $name = $this->get_name();
2036 if (!enrol_is_enabled($name)) {
2037 $trace->finished();
2038 return;
2039 }
2040
8c04252c
PS
2041 // Unfortunately this may take a long time, it should not be interrupted,
2042 // otherwise users get duplicate notification.
2043
3ef7279f 2044 core_php_time_limit::raise();
8c04252c
PS
2045 raise_memory_limit(MEMORY_HUGE);
2046
8c04252c
PS
2047
2048 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2049 $expirynotifyhour = $this->get_config('expirynotifyhour');
2050 if (is_null($expirynotifyhour)) {
2051 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
5d549ffc 2052 $trace->finished();
8c04252c
PS
2053 return;
2054 }
2055
5d549ffc
PS
2056 if (!($trace instanceof progress_trace)) {
2057 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2058 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2059 }
2060
8c04252c
PS
2061 $timenow = time();
2062 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2063
2064 if ($expirynotifylast > $notifytime) {
5d549ffc
PS
2065 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2066 $trace->finished();
8c04252c 2067 return;
5d549ffc 2068
8c04252c 2069 } else if ($timenow < $notifytime) {
5d549ffc
PS
2070 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2071 $trace->finished();
8c04252c
PS
2072 return;
2073 }
2074
5d549ffc 2075 $trace->output('Processing '.$name.' enrolment expiration notifications...');
8c04252c
PS
2076
2077 // Notify users responsible for enrolment once every day.
2078 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2079 FROM {user_enrolments} ue
2080 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2081 JOIN {course} c ON (c.id = e.courseid)
2082 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2083 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2084 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2085 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2086
2087 $rs = $DB->get_recordset_sql($sql, $params);
2088
2089 $lastenrollid = 0;
2090 $users = array();
2091
2092 foreach($rs as $ue) {
2093 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
5d549ffc 2094 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
8c04252c
PS
2095 $users = array();
2096 }
2097 $lastenrollid = $ue->enrolid;
2098
2099 $enroller = $this->get_enroller($ue->enrolid);
2100 $context = context_course::instance($ue->courseid);
2101
2102 $user = $DB->get_record('user', array('id'=>$ue->userid));
2103
2104 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2105
2106 if (!$ue->notifyall) {
2107 continue;
2108 }
2109
2110 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2111 // Notify enrolled users only once at the start of the threshold.
5d549ffc 2112 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c
PS
2113 continue;
2114 }
2115
5d549ffc 2116 $this->notify_expiry_enrolled($user, $ue, $trace);
8c04252c
PS
2117 }
2118 $rs->close();
2119
2120 if ($lastenrollid and $users) {
5d549ffc 2121 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
8c04252c
PS
2122 }
2123
5d549ffc
PS
2124 $trace->output('...notification processing finished.');
2125 $trace->finished();
2126
8c04252c
PS
2127 $this->set_config('expirynotifylast', $timenow);
2128 }
2129
2130 /**
2131 * Returns the user who is responsible for enrolments for given instance.
2132 *
2133 * Override if plugin knows anybody better than admin.
2134 *
2135 * @param int $instanceid enrolment instance id
2136 * @return stdClass user record
2137 */
2138 protected function get_enroller($instanceid) {
2139 return get_admin();
2140 }
2141
2142 /**
2143 * Notify user about incoming expiration of their enrolment,
2144 * it is called only if notification of enrolled users (aka students) is enabled in course.
2145 *
2146 * This is executed only once for each expiring enrolment right
2147 * at the start of the expiration threshold.
2148 *
2149 * @param stdClass $user
2150 * @param stdClass $ue
5d549ffc 2151 * @param progress_trace $trace
8c04252c 2152 */
5d549ffc 2153 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
c484af5a 2154 global $CFG;
8c04252c
PS
2155
2156 $name = $this->get_name();
2157
c484af5a 2158 $oldforcelang = force_current_language($user->lang);
8c04252c
PS
2159
2160 $enroller = $this->get_enroller($ue->enrolid);
2161 $context = context_course::instance($ue->courseid);
2162
2163 $a = new stdClass();
2164 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2165 $a->user = fullname($user, true);
2166 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2167 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2168
2169 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2170 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2171
2172 $message = new stdClass();
2173 $message->notification = 1;
2174 $message->component = 'enrol_'.$name;
2175 $message->name = 'expiry_notification';
2176 $message->userfrom = $enroller;
2177 $message->userto = $user;
2178 $message->subject = $subject;
2179 $message->fullmessage = $body;
2180 $message->fullmessageformat = FORMAT_MARKDOWN;
2181 $message->fullmessagehtml = markdown_to_html($body);
2182 $message->smallmessage = $subject;
2183 $message->contexturlname = $a->course;
2184 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2185
2186 if (message_send($message)) {
5d549ffc 2187 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c 2188 } else {
5d549ffc 2189 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c
PS
2190 }
2191
c484af5a 2192 force_current_language($oldforcelang);
8c04252c
PS
2193 }
2194
2195 /**
2196 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2197 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2198 *
2199 * This is called repeatedly every day for each course if there are any pending expiration
2200 * in the expiration threshold.
2201 *
2202 * @param int $eid
2203 * @param array $users
5d549ffc 2204 * @param progress_trace $trace
8c04252c 2205 */
5d549ffc 2206 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
c484af5a 2207 global $DB;
8c04252c
PS
2208
2209 $name = $this->get_name();
2210
2211 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2212 $context = context_course::instance($instance->courseid);
2213 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2214
2215 $enroller = $this->get_enroller($instance->id);
2216 $admin = get_admin();
2217
c484af5a 2218 $oldforcelang = force_current_language($enroller->lang);
8c04252c
PS
2219
2220 foreach($users as $key=>$info) {
2221 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2222 }
2223
2224 $a = new stdClass();
2225 $a->course = format_string($course->fullname, true, array('context'=>$context));
2226 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
2227 $a->users = implode("\n", $users);
2228 $a->extendurl = (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid));
2229
2230 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2231 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
2232
2233 $message = new stdClass();
2234 $message->notification = 1;
2235 $message->component = 'enrol_'.$name;
2236 $message->name = 'expiry_notification';
2237 $message->userfrom = $admin;
2238 $message->userto = $enroller;
2239 $message->subject = $subject;
2240 $message->fullmessage = $body;
2241 $message->fullmessageformat = FORMAT_MARKDOWN;
2242 $message->fullmessagehtml = markdown_to_html($body);
2243 $message->smallmessage = $subject;
2244 $message->contexturlname = $a->course;
2245 $message->contexturl = $a->extendurl;
2246
2247 if (message_send($message)) {
5d549ffc 2248 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
8c04252c 2249 } else {
5d549ffc 2250 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
8c04252c
PS
2251 }
2252
c484af5a 2253 force_current_language($oldforcelang);
8c04252c
PS
2254 }
2255
7a7b8a1f
PS
2256 /**
2257 * Automatic enrol sync executed during restore.
2258 * Useful for automatic sync by course->idnumber or course category.
2259 * @param stdClass $course course record
2260 */
2261 public function restore_sync_course($course) {
2262 // Override if necessary.
2263 }
2264
2265 /**
2266 * Restore instance and map settings.
2267 *
2268 * @param restore_enrolments_structure_step $step
2269 * @param stdClass $data
2270 * @param stdClass $course
2271 * @param int $oldid
2272 */
2273 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
2274 // Do not call this from overridden methods, restore and set new id there.
2275 $step->set_mapping('enrol', $oldid, 0);
2276 }
2277
2278 /**
2279 * Restore user enrolment.
2280 *
2281 * @param restore_enrolments_structure_step $step
2282 * @param stdClass $data
2283 * @param stdClass $instance
2284 * @param int $oldinstancestatus
2285 * @param int $userid
2286 */
2287 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
2288 // Override as necessary if plugin supports restore of enrolments.
2289 }
2290
2291 /**
2292 * Restore role assignment.
2293 *
2294 * @param stdClass $instance
2295 * @param int $roleid
2296 * @param int $userid
2297 * @param int $contextid
2298 */
2299 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
2300 // No role assignment by default, override if necessary.
2301 }
7881024e
PS
2302
2303 /**
2304 * Restore user group membership.
2305 * @param stdClass $instance
2306 * @param int $groupid
2307 * @param int $userid
2308 */
2309 public function restore_group_member($instance, $groupid, $userid) {
2310 // Implement if you want to restore protected group memberships,
2311 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
2312 }
4b715423 2313}