weekly release
[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 *
ed1d72ea
SH
961 * This should return either a timestamp in the future or false.
962 *
df997f84
PS
963 * @param stdClass $instance course enrol instance
964 * @param stdClass $user record
965 * @return bool|int false means not enrolled, integer means timeend
966 */
967 public function try_autoenrol(stdClass $instance) {
968 global $USER;
969
970 return false;
971 }
972
973 /**
974 * Attempt to automatically gain temporary guest access to course,
975 * calling code has to make sure the plugin and instance are active.
976 *
ed1d72ea
SH
977 * This should return either a timestamp in the future or false.
978 *
df997f84
PS
979 * @param stdClass $instance course enrol instance
980 * @param stdClass $user record
981 * @return bool|int false means no guest access, integer means timeend
982 */
983 public function try_guestaccess(stdClass $instance) {
984 global $USER;
985
986 return false;
987 }
988
989 /**
990 * Enrol user into course via enrol instance.
991 *
992 * @param stdClass $instance
993 * @param int $userid
994 * @param int $roleid optional role id
2a6dcb72
PS
995 * @param int $timestart 0 means unknown
996 * @param int $timeend 0 means forever
f2a9be5f 997 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
df997f84
PS
998 * @return void
999 */
f2a9be5f 1000 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
df997f84
PS
1001 global $DB, $USER, $CFG; // CFG necessary!!!
1002
1003 if ($instance->courseid == SITEID) {
1004 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1005 }
1006
1007 $name = $this->get_name();
1008 $courseid = $instance->courseid;
1009
1010 if ($instance->enrol !== $name) {
1011 throw new coding_exception('invalid enrol instance!');
1012 }
1013 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1014
1015 $inserted = false;
1016 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1017 if ($ue->timestart != $timestart or $ue->timeend != $timeend) {
1018 $ue->timestart = $timestart;
1019 $ue->timeend = $timeend;
1020 $ue->modifier = $USER->id;
1021 $ue->timemodified = time();
1022 $DB->update_record('user_enrolments', $ue);
1023 }
1024 } else {
365a5941 1025 $ue = new stdClass();
df997f84
PS
1026 $ue->enrolid = $instance->id;
1027 $ue->status = ENROL_USER_ACTIVE;
1028 $ue->userid = $userid;
1029 $ue->timestart = $timestart;
1030 $ue->timeend = $timeend;
1031 $ue->modifier = $USER->id;
2a6dcb72
PS
1032 $ue->timecreated = time();
1033 $ue->timemodified = $ue->timecreated;
df997f84
PS
1034 $ue->id = $DB->insert_record('user_enrolments', $ue);
1035
1036 $inserted = true;
1037 }
1038
1039 if ($roleid) {
1040 if ($this->roles_protected()) {
1041 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1042 } else {
1043 role_assign($roleid, $userid, $context->id);
1044 }
1045 }
1046
1047 if ($inserted) {
1048 // add extra info and trigger event
1049 $ue->courseid = $courseid;
1050 $ue->enrol = $name;
1051 events_trigger('user_enrolled', $ue);
1052 }
1053
1054 // reset primitive require_login() caching
1055 if ($userid == $USER->id) {
1056 if (isset($USER->enrol['enrolled'][$courseid])) {
1057 unset($USER->enrol['enrolled'][$courseid]);
1058 }
1059 if (isset($USER->enrol['tempguest'][$courseid])) {
1060 unset($USER->enrol['tempguest'][$courseid]);
1061 $USER->access = remove_temp_roles($context, $USER->access);
1062 }
1063 }
1064 }
1065
1066 /**
1067 * Store user_enrolments changes and trigger event.
1068 *
1069 * @param object $ue
1070 * @param int $user id
1071 * @param int $status
1072 * @param int $timestart
1073 * @param int $timeend
1074 * @return void
1075 */
1076 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1077 global $DB, $USER;
1078
1079 $name = $this->get_name();
1080
1081 if ($instance->enrol !== $name) {
1082 throw new coding_exception('invalid enrol instance!');
1083 }
1084
1085 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1086 // weird, user not enrolled
1087 return;
1088 }
1089
1090 $modified = false;
1091 if (isset($status) and $ue->status != $status) {
1092 $ue->status = $status;
1093 $modified = true;
1094 }
1095 if (isset($timestart) and $ue->timestart != $timestart) {
1096 $ue->timestart = $timestart;
1097 $modified = true;
1098 }
1099 if (isset($timeend) and $ue->timeend != $timeend) {
1100 $ue->timeend = $timeend;
1101 $modified = true;
1102 }
1103
1104 if (!$modified) {
1105 // no change
1106 return;
1107 }
1108
1109 $ue->modifierid = $USER->id;
1110 $DB->update_record('user_enrolments', $ue);
1111
1112 // trigger event
1113 $ue->courseid = $instance->courseid;
1114 $ue->enrol = $instance->name;
1115 events_trigger('user_unenrol_modified', $ue);
1116 }
1117
1118 /**
1119 * Unenrol user from course,
1120 * the last unenrolment removes all remaining roles.
1121 *
1122 * @param stdClass $instance
1123 * @param int $userid
1124 * @return void
1125 */
1126 public function unenrol_user(stdClass $instance, $userid) {
1127 global $CFG, $USER, $DB;
1128
1129 $name = $this->get_name();
1130 $courseid = $instance->courseid;
1131
1132 if ($instance->enrol !== $name) {
1133 throw new coding_exception('invalid enrol instance!');
1134 }
1135 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1136
1137 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1138 // weird, user not enrolled
1139 return;
1140 }
1141
1142 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1143 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1144
1145 // add extra info and trigger event
1146 $ue->courseid = $courseid;
1147 $ue->enrol = $name;
1148
1149 $sql = "SELECT 'x'
1150 FROM {user_enrolments} ue
1151 JOIN {enrol} e ON (e.id = ue.enrolid)
1152 WHERE ue.userid = :userid AND e.courseid = :courseid";
1153 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1154 $ue->lastenrol = false;
1155 events_trigger('user_unenrolled', $ue);
1156 // user still has some enrolments, no big cleanup yet
1157 } else {
1158 // the big cleanup IS necessary!
1159
1160 require_once("$CFG->dirroot/group/lib.php");
1161 require_once("$CFG->libdir/gradelib.php");
1162
1163 // remove all remaining roles
1164 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1165
1166 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1167 groups_delete_group_members($courseid, $userid);
1168
1169 grade_user_unenrol($courseid, $userid);
1170
1171 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1172
7d2800fb 1173 $ue->lastenrol = true; // means user not enrolled any more
df997f84
PS
1174 events_trigger('user_unenrolled', $ue);
1175 }
1176 // reset primitive require_login() caching
1177 if ($userid == $USER->id) {
1178 if (isset($USER->enrol['enrolled'][$courseid])) {
1179 unset($USER->enrol['enrolled'][$courseid]);
1180 }
1181 if (isset($USER->enrol['tempguest'][$courseid])) {
1182 unset($USER->enrol['tempguest'][$courseid]);
1183 $USER->access = remove_temp_roles($context, $USER->access);
1184 }
1185 }
1186 }
1187
1188 /**
1189 * Forces synchronisation of user enrolments.
1190 *
1191 * This is important especially for external enrol plugins,
1192 * this function is called for all enabled enrol plugins
1193 * right after every user login.
1194 *
1195 * @param object $user user record
1196 * @return void
1197 */
1198 public function sync_user_enrolments($user) {
1199 // override if necessary
1200 }
1201
1202 /**
1203 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1204 * @param int $courseid
1205 * @return moodle_url page url
1206 */
e25f2466 1207 public function get_newinstance_link($courseid) {
df997f84
PS
1208 // override for most plugins, check if instance already exists in cases only one instance is supported
1209 return NULL;
1210 }
1211
1212 /**
1213 * Is it possible to delete enrol instance via standard UI?
1214 *
1215 * @param object $instance
1216 * @return bool
1217 */
1218 public function instance_deleteable($instance) {
1219 return true;
1220 }
1221
1222 /**
1223 * Returns link to manual enrol UI if exists.
1224 * Does the access control tests automatically.
1225 *
1226 * @param object $instance
1227 * @return moodle_url
1228 */
1229 public function get_manual_enrol_link($instance) {
1230 return NULL;
1231 }
1232
1233 /**
1234 * Returns list of unenrol links for all enrol instances in course.
1235 *
217d0397 1236 * @param int $instance
bf423bb1 1237 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1238 */
1239 public function get_unenrolself_link($instance) {
1240 global $USER, $CFG, $DB;
1241
1242 $name = $this->get_name();
1243 if ($instance->enrol !== $name) {
1244 throw new coding_exception('invalid enrol instance!');
1245 }
1246
1247 if ($instance->courseid == SITEID) {
1248 return NULL;
1249 }
1250
1251 if (!enrol_is_enabled($name)) {
1252 return NULL;
1253 }
1254
1255 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1256 return NULL;
1257 }
1258
df997f84
PS
1259 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1260 return NULL;
1261 }
1262
217d0397
PS
1263 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1264
df997f84
PS
1265 if (!has_capability("enrol/$name:unenrolself", $context)) {
1266 return NULL;
1267 }
1268
1269 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1270 return NULL;
1271 }
1272
1273 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1274 }
1275
1276 /**
1277 * Adds enrol instance UI to course edit form
1278 *
1279 * @param object $instance enrol instance or null if does not exist yet
1280 * @param MoodleQuickForm $mform
1281 * @param object $data
1282 * @param object $context context of existing course or parent category if course does not exist
1283 * @return void
1284 */
1285 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1286 // override - usually at least enable/disable switch, has to add own form header
1287 }
1288
1289 /**
1290 * Validates course edit form data
1291 *
1292 * @param object $instance enrol instance or null if does not exist yet
1293 * @param array $data
1294 * @param object $context context of existing course or parent category if course does not exist
1295 * @return array errors array
1296 */
1297 public function course_edit_validation($instance, array $data, $context) {
1298 return array();
1299 }
1300
1301 /**
1302 * Called after updating/inserting course.
1303 *
1304 * @param bool $inserted true if course just inserted
1305 * @param object $course
1306 * @param object $data form data
1307 * @return void
1308 */
1309 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
1310 if ($inserted) {
1311 if ($this->get_config('defaultenrol')) {
1312 $this->add_default_instance($course);
1313 }
1314 }
df997f84
PS
1315 }
1316
1317 /**
eafb7a72 1318 * Add new instance of enrol plugin.
df997f84
PS
1319 * @param object $course
1320 * @param array instance fields
0848a196 1321 * @return int id of new instance, null if can not be created
df997f84
PS
1322 */
1323 public function add_instance($course, array $fields = NULL) {
1324 global $DB;
1325
1326 if ($course->id == SITEID) {
1327 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1328 }
1329
365a5941 1330 $instance = new stdClass();
df997f84
PS
1331 $instance->enrol = $this->get_name();
1332 $instance->status = ENROL_INSTANCE_ENABLED;
1333 $instance->courseid = $course->id;
1334 $instance->enrolstartdate = 0;
1335 $instance->enrolenddate = 0;
1336 $instance->timemodified = time();
1337 $instance->timecreated = $instance->timemodified;
1338 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1339
1340 $fields = (array)$fields;
1341 unset($fields['enrol']);
1342 unset($fields['courseid']);
1343 unset($fields['sortorder']);
1344 foreach($fields as $field=>$value) {
1345 $instance->$field = $value;
1346 }
1347
1348 return $DB->insert_record('enrol', $instance);
1349 }
1350
1351 /**
1352 * Add new instance of enrol plugin with default settings,
1353 * called when adding new instance manually or when adding new course.
1354 *
1355 * Not all plugins support this.
1356 *
1357 * @param object $course
1358 * @return int id of new instance or null if no default supported
1359 */
1360 public function add_default_instance($course) {
1361 return null;
1362 }
1363
1364 /**
1365 * Delete course enrol plugin instance, unenrol all users.
1366 * @param object $instance
1367 * @return void
1368 */
1369 public function delete_instance($instance) {
1370 global $DB;
1371
1372 $name = $this->get_name();
1373 if ($instance->enrol !== $name) {
1374 throw new coding_exception('invalid enrol instance!');
1375 }
1376
1377 //first unenrol all users
1378 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1379 foreach ($participants as $participant) {
1380 $this->unenrol_user($instance, $participant->userid);
1381 }
1382 $participants->close();
1383
1384 // now clean up all remainders that were not removed correctly
1385 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1386 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1387
1388 // finally drop the enrol row
1389 $DB->delete_records('enrol', array('id'=>$instance->id));
1390 }
1391
1392 /**
1393 * Creates course enrol form, checks if form submitted
1394 * and enrols user if necessary. It can also redirect.
1395 *
1396 * @param stdClass $instance
1397 * @return string html text, usually a form in a text box
1398 */
1399 public function enrol_page_hook(stdClass $instance) {
1400 return null;
1401 }
1402
1403 /**
1404 * Adds navigation links into course admin block.
1405 *
1406 * By defaults looks for manage links only.
1407 *
1408 * @param navigation_node $instancesnode
1409 * @param object $instance
2d4b1f3e 1410 * @return void
df997f84
PS
1411 */
1412 public function add_course_navigation($instancesnode, stdClass $instance) {
2d4b1f3e 1413 // usually adds manage users
df997f84
PS
1414 }
1415
1416 /**
2d4b1f3e
PS
1417 * Returns edit icons for the page with list of instances
1418 * @param stdClass $instance
1419 * @return array
df997f84 1420 */
2d4b1f3e
PS
1421 public function get_action_icons(stdClass $instance) {
1422 return array();
df997f84
PS
1423 }
1424
1425 /**
1426 * Reads version.php and determines if it is necessary
1427 * to execute the cron job now.
1428 * @return bool
1429 */
1430 public function is_cron_required() {
1431 global $CFG;
1432
1433 $name = $this->get_name();
1434 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 1435 $plugin = new stdClass();
df997f84
PS
1436 include($versionfile);
1437 if (empty($plugin->cron)) {
1438 return false;
1439 }
1440 $lastexecuted = $this->get_config('lastcron', 0);
1441 if ($lastexecuted + $plugin->cron < time()) {
1442 return true;
1443 } else {
1444 return false;
1445 }
1446 }
1447
1448 /**
1449 * Called for all enabled enrol plugins that returned true from is_cron_required().
1450 * @return void
1451 */
1452 public function cron() {
1453 }
1454
1455 /**
1456 * Called when user is about to be deleted
1457 * @param object $user
1458 * @return void
1459 */
1460 public function user_delete($user) {
1461 global $DB;
1462
1463 $sql = "SELECT e.*
1464 FROM {enrol} e
45fb2cf8
PS
1465 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1466 WHERE e.enrol = :name AND ue.userid = :userid";
df997f84
PS
1467 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1468
45fb2cf8 1469 $rs = $DB->get_recordset_sql($sql, $params);
df997f84
PS
1470 foreach($rs as $instance) {
1471 $this->unenrol_user($instance, $user->id);
1472 }
1473 $rs->close();
1474 }
1475}
1476