MDL-22148 backup - support for manual/self/guest enrolments. Credit goes to Petr.
[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
771/**
772 * All enrol plugins should be based on this class,
773 * this is also the main source of documentation.
774 */
775abstract class enrol_plugin {
776 protected $config = null;
777
778 /**
779 * Returns name of this enrol plugin
780 * @return string
781 */
782 public function get_name() {
bf423bb1 783 // second word in class is always enrol name, sorry, no fancy plugin names with _
df997f84
PS
784 $words = explode('_', get_class($this));
785 return $words[1];
786 }
787
788 /**
789 * Returns localised name of enrol instance
790 *
791 * @param object $instance (null is accepted too)
792 * @return string
793 */
794 public function get_instance_name($instance) {
795 if (empty($instance->name)) {
796 $enrol = $this->get_name();
797 return get_string('pluginname', 'enrol_'.$enrol);
798 } else {
54475ccb
PS
799 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
800 return format_string($instance->name, true, array('context'=>$context));
df997f84
PS
801 }
802 }
803
bf423bb1
PS
804 /**
805 * Returns optional enrolment information icons.
806 *
807 * This is used in course list for quick overview of enrolment options.
808 *
809 * We are not using single instance parameter because sometimes
810 * we might want to prevent icon repetition when multiple instances
811 * of one type exist. One instance may also produce several icons.
812 *
813 * @param array $instances all enrol instances of this type in one course
814 * @return array of pix_icon
815 */
816 public function get_info_icons(array $instances) {
817 return array();
818 }
819
820 /**
821 * Returns optional enrolment instance description text.
822 *
823 * This is used in detailed course information.
824 *
825 *
826 * @param object $instance
827 * @return string short html text
828 */
829 public function get_description_text($instance) {
830 return null;
831 }
832
df997f84
PS
833 /**
834 * Makes sure config is loaded and cached.
835 * @return void
836 */
837 protected function load_config() {
838 if (!isset($this->config)) {
839 $name = $this->get_name();
840 if (!$config = get_config("enrol_$name")) {
365a5941 841 $config = new stdClass();
df997f84
PS
842 }
843 $this->config = $config;
844 }
845 }
846
847 /**
848 * Returns plugin config value
849 * @param string $name
850 * @param string $default value if config does not exist yet
851 * @return string value or default
852 */
853 public function get_config($name, $default = NULL) {
854 $this->load_config();
855 return isset($this->config->$name) ? $this->config->$name : $default;
856 }
857
858 /**
859 * Sets plugin config value
860 * @param string $name name of config
861 * @param string $value string config value, null means delete
862 * @return string value
863 */
864 public function set_config($name, $value) {
47811589 865 $pluginname = $this->get_name();
df997f84
PS
866 $this->load_config();
867 if ($value === NULL) {
868 unset($this->config->$name);
869 } else {
870 $this->config->$name = $value;
871 }
47811589 872 set_config($name, $value, "enrol_$pluginname");
df997f84
PS
873 }
874
875 /**
876 * Does this plugin assign protected roles are can they be manually removed?
877 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
878 */
879 public function roles_protected() {
880 return true;
881 }
882
91b99e80
PS
883 /**
884 * Does this plugin allow manual enrolments?
885 *
886 * @param stdClass $instance course enrol instance
887 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
888 *
889 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, trues means nobody may add more enrolments manually
890 */
891 public function allow_enrol(stdClass $instance) {
892 return false;
893 }
894
df997f84
PS
895 /**
896 * Does this plugin allow manual unenrolments?
897 *
898 * @param stdClass $instance course enrol instance
91b99e80 899 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
df997f84 900 *
91b99e80 901 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, trues means nobody may touch user_enrolments
df997f84
PS
902 */
903 public function allow_unenrol(stdClass $instance) {
904 return false;
905 }
906
907 /**
908 * Does this plugin allow manual changes in user_enrolments table?
909 *
91b99e80 910 * All plugins allowing this must implement 'enrol/xxx:manage' capability
df997f84
PS
911 *
912 * @param stdClass $instance course enrol instance
913 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
914 */
915 public function allow_manage(stdClass $instance) {
916 return false;
917 }
918
217d0397
PS
919 /**
920 * Does this plugin support some way to user to self enrol?
921 *
922 * @param stdClass $instance course enrol instance
923 *
924 * @return bool - true means show "Enrol me in this course" link in course UI
925 */
926 public function show_enrolme_link(stdClass $instance) {
927 return false;
928 }
929
df997f84
PS
930 /**
931 * Attempt to automatically enrol current user in course without any interaction,
932 * calling code has to make sure the plugin and instance are active.
933 *
934 * @param stdClass $instance course enrol instance
935 * @param stdClass $user record
936 * @return bool|int false means not enrolled, integer means timeend
937 */
938 public function try_autoenrol(stdClass $instance) {
939 global $USER;
940
941 return false;
942 }
943
944 /**
945 * Attempt to automatically gain temporary guest access to course,
946 * calling code has to make sure the plugin and instance are active.
947 *
948 * @param stdClass $instance course enrol instance
949 * @param stdClass $user record
950 * @return bool|int false means no guest access, integer means timeend
951 */
952 public function try_guestaccess(stdClass $instance) {
953 global $USER;
954
955 return false;
956 }
957
958 /**
959 * Enrol user into course via enrol instance.
960 *
961 * @param stdClass $instance
962 * @param int $userid
963 * @param int $roleid optional role id
2a6dcb72
PS
964 * @param int $timestart 0 means unknown
965 * @param int $timeend 0 means forever
f2a9be5f 966 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
df997f84
PS
967 * @return void
968 */
f2a9be5f 969 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
df997f84
PS
970 global $DB, $USER, $CFG; // CFG necessary!!!
971
972 if ($instance->courseid == SITEID) {
973 throw new coding_exception('invalid attempt to enrol into frontpage course!');
974 }
975
976 $name = $this->get_name();
977 $courseid = $instance->courseid;
978
979 if ($instance->enrol !== $name) {
980 throw new coding_exception('invalid enrol instance!');
981 }
982 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
983
984 $inserted = false;
985 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
986 if ($ue->timestart != $timestart or $ue->timeend != $timeend) {
987 $ue->timestart = $timestart;
988 $ue->timeend = $timeend;
989 $ue->modifier = $USER->id;
990 $ue->timemodified = time();
991 $DB->update_record('user_enrolments', $ue);
992 }
993 } else {
365a5941 994 $ue = new stdClass();
df997f84
PS
995 $ue->enrolid = $instance->id;
996 $ue->status = ENROL_USER_ACTIVE;
997 $ue->userid = $userid;
998 $ue->timestart = $timestart;
999 $ue->timeend = $timeend;
1000 $ue->modifier = $USER->id;
2a6dcb72
PS
1001 $ue->timecreated = time();
1002 $ue->timemodified = $ue->timecreated;
df997f84
PS
1003 $ue->id = $DB->insert_record('user_enrolments', $ue);
1004
1005 $inserted = true;
1006 }
1007
1008 if ($roleid) {
1009 if ($this->roles_protected()) {
1010 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1011 } else {
1012 role_assign($roleid, $userid, $context->id);
1013 }
1014 }
1015
1016 if ($inserted) {
1017 // add extra info and trigger event
1018 $ue->courseid = $courseid;
1019 $ue->enrol = $name;
1020 events_trigger('user_enrolled', $ue);
1021 }
1022
1023 // reset primitive require_login() caching
1024 if ($userid == $USER->id) {
1025 if (isset($USER->enrol['enrolled'][$courseid])) {
1026 unset($USER->enrol['enrolled'][$courseid]);
1027 }
1028 if (isset($USER->enrol['tempguest'][$courseid])) {
1029 unset($USER->enrol['tempguest'][$courseid]);
1030 $USER->access = remove_temp_roles($context, $USER->access);
1031 }
1032 }
1033 }
1034
1035 /**
1036 * Store user_enrolments changes and trigger event.
1037 *
1038 * @param object $ue
1039 * @param int $user id
1040 * @param int $status
1041 * @param int $timestart
1042 * @param int $timeend
1043 * @return void
1044 */
1045 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1046 global $DB, $USER;
1047
1048 $name = $this->get_name();
1049
1050 if ($instance->enrol !== $name) {
1051 throw new coding_exception('invalid enrol instance!');
1052 }
1053
1054 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1055 // weird, user not enrolled
1056 return;
1057 }
1058
1059 $modified = false;
1060 if (isset($status) and $ue->status != $status) {
1061 $ue->status = $status;
1062 $modified = true;
1063 }
1064 if (isset($timestart) and $ue->timestart != $timestart) {
1065 $ue->timestart = $timestart;
1066 $modified = true;
1067 }
1068 if (isset($timeend) and $ue->timeend != $timeend) {
1069 $ue->timeend = $timeend;
1070 $modified = true;
1071 }
1072
1073 if (!$modified) {
1074 // no change
1075 return;
1076 }
1077
1078 $ue->modifierid = $USER->id;
1079 $DB->update_record('user_enrolments', $ue);
1080
1081 // trigger event
1082 $ue->courseid = $instance->courseid;
1083 $ue->enrol = $instance->name;
1084 events_trigger('user_unenrol_modified', $ue);
1085 }
1086
1087 /**
1088 * Unenrol user from course,
1089 * the last unenrolment removes all remaining roles.
1090 *
1091 * @param stdClass $instance
1092 * @param int $userid
1093 * @return void
1094 */
1095 public function unenrol_user(stdClass $instance, $userid) {
1096 global $CFG, $USER, $DB;
1097
1098 $name = $this->get_name();
1099 $courseid = $instance->courseid;
1100
1101 if ($instance->enrol !== $name) {
1102 throw new coding_exception('invalid enrol instance!');
1103 }
1104 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1105
1106 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1107 // weird, user not enrolled
1108 return;
1109 }
1110
1111 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1112 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1113
1114 // add extra info and trigger event
1115 $ue->courseid = $courseid;
1116 $ue->enrol = $name;
1117
1118 $sql = "SELECT 'x'
1119 FROM {user_enrolments} ue
1120 JOIN {enrol} e ON (e.id = ue.enrolid)
1121 WHERE ue.userid = :userid AND e.courseid = :courseid";
1122 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1123 $ue->lastenrol = false;
1124 events_trigger('user_unenrolled', $ue);
1125 // user still has some enrolments, no big cleanup yet
1126 } else {
1127 // the big cleanup IS necessary!
1128
1129 require_once("$CFG->dirroot/group/lib.php");
1130 require_once("$CFG->libdir/gradelib.php");
1131
1132 // remove all remaining roles
1133 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1134
1135 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1136 groups_delete_group_members($courseid, $userid);
1137
1138 grade_user_unenrol($courseid, $userid);
1139
1140 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1141
7d2800fb 1142 $ue->lastenrol = true; // means user not enrolled any more
df997f84
PS
1143 events_trigger('user_unenrolled', $ue);
1144 }
1145 // reset primitive require_login() caching
1146 if ($userid == $USER->id) {
1147 if (isset($USER->enrol['enrolled'][$courseid])) {
1148 unset($USER->enrol['enrolled'][$courseid]);
1149 }
1150 if (isset($USER->enrol['tempguest'][$courseid])) {
1151 unset($USER->enrol['tempguest'][$courseid]);
1152 $USER->access = remove_temp_roles($context, $USER->access);
1153 }
1154 }
1155 }
1156
1157 /**
1158 * Forces synchronisation of user enrolments.
1159 *
1160 * This is important especially for external enrol plugins,
1161 * this function is called for all enabled enrol plugins
1162 * right after every user login.
1163 *
1164 * @param object $user user record
1165 * @return void
1166 */
1167 public function sync_user_enrolments($user) {
1168 // override if necessary
1169 }
1170
1171 /**
1172 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1173 * @param int $courseid
1174 * @return moodle_url page url
1175 */
e25f2466 1176 public function get_newinstance_link($courseid) {
df997f84
PS
1177 // override for most plugins, check if instance already exists in cases only one instance is supported
1178 return NULL;
1179 }
1180
1181 /**
1182 * Is it possible to delete enrol instance via standard UI?
1183 *
1184 * @param object $instance
1185 * @return bool
1186 */
1187 public function instance_deleteable($instance) {
1188 return true;
1189 }
1190
1191 /**
1192 * Returns link to manual enrol UI if exists.
1193 * Does the access control tests automatically.
1194 *
1195 * @param object $instance
1196 * @return moodle_url
1197 */
1198 public function get_manual_enrol_link($instance) {
1199 return NULL;
1200 }
1201
1202 /**
1203 * Returns list of unenrol links for all enrol instances in course.
1204 *
217d0397 1205 * @param int $instance
bf423bb1 1206 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1207 */
1208 public function get_unenrolself_link($instance) {
1209 global $USER, $CFG, $DB;
1210
1211 $name = $this->get_name();
1212 if ($instance->enrol !== $name) {
1213 throw new coding_exception('invalid enrol instance!');
1214 }
1215
1216 if ($instance->courseid == SITEID) {
1217 return NULL;
1218 }
1219
1220 if (!enrol_is_enabled($name)) {
1221 return NULL;
1222 }
1223
1224 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1225 return NULL;
1226 }
1227
df997f84
PS
1228 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1229 return NULL;
1230 }
1231
217d0397
PS
1232 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1233
df997f84
PS
1234 if (!has_capability("enrol/$name:unenrolself", $context)) {
1235 return NULL;
1236 }
1237
1238 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1239 return NULL;
1240 }
1241
1242 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1243 }
1244
1245 /**
1246 * Adds enrol instance UI to course edit form
1247 *
1248 * @param object $instance enrol instance or null if does not exist yet
1249 * @param MoodleQuickForm $mform
1250 * @param object $data
1251 * @param object $context context of existing course or parent category if course does not exist
1252 * @return void
1253 */
1254 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1255 // override - usually at least enable/disable switch, has to add own form header
1256 }
1257
1258 /**
1259 * Validates course edit form data
1260 *
1261 * @param object $instance enrol instance or null if does not exist yet
1262 * @param array $data
1263 * @param object $context context of existing course or parent category if course does not exist
1264 * @return array errors array
1265 */
1266 public function course_edit_validation($instance, array $data, $context) {
1267 return array();
1268 }
1269
1270 /**
1271 * Called after updating/inserting course.
1272 *
1273 * @param bool $inserted true if course just inserted
1274 * @param object $course
1275 * @param object $data form data
1276 * @return void
1277 */
1278 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
1279 if ($inserted) {
1280 if ($this->get_config('defaultenrol')) {
1281 $this->add_default_instance($course);
1282 }
1283 }
df997f84
PS
1284 }
1285
1286 /**
eafb7a72 1287 * Add new instance of enrol plugin.
df997f84
PS
1288 * @param object $course
1289 * @param array instance fields
0848a196 1290 * @return int id of new instance, null if can not be created
df997f84
PS
1291 */
1292 public function add_instance($course, array $fields = NULL) {
1293 global $DB;
1294
1295 if ($course->id == SITEID) {
1296 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1297 }
1298
365a5941 1299 $instance = new stdClass();
df997f84
PS
1300 $instance->enrol = $this->get_name();
1301 $instance->status = ENROL_INSTANCE_ENABLED;
1302 $instance->courseid = $course->id;
1303 $instance->enrolstartdate = 0;
1304 $instance->enrolenddate = 0;
1305 $instance->timemodified = time();
1306 $instance->timecreated = $instance->timemodified;
1307 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1308
1309 $fields = (array)$fields;
1310 unset($fields['enrol']);
1311 unset($fields['courseid']);
1312 unset($fields['sortorder']);
1313 foreach($fields as $field=>$value) {
1314 $instance->$field = $value;
1315 }
1316
1317 return $DB->insert_record('enrol', $instance);
1318 }
1319
1320 /**
1321 * Add new instance of enrol plugin with default settings,
1322 * called when adding new instance manually or when adding new course.
1323 *
1324 * Not all plugins support this.
1325 *
1326 * @param object $course
1327 * @return int id of new instance or null if no default supported
1328 */
1329 public function add_default_instance($course) {
1330 return null;
1331 }
1332
1333 /**
1334 * Delete course enrol plugin instance, unenrol all users.
1335 * @param object $instance
1336 * @return void
1337 */
1338 public function delete_instance($instance) {
1339 global $DB;
1340
1341 $name = $this->get_name();
1342 if ($instance->enrol !== $name) {
1343 throw new coding_exception('invalid enrol instance!');
1344 }
1345
1346 //first unenrol all users
1347 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1348 foreach ($participants as $participant) {
1349 $this->unenrol_user($instance, $participant->userid);
1350 }
1351 $participants->close();
1352
1353 // now clean up all remainders that were not removed correctly
1354 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1355 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1356
1357 // finally drop the enrol row
1358 $DB->delete_records('enrol', array('id'=>$instance->id));
1359 }
1360
1361 /**
1362 * Creates course enrol form, checks if form submitted
1363 * and enrols user if necessary. It can also redirect.
1364 *
1365 * @param stdClass $instance
1366 * @return string html text, usually a form in a text box
1367 */
1368 public function enrol_page_hook(stdClass $instance) {
1369 return null;
1370 }
1371
1372 /**
1373 * Adds navigation links into course admin block.
1374 *
1375 * By defaults looks for manage links only.
1376 *
1377 * @param navigation_node $instancesnode
1378 * @param object $instance
2d4b1f3e 1379 * @return void
df997f84
PS
1380 */
1381 public function add_course_navigation($instancesnode, stdClass $instance) {
2d4b1f3e 1382 // usually adds manage users
df997f84
PS
1383 }
1384
1385 /**
2d4b1f3e
PS
1386 * Returns edit icons for the page with list of instances
1387 * @param stdClass $instance
1388 * @return array
df997f84 1389 */
2d4b1f3e
PS
1390 public function get_action_icons(stdClass $instance) {
1391 return array();
df997f84
PS
1392 }
1393
1394 /**
1395 * Reads version.php and determines if it is necessary
1396 * to execute the cron job now.
1397 * @return bool
1398 */
1399 public function is_cron_required() {
1400 global $CFG;
1401
1402 $name = $this->get_name();
1403 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 1404 $plugin = new stdClass();
df997f84
PS
1405 include($versionfile);
1406 if (empty($plugin->cron)) {
1407 return false;
1408 }
1409 $lastexecuted = $this->get_config('lastcron', 0);
1410 if ($lastexecuted + $plugin->cron < time()) {
1411 return true;
1412 } else {
1413 return false;
1414 }
1415 }
1416
1417 /**
1418 * Called for all enabled enrol plugins that returned true from is_cron_required().
1419 * @return void
1420 */
1421 public function cron() {
1422 }
1423
1424 /**
1425 * Called when user is about to be deleted
1426 * @param object $user
1427 * @return void
1428 */
1429 public function user_delete($user) {
1430 global $DB;
1431
1432 $sql = "SELECT e.*
1433 FROM {enrol} e
1434 JOIN {user_enrolments} ue ON (ue.courseid = e.courseid)
1435 WHERE e.enrol = :meta AND ue.userid = :userid";
1436 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1437
1438 $rs = $DB->get_records_recordset($sql, $params);
1439 foreach($rs as $instance) {
1440 $this->unenrol_user($instance, $user->id);
1441 }
1442 $rs->close();
1443 }
1444}
1445