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