MDL-31243 access/enrol libs: move enrol functions
[moodle.git] / lib / enrollib.php
CommitLineData
df997f84
PS
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This library includes the basic parts of enrol api.
20 * It is available on each page.
21 *
78bfb562
PS
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Petr Skoda {@link http://skodak.org}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
26 */
27
78bfb562 28defined('MOODLE_INTERNAL') || die();
df997f84
PS
29
30/** Course enrol instance enabled. (used in enrol->status) */
31define('ENROL_INSTANCE_ENABLED', 0);
32
33/** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/
34define('ENROL_INSTANCE_DISABLED', 1);
35
36/** User is active participant (used in user_enrolments->status)*/
37define('ENROL_USER_ACTIVE', 0);
38
39/** User participation in course is suspended (used in user_enrolments->status) */
40define('ENROL_USER_SUSPENDED', 1);
41
bbfdff34 42/** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */
df997f84
PS
43define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
44
bbfdff34
PS
45/** The timestamp indicating forever */
46define('ENROL_MAX_TIMESTAMP', 2147483647);
47
34121765
PS
48/** When user disappears from external source, the enrolment is completely removed */
49define('ENROL_EXT_REMOVED_UNENROL', 0);
50
51/** When user disappears from external source, the enrolment is kept as is - one way sync */
52define('ENROL_EXT_REMOVED_KEEP', 1);
53
7a7b8a1f 54/** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */
f2a9be5f 55define('ENROL_RESTORE_TYPE', 'enrolrestore');
f2a9be5f 56
34121765
PS
57/**
58 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
59 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
60 * assignments, etc.
61 */
62define('ENROL_EXT_REMOVED_SUSPEND', 2);
63
64/**
65 * When user disappears from external source, the enrolment is suspended and roles assigned
66 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
67 * */
68define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
69
df997f84
PS
70/**
71 * Returns instances of enrol plugins
bbfdff34 72 * @param bool $enabled return enabled only
df997f84
PS
73 * @return array of enrol plugins name=>instance
74 */
75function enrol_get_plugins($enabled) {
76 global $CFG;
77
78 $result = array();
79
80 if ($enabled) {
81 // sorted by enabled plugin order
82 $enabled = explode(',', $CFG->enrol_plugins_enabled);
83 $plugins = array();
84 foreach ($enabled as $plugin) {
85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
86 }
87 } else {
88 // sorted alphabetically
bd3b3bba 89 $plugins = core_component::get_plugin_list('enrol');
df997f84
PS
90 ksort($plugins);
91 }
92
93 foreach ($plugins as $plugin=>$location) {
df997f84
PS
94 $class = "enrol_{$plugin}_plugin";
95 if (!class_exists($class)) {
d432e0f7
MA
96 if (!file_exists("$location/lib.php")) {
97 continue;
98 }
99 include_once("$location/lib.php");
100 if (!class_exists($class)) {
101 continue;
102 }
df997f84
PS
103 }
104
105 $result[$plugin] = new $class();
106 }
107
108 return $result;
109}
110
111/**
112 * Returns instance of enrol plugin
113 * @param string $name name of enrol plugin ('manual', 'guest', ...)
114 * @return enrol_plugin
115 */
116function enrol_get_plugin($name) {
117 global $CFG;
118
aff24313
PS
119 $name = clean_param($name, PARAM_PLUGIN);
120
121 if (empty($name)) {
122 // ignore malformed or missing plugin names completely
df997f84
PS
123 return null;
124 }
125
126 $location = "$CFG->dirroot/enrol/$name";
127
128 if (!file_exists("$location/lib.php")) {
129 return null;
130 }
131 include_once("$location/lib.php");
132 $class = "enrol_{$name}_plugin";
133 if (!class_exists($class)) {
134 return null;
135 }
136
137 return new $class();
138}
139
140/**
141 * Returns enrolment instances in given course.
142 * @param int $courseid
143 * @param bool $enabled
144 * @return array of enrol instances
145 */
146function enrol_get_instances($courseid, $enabled) {
147 global $DB, $CFG;
148
149 if (!$enabled) {
150 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
151 }
152
153 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
154
79721bd3 155 $enabled = explode(',', $CFG->enrol_plugins_enabled);
df997f84
PS
156 foreach ($result as $key=>$instance) {
157 if (!in_array($instance->enrol, $enabled)) {
158 unset($result[$key]);
159 continue;
160 }
161 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
162 // broken plugin
163 unset($result[$key]);
164 continue;
165 }
166 }
167
168 return $result;
169}
170
171/**
172 * Checks if a given plugin is in the list of enabled enrolment plugins.
173 *
174 * @param string $enrol Enrolment plugin name
175 * @return boolean Whether the plugin is enabled
176 */
177function enrol_is_enabled($enrol) {
178 global $CFG;
179
180 if (empty($CFG->enrol_plugins_enabled)) {
181 return false;
182 }
183 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
184}
185
186/**
187 * Check all the login enrolment information for the given user object
188 * by querying the enrolment plugins
189 *
e922fe23
PS
190 * This function may be very slow, use only once after log-in or login-as.
191 *
192 * @param stdClass $user
df997f84
PS
193 * @return void
194 */
195function enrol_check_plugins($user) {
196 global $CFG;
197
198 if (empty($user->id) or isguestuser($user)) {
199 // shortcut - there is no enrolment work for guests and not-logged-in users
200 return;
201 }
202
bcb368d9
PS
203 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
204 // which proved it was actually not necessary.
e384d2dc 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
181991e7
PS
223/**
224 * Do these two students share any course?
225 *
226 * The courses has to be visible and enrolments has to be active,
227 * timestart and timeend restrictions are ignored.
228 *
61ab8f07
SH
229 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
230 * to true.
231 *
181991e7
PS
232 * @param stdClass|int $user1
233 * @param stdClass|int $user2
234 * @return bool
235 */
236function enrol_sharing_course($user1, $user2) {
61ab8f07 237 return enrol_get_shared_courses($user1, $user2, false, true);
181991e7
PS
238}
239
4b715423
SH
240/**
241 * Returns any courses shared by the two users
242 *
243 * The courses has to be visible and enrolments has to be active,
244 * timestart and timeend restrictions are ignored.
245 *
61ab8f07 246 * @global moodle_database $DB
4b715423
SH
247 * @param stdClass|int $user1
248 * @param stdClass|int $user2
61ab8f07
SH
249 * @param bool $preloadcontexts If set to true contexts for the returned courses
250 * will be preloaded.
251 * @param bool $checkexistsonly If set to true then this function will return true
252 * if the users share any courses and false if not.
253 * @return array|bool An array of courses that both users are enrolled in OR if
254 * $checkexistsonly set returns true if the users share any courses
255 * and false if not.
4b715423 256 */
61ab8f07 257function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
4b715423
SH
258 global $DB, $CFG;
259
5b244e2b
HD
260 $user1 = isset($user1->id) ? $user1->id : $user1;
261 $user2 = isset($user2->id) ? $user2->id : $user2;
4b715423
SH
262
263 if (empty($user1) or empty($user2)) {
264 return false;
265 }
266
267 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
268 return false;
269 }
270
271 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
272 $params['enabled'] = ENROL_INSTANCE_ENABLED;
273 $params['active1'] = ENROL_USER_ACTIVE;
274 $params['active2'] = ENROL_USER_ACTIVE;
275 $params['user1'] = $user1;
276 $params['user2'] = $user2;
277
278 $ctxselect = '';
279 $ctxjoin = '';
280 if ($preloadcontexts) {
2e4c0c91
FM
281 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
282 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
283 $params['contextlevel'] = CONTEXT_COURSE;
4b715423
SH
284 }
285
286 $sql = "SELECT c.* $ctxselect
287 FROM {course} c
288 JOIN (
289 SELECT DISTINCT c.id
290 FROM {enrol} e
291 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
292 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
293 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
294 WHERE e.status = :enabled AND e.enrol $plugins
295 ) ec ON ec.id = c.id
296 $ctxjoin";
4b715423 297
61ab8f07
SH
298 if ($checkexistsonly) {
299 return $DB->record_exists_sql($sql, $params);
300 } else {
301 $courses = $DB->get_records_sql($sql, $params);
302 if ($preloadcontexts) {
a55ad8f8 303 array_map('context_helper::preload_from_record', $courses);
61ab8f07
SH
304 }
305 return $courses;
306 }
4b715423
SH
307}
308
df997f84
PS
309/**
310 * This function adds necessary enrol plugins UI into the course edit form.
311 *
312 * @param MoodleQuickForm $mform
313 * @param object $data course edit form data
314 * @param object $context context of existing course or parent category if course does not exist
315 * @return void
316 */
317function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
318 $plugins = enrol_get_plugins(true);
319 if (!empty($data->id)) {
320 $instances = enrol_get_instances($data->id, false);
321 foreach ($instances as $instance) {
322 if (!isset($plugins[$instance->enrol])) {
323 continue;
324 }
325 $plugin = $plugins[$instance->enrol];
326 $plugin->course_edit_form($instance, $mform, $data, $context);
327 }
328 } else {
329 foreach ($plugins as $plugin) {
330 $plugin->course_edit_form(NULL, $mform, $data, $context);
331 }
332 }
333}
334
335/**
336 * Validate course edit form data
337 *
338 * @param array $data raw form data
339 * @param object $context context of existing course or parent category if course does not exist
340 * @return array errors array
341 */
342function enrol_course_edit_validation(array $data, $context) {
343 $errors = array();
344 $plugins = enrol_get_plugins(true);
345
346 if (!empty($data['id'])) {
347 $instances = enrol_get_instances($data['id'], false);
348 foreach ($instances as $instance) {
349 if (!isset($plugins[$instance->enrol])) {
350 continue;
351 }
352 $plugin = $plugins[$instance->enrol];
353 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
354 }
355 } else {
356 foreach ($plugins as $plugin) {
357 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
358 }
359 }
360
361 return $errors;
362}
363
364/**
365 * Update enrol instances after course edit form submission
366 * @param bool $inserted true means new course added, false course already existed
367 * @param object $course
368 * @param object $data form data
369 * @return void
370 */
371function enrol_course_updated($inserted, $course, $data) {
372 global $DB, $CFG;
373
374 $plugins = enrol_get_plugins(true);
375
376 foreach ($plugins as $plugin) {
377 $plugin->course_updated($inserted, $course, $data);
378 }
379}
380
381/**
382 * Add navigation nodes
383 * @param navigation_node $coursenode
384 * @param object $course
385 * @return void
386 */
387function enrol_add_course_navigation(navigation_node $coursenode, $course) {
6e4c374d 388 global $CFG;
df997f84 389
b0c6dc1c 390 $coursecontext = context_course::instance($course->id);
df997f84
PS
391
392 $instances = enrol_get_instances($course->id, true);
393 $plugins = enrol_get_plugins(true);
394
395 // we do not want to break all course pages if there is some borked enrol plugin, right?
396 foreach ($instances as $k=>$instance) {
397 if (!isset($plugins[$instance->enrol])) {
398 unset($instances[$k]);
399 }
400 }
401
f5ce6b71 402 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
df997f84
PS
403
404 if ($course->id != SITEID) {
f5ce6b71 405 // list all participants - allows assigning roles, groups, etc.
df997f84
PS
406 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
407 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
c42651d6 408 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
df997f84
PS
409 }
410
411 // manage enrol plugin instances
412 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
413 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
414 } else {
415 $url = NULL;
416 }
f5ce6b71 417 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
df997f84
PS
418
419 // each instance decides how to configure itself or how many other nav items are exposed
420 foreach ($instances as $instance) {
421 if (!isset($plugins[$instance->enrol])) {
422 continue;
423 }
424 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
425 }
426
427 if (!$url) {
428 $instancesnode->trim_if_empty();
429 }
430 }
431
432 // Manage groups in this course or even frontpage
433 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
434 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
435 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
436 }
437
438 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
439 // Override roles
440 if (has_capability('moodle/role:review', $coursecontext)) {
441 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
442 } else {
443 $url = NULL;
444 }
f5ce6b71 445 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
df997f84
PS
446
447 // Add assign or override roles if allowed
448 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
449 if (has_capability('moodle/role:assign', $coursecontext)) {
450 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
fbb207c5 451 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
df997f84
PS
452 }
453 }
454 // Check role permissions
77690b69 455 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
df997f84 456 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
f5ce6b71 457 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
df997f84
PS
458 }
459 }
460
461 // Deal somehow with users that are not enrolled but still got a role somehow
462 if ($course->id != SITEID) {
463 //TODO, create some new UI for role assignments at course level
288e7b09 464 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
df997f84 465 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
fbb207c5 466 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
df997f84
PS
467 }
468 }
469
470 // just in case nothing was actually added
471 $usersnode->trim_if_empty();
472
473 if ($course->id != SITEID) {
6813cdf7 474 if (isguestuser() or !isloggedin()) {
39ec18db 475 // guest account can not be enrolled - no links for them
6813cdf7 476 } else if (is_enrolled($coursecontext)) {
39ec18db 477 // unenrol link if possible
217d0397
PS
478 foreach ($instances as $instance) {
479 if (!isset($plugins[$instance->enrol])) {
480 continue;
481 }
482 $plugin = $plugins[$instance->enrol];
483 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
8ebbb06a
SH
484 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
485 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
217d0397
PS
486 break;
487 //TODO. deal with multiple unenrol links - not likely case, but still...
488 }
df997f84 489 }
217d0397 490 } else {
39ec18db 491 // enrol link if possible
217d0397
PS
492 if (is_viewing($coursecontext)) {
493 // better not show any enrol link, this is intended for managers and inspectors
494 } else {
495 foreach ($instances as $instance) {
496 if (!isset($plugins[$instance->enrol])) {
497 continue;
498 }
499 $plugin = $plugins[$instance->enrol];
500 if ($plugin->show_enrolme_link($instance)) {
501 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
8ebbb06a
SH
502 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
503 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
217d0397
PS
504 break;
505 }
506 }
df997f84
PS
507 }
508 }
df997f84
PS
509 }
510}
511
512/**
513 * Returns list of courses current $USER is enrolled in and can access
514 *
515 * - $fields is an array of field names to ADD
516 * so name the fields you really need, which will
517 * be added and uniq'd
518 *
eb6f592a 519 * @param string|array $fields
df997f84
PS
520 * @param string $sort
521 * @param int $limit max number of courses
522 * @return array
523 */
524function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
525 global $DB, $USER;
526
527 // Guest account does not have any courses
528 if (isguestuser() or !isloggedin()) {
529 return(array());
530 }
531
532 $basefields = array('id', 'category', 'sortorder',
533 'shortname', 'fullname', 'idnumber',
534 'startdate', 'visible',
4a3fb71c 535 'groupmode', 'groupmodeforce', 'cacherev');
df997f84
PS
536
537 if (empty($fields)) {
538 $fields = $basefields;
539 } else if (is_string($fields)) {
540 // turn the fields from a string to an array
541 $fields = explode(',', $fields);
542 $fields = array_map('trim', $fields);
543 $fields = array_unique(array_merge($basefields, $fields));
544 } else if (is_array($fields)) {
545 $fields = array_unique(array_merge($basefields, $fields));
546 } else {
547 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
548 }
549 if (in_array('*', $fields)) {
550 $fields = array('*');
551 }
552
553 $orderby = "";
554 $sort = trim($sort);
555 if (!empty($sort)) {
556 $rawsorts = explode(',', $sort);
557 $sorts = array();
558 foreach ($rawsorts as $rawsort) {
559 $rawsort = trim($rawsort);
560 if (strpos($rawsort, 'c.') === 0) {
561 $rawsort = substr($rawsort, 2);
562 }
563 $sorts[] = trim($rawsort);
564 }
565 $sort = 'c.'.implode(',c.', $sorts);
566 $orderby = "ORDER BY $sort";
567 }
568
569 $wheres = array("c.id <> :siteid");
570 $params = array('siteid'=>SITEID);
571
572 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
573 // list _only_ this course - anything else is asking for trouble...
574 $wheres[] = "courseid = :loginas";
575 $params['loginas'] = $USER->loginascontext->instanceid;
576 }
577
578 $coursefields = 'c.' .join(',c.', $fields);
2e4c0c91
FM
579 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
581 $params['contextlevel'] = CONTEXT_COURSE;
4129338c 582 $wheres = implode(" AND ", $wheres);
df997f84 583
4129338c
PS
584 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
585 $sql = "SELECT $coursefields $ccselect
df997f84 586 FROM {course} c
4129338c
PS
587 JOIN (SELECT DISTINCT e.courseid
588 FROM {enrol} e
589 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
590 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
591 ) en ON (en.courseid = c.id)
df997f84 592 $ccjoin
4129338c 593 WHERE $wheres
df997f84
PS
594 $orderby";
595 $params['userid'] = $USER->id;
596 $params['active'] = ENROL_USER_ACTIVE;
597 $params['enabled'] = ENROL_INSTANCE_ENABLED;
598 $params['now1'] = round(time(), -2); // improves db caching
599 $params['now2'] = $params['now1'];
600
601 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
602
603 // preload contexts and check visibility
604 foreach ($courses as $id=>$course) {
db314f34 605 context_helper::preload_from_record($course);
df997f84 606 if (!$course->visible) {
b0c6dc1c 607 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
55880bdd 608 unset($courses[$id]);
df997f84
PS
609 continue;
610 }
611 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
55880bdd 612 unset($courses[$id]);
df997f84
PS
613 continue;
614 }
615 }
616 $courses[$id] = $course;
617 }
618
619 //wow! Is that really all? :-D
620
621 return $courses;
622}
623
bf423bb1
PS
624/**
625 * Returns course enrolment information icons.
626 *
627 * @param object $course
628 * @param array $instances enrol instances of this course, improves performance
629 * @return array of pix_icon
630 */
631function enrol_get_course_info_icons($course, array $instances = NULL) {
632 $icons = array();
633 if (is_null($instances)) {
634 $instances = enrol_get_instances($course->id, true);
635 }
636 $plugins = enrol_get_plugins(true);
637 foreach ($plugins as $name => $plugin) {
638 $pis = array();
639 foreach ($instances as $instance) {
640 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
641 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
642 continue;
643 }
644 if ($instance->enrol == $name) {
645 $pis[$instance->id] = $instance;
646 }
647 }
648 if ($pis) {
649 $icons = array_merge($icons, $plugin->get_info_icons($pis));
650 }
651 }
652 return $icons;
653}
654
655/**
656 * Returns course enrolment detailed information.
657 *
658 * @param object $course
659 * @return array of html fragments - can be used to construct lists
660 */
661function enrol_get_course_description_texts($course) {
662 $lines = array();
663 $instances = enrol_get_instances($course->id, true);
664 $plugins = enrol_get_plugins(true);
665 foreach ($instances as $instance) {
64942a9d 666 if (!isset($plugins[$instance->enrol])) {
bf423bb1
PS
667 //weird
668 continue;
669 }
64942a9d 670 $plugin = $plugins[$instance->enrol];
bf423bb1
PS
671 $text = $plugin->get_description_text($instance);
672 if ($text !== NULL) {
673 $lines[] = $text;
674 }
675 }
676 return $lines;
677}
678
df997f84
PS
679/**
680 * Returns list of courses user is enrolled into.
9ffd29ce 681 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
df997f84
PS
682 *
683 * - $fields is an array of fieldnames to ADD
684 * so name the fields you really need, which will
685 * be added and uniq'd
686 *
687 * @param int $userid
688 * @param bool $onlyactive return only active enrolments in courses user may see
eb6f592a 689 * @param string|array $fields
df997f84
PS
690 * @param string $sort
691 * @return array
692 */
693function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
694 global $DB;
695
9ffd29ce
AA
696 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
697
698 // preload contexts and check visibility
699 if ($onlyactive) {
700 foreach ($courses as $id=>$course) {
db314f34 701 context_helper::preload_from_record($course);
9ffd29ce
AA
702 if (!$course->visible) {
703 if (!$context = context_course::instance($id)) {
704 unset($courses[$id]);
705 continue;
706 }
707 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
708 unset($courses[$id]);
709 continue;
710 }
711 }
712 }
713 }
714
715 return $courses;
716
717}
718
05f6da14
719/**
720 * Can user access at least one enrolled course?
721 *
722 * Cheat if necessary, but find out as fast as possible!
723 *
724 * @param int|stdClass $user null means use current user
725 * @return bool
726 */
727function enrol_user_sees_own_courses($user = null) {
728 global $USER;
729
730 if ($user === null) {
731 $user = $USER;
732 }
733 $userid = is_object($user) ? $user->id : $user;
734
735 // Guest account does not have any courses
736 if (isguestuser($userid) or empty($userid)) {
737 return false;
738 }
739
740 // Let's cheat here if this is the current user,
741 // if user accessed any course recently, then most probably
742 // we do not need to query the database at all.
743 if ($USER->id == $userid) {
744 if (!empty($USER->enrol['enrolled'])) {
745 foreach ($USER->enrol['enrolled'] as $until) {
746 if ($until > time()) {
747 return true;
748 }
749 }
750 }
751 }
752
753 // Now the slow way.
754 $courses = enrol_get_all_users_courses($userid, true);
755 foreach($courses as $course) {
756 if ($course->visible) {
757 return true;
758 }
759 context_helper::preload_from_record($course);
760 $context = context_course::instance($course->id);
761 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
762 return true;
763 }
764 }
765
766 return false;
767}
768
9ffd29ce
AA
769/**
770 * Returns list of courses user is enrolled into without any capability checks
771 * - $fields is an array of fieldnames to ADD
772 * so name the fields you really need, which will
773 * be added and uniq'd
774 *
775 * @param int $userid
776 * @param bool $onlyactive return only active enrolments in courses user may see
777 * @param string|array $fields
778 * @param string $sort
779 * @return array
780 */
781function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
782 global $DB;
783
df997f84 784 // Guest account does not have any courses
87163782 785 if (isguestuser($userid) or empty($userid)) {
df997f84
PS
786 return(array());
787 }
788
789 $basefields = array('id', 'category', 'sortorder',
9ffd29ce
AA
790 'shortname', 'fullname', 'idnumber',
791 'startdate', 'visible',
8eb15a38 792 'defaultgroupingid',
9ffd29ce 793 'groupmode', 'groupmodeforce');
df997f84
PS
794
795 if (empty($fields)) {
796 $fields = $basefields;
797 } else if (is_string($fields)) {
798 // turn the fields from a string to an array
799 $fields = explode(',', $fields);
800 $fields = array_map('trim', $fields);
801 $fields = array_unique(array_merge($basefields, $fields));
802 } else if (is_array($fields)) {
803 $fields = array_unique(array_merge($basefields, $fields));
804 } else {
805 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
806 }
807 if (in_array('*', $fields)) {
808 $fields = array('*');
809 }
810
811 $orderby = "";
812 $sort = trim($sort);
813 if (!empty($sort)) {
814 $rawsorts = explode(',', $sort);
815 $sorts = array();
816 foreach ($rawsorts as $rawsort) {
817 $rawsort = trim($rawsort);
818 if (strpos($rawsort, 'c.') === 0) {
819 $rawsort = substr($rawsort, 2);
820 }
821 $sorts[] = trim($rawsort);
822 }
823 $sort = 'c.'.implode(',c.', $sorts);
824 $orderby = "ORDER BY $sort";
825 }
826
df997f84
PS
827 $params = array('siteid'=>SITEID);
828
829 if ($onlyactive) {
4129338c 830 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
df997f84
PS
831 $params['now1'] = round(time(), -2); // improves db caching
832 $params['now2'] = $params['now1'];
833 $params['active'] = ENROL_USER_ACTIVE;
834 $params['enabled'] = ENROL_INSTANCE_ENABLED;
4129338c
PS
835 } else {
836 $subwhere = "";
df997f84
PS
837 }
838
839 $coursefields = 'c.' .join(',c.', $fields);
2e4c0c91
FM
840 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
841 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
842 $params['contextlevel'] = CONTEXT_COURSE;
df997f84 843
4129338c
PS
844 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
845 $sql = "SELECT $coursefields $ccselect
df997f84 846 FROM {course} c
4129338c
PS
847 JOIN (SELECT DISTINCT e.courseid
848 FROM {enrol} e
849 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
850 $subwhere
851 ) en ON (en.courseid = c.id)
df997f84 852 $ccjoin
4129338c 853 WHERE c.id <> :siteid
df997f84 854 $orderby";
87163782 855 $params['userid'] = $userid;
df997f84
PS
856
857 $courses = $DB->get_records_sql($sql, $params);
858
df997f84 859 return $courses;
df997f84
PS
860}
861
9ffd29ce
AA
862
863
df997f84
PS
864/**
865 * Called when user is about to be deleted.
866 * @param object $user
867 * @return void
868 */
869function enrol_user_delete($user) {
870 global $DB;
871
872 $plugins = enrol_get_plugins(true);
873 foreach ($plugins as $plugin) {
874 $plugin->user_delete($user);
875 }
876
877 // force cleanup of all broken enrolments
878 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
879}
880
582bae08
PS
881/**
882 * Called when course is about to be deleted.
bbfdff34 883 * @param stdClass $course
582bae08
PS
884 * @return void
885 */
886function enrol_course_delete($course) {
887 global $DB;
888
889 $instances = enrol_get_instances($course->id, false);
890 $plugins = enrol_get_plugins(true);
891 foreach ($instances as $instance) {
892 if (isset($plugins[$instance->enrol])) {
893 $plugins[$instance->enrol]->delete_instance($instance);
894 }
895 // low level delete in case plugin did not do it
896 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
897 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
898 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
899 $DB->delete_records('enrol', array('id'=>$instance->id));
900 }
901}
902
df997f84
PS
903/**
904 * Try to enrol user via default internal auth plugin.
905 *
906 * For now this is always using the manual enrol plugin...
907 *
908 * @param $courseid
909 * @param $userid
910 * @param $roleid
911 * @param $timestart
912 * @param $timeend
913 * @return bool success
914 */
915function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
916 global $DB;
917
918 //note: this is hardcoded to manual plugin for now
919
920 if (!enrol_is_enabled('manual')) {
921 return false;
922 }
923
924 if (!$enrol = enrol_get_plugin('manual')) {
925 return false;
926 }
927 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
928 return false;
929 }
930 $instance = reset($instances);
931
932 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
933
934 return true;
935}
936
45ff8a80
PS
937/**
938 * Is there a chance users might self enrol
939 * @param int $courseid
940 * @return bool
941 */
942function enrol_selfenrol_available($courseid) {
943 $result = false;
944
945 $plugins = enrol_get_plugins(true);
946 $enrolinstances = enrol_get_instances($courseid, true);
947 foreach($enrolinstances as $instance) {
948 if (!isset($plugins[$instance->enrol])) {
949 continue;
950 }
951 if ($instance->enrol === 'guest') {
952 // blacklist known temporary guest plugins
953 continue;
954 }
955 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
956 $result = true;
957 break;
958 }
959 }
960
961 return $result;
962}
963
bbfdff34
PS
964/**
965 * This function returns the end of current active user enrolment.
966 *
967 * It deals correctly with multiple overlapping user enrolments.
968 *
969 * @param int $courseid
970 * @param int $userid
971 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
972 */
973function enrol_get_enrolment_end($courseid, $userid) {
974 global $DB;
975
976 $sql = "SELECT ue.*
977 FROM {user_enrolments} ue
978 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
979 JOIN {user} u ON u.id = ue.userid
980 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
981 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
982
983 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
984 return false;
985 }
986
987 $changes = array();
988
989 foreach ($enrolments as $ue) {
990 $start = (int)$ue->timestart;
991 $end = (int)$ue->timeend;
992 if ($end != 0 and $end < $start) {
993 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
994 continue;
995 }
996 if (isset($changes[$start])) {
997 $changes[$start] = $changes[$start] + 1;
998 } else {
999 $changes[$start] = 1;
1000 }
1001 if ($end === 0) {
1002 // no end
1003 } else if (isset($changes[$end])) {
1004 $changes[$end] = $changes[$end] - 1;
1005 } else {
1006 $changes[$end] = -1;
1007 }
1008 }
1009
1010 // let's sort then enrolment starts&ends and go through them chronologically,
1011 // looking for current status and the next future end of enrolment
1012 ksort($changes);
1013
1014 $now = time();
1015 $current = 0;
1016 $present = null;
1017
1018 foreach ($changes as $time => $change) {
1019 if ($time > $now) {
1020 if ($present === null) {
1021 // we have just went past current time
1022 $present = $current;
1023 if ($present < 1) {
1024 // no enrolment active
1025 return false;
1026 }
1027 }
1028 if ($present !== null) {
1029 // we are already in the future - look for possible end
1030 if ($current + $change < 1) {
1031 return $time;
1032 }
1033 }
1034 }
1035 $current += $change;
1036 }
1037
1038 if ($current > 0) {
1039 return 0;
1040 } else {
1041 return false;
1042 }
1043}
1044
12c92bca
PS
1045/**
1046 * Is current user accessing course via this enrolment method?
1047 *
1048 * This is intended for operations that are going to affect enrol instances.
1049 *
1050 * @param stdClass $instance enrol instance
1051 * @return bool
1052 */
1053function enrol_accessing_via_instance(stdClass $instance) {
1054 global $DB, $USER;
1055
1056 if (empty($instance->id)) {
1057 return false;
1058 }
1059
1060 if (is_siteadmin()) {
1061 // Admins may go anywhere.
1062 return false;
1063 }
1064
1065 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1066}
1067
9f5170e9
JB
1068/**
1069 * Returns true if user is enrolled (is participating) in course
1070 * this is intended for students and teachers.
1071 *
1072 * Since 2.2 the result for active enrolments and current user are cached.
1073 *
1074 * @package core_enrol
1075 * @category access
1076 *
1077 * @param context $context
1078 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1079 * @param string $withcapability extra capability name
1080 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1081 * @return bool
1082 */
1083function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1084 global $USER, $DB;
1085
1086 // first find the course context
1087 $coursecontext = $context->get_course_context();
1088
1089 // make sure there is a real user specified
1090 if ($user === null) {
1091 $userid = isset($USER->id) ? $USER->id : 0;
1092 } else {
1093 $userid = is_object($user) ? $user->id : $user;
1094 }
1095
1096 if (empty($userid)) {
1097 // not-logged-in!
1098 return false;
1099 } else if (isguestuser($userid)) {
1100 // guest account can not be enrolled anywhere
1101 return false;
1102 }
1103
1104 if ($coursecontext->instanceid == SITEID) {
1105 // everybody participates on frontpage
1106 } else {
1107 // try cached info first - the enrolled flag is set only when active enrolment present
1108 if ($USER->id == $userid) {
1109 $coursecontext->reload_if_dirty();
1110 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1111 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1112 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1113 return false;
1114 }
1115 return true;
1116 }
1117 }
1118 }
1119
1120 if ($onlyactive) {
1121 // look for active enrolments only
1122 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1123
1124 if ($until === false) {
1125 return false;
1126 }
1127
1128 if ($USER->id == $userid) {
1129 if ($until == 0) {
1130 $until = ENROL_MAX_TIMESTAMP;
1131 }
1132 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1133 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1134 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1135 remove_temp_course_roles($coursecontext);
1136 }
1137 }
1138
1139 } else {
1140 // any enrolment is good for us here, even outdated, disabled or inactive
1141 $sql = "SELECT 'x'
1142 FROM {user_enrolments} ue
1143 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1144 JOIN {user} u ON u.id = ue.userid
1145 WHERE ue.userid = :userid AND u.deleted = 0";
1146 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1147 if (!$DB->record_exists_sql($sql, $params)) {
1148 return false;
1149 }
1150 }
1151 }
1152
1153 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1154 return false;
1155 }
1156
1157 return true;
1158}
1159
1160/**
1161 * Returns array with sql code and parameters returning all ids
1162 * of users enrolled into course.
1163 *
1164 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1165 *
1166 * @package core_enrol
1167 * @category access
1168 *
1169 * @param context $context
1170 * @param string $withcapability
1171 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1172 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1173 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1174 * @return array list($sql, $params)
1175 */
1176function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false) {
1177 global $DB, $CFG;
1178
1179 // use unique prefix just in case somebody makes some SQL magic with the result
1180 static $i = 0;
1181 $i++;
1182 $prefix = 'eu'.$i.'_';
1183
1184 // first find the course context
1185 $coursecontext = $context->get_course_context();
1186
1187 $isfrontpage = ($coursecontext->instanceid == SITEID);
1188
1189 if ($onlyactive && $onlysuspended) {
1190 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1191 }
1192 if ($isfrontpage && $onlysuspended) {
1193 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1194 }
1195
1196 $joins = array();
1197 $wheres = array();
1198 $params = array();
1199
1200 list($contextids, $contextpaths) = get_context_info_list($context);
1201
1202 // get all relevant capability info for all roles
1203 if ($withcapability) {
1204 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
1205 $cparams['cap'] = $withcapability;
1206
1207 $defs = array();
1208 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
1209 FROM {role_capabilities} rc
1210 JOIN {context} ctx on rc.contextid = ctx.id
1211 WHERE rc.contextid $incontexts AND rc.capability = :cap";
1212 $rcs = $DB->get_records_sql($sql, $cparams);
1213 foreach ($rcs as $rc) {
1214 $defs[$rc->path][$rc->roleid] = $rc->permission;
1215 }
1216
1217 $access = array();
1218 if (!empty($defs)) {
1219 foreach ($contextpaths as $path) {
1220 if (empty($defs[$path])) {
1221 continue;
1222 }
1223 foreach($defs[$path] as $roleid => $perm) {
1224 if ($perm == CAP_PROHIBIT) {
1225 $access[$roleid] = CAP_PROHIBIT;
1226 continue;
1227 }
1228 if (!isset($access[$roleid])) {
1229 $access[$roleid] = (int)$perm;
1230 }
1231 }
1232 }
1233 }
1234
1235 unset($defs);
1236
1237 // make lists of roles that are needed and prohibited
1238 $needed = array(); // one of these is enough
1239 $prohibited = array(); // must not have any of these
1240 foreach ($access as $roleid => $perm) {
1241 if ($perm == CAP_PROHIBIT) {
1242 unset($needed[$roleid]);
1243 $prohibited[$roleid] = true;
1244 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
1245 $needed[$roleid] = true;
1246 }
1247 }
1248
1249 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
1250 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
1251
1252 $nobody = false;
1253
1254 if ($isfrontpage) {
1255 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
1256 $nobody = true;
1257 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
1258 // everybody not having prohibit has the capability
1259 $needed = array();
1260 } else if (empty($needed)) {
1261 $nobody = true;
1262 }
1263 } else {
1264 if (!empty($prohibited[$defaultuserroleid])) {
1265 $nobody = true;
1266 } else if (!empty($needed[$defaultuserroleid])) {
1267 // everybody not having prohibit has the capability
1268 $needed = array();
1269 } else if (empty($needed)) {
1270 $nobody = true;
1271 }
1272 }
1273
1274 if ($nobody) {
1275 // nobody can match so return some SQL that does not return any results
1276 $wheres[] = "1 = 2";
1277
1278 } else {
1279
1280 if ($needed) {
1281 $ctxids = implode(',', $contextids);
1282 $roleids = implode(',', array_keys($needed));
1283 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
1284 }
1285
1286 if ($prohibited) {
1287 $ctxids = implode(',', $contextids);
1288 $roleids = implode(',', array_keys($prohibited));
1289 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
1290 $wheres[] = "{$prefix}ra4.id IS NULL";
1291 }
1292
1293 if ($groupid) {
1294 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
1295 $params["{$prefix}gmid"] = $groupid;
1296 }
1297 }
1298
1299 } else {
1300 if ($groupid) {
1301 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
1302 $params["{$prefix}gmid"] = $groupid;
1303 }
1304 }
1305
1306 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
1307 $params["{$prefix}guestid"] = $CFG->siteguest;
1308
1309 if ($isfrontpage) {
1310 // all users are "enrolled" on the frontpage
1311 } else {
1312 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1313 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1314 $ejoin = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
1315 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1316
1317 if (!$onlysuspended) {
1318 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
1319 $joins[] = $ejoin;
1320 if ($onlyactive) {
1321 $wheres[] = "$where1 AND $where2";
1322 }
1323 } else {
1324 // Suspended only where there is enrolment but ALL are suspended.
1325 // Consider multiple enrols where one is not suspended or plain role_assign.
1326 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1327 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = {$prefix}u.id";
1328 $joins[] = "JOIN {enrol} {$prefix}e1 ON ({$prefix}e1.id = {$prefix}ue1.enrolid AND {$prefix}e1.courseid = :{$prefix}_e1_courseid)";
1329 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1330 $wheres[] = "{$prefix}u.id NOT IN ($enrolselect)";
1331 }
1332
1333 if ($onlyactive || $onlysuspended) {
1334 $now = round(time(), -2); // rounding helps caching in DB
1335 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
1336 $prefix.'active'=>ENROL_USER_ACTIVE,
1337 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
1338 }
1339 }
1340
1341 $joins = implode("\n", $joins);
1342 $wheres = "WHERE ".implode(" AND ", $wheres);
1343
1344 $sql = "SELECT DISTINCT {$prefix}u.id
1345 FROM {user} {$prefix}u
1346 $joins
1347 $wheres";
1348
1349 return array($sql, $params);
1350}
1351
1352/**
1353 * Returns list of users enrolled into course.
1354 *
1355 * @package core_enrol
1356 * @category access
1357 *
1358 * @param context $context
1359 * @param string $withcapability
1360 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1361 * @param string $userfields requested user record fields
1362 * @param string $orderby
1363 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1364 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1365 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1366 * @return array of user records
1367 */
1368function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1369 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1370 global $DB;
1371
1372 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1373 $sql = "SELECT $userfields
1374 FROM {user} u
1375 JOIN ($esql) je ON je.id = u.id
1376 WHERE u.deleted = 0";
1377
1378 if ($orderby) {
1379 $sql = "$sql ORDER BY $orderby";
1380 } else {
1381 list($sort, $sortparams) = users_order_by_sql('u');
1382 $sql = "$sql ORDER BY $sort";
1383 $params = array_merge($params, $sortparams);
1384 }
1385
1386 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1387}
1388
1389/**
1390 * Counts list of users enrolled into course (as per above function)
1391 *
1392 * @package core_enrol
1393 * @category access
1394 *
1395 * @param context $context
1396 * @param string $withcapability
1397 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1398 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1399 * @return array of user records
1400 */
1401function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1402 global $DB;
1403
1404 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1405 $sql = "SELECT count(u.id)
1406 FROM {user} u
1407 JOIN ($esql) je ON je.id = u.id
1408 WHERE u.deleted = 0";
1409
1410 return $DB->count_records_sql($sql, $params);
1411}
bbfdff34 1412
df997f84
PS
1413/**
1414 * All enrol plugins should be based on this class,
1415 * this is also the main source of documentation.
1416 */
1417abstract class enrol_plugin {
1418 protected $config = null;
1419
1420 /**
1421 * Returns name of this enrol plugin
1422 * @return string
1423 */
1424 public function get_name() {
bf423bb1 1425 // second word in class is always enrol name, sorry, no fancy plugin names with _
df997f84
PS
1426 $words = explode('_', get_class($this));
1427 return $words[1];
1428 }
1429
1430 /**
1431 * Returns localised name of enrol instance
1432 *
1433 * @param object $instance (null is accepted too)
1434 * @return string
1435 */
1436 public function get_instance_name($instance) {
1437 if (empty($instance->name)) {
1438 $enrol = $this->get_name();
1439 return get_string('pluginname', 'enrol_'.$enrol);
1440 } else {
b0c6dc1c 1441 $context = context_course::instance($instance->courseid);
54475ccb 1442 return format_string($instance->name, true, array('context'=>$context));
df997f84
PS
1443 }
1444 }
1445
bf423bb1
PS
1446 /**
1447 * Returns optional enrolment information icons.
1448 *
1449 * This is used in course list for quick overview of enrolment options.
1450 *
1451 * We are not using single instance parameter because sometimes
1452 * we might want to prevent icon repetition when multiple instances
1453 * of one type exist. One instance may also produce several icons.
1454 *
1455 * @param array $instances all enrol instances of this type in one course
1456 * @return array of pix_icon
1457 */
1458 public function get_info_icons(array $instances) {
1459 return array();
1460 }
1461
1462 /**
1463 * Returns optional enrolment instance description text.
1464 *
1465 * This is used in detailed course information.
1466 *
1467 *
1468 * @param object $instance
1469 * @return string short html text
1470 */
1471 public function get_description_text($instance) {
1472 return null;
1473 }
1474
df997f84
PS
1475 /**
1476 * Makes sure config is loaded and cached.
1477 * @return void
1478 */
1479 protected function load_config() {
1480 if (!isset($this->config)) {
1481 $name = $this->get_name();
820a8188 1482 $this->config = get_config("enrol_$name");
df997f84
PS
1483 }
1484 }
1485
1486 /**
1487 * Returns plugin config value
1488 * @param string $name
1489 * @param string $default value if config does not exist yet
1490 * @return string value or default
1491 */
1492 public function get_config($name, $default = NULL) {
1493 $this->load_config();
1494 return isset($this->config->$name) ? $this->config->$name : $default;
1495 }
1496
1497 /**
1498 * Sets plugin config value
1499 * @param string $name name of config
1500 * @param string $value string config value, null means delete
1501 * @return string value
1502 */
1503 public function set_config($name, $value) {
47811589 1504 $pluginname = $this->get_name();
df997f84
PS
1505 $this->load_config();
1506 if ($value === NULL) {
1507 unset($this->config->$name);
1508 } else {
1509 $this->config->$name = $value;
1510 }
47811589 1511 set_config($name, $value, "enrol_$pluginname");
df997f84
PS
1512 }
1513
1514 /**
1515 * Does this plugin assign protected roles are can they be manually removed?
1516 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1517 */
1518 public function roles_protected() {
1519 return true;
1520 }
1521
91b99e80
PS
1522 /**
1523 * Does this plugin allow manual enrolments?
1524 *
1525 * @param stdClass $instance course enrol instance
1526 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1527 *
282b5cc7 1528 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
91b99e80
PS
1529 */
1530 public function allow_enrol(stdClass $instance) {
1531 return false;
1532 }
1533
df997f84 1534 /**
282b5cc7 1535 * Does this plugin allow manual unenrolment of all users?
91b99e80 1536 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
df997f84 1537 *
282b5cc7
PS
1538 * @param stdClass $instance course enrol instance
1539 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
df997f84
PS
1540 */
1541 public function allow_unenrol(stdClass $instance) {
1542 return false;
1543 }
1544
282b5cc7
PS
1545 /**
1546 * Does this plugin allow manual unenrolment of a specific user?
1547 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1548 *
1549 * This is useful especially for synchronisation plugins that
1550 * do suspend instead of full unenrolment.
1551 *
1552 * @param stdClass $instance course enrol instance
1553 * @param stdClass $ue record from user_enrolments table, specifies user
1554 *
1555 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1556 */
1557 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1558 return $this->allow_unenrol($instance);
1559 }
1560
df997f84
PS
1561 /**
1562 * Does this plugin allow manual changes in user_enrolments table?
1563 *
91b99e80 1564 * All plugins allowing this must implement 'enrol/xxx:manage' capability
df997f84
PS
1565 *
1566 * @param stdClass $instance course enrol instance
1567 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1568 */
1569 public function allow_manage(stdClass $instance) {
1570 return false;
1571 }
1572
217d0397
PS
1573 /**
1574 * Does this plugin support some way to user to self enrol?
1575 *
1576 * @param stdClass $instance course enrol instance
1577 *
1578 * @return bool - true means show "Enrol me in this course" link in course UI
1579 */
1580 public function show_enrolme_link(stdClass $instance) {
1581 return false;
1582 }
1583
df997f84
PS
1584 /**
1585 * Attempt to automatically enrol current user in course without any interaction,
1586 * calling code has to make sure the plugin and instance are active.
1587 *
ed1d72ea
SH
1588 * This should return either a timestamp in the future or false.
1589 *
df997f84 1590 * @param stdClass $instance course enrol instance
df997f84
PS
1591 * @return bool|int false means not enrolled, integer means timeend
1592 */
1593 public function try_autoenrol(stdClass $instance) {
1594 global $USER;
1595
1596 return false;
1597 }
1598
1599 /**
1600 * Attempt to automatically gain temporary guest access to course,
1601 * calling code has to make sure the plugin and instance are active.
1602 *
ed1d72ea
SH
1603 * This should return either a timestamp in the future or false.
1604 *
df997f84 1605 * @param stdClass $instance course enrol instance
df997f84
PS
1606 * @return bool|int false means no guest access, integer means timeend
1607 */
1608 public function try_guestaccess(stdClass $instance) {
1609 global $USER;
1610
1611 return false;
1612 }
1613
1614 /**
1615 * Enrol user into course via enrol instance.
1616 *
1617 * @param stdClass $instance
1618 * @param int $userid
1619 * @param int $roleid optional role id
2a6dcb72
PS
1620 * @param int $timestart 0 means unknown
1621 * @param int $timeend 0 means forever
f2a9be5f 1622 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
ef8a733a 1623 * @param bool $recovergrades restore grade history
df997f84
PS
1624 * @return void
1625 */
ef8a733a 1626 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
df997f84
PS
1627 global $DB, $USER, $CFG; // CFG necessary!!!
1628
1629 if ($instance->courseid == SITEID) {
1630 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1631 }
1632
1633 $name = $this->get_name();
1634 $courseid = $instance->courseid;
1635
1636 if ($instance->enrol !== $name) {
1637 throw new coding_exception('invalid enrol instance!');
1638 }
b0c6dc1c 1639 $context = context_course::instance($instance->courseid, MUST_EXIST);
ef8a733a
CF
1640 if (!isset($recovergrades)) {
1641 $recovergrades = $CFG->recovergradesdefault;
1642 }
df997f84
PS
1643
1644 $inserted = false;
358fb4dc 1645 $updated = false;
df997f84 1646 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
d587f077 1647 //only update if timestart or timeend or status are different.
ae8c1f3d 1648 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
bb78e249 1649 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
df997f84
PS
1650 }
1651 } else {
365a5941 1652 $ue = new stdClass();
df997f84 1653 $ue->enrolid = $instance->id;
ae8c1f3d 1654 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
df997f84
PS
1655 $ue->userid = $userid;
1656 $ue->timestart = $timestart;
1657 $ue->timeend = $timeend;
6006774c 1658 $ue->modifierid = $USER->id;
2a6dcb72
PS
1659 $ue->timecreated = time();
1660 $ue->timemodified = $ue->timecreated;
df997f84
PS
1661 $ue->id = $DB->insert_record('user_enrolments', $ue);
1662
1663 $inserted = true;
1664 }
1665
df997f84 1666 if ($inserted) {
bb78e249
RT
1667 // Trigger event.
1668 $event = \core\event\user_enrolment_created::create(
1669 array(
1670 'objectid' => $ue->id,
1671 'courseid' => $courseid,
1672 'context' => $context,
1673 'relateduserid' => $ue->userid,
1674 'other' => array('enrol' => $name)
1675 )
1676 );
1677 $event->trigger();
5667e602
MG
1678 // Check if course contacts cache needs to be cleared.
1679 require_once($CFG->libdir . '/coursecatlib.php');
1680 coursecat::user_enrolment_changed($courseid, $ue->userid,
1681 $ue->status, $ue->timestart, $ue->timeend);
df997f84
PS
1682 }
1683
0c2701fd 1684 if ($roleid) {
bbfdff34 1685 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
0c2701fd
PS
1686 if ($this->roles_protected()) {
1687 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1688 } else {
1689 role_assign($roleid, $userid, $context->id);
1690 }
1691 }
1692
ef8a733a
CF
1693 // Recover old grades if present.
1694 if ($recovergrades) {
1695 require_once("$CFG->libdir/gradelib.php");
1696 grade_recover_history_grades($userid, $courseid);
1697 }
1698
bbfdff34 1699 // reset current user enrolment caching
df997f84
PS
1700 if ($userid == $USER->id) {
1701 if (isset($USER->enrol['enrolled'][$courseid])) {
1702 unset($USER->enrol['enrolled'][$courseid]);
1703 }
1704 if (isset($USER->enrol['tempguest'][$courseid])) {
1705 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1706 remove_temp_course_roles($context);
df997f84
PS
1707 }
1708 }
1709 }
1710
1711 /**
1712 * Store user_enrolments changes and trigger event.
1713 *
358fb4dc
PS
1714 * @param stdClass $instance
1715 * @param int $userid
df997f84
PS
1716 * @param int $status
1717 * @param int $timestart
1718 * @param int $timeend
1719 * @return void
1720 */
1721 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
5667e602 1722 global $DB, $USER, $CFG;
df997f84
PS
1723
1724 $name = $this->get_name();
1725
1726 if ($instance->enrol !== $name) {
1727 throw new coding_exception('invalid enrol instance!');
1728 }
1729
1730 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1731 // weird, user not enrolled
1732 return;
1733 }
1734
1735 $modified = false;
1736 if (isset($status) and $ue->status != $status) {
1737 $ue->status = $status;
1738 $modified = true;
1739 }
1740 if (isset($timestart) and $ue->timestart != $timestart) {
1741 $ue->timestart = $timestart;
1742 $modified = true;
1743 }
1744 if (isset($timeend) and $ue->timeend != $timeend) {
1745 $ue->timeend = $timeend;
1746 $modified = true;
1747 }
1748
1749 if (!$modified) {
1750 // no change
1751 return;
1752 }
1753
1754 $ue->modifierid = $USER->id;
1755 $DB->update_record('user_enrolments', $ue);
bbfdff34 1756 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
df997f84 1757
eeb9ee8e 1758 // Invalidate core_access cache for get_suspended_userids.
03ecddb4 1759 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
eeb9ee8e 1760
bb78e249
RT
1761 // Trigger event.
1762 $event = \core\event\user_enrolment_updated::create(
1763 array(
1764 'objectid' => $ue->id,
1765 'courseid' => $instance->courseid,
1766 'context' => context_course::instance($instance->courseid),
1767 'relateduserid' => $ue->userid,
1768 'other' => array('enrol' => $name)
1769 )
1770 );
1771 $event->trigger();
5667e602
MG
1772
1773 require_once($CFG->libdir . '/coursecatlib.php');
1774 coursecat::user_enrolment_changed($instance->courseid, $ue->userid,
1775 $ue->status, $ue->timestart, $ue->timeend);
df997f84
PS
1776 }
1777
1778 /**
1779 * Unenrol user from course,
1780 * the last unenrolment removes all remaining roles.
1781 *
1782 * @param stdClass $instance
1783 * @param int $userid
1784 * @return void
1785 */
1786 public function unenrol_user(stdClass $instance, $userid) {
1787 global $CFG, $USER, $DB;
7881024e 1788 require_once("$CFG->dirroot/group/lib.php");
df997f84
PS
1789
1790 $name = $this->get_name();
1791 $courseid = $instance->courseid;
1792
1793 if ($instance->enrol !== $name) {
1794 throw new coding_exception('invalid enrol instance!');
1795 }
b0c6dc1c 1796 $context = context_course::instance($instance->courseid, MUST_EXIST);
df997f84
PS
1797
1798 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1799 // weird, user not enrolled
1800 return;
1801 }
1802
7881024e
PS
1803 // Remove all users groups linked to this enrolment instance.
1804 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
1805 foreach ($gms as $gm) {
1806 groups_remove_member($gm->groupid, $gm->userid);
1807 }
1808 }
1809
df997f84
PS
1810 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1811 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1812
1813 // add extra info and trigger event
1814 $ue->courseid = $courseid;
1815 $ue->enrol = $name;
1816
1817 $sql = "SELECT 'x'
1818 FROM {user_enrolments} ue
1819 JOIN {enrol} e ON (e.id = ue.enrolid)
7881024e 1820 WHERE ue.userid = :userid AND e.courseid = :courseid";
df997f84
PS
1821 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1822 $ue->lastenrol = false;
7881024e 1823
df997f84
PS
1824 } else {
1825 // the big cleanup IS necessary!
df997f84
PS
1826 require_once("$CFG->libdir/gradelib.php");
1827
1828 // remove all remaining roles
1829 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1830
1831 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1832 groups_delete_group_members($courseid, $userid);
1833
1834 grade_user_unenrol($courseid, $userid);
1835
1836 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1837
7d2800fb 1838 $ue->lastenrol = true; // means user not enrolled any more
df997f84 1839 }
bb78e249
RT
1840 // Trigger event.
1841 $event = \core\event\user_enrolment_deleted::create(
1842 array(
1843 'courseid' => $courseid,
1844 'context' => $context,
1845 'relateduserid' => $ue->userid,
4fb6600e 1846 'objectid' => $ue->id,
bb78e249
RT
1847 'other' => array(
1848 'userenrolment' => (array)$ue,
1849 'enrol' => $name
1850 )
1851 )
1852 );
1853 $event->trigger();
bbfdff34
PS
1854 // reset all enrol caches
1855 $context->mark_dirty();
1856
5667e602
MG
1857 // Check if courrse contacts cache needs to be cleared.
1858 require_once($CFG->libdir . '/coursecatlib.php');
1859 coursecat::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
1860
bbfdff34 1861 // reset current user enrolment caching
df997f84
PS
1862 if ($userid == $USER->id) {
1863 if (isset($USER->enrol['enrolled'][$courseid])) {
1864 unset($USER->enrol['enrolled'][$courseid]);
1865 }
1866 if (isset($USER->enrol['tempguest'][$courseid])) {
1867 unset($USER->enrol['tempguest'][$courseid]);
e922fe23 1868 remove_temp_course_roles($context);
df997f84
PS
1869 }
1870 }
1871 }
1872
1873 /**
1874 * Forces synchronisation of user enrolments.
1875 *
1876 * This is important especially for external enrol plugins,
1877 * this function is called for all enabled enrol plugins
1878 * right after every user login.
1879 *
1880 * @param object $user user record
1881 * @return void
1882 */
1883 public function sync_user_enrolments($user) {
1884 // override if necessary
1885 }
1886
60010fd6
DW
1887 /**
1888 * This returns false for backwards compatibility, but it is really recommended.
1889 *
1890 * @since Moodle 3.1
1891 * @return boolean
1892 */
1893 public function use_standard_editing_ui() {
1894 return false;
1895 }
1896
1897 /**
1898 * Return whether or not, given the current state, it is possible to add a new instance
1899 * of this enrolment plugin to the course.
1900 *
1901 * Default implementation is just for backwards compatibility.
1902 *
1903 * @param int $courseid
1904 * @return boolean
1905 */
1906 public function can_add_instance($courseid) {
1907 $link = $this->get_newinstance_link($courseid);
1908 return !empty($link);
1909 }
1910
51c736f0
DW
1911 /**
1912 * Return whether or not, given the current state, it is possible to edit an instance
1913 * of this enrolment plugin in the course. Used by the standard editing UI
1914 * to generate a link to the edit instance form if editing is allowed.
1915 *
1916 * @param stdClass $instance
1917 * @return boolean
1918 */
1919 public function can_edit_instance($instance) {
1920 $context = context_course::instance($instance->courseid);
1921
1922 return has_capability('enrol/' . $instance->enrol . ':config', $context);
1923 }
1924
df997f84
PS
1925 /**
1926 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1927 * @param int $courseid
1928 * @return moodle_url page url
1929 */
e25f2466 1930 public function get_newinstance_link($courseid) {
df997f84
PS
1931 // override for most plugins, check if instance already exists in cases only one instance is supported
1932 return NULL;
1933 }
1934
1935 /**
ee9e079d 1936 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
df997f84
PS
1937 */
1938 public function instance_deleteable($instance) {
648cddcb
AA
1939 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
1940 enrol_plugin::can_delete_instance() instead');
ee9e079d
DN
1941 }
1942
1943 /**
1944 * Is it possible to delete enrol instance via standard UI?
1945 *
b5a289c4 1946 * @param stdClass $instance
ee9e079d
DN
1947 * @return bool
1948 */
1949 public function can_delete_instance($instance) {
1950 return false;
df997f84
PS
1951 }
1952
b5a289c4
DNA
1953 /**
1954 * Is it possible to hide/show enrol instance via standard UI?
1955 *
1956 * @param stdClass $instance
1957 * @return bool
1958 */
1959 public function can_hide_show_instance($instance) {
1960 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
1961 return true;
1962 }
1963
df997f84
PS
1964 /**
1965 * Returns link to manual enrol UI if exists.
1966 * Does the access control tests automatically.
1967 *
1968 * @param object $instance
1969 * @return moodle_url
1970 */
1971 public function get_manual_enrol_link($instance) {
1972 return NULL;
1973 }
1974
1975 /**
1976 * Returns list of unenrol links for all enrol instances in course.
1977 *
217d0397 1978 * @param int $instance
bf423bb1 1979 * @return moodle_url or NULL if self unenrolment not supported
df997f84
PS
1980 */
1981 public function get_unenrolself_link($instance) {
1982 global $USER, $CFG, $DB;
1983
1984 $name = $this->get_name();
1985 if ($instance->enrol !== $name) {
1986 throw new coding_exception('invalid enrol instance!');
1987 }
1988
1989 if ($instance->courseid == SITEID) {
1990 return NULL;
1991 }
1992
1993 if (!enrol_is_enabled($name)) {
1994 return NULL;
1995 }
1996
1997 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1998 return NULL;
1999 }
2000
df997f84
PS
2001 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2002 return NULL;
2003 }
2004
b0c6dc1c 2005 $context = context_course::instance($instance->courseid, MUST_EXIST);
217d0397 2006
df997f84
PS
2007 if (!has_capability("enrol/$name:unenrolself", $context)) {
2008 return NULL;
2009 }
2010
2011 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2012 return NULL;
2013 }
2014
0e35ba6f 2015 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
df997f84
PS
2016 }
2017
2018 /**
2019 * Adds enrol instance UI to course edit form
2020 *
2021 * @param object $instance enrol instance or null if does not exist yet
2022 * @param MoodleQuickForm $mform
2023 * @param object $data
2024 * @param object $context context of existing course or parent category if course does not exist
2025 * @return void
2026 */
2027 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2028 // override - usually at least enable/disable switch, has to add own form header
2029 }
2030
60010fd6
DW
2031 /**
2032 * Adds form elements to add/edit instance form.
2033 *
2034 * @since Moodle 3.1
2035 * @param object $instance enrol instance or null if does not exist yet
2036 * @param MoodleQuickForm $mform
2037 * @param context $context
2038 * @return void
2039 */
2040 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2041 // Do nothing by default.
2042 }
2043
2044 /**
2045 * Perform custom validation of the data used to edit the instance.
2046 *
2047 * @since Moodle 3.1
2048 * @param array $data array of ("fieldname"=>value) of submitted data
2049 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2050 * @param object $instance The instance data loaded from the DB.
2051 * @param context $context The context of the instance we are editing
2052 * @return array of "element_name"=>"error_description" if there are errors,
2053 * or an empty array if everything is OK.
2054 */
2055 public function edit_instance_validation($data, $files, $instance, $context) {
2056 // No errors by default.
2057 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2058 return array();
2059 }
2060
df997f84
PS
2061 /**
2062 * Validates course edit form data
2063 *
2064 * @param object $instance enrol instance or null if does not exist yet
2065 * @param array $data
2066 * @param object $context context of existing course or parent category if course does not exist
2067 * @return array errors array
2068 */
2069 public function course_edit_validation($instance, array $data, $context) {
2070 return array();
2071 }
2072
2073 /**
2074 * Called after updating/inserting course.
2075 *
2076 * @param bool $inserted true if course just inserted
2077 * @param object $course
2078 * @param object $data form data
2079 * @return void
2080 */
2081 public function course_updated($inserted, $course, $data) {
eafb7a72
PS
2082 if ($inserted) {
2083 if ($this->get_config('defaultenrol')) {
2084 $this->add_default_instance($course);
2085 }
2086 }
df997f84
PS
2087 }
2088
2089 /**
eafb7a72 2090 * Add new instance of enrol plugin.
df997f84
PS
2091 * @param object $course
2092 * @param array instance fields
0848a196 2093 * @return int id of new instance, null if can not be created
df997f84
PS
2094 */
2095 public function add_instance($course, array $fields = NULL) {
2096 global $DB;
2097
2098 if ($course->id == SITEID) {
2099 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2100 }
2101
365a5941 2102 $instance = new stdClass();
df997f84
PS
2103 $instance->enrol = $this->get_name();
2104 $instance->status = ENROL_INSTANCE_ENABLED;
2105 $instance->courseid = $course->id;
2106 $instance->enrolstartdate = 0;
2107 $instance->enrolenddate = 0;
2108 $instance->timemodified = time();
2109 $instance->timecreated = $instance->timemodified;
2110 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2111
2112 $fields = (array)$fields;
2113 unset($fields['enrol']);
2114 unset($fields['courseid']);
2115 unset($fields['sortorder']);
2116 foreach($fields as $field=>$value) {
2117 $instance->$field = $value;
2118 }
2119
080c7d47
MG
2120 $instance->id = $DB->insert_record('enrol', $instance);
2121
2122 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2123
2124 return $instance->id;
df997f84
PS
2125 }
2126
60010fd6
DW
2127 /**
2128 * Update instance of enrol plugin.
2129 *
2130 * @since Moodle 3.1
2131 * @param stdClass $instance
2132 * @param stdClass $data modified instance fields
2133 * @return boolean
2134 */
2135 public function update_instance($instance, $data) {
2136 global $DB;
2137 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2138 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2139 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2140 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2141 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2142 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2143
2144 foreach ($properties as $key) {
2145 if (isset($data->$key)) {
2146 $instance->$key = $data->$key;
2147 }
2148 }
2149 $instance->timemodified = time();
2150
2151 $update = $DB->update_record('enrol', $instance);
2152 if ($update) {
2153 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2154 }
2155 return $update;
2156 }
2157
df997f84
PS
2158 /**
2159 * Add new instance of enrol plugin with default settings,
2160 * called when adding new instance manually or when adding new course.
2161 *
2162 * Not all plugins support this.
2163 *
2164 * @param object $course
2165 * @return int id of new instance or null if no default supported
2166 */
2167 public function add_default_instance($course) {
2168 return null;
2169 }
2170
af7177db
PS
2171 /**
2172 * Update instance status
2173 *
2174 * Override when plugin needs to do some action when enabled or disabled.
2175 *
2176 * @param stdClass $instance
2177 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2178 * @return void
2179 */
2180 public function update_status($instance, $newstatus) {
2181 global $DB;
2182
2183 $instance->status = $newstatus;
2184 $DB->update_record('enrol', $instance);
2185
af7177db 2186 $context = context_course::instance($instance->courseid);
080c7d47
MG
2187 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2188
2189 // Invalidate all enrol caches.
af7177db
PS
2190 $context->mark_dirty();
2191 }
2192
df997f84
PS
2193 /**
2194 * Delete course enrol plugin instance, unenrol all users.
2195 * @param object $instance
2196 * @return void
2197 */
2198 public function delete_instance($instance) {
2199 global $DB;
2200
2201 $name = $this->get_name();
2202 if ($instance->enrol !== $name) {
2203 throw new coding_exception('invalid enrol instance!');
2204 }
2205
2206 //first unenrol all users
2207 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2208 foreach ($participants as $participant) {
2209 $this->unenrol_user($instance, $participant->userid);
2210 }
2211 $participants->close();
2212
2213 // now clean up all remainders that were not removed correctly
a1cedcc9
PS
2214 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2215 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
df997f84
PS
2216 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2217
2218 // finally drop the enrol row
2219 $DB->delete_records('enrol', array('id'=>$instance->id));
af7177db 2220
af7177db 2221 $context = context_course::instance($instance->courseid);
080c7d47
MG
2222 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2223
2224 // Invalidate all enrol caches.
af7177db 2225 $context->mark_dirty();
df997f84
PS
2226 }
2227
2228 /**
2229 * Creates course enrol form, checks if form submitted
2230 * and enrols user if necessary. It can also redirect.
2231 *
2232 * @param stdClass $instance
2233 * @return string html text, usually a form in a text box
2234 */
2235 public function enrol_page_hook(stdClass $instance) {
2236 return null;
2237 }
2238
85d1c53a
RT
2239 /**
2240 * Checks if user can self enrol.
2241 *
2242 * @param stdClass $instance enrolment instance
cc1b5015
RT
2243 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2244 * used by navigation to improve performance.
2245 * @return bool|string true if successful, else error message or false
85d1c53a 2246 */
cc1b5015 2247 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
85d1c53a
RT
2248 return false;
2249 }
2250
2251 /**
2252 * Return information for enrolment instance containing list of parameters required
2253 * for enrolment, name of enrolment plugin etc.
2254 *
2255 * @param stdClass $instance enrolment instance
2256 * @return array instance info.
2257 */
2258 public function get_enrol_info(stdClass $instance) {
2259 return null;
2260 }
2261
df997f84
PS
2262 /**
2263 * Adds navigation links into course admin block.
2264 *
2265 * By defaults looks for manage links only.
2266 *
2267 * @param navigation_node $instancesnode
bbfdff34 2268 * @param stdClass $instance
2d4b1f3e 2269 * @return void
df997f84
PS
2270 */
2271 public function add_course_navigation($instancesnode, stdClass $instance) {
f7589515
DW
2272 if ($this->use_standard_editing_ui()) {
2273 $context = context_course::instance($instance->courseid);
2274 $cap = 'enrol/' . $instance->enrol . ':config';
2275 if (has_capability($cap, $context)) {
2276 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2277 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2278 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2279 }
2280 }
df997f84
PS
2281 }
2282
2283 /**
2d4b1f3e
PS
2284 * Returns edit icons for the page with list of instances
2285 * @param stdClass $instance
2286 * @return array
df997f84 2287 */
2d4b1f3e 2288 public function get_action_icons(stdClass $instance) {
51c736f0
DW
2289 global $OUTPUT;
2290
2291 $icons = array();
2292 if ($this->use_standard_editing_ui()) {
2293 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2294 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2295 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2296 array('class' => 'iconsmall')));
2297 }
2298 return $icons;
df997f84
PS
2299 }
2300
2301 /**
2302 * Reads version.php and determines if it is necessary
2303 * to execute the cron job now.
2304 * @return bool
2305 */
2306 public function is_cron_required() {
2307 global $CFG;
2308
2309 $name = $this->get_name();
2310 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
365a5941 2311 $plugin = new stdClass();
df997f84
PS
2312 include($versionfile);
2313 if (empty($plugin->cron)) {
2314 return false;
2315 }
2316 $lastexecuted = $this->get_config('lastcron', 0);
2317 if ($lastexecuted + $plugin->cron < time()) {
2318 return true;
2319 } else {
2320 return false;
2321 }
2322 }
2323
2324 /**
2325 * Called for all enabled enrol plugins that returned true from is_cron_required().
2326 * @return void
2327 */
2328 public function cron() {
2329 }
2330
2331 /**
2332 * Called when user is about to be deleted
2333 * @param object $user
2334 * @return void
2335 */
2336 public function user_delete($user) {
2337 global $DB;
2338
2339 $sql = "SELECT e.*
2340 FROM {enrol} e
45fb2cf8
PS
2341 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2342 WHERE e.enrol = :name AND ue.userid = :userid";
df997f84
PS
2343 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2344
45fb2cf8 2345 $rs = $DB->get_recordset_sql($sql, $params);
df997f84
PS
2346 foreach($rs as $instance) {
2347 $this->unenrol_user($instance, $user->id);
2348 }
2349 $rs->close();
2350 }
df997f84 2351
b69ca6be
SH
2352 /**
2353 * Returns an enrol_user_button that takes the user to a page where they are able to
2354 * enrol users into the managers course through this plugin.
2355 *
2356 * Optional: If the plugin supports manual enrolments it can choose to override this
2357 * otherwise it shouldn't
2358 *
2359 * @param course_enrolment_manager $manager
2360 * @return enrol_user_button|false
2361 */
2362 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2363 return false;
2364 }
291215f4
SH
2365
2366 /**
2367 * Gets an array of the user enrolment actions
2368 *
2369 * @param course_enrolment_manager $manager
2370 * @param stdClass $ue
2371 * @return array An array of user_enrolment_actions
2372 */
2373 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
12a52d7c 2374 return array();
291215f4 2375 }
75ee207b
SH
2376
2377 /**
2378 * Returns true if the plugin has one or more bulk operations that can be performed on
2379 * user enrolments.
2380 *
f20edd52 2381 * @param course_enrolment_manager $manager
75ee207b
SH
2382 * @return bool
2383 */
f20edd52 2384 public function has_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
2385 return false;
2386 }
2387
2388 /**
2389 * Return an array of enrol_bulk_enrolment_operation objects that define
2390 * the bulk actions that can be performed on user enrolments by the plugin.
2391 *
f20edd52 2392 * @param course_enrolment_manager $manager
75ee207b
SH
2393 * @return array
2394 */
f20edd52 2395 public function get_bulk_operations(course_enrolment_manager $manager) {
75ee207b
SH
2396 return array();
2397 }
7a7b8a1f 2398
d8f22c49
PS
2399 /**
2400 * Do any enrolments need expiration processing.
2401 *
2402 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2403 *
2404 * @param progress_trace $trace
2405 * @param int $courseid one course, empty mean all
2406 * @return bool true if any data processed, false if not
2407 */
2408 public function process_expirations(progress_trace $trace, $courseid = null) {
2409 global $DB;
2410
2411 $name = $this->get_name();
2412 if (!enrol_is_enabled($name)) {
2413 $trace->finished();
2414 return false;
2415 }
2416
2417 $processed = false;
2418 $params = array();
2419 $coursesql = "";
2420 if ($courseid) {
2421 $coursesql = "AND e.courseid = :courseid";
2422 }
2423
2424 // Deal with expired accounts.
2425 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2426
2427 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2428 $instances = array();
2429 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2430 FROM {user_enrolments} ue
2431 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2432 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2433 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2434 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2435
2436 $rs = $DB->get_recordset_sql($sql, $params);
2437 foreach ($rs as $ue) {
2438 if (!$processed) {
2439 $trace->output("Starting processing of enrol_$name expirations...");
2440 $processed = true;
2441 }
2442 if (empty($instances[$ue->enrolid])) {
2443 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2444 }
2445 $instance = $instances[$ue->enrolid];
2446 if (!$this->roles_protected()) {
2447 // Let's just guess what extra roles are supposed to be removed.
2448 if ($instance->roleid) {
2449 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2450 }
2451 }
2452 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2453 $this->unenrol_user($instance, $ue->userid);
2454 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2455 }
2456 $rs->close();
2457 unset($instances);
2458
2459 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2460 $instances = array();
2461 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2462 FROM {user_enrolments} ue
2463 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2464 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2465 WHERE ue.timeend > 0 AND ue.timeend < :now
2466 AND ue.status = :useractive $coursesql";
2467 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2468 $rs = $DB->get_recordset_sql($sql, $params);
2469 foreach ($rs as $ue) {
2470 if (!$processed) {
2471 $trace->output("Starting processing of enrol_$name expirations...");
2472 $processed = true;
2473 }
2474 if (empty($instances[$ue->enrolid])) {
2475 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2476 }
2477 $instance = $instances[$ue->enrolid];
2478
2479 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2480 if (!$this->roles_protected()) {
2481 // Let's just guess what roles should be removed.
2482 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2483 if ($count == 1) {
2484 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2485
2486 } else if ($count > 1 and $instance->roleid) {
2487 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2488 }
2489 }
2490 // In any case remove all roles that belong to this instance and user.
2491 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2492 // Final cleanup of subcontexts if there are no more course roles.
2493 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2494 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2495 }
2496 }
2497
2498 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2499 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2500 }
2501 $rs->close();
2502 unset($instances);
2503
2504 } else {
2505 // ENROL_EXT_REMOVED_KEEP means no changes.
2506 }
2507
2508 if ($processed) {
2509 $trace->output("...finished processing of enrol_$name expirations");
2510 } else {
2511 $trace->output("No expired enrol_$name enrolments detected");
2512 }
2513 $trace->finished();
2514
2515 return $processed;
2516 }
2517
8c04252c
PS
2518 /**
2519 * Send expiry notifications.
2520 *
2521 * Plugin that wants to have expiry notification MUST implement following:
2522 * - expirynotifyhour plugin setting,
2523 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2524 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2525 * expirymessageenrolledsubject and expirymessageenrolledbody),
2526 * - expiry_notification provider in db/messages.php,
2527 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2528 * - something that calls this method, such as cron.
2529 *
5d549ffc 2530 * @param progress_trace $trace (accepts bool for backwards compatibility only)
8c04252c 2531 */
5d549ffc 2532 public function send_expiry_notifications($trace) {
8c04252c
PS
2533 global $DB, $CFG;
2534
d8f22c49
PS
2535 $name = $this->get_name();
2536 if (!enrol_is_enabled($name)) {
2537 $trace->finished();
2538 return;
2539 }
2540
8c04252c
PS
2541 // Unfortunately this may take a long time, it should not be interrupted,
2542 // otherwise users get duplicate notification.
2543
3ef7279f 2544 core_php_time_limit::raise();
8c04252c
PS
2545 raise_memory_limit(MEMORY_HUGE);
2546
8c04252c
PS
2547
2548 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2549 $expirynotifyhour = $this->get_config('expirynotifyhour');
2550 if (is_null($expirynotifyhour)) {
2551 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
5d549ffc 2552 $trace->finished();
8c04252c
PS
2553 return;
2554 }
2555
5d549ffc
PS
2556 if (!($trace instanceof progress_trace)) {
2557 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2558 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2559 }
2560
8c04252c
PS
2561 $timenow = time();
2562 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2563
2564 if ($expirynotifylast > $notifytime) {
5d549ffc
PS
2565 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2566 $trace->finished();
8c04252c 2567 return;
5d549ffc 2568
8c04252c 2569 } else if ($timenow < $notifytime) {
5d549ffc
PS
2570 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2571 $trace->finished();
8c04252c
PS
2572 return;
2573 }
2574
5d549ffc 2575 $trace->output('Processing '.$name.' enrolment expiration notifications...');
8c04252c
PS
2576
2577 // Notify users responsible for enrolment once every day.
2578 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2579 FROM {user_enrolments} ue
2580 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2581 JOIN {course} c ON (c.id = e.courseid)
2582 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2583 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2584 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2585 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2586
2587 $rs = $DB->get_recordset_sql($sql, $params);
2588
2589 $lastenrollid = 0;
2590 $users = array();
2591
2592 foreach($rs as $ue) {
2593 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
5d549ffc 2594 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
8c04252c
PS
2595 $users = array();
2596 }
2597 $lastenrollid = $ue->enrolid;
2598
2599 $enroller = $this->get_enroller($ue->enrolid);
2600 $context = context_course::instance($ue->courseid);
2601
2602 $user = $DB->get_record('user', array('id'=>$ue->userid));
2603
2604 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2605
2606 if (!$ue->notifyall) {
2607 continue;
2608 }
2609
2610 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2611 // Notify enrolled users only once at the start of the threshold.
5d549ffc 2612 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c
PS
2613 continue;
2614 }
2615
5d549ffc 2616 $this->notify_expiry_enrolled($user, $ue, $trace);
8c04252c
PS
2617 }
2618 $rs->close();
2619
2620 if ($lastenrollid and $users) {
5d549ffc 2621 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
8c04252c
PS
2622 }
2623
5d549ffc
PS
2624 $trace->output('...notification processing finished.');
2625 $trace->finished();
2626
8c04252c
PS
2627 $this->set_config('expirynotifylast', $timenow);
2628 }
2629
2630 /**
2631 * Returns the user who is responsible for enrolments for given instance.
2632 *
2633 * Override if plugin knows anybody better than admin.
2634 *
2635 * @param int $instanceid enrolment instance id
2636 * @return stdClass user record
2637 */
2638 protected function get_enroller($instanceid) {
2639 return get_admin();
2640 }
2641
2642 /**
2643 * Notify user about incoming expiration of their enrolment,
2644 * it is called only if notification of enrolled users (aka students) is enabled in course.
2645 *
2646 * This is executed only once for each expiring enrolment right
2647 * at the start of the expiration threshold.
2648 *
2649 * @param stdClass $user
2650 * @param stdClass $ue
5d549ffc 2651 * @param progress_trace $trace
8c04252c 2652 */
5d549ffc 2653 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
c484af5a 2654 global $CFG;
8c04252c
PS
2655
2656 $name = $this->get_name();
2657
c484af5a 2658 $oldforcelang = force_current_language($user->lang);
8c04252c
PS
2659
2660 $enroller = $this->get_enroller($ue->enrolid);
2661 $context = context_course::instance($ue->courseid);
2662
2663 $a = new stdClass();
2664 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2665 $a->user = fullname($user, true);
2666 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2667 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2668
2669 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2670 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2671
2672 $message = new stdClass();
2673 $message->notification = 1;
2674 $message->component = 'enrol_'.$name;
2675 $message->name = 'expiry_notification';
2676 $message->userfrom = $enroller;
2677 $message->userto = $user;
2678 $message->subject = $subject;
2679 $message->fullmessage = $body;
2680 $message->fullmessageformat = FORMAT_MARKDOWN;
2681 $message->fullmessagehtml = markdown_to_html($body);
2682 $message->smallmessage = $subject;
2683 $message->contexturlname = $a->course;
2684 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2685
2686 if (message_send($message)) {
5d549ffc 2687 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c 2688 } else {
5d549ffc 2689 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
8c04252c
PS
2690 }
2691
c484af5a 2692 force_current_language($oldforcelang);
8c04252c
PS
2693 }
2694
2695 /**
2696 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2697 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2698 *
2699 * This is called repeatedly every day for each course if there are any pending expiration
2700 * in the expiration threshold.
2701 *
2702 * @param int $eid
2703 * @param array $users
5d549ffc 2704 * @param progress_trace $trace
8c04252c 2705 */
5d549ffc 2706 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
c484af5a 2707 global $DB;
8c04252c
PS
2708
2709 $name = $this->get_name();
2710
2711 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2712 $context = context_course::instance($instance->courseid);
2713 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2714
2715 $enroller = $this->get_enroller($instance->id);
2716 $admin = get_admin();
2717
c484af5a 2718 $oldforcelang = force_current_language($enroller->lang);
8c04252c
PS
2719
2720 foreach($users as $key=>$info) {
2721 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2722 }
2723
2724 $a = new stdClass();
2725 $a->course = format_string($course->fullname, true, array('context'=>$context));
2726 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
2727 $a->users = implode("\n", $users);
2728 $a->extendurl = (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid));
2729
2730 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2731 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
2732
2733 $message = new stdClass();
2734 $message->notification = 1;
2735 $message->component = 'enrol_'.$name;
2736 $message->name = 'expiry_notification';
2737 $message->userfrom = $admin;
2738 $message->userto = $enroller;
2739 $message->subject = $subject;
2740 $message->fullmessage = $body;
2741 $message->fullmessageformat = FORMAT_MARKDOWN;
2742 $message->fullmessagehtml = markdown_to_html($body);
2743 $message->smallmessage = $subject;
2744 $message->contexturlname = $a->course;
2745 $message->contexturl = $a->extendurl;
2746
2747 if (message_send($message)) {
5d549ffc 2748 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
8c04252c 2749 } else {
5d549ffc 2750 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
8c04252c
PS
2751 }
2752
c484af5a 2753 force_current_language($oldforcelang);
8c04252c
PS
2754 }
2755
f6199295
MP
2756 /**
2757 * Backup execution step hook to annotate custom fields.
2758 *
2759 * @param backup_enrolments_execution_step $step
2760 * @param stdClass $enrol
2761 */
2762 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
2763 // Override as necessary to annotate custom fields in the enrol table.
2764 }
2765
7a7b8a1f
PS
2766 /**
2767 * Automatic enrol sync executed during restore.
2768 * Useful for automatic sync by course->idnumber or course category.
2769 * @param stdClass $course course record
2770 */
2771 public function restore_sync_course($course) {
2772 // Override if necessary.
2773 }
2774
2775 /**
2776 * Restore instance and map settings.
2777 *
2778 * @param restore_enrolments_structure_step $step
2779 * @param stdClass $data
2780 * @param stdClass $course
2781 * @param int $oldid
2782 */
2783 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
2784 // Do not call this from overridden methods, restore and set new id there.
2785 $step->set_mapping('enrol', $oldid, 0);
2786 }
2787
2788 /**
2789 * Restore user enrolment.
2790 *
2791 * @param restore_enrolments_structure_step $step
2792 * @param stdClass $data
2793 * @param stdClass $instance
2794 * @param int $oldinstancestatus
2795 * @param int $userid
2796 */
2797 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
2798 // Override as necessary if plugin supports restore of enrolments.
2799 }
2800
2801 /**
2802 * Restore role assignment.
2803 *
2804 * @param stdClass $instance
2805 * @param int $roleid
2806 * @param int $userid
2807 * @param int $contextid
2808 */
2809 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
2810 // No role assignment by default, override if necessary.
2811 }
7881024e
PS
2812
2813 /**
2814 * Restore user group membership.
2815 * @param stdClass $instance
2816 * @param int $groupid
2817 * @param int $userid
2818 */
2819 public function restore_group_member($instance, $groupid, $userid) {
2820 // Implement if you want to restore protected group memberships,
2821 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
2822 }
60010fd6
DW
2823
2824 /**
2825 * Returns defaults for new instances.
2826 * @since Moodle 3.1
2827 * @return array
2828 */
2829 public function get_instance_defaults() {
2830 return array();
2831 }
2832
2833 /**
2834 * Validate a list of parameter names and types.
2835 * @since Moodle 3.1
2836 *
2837 * @param array $data array of ("fieldname"=>value) of submitted data
2838 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
2839 * @return array of "element_name"=>"error_description" if there are errors,
2840 * or an empty array if everything is OK.
2841 */
2842 public function validate_param_types($data, $rules) {
2843 $errors = array();
2844 $invalidstr = get_string('invaliddata', 'error');
2845 foreach ($rules as $fieldname => $rule) {
2846 if (is_array($rule)) {
2847 if (!in_array($data[$fieldname], $rule)) {
2848 $errors[$fieldname] = $invalidstr;
2849 }
2850 } else {
2851 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
2852 $errors[$fieldname] = $invalidstr;
2853 }
2854 }
2855 }
2856 return $errors;
2857 }
4b715423 2858}