MDL-24955 improved detection of available self enrol plugins
[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
42/** Enrol info is cached for this number of seconds in require_login() */
43define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
44
34121765
PS
45/** When user disappears from external source, the enrolment is completely removed */
46define('ENROL_EXT_REMOVED_UNENROL', 0);
47
48/** When user disappears from external source, the enrolment is kept as is - one way sync */
49define('ENROL_EXT_REMOVED_KEEP', 1);
50
f2a9be5f
EL
51/** enrol plugin feature describing requested restore type */
52define('ENROL_RESTORE_TYPE', 'enrolrestore');
53/** User custom backup/restore class stored in backup/moodle2/ subdirectory */
54define('ENROL_RESTORE_CLASS', 'class');
55/** Restore all custom fields from enrol table without any changes and all user_enrolments records */
56define('ENROL_RESTORE_EXACT', 'exact');
57/** Restore enrol record like ENROL_RESTORE_EXACT, but no user enrolments */
58define('ENROL_RESTORE_NOUSERS', 'nousers');
59
34121765
PS
60/**
61 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
62 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
63 * assignments, etc.
64 */
65define('ENROL_EXT_REMOVED_SUSPEND', 2);
66
67/**
68 * When user disappears from external source, the enrolment is suspended and roles assigned
69 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
70 * */
71define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
72
df997f84
PS
73/**
74 * Returns instances of enrol plugins
75 * @param bool $enable return enabled only
76 * @return array of enrol plugins name=>instance
77 */
78function enrol_get_plugins($enabled) {
79 global $CFG;
80
81 $result = array();
82
83 if ($enabled) {
84 // sorted by enabled plugin order
85 $enabled = explode(',', $CFG->enrol_plugins_enabled);
86 $plugins = array();
87 foreach ($enabled as $plugin) {
88 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
89 }
90 } else {
91 // sorted alphabetically
92 $plugins = get_plugin_list('enrol');
93 ksort($plugins);
94 }
95
96 foreach ($plugins as $plugin=>$location) {
97 if (!file_exists("$location/lib.php")) {
98 continue;
99 }
100 include_once("$location/lib.php");
101 $class = "enrol_{$plugin}_plugin";
102 if (!class_exists($class)) {
103 continue;
104 }
105
106 $result[$plugin] = new $class();
107 }
108
109 return $result;
110}
111
112/**
113 * Returns instance of enrol plugin
114 * @param string $name name of enrol plugin ('manual', 'guest', ...)
115 * @return enrol_plugin
116 */
117function enrol_get_plugin($name) {
118 global $CFG;
119
120 if ($name !== clean_param($name, PARAM_SAFEDIR)) {
121 // ignore malformed plugin names completely
122 return null;
123 }
124
125 $location = "$CFG->dirroot/enrol/$name";
126
127 if (!file_exists("$location/lib.php")) {
128 return null;
129 }
130 include_once("$location/lib.php");
131 $class = "enrol_{$name}_plugin";
132 if (!class_exists($class)) {
133 return null;
134 }
135
136 return new $class();
137}
138
139/**
140 * Returns enrolment instances in given course.
141 * @param int $courseid
142 * @param bool $enabled
143 * @return array of enrol instances
144 */
145function enrol_get_instances($courseid, $enabled) {
146 global $DB, $CFG;
147
148 if (!$enabled) {
149 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
150 }
151
152 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
153
79721bd3 154 $enabled = explode(',', $CFG->enrol_plugins_enabled);
df997f84
PS
155 foreach ($result as $key=>$instance) {
156 if (!in_array($instance->enrol, $enabled)) {
157 unset($result[$key]);
158 continue;
159 }
160 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
161 // broken plugin
162 unset($result[$key]);
163 continue;
164 }
165 }
166
167 return $result;
168}
169
170/**
171 * Checks if a given plugin is in the list of enabled enrolment plugins.
172 *
173 * @param string $enrol Enrolment plugin name
174 * @return boolean Whether the plugin is enabled
175 */
176function enrol_is_enabled($enrol) {
177 global $CFG;
178
179 if (empty($CFG->enrol_plugins_enabled)) {
180 return false;
181 }
182 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
183}
184
185/**
186 * Check all the login enrolment information for the given user object
187 * by querying the enrolment plugins
188 *
189 * @param object $user
190 * @return void
191 */
192function enrol_check_plugins($user) {
193 global $CFG;
194
195 if (empty($user->id) or isguestuser($user)) {
196 // shortcut - there is no enrolment work for guests and not-logged-in users
197 return;
198 }
199
e384d2dc
PS
200 if (is_siteadmin()) {
201 // no sync for admin user, please use admin accounts only for admin tasks like the unix root user!
202 // if plugin fails on sync admins need to be able to log in
203 return;
204 }
205
df997f84
PS
206 static $inprogress = array(); // To prevent this function being called more than once in an invocation
207
208 if (!empty($inprogress[$user->id])) {
209 return;
210 }
211
212 $inprogress[$user->id] = true; // Set the flag
213
214 $enabled = enrol_get_plugins(true);
215
216 foreach($enabled as $enrol) {
217 $enrol->sync_user_enrolments($user);
218 }
219
220 unset($inprogress[$user->id]); // Unset the flag
221}
222
223/**
224 * This function adds necessary enrol plugins UI into the course edit form.
225 *
226 * @param MoodleQuickForm $mform
227 * @param object $data course edit form data
228 * @param object $context context of existing course or parent category if course does not exist
229 * @return void
230 */
231function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
232 $plugins = enrol_get_plugins(true);
233 if (!empty($data->id)) {
234 $instances = enrol_get_instances($data->id, false);
235 foreach ($instances as $instance) {
236 if (!isset($plugins[$instance->enrol])) {
237 continue;
238 }
239 $plugin = $plugins[$instance->enrol];
240 $plugin->course_edit_form($instance, $mform, $data, $context);
241 }
242 } else {
243 foreach ($plugins as $plugin) {
244 $plugin->course_edit_form(NULL, $mform, $data, $context);
245 }
246 }
247}
248
249/**
250 * Validate course edit form data
251 *
252 * @param array $data raw form data
253 * @param object $context context of existing course or parent category if course does not exist
254 * @return array errors array
255 */
256function enrol_course_edit_validation(array $data, $context) {
257 $errors = array();
258 $plugins = enrol_get_plugins(true);
259
260 if (!empty($data['id'])) {
261 $instances = enrol_get_instances($data['id'], false);
262 foreach ($instances as $instance) {
263 if (!isset($plugins[$instance->enrol])) {
264 continue;
265 }
266 $plugin = $plugins[$instance->enrol];
267 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
268 }
269 } else {
270 foreach ($plugins as $plugin) {
271 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
272 }
273 }
274
275 return $errors;
276}
277
278/**
279 * Update enrol instances after course edit form submission
280 * @param bool $inserted true means new course added, false course already existed
281 * @param object $course
282 * @param object $data form data
283 * @return void
284 */
285function enrol_course_updated($inserted, $course, $data) {
286 global $DB, $CFG;
287
288 $plugins = enrol_get_plugins(true);
289
290 foreach ($plugins as $plugin) {
291 $plugin->course_updated($inserted, $course, $data);
292 }
293}
294
295/**
296 * Add navigation nodes
297 * @param navigation_node $coursenode
298 * @param object $course
299 * @return void
300 */
301function enrol_add_course_navigation(navigation_node $coursenode, $course) {
6e4c374d 302 global $CFG;
df997f84
PS
303
304 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
305
306 $instances = enrol_get_instances($course->id, true);
307 $plugins = enrol_get_plugins(true);
308
309 // we do not want to break all course pages if there is some borked enrol plugin, right?
310 foreach ($instances as $k=>$instance) {
311 if (!isset($plugins[$instance->enrol])) {
312 unset($instances[$k]);
313 }
314 }
315
f5ce6b71 316 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
df997f84
PS
317
318 if ($course->id != SITEID) {
f5ce6b71 319 // list all participants - allows assigning roles, groups, etc.
df997f84
PS
320 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
321 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
f5ce6b71 322 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
df997f84
PS
323 }
324
325 // manage enrol plugin instances
326 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
327 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
328 } else {
329 $url = NULL;
330 }
f5ce6b71 331 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
df997f84
PS
332
333 // each instance decides how to configure itself or how many other nav items are exposed
334 foreach ($instances as $instance) {
335 if (!isset($plugins[$instance->enrol])) {
336 continue;
337 }
338 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
339 }
340
341 if (!$url) {
342 $instancesnode->trim_if_empty();
343 }
344 }
345
346 // Manage groups in this course or even frontpage
347 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
348 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
349 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
350 }
351
352 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
353 // Override roles
354 if (has_capability('moodle/role:review', $coursecontext)) {
355 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
356 } else {
357 $url = NULL;
358 }
f5ce6b71 359 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
df997f84
PS
360
361 // Add assign or override roles if allowed
362 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
363 if (has_capability('moodle/role:assign', $coursecontext)) {
364 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
f5ce6b71 365 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
df997f84
PS
366 }
367 }
368 // Check role permissions
369 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
370 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
f5ce6b71 371 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
df997f84
PS
372 }
373 }
374
375 // Deal somehow with users that are not enrolled but still got a role somehow
376 if ($course->id != SITEID) {
377 //TODO, create some new UI for role assignments at course level
378 if (has_capability('moodle/role:assign', $coursecontext)) {
379 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
f5ce6b71 380 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
df997f84
PS
381 }
382 }
383
384 // just in case nothing was actually added
385 $usersnode->trim_if_empty();
386
387 if ($course->id != SITEID) {
388 // Unenrol link
217d0397
PS
389 if (is_enrolled($coursecontext)) {
390 foreach ($instances as $instance) {
391 if (!isset($plugins[$instance->enrol])) {
392 continue;
393 }
394 $plugin = $plugins[$instance->enrol];
395 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
396 $coursenode->add(get_string('unenrolme', 'core_enrol', format_string($course->shortname)), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
397 break;
398 //TODO. deal with multiple unenrol links - not likely case, but still...
399 }
df997f84 400 }
217d0397
PS
401 } else {
402 if (is_viewing($coursecontext)) {
403 // better not show any enrol link, this is intended for managers and inspectors
404 } else {
405 foreach ($instances as $instance) {
406 if (!isset($plugins[$instance->enrol])) {
407 continue;
408 }
409 $plugin = $plugins[$instance->enrol];
410 if ($plugin->show_enrolme_link($instance)) {
411 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
412 $coursenode->add(get_string('enrolme', 'core_enrol', format_string($course->shortname)), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
413 break;
414 }
415 }
df997f84
PS
416 }
417 }
df997f84
PS
418 }
419}
420
421/**
422 * Returns list of courses current $USER is enrolled in and can access
423 *
424 * - $fields is an array of field names to ADD
425 * so name the fields you really need, which will
426 * be added and uniq'd
427 *
eb6f592a 428 * @param string|array $fields
df997f84
PS
429 * @param string $sort
430 * @param int $limit max number of courses
431 * @return array
432 */
433function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
434 global $DB, $USER;
435
436 // Guest account does not have any courses
437 if (isguestuser() or !isloggedin()) {
438 return(array());
439 }
440
441 $basefields = array('id', 'category', 'sortorder',
442 'shortname', 'fullname', 'idnumber',
443 'startdate', 'visible',
444 'groupmode', 'groupmodeforce');
445
446 if (empty($fields)) {
447 $fields = $basefields;
448 } else if (is_string($fields)) {
449 // turn the fields from a string to an array
450 $fields = explode(',', $fields);
451 $fields = array_map('trim', $fields);
452 $fields = array_unique(array_merge($basefields, $fields));
453 } else if (is_array($fields)) {
454 $fields = array_unique(array_merge($basefields, $fields));
455 } else {
456 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
457 }
458 if (in_array('*', $fields)) {
459 $fields = array('*');
460 }
461
462 $orderby = "";
463 $sort = trim($sort);
464 if (!empty($sort)) {
465 $rawsorts = explode(',', $sort);
466 $sorts = array();
467 foreach ($rawsorts as $rawsort) {
468 $rawsort = trim($rawsort);
469 if (strpos($rawsort, 'c.') === 0) {
470 $rawsort = substr($rawsort, 2);
471 }
472 $sorts[] = trim($rawsort);
473 }
474 $sort = 'c.'.implode(',c.', $sorts);
475 $orderby = "ORDER BY $sort";
476 }
477
478 $wheres = array("c.id <> :siteid");
479 $params = array('siteid'=>SITEID);
480
481 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
482 // list _only_ this course - anything else is asking for trouble...
483 $wheres[] = "courseid = :loginas";
484 $params['loginas'] = $USER->loginascontext->instanceid;
485 }
486
487 $coursefields = 'c.' .join(',c.', $fields);
488 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
4129338c 489 $wheres = implode(" AND ", $wheres);
df997f84 490
4129338c
PS
491 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
492 $sql = "SELECT $coursefields $ccselect
df997f84 493 FROM {course} c
4129338c
PS
494 JOIN (SELECT DISTINCT e.courseid
495 FROM {enrol} e
496 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
497 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
498 ) en ON (en.courseid = c.id)
df997f84 499 $ccjoin
4129338c 500 WHERE $wheres
df997f84
PS
501 $orderby";
502 $params['userid'] = $USER->id;
503 $params['active'] = ENROL_USER_ACTIVE;
504 $params['enabled'] = ENROL_INSTANCE_ENABLED;
505 $params['now1'] = round(time(), -2); // improves db caching
506 $params['now2'] = $params['now1'];
507
508 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
509
510 // preload contexts and check visibility
511 foreach ($courses as $id=>$course) {
512 context_instance_preload($course);
513 if (!$course->visible) {
514 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
55880bdd 515 unset($courses[$id]);
df997f84
PS
516 continue;
517 }
518 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
55880bdd 519 unset($courses[$id]);
df997f84
PS
520 continue;
521 }
522 }
523 $courses[$id] = $course;
524 }
525
526 //wow! Is that really all? :-D
527
528 return $courses;
529}
530
bf423bb1
PS
531/**
532 * Returns course enrolment information icons.
533 *
534 * @param object $course
535 * @param array $instances enrol instances of this course, improves performance
536 * @return array of pix_icon
537 */
538function enrol_get_course_info_icons($course, array $instances = NULL) {
539 $icons = array();
540 if (is_null($instances)) {
541 $instances = enrol_get_instances($course->id, true);
542 }
543 $plugins = enrol_get_plugins(true);
544 foreach ($plugins as $name => $plugin) {
545 $pis = array();
546 foreach ($instances as $instance) {
547 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
548 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
549 continue;
550 }
551 if ($instance->enrol == $name) {
552 $pis[$instance->id] = $instance;
553 }
554 }
555 if ($pis) {
556 $icons = array_merge($icons, $plugin->get_info_icons($pis));
557 }
558 }
559 return $icons;
560}
561
562/**
563 * Returns course enrolment detailed information.
564 *
565 * @param object $course
566 * @return array of html fragments - can be used to construct lists
567 */
568function enrol_get_course_description_texts($course) {
569 $lines = array();
570 $instances = enrol_get_instances($course->id, true);
571 $plugins = enrol_get_plugins(true);
572 foreach ($instances as $instance) {
64942a9d 573 if (!isset($plugins[$instance->enrol])) {
bf423bb1
PS
574 //weird
575 continue;
576 }
64942a9d 577 $plugin = $plugins[$instance->enrol];
bf423bb1
PS
578 $text = $plugin->get_description_text($instance);
579 if ($text !== NULL) {
580 $lines[] = $text;
581 }
582 }
583 return $lines;
584}
585
df997f84
PS
586/**
587 * Returns list of courses user is enrolled into.
588 *
589 * - $fields is an array of fieldnames to ADD
590 * so name the fields you really need, which will
591 * be added and uniq'd
592 *
593 * @param int $userid
594 * @param bool $onlyactive return only active enrolments in courses user may see
eb6f592a 595 * @param string|array $fields
df997f84
PS
596 * @param string $sort
597 * @return array
598 */
599function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
600 global $DB;
601
602 // Guest account does not have any courses
87163782 603 if (isguestuser($userid) or empty($userid)) {
df997f84
PS
604 return(array());
605 }
606
607 $basefields = array('id', 'category', 'sortorder',
608 'shortname', 'fullname', 'idnumber',
609 'startdate', 'visible',
610 'groupmode', 'groupmodeforce');
611
612 if (empty($fields)) {
613 $fields = $basefields;
614 } else if (is_string($fields)) {
615 // turn the fields from a string to an array
616 $fields = explode(',', $fields);
617 $fields = array_map('trim', $fields);
618 $fields = array_unique(array_merge($basefields, $fields));
619 } else if (is_array($fields)) {
620 $fields = array_unique(array_merge($basefields, $fields));
621 } else {
622 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
623 }
624 if (in_array('*', $fields)) {
625 $fields = array('*');
626 }
627
628 $orderby = "";
629 $sort = trim($sort);
630 if (!empty($sort)) {
631 $rawsorts = explode(',', $sort);
632 $sorts = array();
633 foreach ($rawsorts as $rawsort) {
634 $rawsort = trim($rawsort);
635 if (strpos($rawsort, 'c.') === 0) {
636 $rawsort = substr($rawsort, 2);
637 }
638 $sorts[] = trim($rawsort);
639 }
640 $sort = 'c.'.implode(',c.', $sorts);
641 $orderby = "ORDER BY $sort";
642 }
643
df997f84
PS
644 $params = array('siteid'=>SITEID);
645
646 if ($onlyactive) {
4129338c 647 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
df997f84
PS
648 $params['now1'] = round(time(), -2); // improves db caching
649 $params['now2'] = $params['now1'];
650 $params['active'] = ENROL_USER_ACTIVE;
651 $params['enabled'] = ENROL_INSTANCE_ENABLED;
4129338c
PS
652 } else {
653 $subwhere = "";
df997f84
PS
654 }
655
656 $coursefields = 'c.' .join(',c.', $fields);
657 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
df997f84 658
4129338c
PS
659 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
660 $sql = "SELECT $coursefields $ccselect
df997f84 661 FROM {course} c
4129338c
PS
662 JOIN (SELECT DISTINCT e.courseid
663 FROM {enrol} e
664 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
665 $subwhere
666 ) en ON (en.courseid = c.id)
df997f84 667 $ccjoin
4129338c 668 WHERE c.id <> :siteid
df997f84 669 $orderby";
87163782 670 $params['userid'] = $userid;
df997f84
PS
671
672 $courses = $DB->get_records_sql($sql, $params);
673
674 // preload contexts and check visibility
675 foreach ($courses as $id=>$course) {
676 context_instance_preload($course);
677 if ($onlyactive) {
678 if (!$course->visible) {
679 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
4a5aba7c 680 unset($courses[$id]);
df997f84
PS
681 continue;
682 }
683 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
4a5aba7c 684 unset($courses[$id]);
df997f84
PS
685 continue;
686 }
687 }
688 }
689 $courses[$id] = $course;
690 }
691
692 //wow! Is that really all? :-D
693
694 return $courses;
695
696}
697
698/**
699 * Called when user is about to be deleted.
700 * @param object $user
701 * @return void
702 */
703function enrol_user_delete($user) {
704 global $DB;
705
706 $plugins = enrol_get_plugins(true);
707 foreach ($plugins as $plugin) {
708 $plugin->user_delete($user);
709 }
710
711 // force cleanup of all broken enrolments
712 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
713}
714
582bae08
PS
715/**
716 * Called when course is about to be deleted.
717 * @param stdClass $object
718 * @return void
719 */
720function enrol_course_delete($course) {
721 global $DB;
722
723 $instances = enrol_get_instances($course->id, false);
724 $plugins = enrol_get_plugins(true);
725 foreach ($instances as $instance) {
726 if (isset($plugins[$instance->enrol])) {
727 $plugins[$instance->enrol]->delete_instance($instance);
728 }
729 // low level delete in case plugin did not do it
730 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
731 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
732 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
733 $DB->delete_records('enrol', array('id'=>$instance->id));
734 }
735}
736
df997f84
PS
737/**
738 * Try to enrol user via default internal auth plugin.
739 *
740 * For now this is always using the manual enrol plugin...
741 *
742 * @param $courseid
743 * @param $userid
744 * @param $roleid
745 * @param $timestart
746 * @param $timeend
747 * @return bool success
748 */
749function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
750 global $DB;
751
752 //note: this is hardcoded to manual plugin for now
753
754 if (!enrol_is_enabled('manual')) {
755 return false;
756 }
757
758 if (!$enrol = enrol_get_plugin('manual')) {
759 return false;
760 }
761 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
762 return false;
763 }
764 $instance = reset($instances);
765
766 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
767
768 return true;
769}
770
45ff8a80
PS
771/**
772 * Is there a chance users might self enrol
773 * @param int $courseid
774 * @return bool
775 */
776function enrol_selfenrol_available($courseid) {
777 $result = false;
778
779 $plugins = enrol_get_plugins(true);
780 $enrolinstances = enrol_get_instances($courseid, true);
781 foreach($enrolinstances as $instance) {
782 if (!isset($plugins[$instance->enrol])) {
783 continue;
784 }
785 if ($instance->enrol === 'guest') {
786 // blacklist known temporary guest plugins
787 continue;
788 }
789 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
790 $result = true;
791 break;
792 }
793 }
794
795 return $result;
796}
797
df997f84
PS
798/**
799 * All enrol plugins should be based on this class,
800 * this is also the main source of documentation.
801 */
802abstract class enrol_plugin {
803 protected $config = null;
804
805 /**
806 * Returns name of this enrol plugin
807 * @return string
808 */
809 public function get_name() {
bf423bb1 810 // second word in class is always enrol name, sorry, no fancy plugin names with _
df997f84
PS
811 $words = explode('_', get_class($this));
812 return $words[1];
813 }
814
815 /**
816 * Returns localised name of enrol instance
817 *
818 * @param object $instance (null is accepted too)
819 * @return string
820 */
821 public function get_instance_name($instance) {
822 if (empty($instance->name)) {
823 $enrol = $this->get_name();
824 return get_string('pluginname', 'enrol_'.$enrol);
825 } else {
54475ccb
PS
826 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
827 return format_string($instance->name, true, array('context'=>$context));
df997f84
PS
828 }
829 }
830
bf423bb1
PS
831 /**
832 * Returns optional enrolment information icons.
833 *
834 * This is used in course list for quick overview of enrolment options.
835 *
836 * We are not using single instance parameter because sometimes
837 * we might want to prevent icon repetition when multiple instances
838 * of one type exist. One instance may also produce several icons.
839 *
840 * @param array $instances all enrol instances of this type in one course
841 * @return array of pix_icon
842 */
843 public function get_info_icons(array $instances) {
844 return array();
845 }
846
847 /**
848 * Returns optional enrolment instance description text.
849 *
850 * This is used in detailed course information.
851 *
852 *
853 * @param object $instance
854 * @return string short html text
855 */
856 public function get_description_text($instance) {
857 return null;
858 }
859
df997f84
PS
860 /**
861 * Makes sure config is loaded and cached.
862 * @return void
863 */
864 protected function load_config() {
865 if (!isset($this->config)) {
866 $name = $this->get_name();
867 if (!$config = get_config("enrol_$name")) {
365a5941 868 $config = new stdClass();
df997f84
PS
869 }
870 $this->config = $config;
871 }
872 }
873
874 /**
875 * Returns plugin config value
876 * @param string $name
877 * @param string $default value if config does not exist yet
878 * @return string value or default
879 */
880 public function get_config($name, $default = NULL) {
881 $this->load_config();
882 return isset($this->config->$name) ? $this->config->$name : $default;
883 }
884
885 /**
886 * Sets plugin config value
887 * @param string $name name of config
888 * @param string $value string config value, null means delete
889 * @return string value
890 */
891 public function set_config($name, $value) {
47811589 892 $pluginname = $this->get_name();
df997f84
PS
893 $this->load_config();
894 if ($value === NULL) {
895 unset($this->config->$name);
896 } else {
897 $this->config->$name = $value;
898 }
47811589 899 set_config($name, $value, "enrol_$pluginname");
df997f84
PS
900 }
901
902 /**
903 * Does this plugin assign protected roles are can they be manually removed?
904 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
905 */
906 public function roles_protected() {
907 return true;
908 }
909
91b99e80
PS
910 /**
911 * Does this plugin allow manual enrolments?
912 *
913 * @param stdClass $instance course enrol instance
914 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
915 *
916 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, trues means nobody may add more enrolments manually
917 */
918 public function allow_enrol(stdClass $instance) {
919 return false;
920 }
921
df997f84
PS
922 /**
923 * Does this plugin allow manual unenrolments?
924 *
925 * @param stdClass $instance course enrol instance
91b99e80 926 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
df997f84 927 *
91b99e80 928 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, trues means nobody may touch user_enrolments
df997f84
PS
929 */
930 public function allow_unenrol(stdClass $instance) {
931 return false;
932 }
933
934 /**
935 * Does this plugin allow manual changes in user_enrolments table?
936 *
91b99e80 937 * All plugins allowing this must implement 'enrol/xxx:manage' capability
df997f84
PS
938 *
939 * @param stdClass $instance course enrol instance
940 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
941 */
942 public function allow_manage(stdClass $instance) {
943 return false;
944 }
945
217d0397
PS
946 /**
947 * Does this plugin support some way to user to self enrol?
948 *
949 * @param stdClass $instance course enrol instance
950 *
951 * @return bool - true means show "Enrol me in this course" link in course UI
952 */
953 public function show_enrolme_link(stdClass $instance) {
954 return false;
955 }
956
df997f84
PS
957 /**
958 * Attempt to automatically enrol current user in course without any interaction,
959 * calling code has to make sure the plugin and instance are active.
960 *
961 * @param stdClass $instance course enrol instance
962 * @param stdClass $user record
963 * @return bool|int false means not enrolled, integer means timeend
964 */
965 public function try_autoenrol(stdClass $instance) {
966 global $USER;
967
968 return false;
969 }
970
971 /**
972 * Attempt to automatically gain temporary guest access to course,
973 * calling code has to make sure the plugin and instance are active.
974 *
975 * @param stdClass $instance course enrol instance
976 * @param stdClass $user record
977 * @return bool|int false means no guest access, integer means timeend
978 */
979 public function try_guestaccess(stdClass $instance) {
980 global $USER;
981
982 return false;
983 }
984
985 /**
986 * Enrol user into course via enrol instance.
987 *
988 * @param stdClass $instance
989 * @param int $userid
990 * @param int $roleid optional role id
2a6dcb72
PS
991 * @param int $timestart 0 means unknown
992 * @param int $timeend 0 means forever
f2a9be5f 993 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
df997f84
PS
994 * @return void
995 */
f2a9be5f 996 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
df997f84
PS
997 global $DB, $USER, $CFG; // CFG necessary!!!
998
999 if ($instance->courseid == SITEID) {
1000 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1001 }
1002
1003 $name = $this->get_name();
1004 $courseid = $instance->courseid;
1005
1006 if ($instance->enrol !== $name) {
1007 throw new coding_exception('invalid enrol instance!');
1008 }
1009 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1010
1011 $inserted = false;
1012 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1013 if ($ue->timestart != $timestart or $ue->timeend != $timeend) {
1014 $ue->timestart = $timestart;
1015 $ue->timeend = $timeend;
1016 $ue->modifier = $USER->id;
1017 $ue->timemodified = time();
1018 $DB->update_record('user_enrolments', $ue);
1019 }
1020 } else {
365a5941 1021 $ue = new stdClass();
df997f84
PS
1022 $ue->enrolid = $instance->id;
1023 $ue->status = ENROL_USER_ACTIVE;
1024 $ue->userid = $userid;
1025 $ue->timestart = $timestart;
1026 $ue->timeend = $timeend;
1027 $ue->modifier = $USER->id;
2a6dcb72
PS
1028 $ue->timecreated = time();
1029 $ue->timemodified = $ue->timecreated;
df997f84
PS
1030 $ue->id = $DB->insert_record('user_enrolments', $ue);
1031
1032 $inserted = true;
1033 }
1034
1035 if ($roleid) {
1036 if ($this->roles_protected()) {
1037 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1038 } else {
1039 role_assign($roleid, $userid, $context->id);
1040 }
1041 }
1042
1043 if ($inserted) {
1044 // add extra info and trigger event
1045 $ue->courseid = $courseid;
1046 $ue->enrol = $name;
1047 events_trigger('user_enrolled', $ue);
1048 }
1049
1050 // reset primitive require_login() caching
1051 if ($userid == $USER->id) {
1052 if (isset($USER->enrol['enrolled'][$courseid])) {
1053 unset($USER->enrol['enrolled'][$courseid]);
1054 }
1055 if (isset($USER->enrol['tempguest'][$courseid])) {
1056 unset($USER->enrol['tempguest'][$courseid]);
1057 $USER->access = remove_temp_roles($context, $USER->access);
1058 }
1059 }
1060 }
1061
1062 /**
1063 * Store user_enrolments changes and trigger event.
1064 *
1065 * @param object $ue
1066 * @param int $user id
1067 * @param int $status
1068 * @param int $timestart
1069 * @param int $timeend
1070 * @return void
1071 */
1072 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1073 global $DB, $USER;
1074
1075 $name = $this->get_name();
1076
1077 if ($instance->enrol !== $name) {
1078 throw new coding_exception('invalid enrol instance!');
1079 }
1080
1081 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1082 // weird, user not enrolled
1083 return;
1084 }
1085
1086 $modified = false;
1087 if (isset($status) and $ue->status != $status) {
1088 $ue->status = $status;
1089 $modified = true;
1090 }
1091 if (isset($timestart) and $ue->timestart != $timestart) {
1092 $ue->timestart = $timestart;
1093 $modified = true;
1094 }
1095 if (isset($timeend) and $ue->timeend != $timeend) {
1096 $ue->timeend = $timeend;
1097 $modified = true;
1098 }
1099
1100 if (!$modified) {
1101 // no change
1102 return;
1103 }
1104
1105 $ue->modifierid = $USER->id;
1106 $DB->update_record('user_enrolments', $ue);
1107
1108 // trigger event
1109 $ue->courseid = $instance->courseid;
1110 $ue->enrol = $instance->name;
1111 events_trigger('user_unenrol_modified', $ue);
1112 }
1113
1114 /**
1115 * Unenrol user from course,
1116 * the last unenrolment removes all remaining roles.
1117 *
1118 * @param stdClass $instance
1119 * @param int $userid
1120 * @return void
1121 */
1122 public function unenrol_user(stdClass $instance, $userid) {
1123 global $CFG, $USER, $DB;
1124
1125 $name = $this->get_name();
1126 $courseid = $instance->courseid;
1127
1128 if ($instance->enrol !== $name) {
1129 throw new coding_exception('invalid enrol instance!');
1130 }
1131 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1132
1133 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1134 // weird, user not enrolled
1135 return;
1136 }
1137
1138 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1139 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1140
1141 // add extra info and trigger event
1142 $ue->courseid = $courseid;
1143 $ue->enrol = $name;
1144
1145 $sql = "SELECT 'x'
1146 FROM {user_enrolments} ue
1147 JOIN {enrol} e ON (e.id = ue.enrolid)
1148 WHERE ue.userid = :userid AND e.courseid = :courseid";
1149 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1150 $ue->lastenrol = false;
1151 events_trigger('user_unenrolled', $ue);
1152 // user still has some enrolments, no big cleanup yet
1153 } else {
1154 // the big cleanup IS necessary!
1155
1156 require_once("$CFG->dirroot/group/lib.php");
1157 require_once("$CFG->libdir/gradelib.php");
1158
1159 // remove all remaining roles
1160 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1161
1162 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1163 groups_delete_group_members($courseid, $userid);
1164
1165 grade_user_unenrol($courseid, $userid);
1166
1167 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1168
7d2800fb 1169 $ue->lastenrol = true; // means user not enrolled any more
df997f84
PS
1170 events_trigger('user_unenrolled', $ue);
1171 }
1172 // reset primitive require_login() caching
1173 if ($userid == $USER->id) {
1174 if (isset($USER->enrol['enrolled'][$courseid])) {
1175 unset($USER->enrol['enrolled'][$courseid]);
1176 }
1177 if (isset($USER->enrol['tempguest'][$courseid])) {
1178 unset($USER->enrol['tempguest'][$courseid]);
1179 $USER->access = remove_temp_roles($context, $USER->access);
1180 }
1181 }
1182 }
1183
1184 /**
1185 * Forces synchronisation of user enrolments.
1186 *
1187 * This is important especially for external enrol plugins,
1188 * this function is called for all enabled enrol plugins
1189 * right after every user login.
1190 *
1191 * @param object $user user record
1192 * @return void
1193 */
1194 public function sync_user_enrolments($user) {
1195 // override if necessary
1196 }
1197
1198 /**
1199 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1200 * @param int $courseid
1201 * @return moodle_url page url
1202 */
e25f2466 1203 public function get_newinstance_link($courseid) {
df997f84
PS
1204 // override for most plugins, check if instance already exists in cases only one instance is supported
1205 return NULL;
1206 }
1207
1208 /**
1209 * Is it possible to delete enrol instance via standard UI?
1210 *
1211 * @param object $instance
1212 * @return bool
1213 */
1214 public function instance_deleteable($instance) {
1215 return true;
1216 }
1217
1218 /**
1219 * Returns link to manual enrol UI if exists.
1220 * Does the access control tests automatically.
1221 *
1222 * @param object $instance
1223 * @return moodle_url
1224 */
1225 public function get_manual_enrol_link($instance) {
1226 return NULL;
1227 }
1228
1229 /**
1230 * Returns list of unenrol links for all enrol instances in course.
1231 *
217d0397 1232 * @param int $instance
bf423bb1 1233 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1234 */
1235 public function get_unenrolself_link($instance) {
1236 global $USER, $CFG, $DB;
1237
1238 $name = $this->get_name();
1239 if ($instance->enrol !== $name) {
1240 throw new coding_exception('invalid enrol instance!');
1241 }
1242
1243 if ($instance->courseid == SITEID) {
1244 return NULL;
1245 }
1246
1247 if (!enrol_is_enabled($name)) {
1248 return NULL;
1249 }
1250
1251 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1252 return NULL;
1253 }
1254
df997f84
PS
1255 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1256 return NULL;
1257 }
1258
217d0397
PS
1259 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1260
df997f84
PS
1261 if (!has_capability("enrol/$name:unenrolself", $context)) {
1262 return NULL;
1263 }
1264
1265 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1266 return NULL;
1267 }
1268
1269 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1270 }
1271
1272 /**
1273 * Adds enrol instance UI to course edit form
1274 *
1275 * @param object $instance enrol instance or null if does not exist yet
1276 * @param MoodleQuickForm $mform
1277 * @param object $data
1278 * @param object $context context of existing course or parent category if course does not exist
1279 * @return void
1280 */
1281 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1282 // override - usually at least enable/disable switch, has to add own form header
1283 }
1284
1285 /**
1286 * Validates course edit form data
1287 *
1288 * @param object $instance enrol instance or null if does not exist yet
1289 * @param array $data
1290 * @param object $context context of existing course or parent category if course does not exist
1291 * @return array errors array
1292 */
1293 public function course_edit_validation($instance, array $data, $context) {
1294 return array();
1295 }
1296
1297 /**
1298 * Called after updating/inserting course.
1299 *
1300 * @param bool $inserted true if course just inserted
1301 * @param object $course
1302 * @param object $data form data
1303 * @return void
1304 */
1305 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
1306 if ($inserted) {
1307 if ($this->get_config('defaultenrol')) {
1308 $this->add_default_instance($course);
1309 }
1310 }
df997f84
PS
1311 }
1312
1313 /**
eafb7a72 1314 * Add new instance of enrol plugin.
df997f84
PS
1315 * @param object $course
1316 * @param array instance fields
0848a196 1317 * @return int id of new instance, null if can not be created
df997f84
PS
1318 */
1319 public function add_instance($course, array $fields = NULL) {
1320 global $DB;
1321
1322 if ($course->id == SITEID) {
1323 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1324 }
1325
365a5941 1326 $instance = new stdClass();
df997f84
PS
1327 $instance->enrol = $this->get_name();
1328 $instance->status = ENROL_INSTANCE_ENABLED;
1329 $instance->courseid = $course->id;
1330 $instance->enrolstartdate = 0;
1331 $instance->enrolenddate = 0;
1332 $instance->timemodified = time();
1333 $instance->timecreated = $instance->timemodified;
1334 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1335
1336 $fields = (array)$fields;
1337 unset($fields['enrol']);
1338 unset($fields['courseid']);
1339 unset($fields['sortorder']);
1340 foreach($fields as $field=>$value) {
1341 $instance->$field = $value;
1342 }
1343
1344 return $DB->insert_record('enrol', $instance);
1345 }
1346
1347 /**
1348 * Add new instance of enrol plugin with default settings,
1349 * called when adding new instance manually or when adding new course.
1350 *
1351 * Not all plugins support this.
1352 *
1353 * @param object $course
1354 * @return int id of new instance or null if no default supported
1355 */
1356 public function add_default_instance($course) {
1357 return null;
1358 }
1359
1360 /**
1361 * Delete course enrol plugin instance, unenrol all users.
1362 * @param object $instance
1363 * @return void
1364 */
1365 public function delete_instance($instance) {
1366 global $DB;
1367
1368 $name = $this->get_name();
1369 if ($instance->enrol !== $name) {
1370 throw new coding_exception('invalid enrol instance!');
1371 }
1372
1373 //first unenrol all users
1374 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1375 foreach ($participants as $participant) {
1376 $this->unenrol_user($instance, $participant->userid);
1377 }
1378 $participants->close();
1379
1380 // now clean up all remainders that were not removed correctly
1381 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1382 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1383
1384 // finally drop the enrol row
1385 $DB->delete_records('enrol', array('id'=>$instance->id));
1386 }
1387
1388 /**
1389 * Creates course enrol form, checks if form submitted
1390 * and enrols user if necessary. It can also redirect.
1391 *
1392 * @param stdClass $instance
1393 * @return string html text, usually a form in a text box
1394 */
1395 public function enrol_page_hook(stdClass $instance) {
1396 return null;
1397 }
1398
1399 /**
1400 * Adds navigation links into course admin block.
1401 *
1402 * By defaults looks for manage links only.
1403 *
1404 * @param navigation_node $instancesnode
1405 * @param object $instance
2d4b1f3e 1406 * @return void
df997f84
PS
1407 */
1408 public function add_course_navigation($instancesnode, stdClass $instance) {
2d4b1f3e 1409 // usually adds manage users
df997f84
PS
1410 }
1411
1412 /**
2d4b1f3e
PS
1413 * Returns edit icons for the page with list of instances
1414 * @param stdClass $instance
1415 * @return array
df997f84 1416 */
2d4b1f3e
PS
1417 public function get_action_icons(stdClass $instance) {
1418 return array();
df997f84
PS
1419 }
1420
1421 /**
1422 * Reads version.php and determines if it is necessary
1423 * to execute the cron job now.
1424 * @return bool
1425 */
1426 public function is_cron_required() {
1427 global $CFG;
1428
1429 $name = $this->get_name();
1430 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 1431 $plugin = new stdClass();
df997f84
PS
1432 include($versionfile);
1433 if (empty($plugin->cron)) {
1434 return false;
1435 }
1436 $lastexecuted = $this->get_config('lastcron', 0);
1437 if ($lastexecuted + $plugin->cron < time()) {
1438 return true;
1439 } else {
1440 return false;
1441 }
1442 }
1443
1444 /**
1445 * Called for all enabled enrol plugins that returned true from is_cron_required().
1446 * @return void
1447 */
1448 public function cron() {
1449 }
1450
1451 /**
1452 * Called when user is about to be deleted
1453 * @param object $user
1454 * @return void
1455 */
1456 public function user_delete($user) {
1457 global $DB;
1458
1459 $sql = "SELECT e.*
1460 FROM {enrol} e
45fb2cf8
PS
1461 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1462 WHERE e.enrol = :name AND ue.userid = :userid";
df997f84
PS
1463 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1464
45fb2cf8 1465 $rs = $DB->get_recordset_sql($sql, $params);
df997f84
PS
1466 foreach($rs as $instance) {
1467 $this->unenrol_user($instance, $user->id);
1468 }
1469 $rs->close();
1470 }
1471}
1472