MDL-35843 prepare fox expiry refactoring to core enrol feature
[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
89 $plugins = get_plugin_list('enrol');
90 ksort($plugins);
91 }
92
93 foreach ($plugins as $plugin=>$location) {
94 if (!file_exists("$location/lib.php")) {
95 continue;
96 }
97 include_once("$location/lib.php");
98 $class = "enrol_{$plugin}_plugin";
99 if (!class_exists($class)) {
100 continue;
101 }
102
103 $result[$plugin] = new $class();
104 }
105
106 return $result;
107}
108
109/**
110 * Returns instance of enrol plugin
111 * @param string $name name of enrol plugin ('manual', 'guest', ...)
112 * @return enrol_plugin
113 */
114function enrol_get_plugin($name) {
115 global $CFG;
116
aff24313
PS
117 $name = clean_param($name, PARAM_PLUGIN);
118
119 if (empty($name)) {
120 // ignore malformed or missing plugin names completely
df997f84
PS
121 return null;
122 }
123
124 $location = "$CFG->dirroot/enrol/$name";
125
126 if (!file_exists("$location/lib.php")) {
127 return null;
128 }
129 include_once("$location/lib.php");
130 $class = "enrol_{$name}_plugin";
131 if (!class_exists($class)) {
132 return null;
133 }
134
135 return new $class();
136}
137
138/**
139 * Returns enrolment instances in given course.
140 * @param int $courseid
141 * @param bool $enabled
142 * @return array of enrol instances
143 */
144function enrol_get_instances($courseid, $enabled) {
145 global $DB, $CFG;
146
147 if (!$enabled) {
148 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
149 }
150
151 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
152
79721bd3 153 $enabled = explode(',', $CFG->enrol_plugins_enabled);
df997f84
PS
154 foreach ($result as $key=>$instance) {
155 if (!in_array($instance->enrol, $enabled)) {
156 unset($result[$key]);
157 continue;
158 }
159 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
160 // broken plugin
161 unset($result[$key]);
162 continue;
163 }
164 }
165
166 return $result;
167}
168
169/**
170 * Checks if a given plugin is in the list of enabled enrolment plugins.
171 *
172 * @param string $enrol Enrolment plugin name
173 * @return boolean Whether the plugin is enabled
174 */
175function enrol_is_enabled($enrol) {
176 global $CFG;
177
178 if (empty($CFG->enrol_plugins_enabled)) {
179 return false;
180 }
181 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
182}
183
184/**
185 * Check all the login enrolment information for the given user object
186 * by querying the enrolment plugins
187 *
e922fe23
PS
188 * This function may be very slow, use only once after log-in or login-as.
189 *
190 * @param stdClass $user
df997f84
PS
191 * @return void
192 */
193function enrol_check_plugins($user) {
194 global $CFG;
195
196 if (empty($user->id) or isguestuser($user)) {
197 // shortcut - there is no enrolment work for guests and not-logged-in users
198 return;
199 }
200
bcb368d9
PS
201 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
202 // which proved it was actually not necessary.
e384d2dc 203
df997f84
PS
204 static $inprogress = array(); // To prevent this function being called more than once in an invocation
205
206 if (!empty($inprogress[$user->id])) {
207 return;
208 }
209
210 $inprogress[$user->id] = true; // Set the flag
211
212 $enabled = enrol_get_plugins(true);
213
214 foreach($enabled as $enrol) {
215 $enrol->sync_user_enrolments($user);
216 }
217
218 unset($inprogress[$user->id]); // Unset the flag
219}
220
181991e7
PS
221/**
222 * Do these two students share any course?
223 *
224 * The courses has to be visible and enrolments has to be active,
225 * timestart and timeend restrictions are ignored.
226 *
61ab8f07
SH
227 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
228 * to true.
229 *
181991e7
PS
230 * @param stdClass|int $user1
231 * @param stdClass|int $user2
232 * @return bool
233 */
234function enrol_sharing_course($user1, $user2) {
61ab8f07 235 return enrol_get_shared_courses($user1, $user2, false, true);
181991e7
PS
236}
237
4b715423
SH
238/**
239 * Returns any courses shared by the two users
240 *
241 * The courses has to be visible and enrolments has to be active,
242 * timestart and timeend restrictions are ignored.
243 *
61ab8f07 244 * @global moodle_database $DB
4b715423
SH
245 * @param stdClass|int $user1
246 * @param stdClass|int $user2
61ab8f07
SH
247 * @param bool $preloadcontexts If set to true contexts for the returned courses
248 * will be preloaded.
249 * @param bool $checkexistsonly If set to true then this function will return true
250 * if the users share any courses and false if not.
251 * @return array|bool An array of courses that both users are enrolled in OR if
252 * $checkexistsonly set returns true if the users share any courses
253 * and false if not.
4b715423 254 */
61ab8f07 255function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
4b715423
SH
256 global $DB, $CFG;
257
5b244e2b
HD
258 $user1 = isset($user1->id) ? $user1->id : $user1;
259 $user2 = isset($user2->id) ? $user2->id : $user2;
4b715423
SH
260
261 if (empty($user1) or empty($user2)) {
262 return false;
263 }
264
265 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
266 return false;
267 }
268
269 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
270 $params['enabled'] = ENROL_INSTANCE_ENABLED;
271 $params['active1'] = ENROL_USER_ACTIVE;
272 $params['active2'] = ENROL_USER_ACTIVE;
273 $params['user1'] = $user1;
274 $params['user2'] = $user2;
275
276 $ctxselect = '';
277 $ctxjoin = '';
278 if ($preloadcontexts) {
279 list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
280 }
281
282 $sql = "SELECT c.* $ctxselect
283 FROM {course} c
284 JOIN (
285 SELECT DISTINCT c.id
286 FROM {enrol} e
287 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
288 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
289 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
290 WHERE e.status = :enabled AND e.enrol $plugins
291 ) ec ON ec.id = c.id
292 $ctxjoin";
4b715423 293
61ab8f07
SH
294 if ($checkexistsonly) {
295 return $DB->record_exists_sql($sql, $params);
296 } else {
297 $courses = $DB->get_records_sql($sql, $params);
298 if ($preloadcontexts) {
299 array_map('context_instance_preload', $courses);
300 }
301 return $courses;
302 }
4b715423
SH
303}
304
df997f84
PS
305/**
306 * This function adds necessary enrol plugins UI into the course edit form.
307 *
308 * @param MoodleQuickForm $mform
309 * @param object $data course edit form data
310 * @param object $context context of existing course or parent category if course does not exist
311 * @return void
312 */
313function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
314 $plugins = enrol_get_plugins(true);
315 if (!empty($data->id)) {
316 $instances = enrol_get_instances($data->id, false);
317 foreach ($instances as $instance) {
318 if (!isset($plugins[$instance->enrol])) {
319 continue;
320 }
321 $plugin = $plugins[$instance->enrol];
322 $plugin->course_edit_form($instance, $mform, $data, $context);
323 }
324 } else {
325 foreach ($plugins as $plugin) {
326 $plugin->course_edit_form(NULL, $mform, $data, $context);
327 }
328 }
329}
330
331/**
332 * Validate course edit form data
333 *
334 * @param array $data raw form data
335 * @param object $context context of existing course or parent category if course does not exist
336 * @return array errors array
337 */
338function enrol_course_edit_validation(array $data, $context) {
339 $errors = array();
340 $plugins = enrol_get_plugins(true);
341
342 if (!empty($data['id'])) {
343 $instances = enrol_get_instances($data['id'], false);
344 foreach ($instances as $instance) {
345 if (!isset($plugins[$instance->enrol])) {
346 continue;
347 }
348 $plugin = $plugins[$instance->enrol];
349 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
350 }
351 } else {
352 foreach ($plugins as $plugin) {
353 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
354 }
355 }
356
357 return $errors;
358}
359
360/**
361 * Update enrol instances after course edit form submission
362 * @param bool $inserted true means new course added, false course already existed
363 * @param object $course
364 * @param object $data form data
365 * @return void
366 */
367function enrol_course_updated($inserted, $course, $data) {
368 global $DB, $CFG;
369
370 $plugins = enrol_get_plugins(true);
371
372 foreach ($plugins as $plugin) {
373 $plugin->course_updated($inserted, $course, $data);
374 }
375}
376
377/**
378 * Add navigation nodes
379 * @param navigation_node $coursenode
380 * @param object $course
381 * @return void
382 */
383function enrol_add_course_navigation(navigation_node $coursenode, $course) {
6e4c374d 384 global $CFG;
df997f84 385
b0c6dc1c 386 $coursecontext = context_course::instance($course->id);
df997f84
PS
387
388 $instances = enrol_get_instances($course->id, true);
389 $plugins = enrol_get_plugins(true);
390
391 // we do not want to break all course pages if there is some borked enrol plugin, right?
392 foreach ($instances as $k=>$instance) {
393 if (!isset($plugins[$instance->enrol])) {
394 unset($instances[$k]);
395 }
396 }
397
f5ce6b71 398 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
df997f84
PS
399
400 if ($course->id != SITEID) {
f5ce6b71 401 // list all participants - allows assigning roles, groups, etc.
df997f84
PS
402 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
403 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
f5ce6b71 404 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
df997f84
PS
405 }
406
407 // manage enrol plugin instances
408 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
409 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
410 } else {
411 $url = NULL;
412 }
f5ce6b71 413 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
df997f84
PS
414
415 // each instance decides how to configure itself or how many other nav items are exposed
416 foreach ($instances as $instance) {
417 if (!isset($plugins[$instance->enrol])) {
418 continue;
419 }
420 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
421 }
422
423 if (!$url) {
424 $instancesnode->trim_if_empty();
425 }
426 }
427
428 // Manage groups in this course or even frontpage
429 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
430 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
431 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
432 }
433
434 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
435 // Override roles
436 if (has_capability('moodle/role:review', $coursecontext)) {
437 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
438 } else {
439 $url = NULL;
440 }
f5ce6b71 441 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
df997f84
PS
442
443 // Add assign or override roles if allowed
444 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
445 if (has_capability('moodle/role:assign', $coursecontext)) {
446 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
f5ce6b71 447 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
df997f84
PS
448 }
449 }
450 // Check role permissions
451 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
452 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
f5ce6b71 453 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
df997f84
PS
454 }
455 }
456
457 // Deal somehow with users that are not enrolled but still got a role somehow
458 if ($course->id != SITEID) {
459 //TODO, create some new UI for role assignments at course level
460 if (has_capability('moodle/role:assign', $coursecontext)) {
461 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
f5ce6b71 462 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
df997f84
PS
463 }
464 }
465
466 // just in case nothing was actually added
467 $usersnode->trim_if_empty();
468
469 if ($course->id != SITEID) {
6813cdf7 470 if (isguestuser() or !isloggedin()) {
39ec18db 471 // guest account can not be enrolled - no links for them
6813cdf7 472 } else if (is_enrolled($coursecontext)) {
39ec18db 473 // unenrol link if possible
217d0397
PS
474 foreach ($instances as $instance) {
475 if (!isset($plugins[$instance->enrol])) {
476 continue;
477 }
478 $plugin = $plugins[$instance->enrol];
479 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
8ebbb06a
SH
480 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
481 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
217d0397
PS
482 break;
483 //TODO. deal with multiple unenrol links - not likely case, but still...
484 }
df997f84 485 }
217d0397 486 } else {
39ec18db 487 // enrol link if possible
217d0397
PS
488 if (is_viewing($coursecontext)) {
489 // better not show any enrol link, this is intended for managers and inspectors
490 } else {
491 foreach ($instances as $instance) {
492 if (!isset($plugins[$instance->enrol])) {
493 continue;
494 }
495 $plugin = $plugins[$instance->enrol];
496 if ($plugin->show_enrolme_link($instance)) {
497 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
8ebbb06a
SH
498 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
499 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
217d0397
PS
500 break;
501 }
502 }
df997f84
PS
503 }
504 }
df997f84
PS
505 }
506}
507
508/**
509 * Returns list of courses current $USER is enrolled in and can access
510 *
511 * - $fields is an array of field names to ADD
512 * so name the fields you really need, which will
513 * be added and uniq'd
514 *
eb6f592a 515 * @param string|array $fields
df997f84
PS
516 * @param string $sort
517 * @param int $limit max number of courses
518 * @return array
519 */
520function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
521 global $DB, $USER;
522
523 // Guest account does not have any courses
524 if (isguestuser() or !isloggedin()) {
525 return(array());
526 }
527
528 $basefields = array('id', 'category', 'sortorder',
529 'shortname', 'fullname', 'idnumber',
530 'startdate', 'visible',
531 'groupmode', 'groupmodeforce');
532
533 if (empty($fields)) {
534 $fields = $basefields;
535 } else if (is_string($fields)) {
536 // turn the fields from a string to an array
537 $fields = explode(',', $fields);
538 $fields = array_map('trim', $fields);
539 $fields = array_unique(array_merge($basefields, $fields));
540 } else if (is_array($fields)) {
541 $fields = array_unique(array_merge($basefields, $fields));
542 } else {
543 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
544 }
545 if (in_array('*', $fields)) {
546 $fields = array('*');
547 }
548
549 $orderby = "";
550 $sort = trim($sort);
551 if (!empty($sort)) {
552 $rawsorts = explode(',', $sort);
553 $sorts = array();
554 foreach ($rawsorts as $rawsort) {
555 $rawsort = trim($rawsort);
556 if (strpos($rawsort, 'c.') === 0) {
557 $rawsort = substr($rawsort, 2);
558 }
559 $sorts[] = trim($rawsort);
560 }
561 $sort = 'c.'.implode(',c.', $sorts);
562 $orderby = "ORDER BY $sort";
563 }
564
565 $wheres = array("c.id <> :siteid");
566 $params = array('siteid'=>SITEID);
567
568 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
569 // list _only_ this course - anything else is asking for trouble...
570 $wheres[] = "courseid = :loginas";
571 $params['loginas'] = $USER->loginascontext->instanceid;
572 }
573
574 $coursefields = 'c.' .join(',c.', $fields);
575 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
4129338c 576 $wheres = implode(" AND ", $wheres);
df997f84 577
4129338c
PS
578 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
579 $sql = "SELECT $coursefields $ccselect
df997f84 580 FROM {course} c
4129338c
PS
581 JOIN (SELECT DISTINCT e.courseid
582 FROM {enrol} e
583 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
584 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
585 ) en ON (en.courseid = c.id)
df997f84 586 $ccjoin
4129338c 587 WHERE $wheres
df997f84
PS
588 $orderby";
589 $params['userid'] = $USER->id;
590 $params['active'] = ENROL_USER_ACTIVE;
591 $params['enabled'] = ENROL_INSTANCE_ENABLED;
592 $params['now1'] = round(time(), -2); // improves db caching
593 $params['now2'] = $params['now1'];
594
595 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
596
597 // preload contexts and check visibility
598 foreach ($courses as $id=>$course) {
599 context_instance_preload($course);
600 if (!$course->visible) {
b0c6dc1c 601 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
55880bdd 602 unset($courses[$id]);
df997f84
PS
603 continue;
604 }
605 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
55880bdd 606 unset($courses[$id]);
df997f84
PS
607 continue;
608 }
609 }
610 $courses[$id] = $course;
611 }
612
613 //wow! Is that really all? :-D
614
615 return $courses;
616}
617
bf423bb1
PS
618/**
619 * Returns course enrolment information icons.
620 *
621 * @param object $course
622 * @param array $instances enrol instances of this course, improves performance
623 * @return array of pix_icon
624 */
625function enrol_get_course_info_icons($course, array $instances = NULL) {
626 $icons = array();
627 if (is_null($instances)) {
628 $instances = enrol_get_instances($course->id, true);
629 }
630 $plugins = enrol_get_plugins(true);
631 foreach ($plugins as $name => $plugin) {
632 $pis = array();
633 foreach ($instances as $instance) {
634 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
635 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
636 continue;
637 }
638 if ($instance->enrol == $name) {
639 $pis[$instance->id] = $instance;
640 }
641 }
642 if ($pis) {
643 $icons = array_merge($icons, $plugin->get_info_icons($pis));
644 }
645 }
646 return $icons;
647}
648
649/**
650 * Returns course enrolment detailed information.
651 *
652 * @param object $course
653 * @return array of html fragments - can be used to construct lists
654 */
655function enrol_get_course_description_texts($course) {
656 $lines = array();
657 $instances = enrol_get_instances($course->id, true);
658 $plugins = enrol_get_plugins(true);
659 foreach ($instances as $instance) {
64942a9d 660 if (!isset($plugins[$instance->enrol])) {
bf423bb1
PS
661 //weird
662 continue;
663 }
64942a9d 664 $plugin = $plugins[$instance->enrol];
bf423bb1
PS
665 $text = $plugin->get_description_text($instance);
666 if ($text !== NULL) {
667 $lines[] = $text;
668 }
669 }
670 return $lines;
671}
672
df997f84
PS
673/**
674 * Returns list of courses user is enrolled into.
9ffd29ce 675 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
df997f84
PS
676 *
677 * - $fields is an array of fieldnames to ADD
678 * so name the fields you really need, which will
679 * be added and uniq'd
680 *
681 * @param int $userid
682 * @param bool $onlyactive return only active enrolments in courses user may see
eb6f592a 683 * @param string|array $fields
df997f84
PS
684 * @param string $sort
685 * @return array
686 */
687function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
688 global $DB;
689
9ffd29ce
AA
690 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
691
692 // preload contexts and check visibility
693 if ($onlyactive) {
694 foreach ($courses as $id=>$course) {
695 context_instance_preload($course);
696 if (!$course->visible) {
697 if (!$context = context_course::instance($id)) {
698 unset($courses[$id]);
699 continue;
700 }
701 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
702 unset($courses[$id]);
703 continue;
704 }
705 }
706 }
707 }
708
709 return $courses;
710
711}
712
713/**
714 * Returns list of courses user is enrolled into without any capability checks
715 * - $fields is an array of fieldnames to ADD
716 * so name the fields you really need, which will
717 * be added and uniq'd
718 *
719 * @param int $userid
720 * @param bool $onlyactive return only active enrolments in courses user may see
721 * @param string|array $fields
722 * @param string $sort
723 * @return array
724 */
725function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
726 global $DB;
727
df997f84 728 // Guest account does not have any courses
87163782 729 if (isguestuser($userid) or empty($userid)) {
df997f84
PS
730 return(array());
731 }
732
733 $basefields = array('id', 'category', 'sortorder',
9ffd29ce
AA
734 'shortname', 'fullname', 'idnumber',
735 'startdate', 'visible',
736 'groupmode', 'groupmodeforce');
df997f84
PS
737
738 if (empty($fields)) {
739 $fields = $basefields;
740 } else if (is_string($fields)) {
741 // turn the fields from a string to an array
742 $fields = explode(',', $fields);
743 $fields = array_map('trim', $fields);
744 $fields = array_unique(array_merge($basefields, $fields));
745 } else if (is_array($fields)) {
746 $fields = array_unique(array_merge($basefields, $fields));
747 } else {
748 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
749 }
750 if (in_array('*', $fields)) {
751 $fields = array('*');
752 }
753
754 $orderby = "";
755 $sort = trim($sort);
756 if (!empty($sort)) {
757 $rawsorts = explode(',', $sort);
758 $sorts = array();
759 foreach ($rawsorts as $rawsort) {
760 $rawsort = trim($rawsort);
761 if (strpos($rawsort, 'c.') === 0) {
762 $rawsort = substr($rawsort, 2);
763 }
764 $sorts[] = trim($rawsort);
765 }
766 $sort = 'c.'.implode(',c.', $sorts);
767 $orderby = "ORDER BY $sort";
768 }
769
df997f84
PS
770 $params = array('siteid'=>SITEID);
771
772 if ($onlyactive) {
4129338c 773 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
df997f84
PS
774 $params['now1'] = round(time(), -2); // improves db caching
775 $params['now2'] = $params['now1'];
776 $params['active'] = ENROL_USER_ACTIVE;
777 $params['enabled'] = ENROL_INSTANCE_ENABLED;
4129338c
PS
778 } else {
779 $subwhere = "";
df997f84
PS
780 }
781
782 $coursefields = 'c.' .join(',c.', $fields);
783 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
df997f84 784
4129338c
PS
785 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
786 $sql = "SELECT $coursefields $ccselect
df997f84 787 FROM {course} c
4129338c
PS
788 JOIN (SELECT DISTINCT e.courseid
789 FROM {enrol} e
790 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
791 $subwhere
792 ) en ON (en.courseid = c.id)
df997f84 793 $ccjoin
4129338c 794 WHERE c.id <> :siteid
df997f84 795 $orderby";
87163782 796 $params['userid'] = $userid;
df997f84
PS
797
798 $courses = $DB->get_records_sql($sql, $params);
799
df997f84 800 return $courses;
df997f84
PS
801}
802
9ffd29ce
AA
803
804
df997f84
PS
805/**
806 * Called when user is about to be deleted.
807 * @param object $user
808 * @return void
809 */
810function enrol_user_delete($user) {
811 global $DB;
812
813 $plugins = enrol_get_plugins(true);
814 foreach ($plugins as $plugin) {
815 $plugin->user_delete($user);
816 }
817
818 // force cleanup of all broken enrolments
819 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
820}
821
582bae08
PS
822/**
823 * Called when course is about to be deleted.
bbfdff34 824 * @param stdClass $course
582bae08
PS
825 * @return void
826 */
827function enrol_course_delete($course) {
828 global $DB;
829
830 $instances = enrol_get_instances($course->id, false);
831 $plugins = enrol_get_plugins(true);
832 foreach ($instances as $instance) {
833 if (isset($plugins[$instance->enrol])) {
834 $plugins[$instance->enrol]->delete_instance($instance);
835 }
836 // low level delete in case plugin did not do it
837 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
838 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
839 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
840 $DB->delete_records('enrol', array('id'=>$instance->id));
841 }
842}
843
df997f84
PS
844/**
845 * Try to enrol user via default internal auth plugin.
846 *
847 * For now this is always using the manual enrol plugin...
848 *
849 * @param $courseid
850 * @param $userid
851 * @param $roleid
852 * @param $timestart
853 * @param $timeend
854 * @return bool success
855 */
856function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
857 global $DB;
858
859 //note: this is hardcoded to manual plugin for now
860
861 if (!enrol_is_enabled('manual')) {
862 return false;
863 }
864
865 if (!$enrol = enrol_get_plugin('manual')) {
866 return false;
867 }
868 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
869 return false;
870 }
871 $instance = reset($instances);
872
873 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
874
875 return true;
876}
877
45ff8a80
PS
878/**
879 * Is there a chance users might self enrol
880 * @param int $courseid
881 * @return bool
882 */
883function enrol_selfenrol_available($courseid) {
884 $result = false;
885
886 $plugins = enrol_get_plugins(true);
887 $enrolinstances = enrol_get_instances($courseid, true);
888 foreach($enrolinstances as $instance) {
889 if (!isset($plugins[$instance->enrol])) {
890 continue;
891 }
892 if ($instance->enrol === 'guest') {
893 // blacklist known temporary guest plugins
894 continue;
895 }
896 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
897 $result = true;
898 break;
899 }
900 }
901
902 return $result;
903}
904
bbfdff34
PS
905/**
906 * This function returns the end of current active user enrolment.
907 *
908 * It deals correctly with multiple overlapping user enrolments.
909 *
910 * @param int $courseid
911 * @param int $userid
912 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
913 */
914function enrol_get_enrolment_end($courseid, $userid) {
915 global $DB;
916
917 $sql = "SELECT ue.*
918 FROM {user_enrolments} ue
919 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
920 JOIN {user} u ON u.id = ue.userid
921 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
922 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
923
924 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
925 return false;
926 }
927
928 $changes = array();
929
930 foreach ($enrolments as $ue) {
931 $start = (int)$ue->timestart;
932 $end = (int)$ue->timeend;
933 if ($end != 0 and $end < $start) {
934 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
935 continue;
936 }
937 if (isset($changes[$start])) {
938 $changes[$start] = $changes[$start] + 1;
939 } else {
940 $changes[$start] = 1;
941 }
942 if ($end === 0) {
943 // no end
944 } else if (isset($changes[$end])) {
945 $changes[$end] = $changes[$end] - 1;
946 } else {
947 $changes[$end] = -1;
948 }
949 }
950
951 // let's sort then enrolment starts&ends and go through them chronologically,
952 // looking for current status and the next future end of enrolment
953 ksort($changes);
954
955 $now = time();
956 $current = 0;
957 $present = null;
958
959 foreach ($changes as $time => $change) {
960 if ($time > $now) {
961 if ($present === null) {
962 // we have just went past current time
963 $present = $current;
964 if ($present < 1) {
965 // no enrolment active
966 return false;
967 }
968 }
969 if ($present !== null) {
970 // we are already in the future - look for possible end
971 if ($current + $change < 1) {
972 return $time;
973 }
974 }
975 }
976 $current += $change;
977 }
978
979 if ($current > 0) {
980 return 0;
981 } else {
982 return false;
983 }
984}
985
986
df997f84
PS
987/**
988 * All enrol plugins should be based on this class,
989 * this is also the main source of documentation.
990 */
991abstract class enrol_plugin {
992 protected $config = null;
993
994 /**
995 * Returns name of this enrol plugin
996 * @return string
997 */
998 public function get_name() {
bf423bb1 999 // second word in class is always enrol name, sorry, no fancy plugin names with _
df997f84
PS
1000 $words = explode('_', get_class($this));
1001 return $words[1];
1002 }
1003
1004 /**
1005 * Returns localised name of enrol instance
1006 *
1007 * @param object $instance (null is accepted too)
1008 * @return string
1009 */
1010 public function get_instance_name($instance) {
1011 if (empty($instance->name)) {
1012 $enrol = $this->get_name();
1013 return get_string('pluginname', 'enrol_'.$enrol);
1014 } else {
b0c6dc1c 1015 $context = context_course::instance($instance->courseid);
54475ccb 1016 return format_string($instance->name, true, array('context'=>$context));
df997f84
PS
1017 }
1018 }
1019
bf423bb1
PS
1020 /**
1021 * Returns optional enrolment information icons.
1022 *
1023 * This is used in course list for quick overview of enrolment options.
1024 *
1025 * We are not using single instance parameter because sometimes
1026 * we might want to prevent icon repetition when multiple instances
1027 * of one type exist. One instance may also produce several icons.
1028 *
1029 * @param array $instances all enrol instances of this type in one course
1030 * @return array of pix_icon
1031 */
1032 public function get_info_icons(array $instances) {
1033 return array();
1034 }
1035
1036 /**
1037 * Returns optional enrolment instance description text.
1038 *
1039 * This is used in detailed course information.
1040 *
1041 *
1042 * @param object $instance
1043 * @return string short html text
1044 */
1045 public function get_description_text($instance) {
1046 return null;
1047 }
1048
df997f84
PS
1049 /**
1050 * Makes sure config is loaded and cached.
1051 * @return void
1052 */
1053 protected function load_config() {
1054 if (!isset($this->config)) {
1055 $name = $this->get_name();
820a8188 1056 $this->config = get_config("enrol_$name");
df997f84
PS
1057 }
1058 }
1059
1060 /**
1061 * Returns plugin config value
1062 * @param string $name
1063 * @param string $default value if config does not exist yet
1064 * @return string value or default
1065 */
1066 public function get_config($name, $default = NULL) {
1067 $this->load_config();
1068 return isset($this->config->$name) ? $this->config->$name : $default;
1069 }
1070
1071 /**
1072 * Sets plugin config value
1073 * @param string $name name of config
1074 * @param string $value string config value, null means delete
1075 * @return string value
1076 */
1077 public function set_config($name, $value) {
47811589 1078 $pluginname = $this->get_name();
df997f84
PS
1079 $this->load_config();
1080 if ($value === NULL) {
1081 unset($this->config->$name);
1082 } else {
1083 $this->config->$name = $value;
1084 }
47811589 1085 set_config($name, $value, "enrol_$pluginname");
df997f84
PS
1086 }
1087
1088 /**
1089 * Does this plugin assign protected roles are can they be manually removed?
1090 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1091 */
1092 public function roles_protected() {
1093 return true;
1094 }
1095
91b99e80
PS
1096 /**
1097 * Does this plugin allow manual enrolments?
1098 *
1099 * @param stdClass $instance course enrol instance
1100 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1101 *
282b5cc7 1102 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
91b99e80
PS
1103 */
1104 public function allow_enrol(stdClass $instance) {
1105 return false;
1106 }
1107
df997f84 1108 /**
282b5cc7 1109 * Does this plugin allow manual unenrolment of all users?
91b99e80 1110 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
df997f84 1111 *
282b5cc7
PS
1112 * @param stdClass $instance course enrol instance
1113 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
df997f84
PS
1114 */
1115 public function allow_unenrol(stdClass $instance) {
1116 return false;
1117 }
1118
282b5cc7
PS
1119 /**
1120 * Does this plugin allow manual unenrolment of a specific user?
1121 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1122 *
1123 * This is useful especially for synchronisation plugins that
1124 * do suspend instead of full unenrolment.
1125 *
1126 * @param stdClass $instance course enrol instance
1127 * @param stdClass $ue record from user_enrolments table, specifies user
1128 *
1129 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1130 */
1131 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1132 return $this->allow_unenrol($instance);
1133 }
1134
df997f84
PS
1135 /**
1136 * Does this plugin allow manual changes in user_enrolments table?
1137 *
91b99e80 1138 * All plugins allowing this must implement 'enrol/xxx:manage' capability
df997f84
PS
1139 *
1140 * @param stdClass $instance course enrol instance
1141 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1142 */
1143 public function allow_manage(stdClass $instance) {
1144 return false;
1145 }
1146
217d0397
PS
1147 /**
1148 * Does this plugin support some way to user to self enrol?
1149 *
1150 * @param stdClass $instance course enrol instance
1151 *
1152 * @return bool - true means show "Enrol me in this course" link in course UI
1153 */
1154 public function show_enrolme_link(stdClass $instance) {
1155 return false;
1156 }
1157
df997f84
PS
1158 /**
1159 * Attempt to automatically enrol current user in course without any interaction,
1160 * calling code has to make sure the plugin and instance are active.
1161 *
ed1d72ea
SH
1162 * This should return either a timestamp in the future or false.
1163 *
df997f84 1164 * @param stdClass $instance course enrol instance
df997f84
PS
1165 * @return bool|int false means not enrolled, integer means timeend
1166 */
1167 public function try_autoenrol(stdClass $instance) {
1168 global $USER;
1169
1170 return false;
1171 }
1172
1173 /**
1174 * Attempt to automatically gain temporary guest access to course,
1175 * calling code has to make sure the plugin and instance are active.
1176 *
ed1d72ea
SH
1177 * This should return either a timestamp in the future or false.
1178 *
df997f84 1179 * @param stdClass $instance course enrol instance
df997f84
PS
1180 * @return bool|int false means no guest access, integer means timeend
1181 */
1182 public function try_guestaccess(stdClass $instance) {
1183 global $USER;
1184
1185 return false;
1186 }
1187
1188 /**
1189 * Enrol user into course via enrol instance.
1190 *
1191 * @param stdClass $instance
1192 * @param int $userid
1193 * @param int $roleid optional role id
2a6dcb72
PS
1194 * @param int $timestart 0 means unknown
1195 * @param int $timeend 0 means forever
f2a9be5f 1196 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
df997f84
PS
1197 * @return void
1198 */
f2a9be5f 1199 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
df997f84
PS
1200 global $DB, $USER, $CFG; // CFG necessary!!!
1201
1202 if ($instance->courseid == SITEID) {
1203 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1204 }
1205
1206 $name = $this->get_name();
1207 $courseid = $instance->courseid;
1208
1209 if ($instance->enrol !== $name) {
1210 throw new coding_exception('invalid enrol instance!');
1211 }
b0c6dc1c 1212 $context = context_course::instance($instance->courseid, MUST_EXIST);
df997f84
PS
1213
1214 $inserted = false;
358fb4dc 1215 $updated = false;
df997f84 1216 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
d587f077 1217 //only update if timestart or timeend or status are different.
ae8c1f3d 1218 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
df997f84
PS
1219 $ue->timestart = $timestart;
1220 $ue->timeend = $timeend;
d587f077 1221 if (!is_null($status)) {
ae8c1f3d 1222 $ue->status = $status;
d587f077 1223 }
6006774c 1224 $ue->modifierid = $USER->id;
df997f84
PS
1225 $ue->timemodified = time();
1226 $DB->update_record('user_enrolments', $ue);
358fb4dc
PS
1227
1228 $updated = true;
df997f84
PS
1229 }
1230 } else {
365a5941 1231 $ue = new stdClass();
df997f84 1232 $ue->enrolid = $instance->id;
ae8c1f3d 1233 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
df997f84
PS
1234 $ue->userid = $userid;
1235 $ue->timestart = $timestart;
1236 $ue->timeend = $timeend;
6006774c 1237 $ue->modifierid = $USER->id;
2a6dcb72
PS
1238 $ue->timecreated = time();
1239 $ue->timemodified = $ue->timecreated;
df997f84
PS
1240 $ue->id = $DB->insert_record('user_enrolments', $ue);
1241
1242 $inserted = true;
1243 }
1244
df997f84
PS
1245 if ($inserted) {
1246 // add extra info and trigger event
1247 $ue->courseid = $courseid;
1248 $ue->enrol = $name;
1249 events_trigger('user_enrolled', $ue);
358fb4dc
PS
1250 } else if ($updated) {
1251 $ue->courseid = $courseid;
1252 $ue->enrol = $name;
1253 events_trigger('user_enrol_modified', $ue);
bbfdff34
PS
1254 // resets current enrolment caches
1255 $context->mark_dirty();
df997f84
PS
1256 }
1257
0c2701fd 1258 if ($roleid) {
bbfdff34 1259 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
0c2701fd
PS
1260 if ($this->roles_protected()) {
1261 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1262 } else {
1263 role_assign($roleid, $userid, $context->id);
1264 }
1265 }
1266
bbfdff34 1267 // reset current user enrolment caching
df997f84
PS
1268 if ($userid == $USER->id) {
1269 if (isset($USER->enrol['enrolled'][$courseid])) {
1270 unset($USER->enrol['enrolled'][$courseid]);
1271 }
1272 if (isset($USER->enrol['tempguest'][$courseid])) {
1273 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1274 remove_temp_course_roles($context);
df997f84
PS
1275 }
1276 }
1277 }
1278
1279 /**
1280 * Store user_enrolments changes and trigger event.
1281 *
358fb4dc
PS
1282 * @param stdClass $instance
1283 * @param int $userid
df997f84
PS
1284 * @param int $status
1285 * @param int $timestart
1286 * @param int $timeend
1287 * @return void
1288 */
1289 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1290 global $DB, $USER;
1291
1292 $name = $this->get_name();
1293
1294 if ($instance->enrol !== $name) {
1295 throw new coding_exception('invalid enrol instance!');
1296 }
1297
1298 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1299 // weird, user not enrolled
1300 return;
1301 }
1302
1303 $modified = false;
1304 if (isset($status) and $ue->status != $status) {
1305 $ue->status = $status;
1306 $modified = true;
1307 }
1308 if (isset($timestart) and $ue->timestart != $timestart) {
1309 $ue->timestart = $timestart;
1310 $modified = true;
1311 }
1312 if (isset($timeend) and $ue->timeend != $timeend) {
1313 $ue->timeend = $timeend;
1314 $modified = true;
1315 }
1316
1317 if (!$modified) {
1318 // no change
1319 return;
1320 }
1321
1322 $ue->modifierid = $USER->id;
1323 $DB->update_record('user_enrolments', $ue);
bbfdff34 1324 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
df997f84
PS
1325
1326 // trigger event
1327 $ue->courseid = $instance->courseid;
1328 $ue->enrol = $instance->name;
358fb4dc 1329 events_trigger('user_enrol_modified', $ue);
df997f84
PS
1330 }
1331
1332 /**
1333 * Unenrol user from course,
1334 * the last unenrolment removes all remaining roles.
1335 *
1336 * @param stdClass $instance
1337 * @param int $userid
1338 * @return void
1339 */
1340 public function unenrol_user(stdClass $instance, $userid) {
1341 global $CFG, $USER, $DB;
7881024e 1342 require_once("$CFG->dirroot/group/lib.php");
df997f84
PS
1343
1344 $name = $this->get_name();
1345 $courseid = $instance->courseid;
1346
1347 if ($instance->enrol !== $name) {
1348 throw new coding_exception('invalid enrol instance!');
1349 }
b0c6dc1c 1350 $context = context_course::instance($instance->courseid, MUST_EXIST);
df997f84
PS
1351
1352 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1353 // weird, user not enrolled
1354 return;
1355 }
1356
7881024e
PS
1357 // Remove all users groups linked to this enrolment instance.
1358 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
1359 foreach ($gms as $gm) {
1360 groups_remove_member($gm->groupid, $gm->userid);
1361 }
1362 }
1363
df997f84
PS
1364 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1365 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1366
1367 // add extra info and trigger event
1368 $ue->courseid = $courseid;
1369 $ue->enrol = $name;
1370
1371 $sql = "SELECT 'x'
1372 FROM {user_enrolments} ue
1373 JOIN {enrol} e ON (e.id = ue.enrolid)
7881024e 1374 WHERE ue.userid = :userid AND e.courseid = :courseid";
df997f84
PS
1375 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1376 $ue->lastenrol = false;
1377 events_trigger('user_unenrolled', $ue);
1378 // user still has some enrolments, no big cleanup yet
7881024e 1379
df997f84
PS
1380 } else {
1381 // the big cleanup IS necessary!
df997f84
PS
1382 require_once("$CFG->libdir/gradelib.php");
1383
1384 // remove all remaining roles
1385 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1386
1387 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1388 groups_delete_group_members($courseid, $userid);
1389
1390 grade_user_unenrol($courseid, $userid);
1391
1392 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1393
7d2800fb 1394 $ue->lastenrol = true; // means user not enrolled any more
df997f84
PS
1395 events_trigger('user_unenrolled', $ue);
1396 }
bbfdff34
PS
1397
1398 // reset all enrol caches
1399 $context->mark_dirty();
1400
1401 // reset current user enrolment caching
df997f84
PS
1402 if ($userid == $USER->id) {
1403 if (isset($USER->enrol['enrolled'][$courseid])) {
1404 unset($USER->enrol['enrolled'][$courseid]);
1405 }
1406 if (isset($USER->enrol['tempguest'][$courseid])) {
1407 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1408 remove_temp_course_roles($context);
df997f84
PS
1409 }
1410 }
1411 }
1412
1413 /**
1414 * Forces synchronisation of user enrolments.
1415 *
1416 * This is important especially for external enrol plugins,
1417 * this function is called for all enabled enrol plugins
1418 * right after every user login.
1419 *
1420 * @param object $user user record
1421 * @return void
1422 */
1423 public function sync_user_enrolments($user) {
1424 // override if necessary
1425 }
1426
1427 /**
1428 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1429 * @param int $courseid
1430 * @return moodle_url page url
1431 */
e25f2466 1432 public function get_newinstance_link($courseid) {
df997f84
PS
1433 // override for most plugins, check if instance already exists in cases only one instance is supported
1434 return NULL;
1435 }
1436
1437 /**
1438 * Is it possible to delete enrol instance via standard UI?
1439 *
1440 * @param object $instance
1441 * @return bool
1442 */
1443 public function instance_deleteable($instance) {
1444 return true;
1445 }
1446
1447 /**
1448 * Returns link to manual enrol UI if exists.
1449 * Does the access control tests automatically.
1450 *
1451 * @param object $instance
1452 * @return moodle_url
1453 */
1454 public function get_manual_enrol_link($instance) {
1455 return NULL;
1456 }
1457
1458 /**
1459 * Returns list of unenrol links for all enrol instances in course.
1460 *
217d0397 1461 * @param int $instance
bf423bb1 1462 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1463 */
1464 public function get_unenrolself_link($instance) {
1465 global $USER, $CFG, $DB;
1466
1467 $name = $this->get_name();
1468 if ($instance->enrol !== $name) {
1469 throw new coding_exception('invalid enrol instance!');
1470 }
1471
1472 if ($instance->courseid == SITEID) {
1473 return NULL;
1474 }
1475
1476 if (!enrol_is_enabled($name)) {
1477 return NULL;
1478 }
1479
1480 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1481 return NULL;
1482 }
1483
df997f84
PS
1484 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1485 return NULL;
1486 }
1487
b0c6dc1c 1488 $context = context_course::instance($instance->courseid, MUST_EXIST);
217d0397 1489
df997f84
PS
1490 if (!has_capability("enrol/$name:unenrolself", $context)) {
1491 return NULL;
1492 }
1493
1494 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1495 return NULL;
1496 }
1497
1498 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1499 }
1500
1501 /**
1502 * Adds enrol instance UI to course edit form
1503 *
1504 * @param object $instance enrol instance or null if does not exist yet
1505 * @param MoodleQuickForm $mform
1506 * @param object $data
1507 * @param object $context context of existing course or parent category if course does not exist
1508 * @return void
1509 */
1510 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1511 // override - usually at least enable/disable switch, has to add own form header
1512 }
1513
1514 /**
1515 * Validates course edit form data
1516 *
1517 * @param object $instance enrol instance or null if does not exist yet
1518 * @param array $data
1519 * @param object $context context of existing course or parent category if course does not exist
1520 * @return array errors array
1521 */
1522 public function course_edit_validation($instance, array $data, $context) {
1523 return array();
1524 }
1525
1526 /**
1527 * Called after updating/inserting course.
1528 *
1529 * @param bool $inserted true if course just inserted
1530 * @param object $course
1531 * @param object $data form data
1532 * @return void
1533 */
1534 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
1535 if ($inserted) {
1536 if ($this->get_config('defaultenrol')) {
1537 $this->add_default_instance($course);
1538 }
1539 }
df997f84
PS
1540 }
1541
1542 /**
eafb7a72 1543 * Add new instance of enrol plugin.
df997f84
PS
1544 * @param object $course
1545 * @param array instance fields
0848a196 1546 * @return int id of new instance, null if can not be created
df997f84
PS
1547 */
1548 public function add_instance($course, array $fields = NULL) {
1549 global $DB;
1550
1551 if ($course->id == SITEID) {
1552 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1553 }
1554
365a5941 1555 $instance = new stdClass();
df997f84
PS
1556 $instance->enrol = $this->get_name();
1557 $instance->status = ENROL_INSTANCE_ENABLED;
1558 $instance->courseid = $course->id;
1559 $instance->enrolstartdate = 0;
1560 $instance->enrolenddate = 0;
1561 $instance->timemodified = time();
1562 $instance->timecreated = $instance->timemodified;
1563 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1564
1565 $fields = (array)$fields;
1566 unset($fields['enrol']);
1567 unset($fields['courseid']);
1568 unset($fields['sortorder']);
1569 foreach($fields as $field=>$value) {
1570 $instance->$field = $value;
1571 }
1572
1573 return $DB->insert_record('enrol', $instance);
1574 }
1575
1576 /**
1577 * Add new instance of enrol plugin with default settings,
1578 * called when adding new instance manually or when adding new course.
1579 *
1580 * Not all plugins support this.
1581 *
1582 * @param object $course
1583 * @return int id of new instance or null if no default supported
1584 */
1585 public function add_default_instance($course) {
1586 return null;
1587 }
1588
af7177db
PS
1589 /**
1590 * Update instance status
1591 *
1592 * Override when plugin needs to do some action when enabled or disabled.
1593 *
1594 * @param stdClass $instance
1595 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1596 * @return void
1597 */
1598 public function update_status($instance, $newstatus) {
1599 global $DB;
1600
1601 $instance->status = $newstatus;
1602 $DB->update_record('enrol', $instance);
1603
1604 // invalidate all enrol caches
1605 $context = context_course::instance($instance->courseid);
1606 $context->mark_dirty();
1607 }
1608
df997f84
PS
1609 /**
1610 * Delete course enrol plugin instance, unenrol all users.
1611 * @param object $instance
1612 * @return void
1613 */
1614 public function delete_instance($instance) {
1615 global $DB;
1616
1617 $name = $this->get_name();
1618 if ($instance->enrol !== $name) {
1619 throw new coding_exception('invalid enrol instance!');
1620 }
1621
1622 //first unenrol all users
1623 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1624 foreach ($participants as $participant) {
1625 $this->unenrol_user($instance, $participant->userid);
1626 }
1627 $participants->close();
1628
1629 // now clean up all remainders that were not removed correctly
a1cedcc9
PS
1630 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
1631 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
df997f84
PS
1632 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1633
1634 // finally drop the enrol row
1635 $DB->delete_records('enrol', array('id'=>$instance->id));
af7177db
PS
1636
1637 // invalidate all enrol caches
1638 $context = context_course::instance($instance->courseid);
1639 $context->mark_dirty();
df997f84
PS
1640 }
1641
1642 /**
1643 * Creates course enrol form, checks if form submitted
1644 * and enrols user if necessary. It can also redirect.
1645 *
1646 * @param stdClass $instance
1647 * @return string html text, usually a form in a text box
1648 */
1649 public function enrol_page_hook(stdClass $instance) {
1650 return null;
1651 }
1652
1653 /**
1654 * Adds navigation links into course admin block.
1655 *
1656 * By defaults looks for manage links only.
1657 *
1658 * @param navigation_node $instancesnode
bbfdff34 1659 * @param stdClass $instance
2d4b1f3e 1660 * @return void
df997f84
PS
1661 */
1662 public function add_course_navigation($instancesnode, stdClass $instance) {
2d4b1f3e 1663 // usually adds manage users
df997f84
PS
1664 }
1665
1666 /**
2d4b1f3e
PS
1667 * Returns edit icons for the page with list of instances
1668 * @param stdClass $instance
1669 * @return array
df997f84 1670 */
2d4b1f3e
PS
1671 public function get_action_icons(stdClass $instance) {
1672 return array();
df997f84
PS
1673 }
1674
1675 /**
1676 * Reads version.php and determines if it is necessary
1677 * to execute the cron job now.
1678 * @return bool
1679 */
1680 public function is_cron_required() {
1681 global $CFG;
1682
1683 $name = $this->get_name();
1684 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 1685 $plugin = new stdClass();
df997f84
PS
1686 include($versionfile);
1687 if (empty($plugin->cron)) {
1688 return false;
1689 }
1690 $lastexecuted = $this->get_config('lastcron', 0);
1691 if ($lastexecuted + $plugin->cron < time()) {
1692 return true;
1693 } else {
1694 return false;
1695 }
1696 }
1697
1698 /**
1699 * Called for all enabled enrol plugins that returned true from is_cron_required().
1700 * @return void
1701 */
1702 public function cron() {
1703 }
1704
1705 /**
1706 * Called when user is about to be deleted
1707 * @param object $user
1708 * @return void
1709 */
1710 public function user_delete($user) {
1711 global $DB;
1712
1713 $sql = "SELECT e.*
1714 FROM {enrol} e
45fb2cf8
PS
1715 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1716 WHERE e.enrol = :name AND ue.userid = :userid";
df997f84
PS
1717 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1718
45fb2cf8 1719 $rs = $DB->get_recordset_sql($sql, $params);
df997f84
PS
1720 foreach($rs as $instance) {
1721 $this->unenrol_user($instance, $user->id);
1722 }
1723 $rs->close();
1724 }
df997f84 1725
b69ca6be
SH
1726 /**
1727 * Returns an enrol_user_button that takes the user to a page where they are able to
1728 * enrol users into the managers course through this plugin.
1729 *
1730 * Optional: If the plugin supports manual enrolments it can choose to override this
1731 * otherwise it shouldn't
1732 *
1733 * @param course_enrolment_manager $manager
1734 * @return enrol_user_button|false
1735 */
1736 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1737 return false;
1738 }
291215f4
SH
1739
1740 /**
1741 * Gets an array of the user enrolment actions
1742 *
1743 * @param course_enrolment_manager $manager
1744 * @param stdClass $ue
1745 * @return array An array of user_enrolment_actions
1746 */
1747 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
12a52d7c 1748 return array();
291215f4 1749 }
75ee207b
SH
1750
1751 /**
1752 * Returns true if the plugin has one or more bulk operations that can be performed on
1753 * user enrolments.
1754 *
f20edd52 1755 * @param course_enrolment_manager $manager
75ee207b
SH
1756 * @return bool
1757 */
f20edd52 1758 public function has_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
1759 return false;
1760 }
1761
1762 /**
1763 * Return an array of enrol_bulk_enrolment_operation objects that define
1764 * the bulk actions that can be performed on user enrolments by the plugin.
1765 *
f20edd52 1766 * @param course_enrolment_manager $manager
75ee207b
SH
1767 * @return array
1768 */
f20edd52 1769 public function get_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
1770 return array();
1771 }
7a7b8a1f
PS
1772
1773 /**
1774 * Automatic enrol sync executed during restore.
1775 * Useful for automatic sync by course->idnumber or course category.
1776 * @param stdClass $course course record
1777 */
1778 public function restore_sync_course($course) {
1779 // Override if necessary.
1780 }
1781
1782 /**
1783 * Restore instance and map settings.
1784 *
1785 * @param restore_enrolments_structure_step $step
1786 * @param stdClass $data
1787 * @param stdClass $course
1788 * @param int $oldid
1789 */
1790 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
1791 // Do not call this from overridden methods, restore and set new id there.
1792 $step->set_mapping('enrol', $oldid, 0);
1793 }
1794
1795 /**
1796 * Restore user enrolment.
1797 *
1798 * @param restore_enrolments_structure_step $step
1799 * @param stdClass $data
1800 * @param stdClass $instance
1801 * @param int $oldinstancestatus
1802 * @param int $userid
1803 */
1804 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
1805 // Override as necessary if plugin supports restore of enrolments.
1806 }
1807
1808 /**
1809 * Restore role assignment.
1810 *
1811 * @param stdClass $instance
1812 * @param int $roleid
1813 * @param int $userid
1814 * @param int $contextid
1815 */
1816 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
1817 // No role assignment by default, override if necessary.
1818 }
7881024e
PS
1819
1820 /**
1821 * Restore user group membership.
1822 * @param stdClass $instance
1823 * @param int $groupid
1824 * @param int $userid
1825 */
1826 public function restore_group_member($instance, $groupid, $userid) {
1827 // Implement if you want to restore protected group memberships,
1828 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
1829 }
4b715423 1830}