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