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