Merge branch 'MDL-63381_311_v3' of https://github.com/TomoTsuyuki/moodle into MOODLE_...
[moodle.git] / enrol / locallib.php
blob10f3a0d328710c026767486f5affc4678dd31415
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains the course_enrolment_manager class which is used to interface
19 * with the functions that exist in enrollib.php in relation to a single course.
21 * @package core_enrol
22 * @copyright 2010 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 use core_user\fields;
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class provides a targeted tied together means of interfacing the enrolment
32 * tasks together with a course.
34 * It is provided as a convenience more than anything else.
36 * @copyright 2010 Sam Hemelryk
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class course_enrolment_manager {
41 /**
42 * The course context
43 * @var context
45 protected $context;
46 /**
47 * The course we are managing enrolments for
48 * @var stdClass
50 protected $course = null;
51 /**
52 * Limits the focus of the manager to one enrolment plugin instance
53 * @var string
55 protected $instancefilter = null;
56 /**
57 * Limits the focus of the manager to users with specified role
58 * @var int
60 protected $rolefilter = 0;
61 /**
62 * Limits the focus of the manager to users who match search string
63 * @var string
65 protected $searchfilter = '';
66 /**
67 * Limits the focus of the manager to users in specified group
68 * @var int
70 protected $groupfilter = 0;
71 /**
72 * Limits the focus of the manager to users who match status active/inactive
73 * @var int
75 protected $statusfilter = -1;
77 /**
78 * The total number of users enrolled in the course
79 * Populated by course_enrolment_manager::get_total_users
80 * @var int
82 protected $totalusers = null;
83 /**
84 * An array of users currently enrolled in the course
85 * Populated by course_enrolment_manager::get_users
86 * @var array
88 protected $users = array();
90 /**
91 * An array of users who have roles within this course but who have not
92 * been enrolled in the course
93 * @var array
95 protected $otherusers = array();
97 /**
98 * The total number of users who hold a role within the course but who
99 * arn't enrolled.
100 * @var int
102 protected $totalotherusers = null;
105 * The current moodle_page object
106 * @var moodle_page
108 protected $moodlepage = null;
110 /**#@+
111 * These variables are used to cache the information this class uses
112 * please never use these directly instead use their get_ counterparts.
113 * @access private
114 * @var array
116 private $_instancessql = null;
117 private $_instances = null;
118 private $_inames = null;
119 private $_plugins = null;
120 private $_allplugins = null;
121 private $_roles = null;
122 private $_visibleroles = null;
123 private $_assignableroles = null;
124 private $_assignablerolesothers = null;
125 private $_groups = null;
126 /**#@-*/
129 * Constructs the course enrolment manager
131 * @param moodle_page $moodlepage
132 * @param stdClass $course
133 * @param string $instancefilter
134 * @param int $rolefilter If non-zero, filters to users with specified role
135 * @param string $searchfilter If non-blank, filters to users with search text
136 * @param int $groupfilter if non-zero, filter users with specified group
137 * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
139 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
140 $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
141 $this->moodlepage = $moodlepage;
142 $this->context = context_course::instance($course->id);
143 $this->course = $course;
144 $this->instancefilter = $instancefilter;
145 $this->rolefilter = $rolefilter;
146 $this->searchfilter = $searchfilter;
147 $this->groupfilter = $groupfilter;
148 $this->statusfilter = $statusfilter;
152 * Returns the current moodle page
153 * @return moodle_page
155 public function get_moodlepage() {
156 return $this->moodlepage;
160 * Returns the total number of enrolled users in the course.
162 * If a filter was specificed this will be the total number of users enrolled
163 * in this course by means of that instance.
165 * @global moodle_database $DB
166 * @return int
168 public function get_total_users() {
169 global $DB;
170 if ($this->totalusers === null) {
171 list($instancessql, $params, $filter) = $this->get_instance_sql();
172 list($filtersql, $moreparams) = $this->get_filter_sql();
173 $params += $moreparams;
174 $sqltotal = "SELECT COUNT(DISTINCT u.id)
175 FROM {user} u
176 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
177 JOIN {enrol} e ON (e.id = ue.enrolid)";
178 if ($this->groupfilter) {
179 $sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
180 ON (u.id = gm.userid AND g.courseid = e.courseid)";
182 $sqltotal .= "WHERE $filtersql";
183 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
185 return $this->totalusers;
189 * Returns the total number of enrolled users in the course.
191 * If a filter was specificed this will be the total number of users enrolled
192 * in this course by means of that instance.
194 * @global moodle_database $DB
195 * @return int
197 public function get_total_other_users() {
198 global $DB;
199 if ($this->totalotherusers === null) {
200 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
201 $params['courseid'] = $this->course->id;
202 $sql = "SELECT COUNT(DISTINCT u.id)
203 FROM {role_assignments} ra
204 JOIN {user} u ON u.id = ra.userid
205 JOIN {context} ctx ON ra.contextid = ctx.id
206 LEFT JOIN (
207 SELECT ue.id, ue.userid
208 FROM {user_enrolments} ue
209 LEFT JOIN {enrol} e ON e.id=ue.enrolid
210 WHERE e.courseid = :courseid
211 ) ue ON ue.userid=u.id
212 WHERE ctx.id $ctxcondition AND
213 ue.id IS NULL";
214 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
216 return $this->totalotherusers;
220 * Gets all of the users enrolled in this course.
222 * If a filter was specified this will be the users who were enrolled
223 * in this course by means of that instance. If role or search filters were
224 * specified then these will also be applied.
226 * @global moodle_database $DB
227 * @param string $sort
228 * @param string $direction ASC or DESC
229 * @param int $page First page should be 0
230 * @param int $perpage Defaults to 25
231 * @return array
233 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
234 global $DB;
235 if ($direction !== 'ASC') {
236 $direction = 'DESC';
238 $key = md5("$sort-$direction-$page-$perpage");
239 if (!array_key_exists($key, $this->users)) {
240 list($instancessql, $params, $filter) = $this->get_instance_sql();
241 list($filtersql, $moreparams) = $this->get_filter_sql();
242 $params += $moreparams;
243 $userfields = fields::for_identity($this->get_context())->with_userpic()->excluding('lastaccess');
244 ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] =
245 (array)$userfields->get_sql('u', true, '', '', false);
246 $params += $fieldjoinparams;
247 $sql = "SELECT DISTINCT $fieldselect, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
248 FROM {user} u
249 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
250 JOIN {enrol} e ON (e.id = ue.enrolid)
251 $fieldjoin
252 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
253 if ($this->groupfilter) {
254 $sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
255 ON (u.id = gm.userid AND g.courseid = e.courseid)";
257 $sql .= "WHERE $filtersql
258 ORDER BY $sort $direction";
259 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
261 return $this->users[$key];
265 * Obtains WHERE clause to filter results by defined search and role filter
266 * (instance filter is handled separately in JOIN clause, see
267 * get_instance_sql).
269 * @return array Two-element array with SQL and params for WHERE clause
271 protected function get_filter_sql() {
272 global $DB;
274 // Search condition.
275 // TODO Does not support custom user profile fields (MDL-70456).
276 $extrafields = fields::get_identity_fields($this->get_context(), false);
277 list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
279 // Role condition.
280 if ($this->rolefilter) {
281 // Get context SQL.
282 $contextids = $this->context->get_parent_context_ids();
283 $contextids[] = $this->context->id;
284 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
285 $params += $contextparams;
287 // Role check condition.
288 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
289 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
290 $params['roleid'] = $this->rolefilter;
293 // Group condition.
294 if ($this->groupfilter) {
295 if ($this->groupfilter < 0) {
296 // Show users who are not in any group.
297 $sql .= " AND gm.groupid IS NULL";
298 } else {
299 $sql .= " AND gm.groupid = :groupid";
300 $params['groupid'] = $this->groupfilter;
304 // Status condition.
305 if ($this->statusfilter === ENROL_USER_ACTIVE) {
306 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
307 AND (ue.timeend = 0 OR ue.timeend > :now2)";
308 $now = round(time(), -2); // rounding helps caching in DB
309 $params += array('enabled' => ENROL_INSTANCE_ENABLED,
310 'active' => ENROL_USER_ACTIVE,
311 'now1' => $now,
312 'now2' => $now);
313 } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
314 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
315 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
316 $now = round(time(), -2); // rounding helps caching in DB
317 $params += array('disabled' => ENROL_INSTANCE_DISABLED,
318 'inactive' => ENROL_USER_SUSPENDED,
319 'now1' => $now,
320 'now2' => $now);
323 return array($sql, $params);
327 * Gets and array of other users.
329 * Other users are users who have been assigned roles or inherited roles
330 * within this course but who have not been enrolled in the course
332 * @global moodle_database $DB
333 * @param string $sort
334 * @param string $direction
335 * @param int $page
336 * @param int $perpage
337 * @return array
339 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
340 global $DB;
341 if ($direction !== 'ASC') {
342 $direction = 'DESC';
344 $key = md5("$sort-$direction-$page-$perpage");
345 if (!array_key_exists($key, $this->otherusers)) {
346 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
347 $params['courseid'] = $this->course->id;
348 $params['cid'] = $this->course->id;
349 $userfields = fields::for_identity($this->get_context())->with_userpic();
350 ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] =
351 (array)$userfields->get_sql('u', true);
352 $params += $fieldjoinparams;
353 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid,
354 coalesce(u.lastaccess,0) AS lastaccess
355 $fieldselect
356 FROM {role_assignments} ra
357 JOIN {user} u ON u.id = ra.userid
358 JOIN {context} ctx ON ra.contextid = ctx.id
359 $fieldjoin
360 LEFT JOIN (
361 SELECT ue.id, ue.userid
362 FROM {user_enrolments} ue
363 JOIN {enrol} e ON e.id = ue.enrolid
364 WHERE e.courseid = :courseid
365 ) ue ON ue.userid=u.id
366 WHERE ctx.id $ctxcondition AND
367 ue.id IS NULL
368 ORDER BY $sort $direction, ctx.depth DESC";
369 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
371 return $this->otherusers[$key];
375 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
377 * @param string $search the search term, if any.
378 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
379 * @return array with three elements:
380 * string list of fields to SELECT,
381 * string possible database joins for user fields
382 * string contents of SQL WHERE clause,
383 * array query params. Note that the SQL snippets use named parameters.
385 protected function get_basic_search_conditions($search, $searchanywhere) {
386 global $DB, $CFG;
388 // Get custom user field SQL used for querying all the fields we need (identity, name, and
389 // user picture).
390 $userfields = fields::for_identity($this->context)->with_name()->with_userpic()
391 ->excluding('username', 'lastaccess', 'maildisplay');
392 ['selects' => $fieldselects, 'joins' => $fieldjoins, 'params' => $params, 'mappings' => $mappings] =
393 (array)$userfields->get_sql('u', true, '', '', false);
395 // Searchable fields are only the identity and name ones (not userpic).
396 $searchable = array_fill_keys($userfields->get_required_fields(
397 [fields::PURPOSE_IDENTITY, fields::PURPOSE_NAME]), true);
399 // Add some additional sensible conditions
400 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
401 $params['guestid'] = $CFG->siteguest;
402 if (!empty($search)) {
403 // Include identity and name fields as conditions.
404 foreach ($mappings as $fieldname => $fieldsql) {
405 if (array_key_exists($fieldname, $searchable)) {
406 $conditions[] = $fieldsql;
409 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
410 if ($searchanywhere) {
411 $searchparam = '%' . $search . '%';
412 } else {
413 $searchparam = $search . '%';
415 $i = 0;
416 foreach ($conditions as $key => $condition) {
417 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
418 $params["con{$i}00"] = $searchparam;
419 $i++;
421 $tests[] = '(' . implode(' OR ', $conditions) . ')';
423 $wherecondition = implode(' AND ', $tests);
425 $selects = $fieldselects . ', u.username, u.lastaccess, u.maildisplay';
426 return [$selects, $fieldjoins, $params, $wherecondition];
430 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
432 * @param string $search the search string, if any.
433 * @param string $fields the first bit of the SQL when returning some users.
434 * @param string $countfields fhe first bit of the SQL when counting the users.
435 * @param string $sql the bulk of the SQL statement.
436 * @param array $params query parameters.
437 * @param int $page which page number of the results to show.
438 * @param int $perpage number of users per page.
439 * @param int $addedenrollment number of users added to enrollment.
440 * @param bool $returnexactcount Return the exact total users using count_record or not.
441 * @return array with two or three elements:
442 * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
443 * array users List of user objects returned by the query.
444 * boolean moreusers True if there are still more users, otherwise is False.
445 * @throws dml_exception
447 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage,
448 $addedenrollment = 0, $returnexactcount = false) {
449 global $DB, $CFG;
451 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
452 $order = ' ORDER BY ' . $sort;
454 $totalusers = 0;
455 $moreusers = false;
456 $results = [];
458 $availableusers = $DB->get_records_sql($fields . $sql . $order,
459 array_merge($params, $sortparams), ($page * $perpage) - $addedenrollment, $perpage + 1);
460 if ($availableusers) {
461 $totalusers = count($availableusers);
462 $moreusers = $totalusers > $perpage;
464 if ($moreusers) {
465 // We need to discard the last record.
466 array_pop($availableusers);
469 if ($returnexactcount && $moreusers) {
470 // There is more data. We need to do the exact count.
471 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
475 $results['users'] = $availableusers;
476 $results['moreusers'] = $moreusers;
478 if ($returnexactcount) {
479 // Include totalusers in result if $returnexactcount flag is true.
480 $results['totalusers'] = $totalusers;
483 return $results;
487 * Gets an array of the users that can be enrolled in this course.
489 * @global moodle_database $DB
490 * @param int $enrolid
491 * @param string $search
492 * @param bool $searchanywhere
493 * @param int $page Defaults to 0
494 * @param int $perpage Defaults to 25
495 * @param int $addedenrollment Defaults to 0
496 * @param bool $returnexactcount Return the exact total users using count_record or not.
497 * @return array with two or three elements:
498 * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
499 * array users List of user objects returned by the query.
500 * boolean moreusers True if there are still more users, otherwise is False.
501 * @throws dml_exception
503 public function get_potential_users($enrolid, $search = '', $searchanywhere = false, $page = 0, $perpage = 25,
504 $addedenrollment = 0, $returnexactcount = false) {
505 global $DB;
507 [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
509 $fields = 'SELECT '.$ufields;
510 $countfields = 'SELECT COUNT(1)';
511 $sql = " FROM {user} u
512 $joins
513 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
514 WHERE $wherecondition
515 AND ue.id IS NULL";
516 $params['enrolid'] = $enrolid;
518 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment,
519 $returnexactcount);
523 * Searches other users and returns paginated results
525 * @global moodle_database $DB
526 * @param string $search
527 * @param bool $searchanywhere
528 * @param int $page Starting at 0
529 * @param int $perpage
530 * @param bool $returnexactcount Return the exact total users using count_record or not.
531 * @return array with two or three elements:
532 * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
533 * array users List of user objects returned by the query.
534 * boolean moreusers True if there are still more users, otherwise is False.
535 * @throws dml_exception
537 public function search_other_users($search = '', $searchanywhere = false, $page = 0, $perpage = 25, $returnexactcount = false) {
538 global $DB, $CFG;
540 [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
542 $fields = 'SELECT ' . $ufields;
543 $countfields = 'SELECT COUNT(u.id)';
544 $sql = " FROM {user} u
545 $joins
546 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
547 WHERE $wherecondition
548 AND ra.id IS NULL";
549 $params['contextid'] = $this->context->id;
551 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount);
555 * Searches through the enrolled users in this course.
557 * @param string $search The search term.
558 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
559 * @param int $page Starting at 0.
560 * @param int $perpage Number of users returned per page.
561 * @param bool $returnexactcount Return the exact total users using count_record or not.
562 * @return array with two or three elements:
563 * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
564 * array users List of user objects returned by the query.
565 * boolean moreusers True if there are still more users, otherwise is False.
567 public function search_users(string $search = '', bool $searchanywhere = false, int $page = 0, int $perpage = 25,
568 bool $returnexactcount = false) {
569 [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
571 $fields = 'SELECT ' . $ufields;
572 $countfields = 'SELECT COUNT(u.id)';
573 $sql = " FROM {user} u
574 $joins
575 JOIN {user_enrolments} ue ON ue.userid = u.id
576 JOIN {enrol} e ON ue.enrolid = e.id
577 WHERE $wherecondition
578 AND e.courseid = :courseid";
579 $params['courseid'] = $this->course->id;
581 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount);
585 * Gets an array containing some SQL to user for when selecting, params for
586 * that SQL, and the filter that was used in constructing the sql.
588 * @global moodle_database $DB
589 * @return string
591 protected function get_instance_sql() {
592 global $DB;
593 if ($this->_instancessql === null) {
594 $instances = $this->get_enrolment_instances();
595 $filter = $this->get_enrolment_filter();
596 if ($filter && array_key_exists($filter, $instances)) {
597 $sql = " = :ifilter";
598 $params = array('ifilter'=>$filter);
599 } else {
600 $filter = 0;
601 if ($instances) {
602 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
603 } else {
604 // no enabled instances, oops, we should probably say something
605 $sql = "= :never";
606 $params = array('never'=>-1);
609 $this->instancefilter = $filter;
610 $this->_instancessql = array($sql, $params, $filter);
612 return $this->_instancessql;
616 * Returns all of the enrolment instances for this course.
618 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
619 * @return array
621 public function get_enrolment_instances($onlyenabled = false) {
622 if ($this->_instances === null) {
623 $this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
625 return $this->_instances;
629 * Returns the names for all of the enrolment instances for this course.
631 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
632 * @return array
634 public function get_enrolment_instance_names($onlyenabled = false) {
635 if ($this->_inames === null) {
636 $instances = $this->get_enrolment_instances($onlyenabled);
637 $plugins = $this->get_enrolment_plugins(false);
638 foreach ($instances as $key=>$instance) {
639 if (!isset($plugins[$instance->enrol])) {
640 // weird, some broken stuff in plugin
641 unset($instances[$key]);
642 continue;
644 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
647 return $this->_inames;
651 * Gets all of the enrolment plugins that are available for this course.
653 * @param bool $onlyenabled return only enabled enrol plugins
654 * @return array
656 public function get_enrolment_plugins($onlyenabled = true) {
657 if ($this->_plugins === null) {
658 $this->_plugins = enrol_get_plugins(true);
661 if ($onlyenabled) {
662 return $this->_plugins;
665 if ($this->_allplugins === null) {
666 // Make sure we have the same objects in _allplugins and _plugins.
667 $this->_allplugins = $this->_plugins;
668 foreach (enrol_get_plugins(false) as $name=>$plugin) {
669 if (!isset($this->_allplugins[$name])) {
670 $this->_allplugins[$name] = $plugin;
675 return $this->_allplugins;
679 * Gets all of the roles this course can contain.
681 * @return array
683 public function get_all_roles() {
684 if ($this->_roles === null) {
685 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
687 return $this->_roles;
691 * Gets all of the roles this course can contain.
693 * @return array
695 public function get_viewable_roles() {
696 if ($this->_visibleroles === null) {
697 $this->_visibleroles = get_viewable_roles($this->context);
699 return $this->_visibleroles;
703 * Gets all of the assignable roles for this course.
705 * @return array
707 public function get_assignable_roles($otherusers = false) {
708 if ($this->_assignableroles === null) {
709 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
712 if ($otherusers) {
713 if (!is_array($this->_assignablerolesothers)) {
714 $this->_assignablerolesothers = array();
715 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
716 foreach ($this->_assignableroles as $roleid=>$role) {
717 if (isset($courseviewroles[$roleid])) {
718 $this->_assignablerolesothers[$roleid] = $role;
722 return $this->_assignablerolesothers;
723 } else {
724 return $this->_assignableroles;
729 * Gets all of the assignable roles for this course, wrapped in an array to ensure
730 * role sort order is not lost during json deserialisation.
732 * @param boolean $otherusers whether to include the assignable roles for other users
733 * @return array
735 public function get_assignable_roles_for_json($otherusers = false) {
736 $rolesarray = array();
737 $assignable = $this->get_assignable_roles($otherusers);
738 foreach ($assignable as $id => $role) {
739 $rolesarray[] = array('id' => $id, 'name' => $role);
741 return $rolesarray;
745 * Gets all of the groups for this course.
747 * @return array
749 public function get_all_groups() {
750 if ($this->_groups === null) {
751 $this->_groups = groups_get_all_groups($this->course->id);
752 foreach ($this->_groups as $gid=>$group) {
753 $this->_groups[$gid]->name = format_string($group->name);
756 return $this->_groups;
760 * Unenrols a user from the course given the users ue entry
762 * @global moodle_database $DB
763 * @param stdClass $ue
764 * @return bool
766 public function unenrol_user($ue) {
767 global $DB;
768 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
769 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
770 $plugin->unenrol_user($instance, $ue->userid);
771 return true;
773 return false;
777 * Given a user enrolment record this method returns the plugin and enrolment
778 * instance that relate to it.
780 * @param stdClass|int $userenrolment
781 * @return array array($instance, $plugin)
783 public function get_user_enrolment_components($userenrolment) {
784 global $DB;
785 if (is_numeric($userenrolment)) {
786 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
788 $instances = $this->get_enrolment_instances();
789 $plugins = $this->get_enrolment_plugins(false);
790 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
791 return array(false, false);
793 $instance = $instances[$userenrolment->enrolid];
794 $plugin = $plugins[$instance->enrol];
795 return array($instance, $plugin);
799 * Removes an assigned role from a user.
801 * @global moodle_database $DB
802 * @param int $userid
803 * @param int $roleid
804 * @return bool
806 public function unassign_role_from_user($userid, $roleid) {
807 global $DB;
808 // Admins may unassign any role, others only those they could assign.
809 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
810 if (defined('AJAX_SCRIPT')) {
811 throw new moodle_exception('invalidrole');
813 return false;
815 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
816 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
817 foreach ($ras as $ra) {
818 if ($ra->component) {
819 if (strpos($ra->component, 'enrol_') !== 0) {
820 continue;
822 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
823 continue;
825 if ($plugin->roles_protected()) {
826 continue;
829 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
831 return true;
835 * Assigns a role to a user.
837 * @param int $roleid
838 * @param int $userid
839 * @return int|false
841 public function assign_role_to_user($roleid, $userid) {
842 require_capability('moodle/role:assign', $this->context);
843 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
844 if (defined('AJAX_SCRIPT')) {
845 throw new moodle_exception('invalidrole');
847 return false;
849 return role_assign($roleid, $userid, $this->context->id, '', NULL);
853 * Adds a user to a group
855 * @param stdClass $user
856 * @param int $groupid
857 * @return bool
859 public function add_user_to_group($user, $groupid) {
860 require_capability('moodle/course:managegroups', $this->context);
861 $group = $this->get_group($groupid);
862 if (!$group) {
863 return false;
865 return groups_add_member($group->id, $user->id);
869 * Removes a user from a group
871 * @global moodle_database $DB
872 * @param StdClass $user
873 * @param int $groupid
874 * @return bool
876 public function remove_user_from_group($user, $groupid) {
877 global $DB;
878 require_capability('moodle/course:managegroups', $this->context);
879 $group = $this->get_group($groupid);
880 if (!groups_remove_member_allowed($group, $user)) {
881 return false;
883 if (!$group) {
884 return false;
886 return groups_remove_member($group, $user);
890 * Gets the requested group
892 * @param int $groupid
893 * @return stdClass|int
895 public function get_group($groupid) {
896 $groups = $this->get_all_groups();
897 if (!array_key_exists($groupid, $groups)) {
898 return false;
900 return $groups[$groupid];
904 * Edits an enrolment
906 * @param stdClass $userenrolment
907 * @param stdClass $data
908 * @return bool
910 public function edit_enrolment($userenrolment, $data) {
911 //Only allow editing if the user has the appropriate capability
912 //Already checked in /user/index.php but checking again in case this function is called from elsewhere
913 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
914 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
915 if (!isset($data->status)) {
916 $data->status = $userenrolment->status;
918 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
919 return true;
921 return false;
925 * Returns the current enrolment filter that is being applied by this class
926 * @return string
928 public function get_enrolment_filter() {
929 return $this->instancefilter;
933 * Gets the roles assigned to this user that are applicable for this course.
935 * @param int $userid
936 * @return array
938 public function get_user_roles($userid) {
939 $roles = array();
940 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
941 $plugins = $this->get_enrolment_plugins(false);
942 foreach ($ras as $ra) {
943 if ($ra->contextid != $this->context->id) {
944 if (!array_key_exists($ra->roleid, $roles)) {
945 $roles[$ra->roleid] = null;
947 // higher ras, course always takes precedence
948 continue;
950 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
951 continue;
953 $changeable = true;
954 if ($ra->component) {
955 $changeable = false;
956 if (strpos($ra->component, 'enrol_') === 0) {
957 $plugin = substr($ra->component, 6);
958 if (isset($plugins[$plugin])) {
959 $changeable = !$plugins[$plugin]->roles_protected();
964 $roles[$ra->roleid] = $changeable;
966 return $roles;
970 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
972 * @global moodle_database $DB
973 * @param int $userid
974 * @return array
976 public function get_user_enrolments($userid) {
977 global $DB;
978 list($instancessql, $params, $filter) = $this->get_instance_sql();
979 $params['userid'] = $userid;
980 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
981 $instances = $this->get_enrolment_instances();
982 $plugins = $this->get_enrolment_plugins(false);
983 $inames = $this->get_enrolment_instance_names();
984 foreach ($userenrolments as &$ue) {
985 $ue->enrolmentinstance = $instances[$ue->enrolid];
986 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
987 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
989 return $userenrolments;
993 * Gets the groups this user belongs to
995 * @param int $userid
996 * @return array
998 public function get_user_groups($userid) {
999 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
1003 * Retursn an array of params that would go into the URL to return to this
1004 * exact page.
1006 * @return array
1008 public function get_url_params() {
1009 $args = array(
1010 'id' => $this->course->id
1012 if (!empty($this->instancefilter)) {
1013 $args['ifilter'] = $this->instancefilter;
1015 if (!empty($this->rolefilter)) {
1016 $args['role'] = $this->rolefilter;
1018 if ($this->searchfilter !== '') {
1019 $args['search'] = $this->searchfilter;
1021 if (!empty($this->groupfilter)) {
1022 $args['filtergroup'] = $this->groupfilter;
1024 if ($this->statusfilter !== -1) {
1025 $args['status'] = $this->statusfilter;
1027 return $args;
1031 * Returns the course this object is managing enrolments for
1033 * @return stdClass
1035 public function get_course() {
1036 return $this->course;
1040 * Returns the course context
1042 * @return context
1044 public function get_context() {
1045 return $this->context;
1049 * Gets an array of other users in this course ready for display.
1051 * Other users are users who have been assigned or inherited roles within this
1052 * course but have not been enrolled.
1054 * @param core_enrol_renderer $renderer
1055 * @param moodle_url $pageurl
1056 * @param string $sort
1057 * @param string $direction ASC | DESC
1058 * @param int $page Starting from 0
1059 * @param int $perpage
1060 * @return array
1062 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
1064 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
1065 $roles = $this->get_all_roles();
1066 $plugins = $this->get_enrolment_plugins(false);
1068 $context = $this->get_context();
1069 $now = time();
1070 // TODO Does not support custom user profile fields (MDL-70456).
1071 $extrafields = fields::get_identity_fields($context, false);
1073 $users = array();
1074 foreach ($userroles as $userrole) {
1075 $contextid = $userrole->contextid;
1076 unset($userrole->contextid); // This would collide with user avatar.
1077 if (!array_key_exists($userrole->id, $users)) {
1078 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
1080 $a = new stdClass;
1081 $a->role = $roles[$userrole->roleid]->localname;
1082 if ($contextid == $this->context->id) {
1083 $changeable = true;
1084 if ($userrole->component) {
1085 $changeable = false;
1086 if (strpos($userrole->component, 'enrol_') === 0) {
1087 $plugin = substr($userrole->component, 6);
1088 if (isset($plugins[$plugin])) {
1089 $changeable = !$plugins[$plugin]->roles_protected();
1093 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
1094 } else {
1095 $changeable = false;
1096 switch ($userrole->contextlevel) {
1097 case CONTEXT_COURSE :
1098 // Meta course
1099 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
1100 break;
1101 case CONTEXT_COURSECAT :
1102 $roletext = get_string('rolefromcategory', 'enrol', $a);
1103 break;
1104 case CONTEXT_SYSTEM:
1105 default:
1106 $roletext = get_string('rolefromsystem', 'enrol', $a);
1107 break;
1110 if (!isset($users[$userrole->id]['roles'])) {
1111 $users[$userrole->id]['roles'] = array();
1113 $users[$userrole->id]['roles'][$userrole->roleid] = array(
1114 'text' => $roletext,
1115 'unchangeable' => !$changeable
1118 return $users;
1122 * Gets an array of users for display, this includes minimal user information
1123 * as well as minimal information on the users roles, groups, and enrolments.
1125 * @param core_enrol_renderer $renderer
1126 * @param moodle_url $pageurl
1127 * @param int $sort
1128 * @param string $direction ASC or DESC
1129 * @param int $page
1130 * @param int $perpage
1131 * @return array
1133 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1134 $pageurl = $manager->get_moodlepage()->url;
1135 $users = $this->get_users($sort, $direction, $page, $perpage);
1137 $now = time();
1138 $straddgroup = get_string('addgroup', 'group');
1139 $strunenrol = get_string('unenrol', 'enrol');
1140 $stredit = get_string('edit');
1142 $visibleroles = $this->get_viewable_roles();
1143 $assignable = $this->get_assignable_roles();
1144 $allgroups = $this->get_all_groups();
1145 $context = $this->get_context();
1146 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1148 $url = new moodle_url($pageurl, $this->get_url_params());
1149 // TODO Does not support custom user profile fields (MDL-70456).
1150 $extrafields = fields::get_identity_fields($context, false);
1152 $enabledplugins = $this->get_enrolment_plugins(true);
1154 $userdetails = array();
1155 foreach ($users as $user) {
1156 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1158 // Roles
1159 $details['roles'] = array();
1160 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1161 $unchangeable = !$rassignable;
1162 if (!is_siteadmin() and !isset($assignable[$rid])) {
1163 $unchangeable = true;
1166 if (isset($visibleroles[$rid])) {
1167 $label = $visibleroles[$rid];
1168 } else {
1169 $label = get_string('novisibleroles', 'role');
1170 $unchangeable = true;
1173 $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable);
1176 // Users
1177 $usergroups = $this->get_user_groups($user->id);
1178 $details['groups'] = array();
1179 foreach($usergroups as $gid=>$unused) {
1180 $details['groups'][$gid] = $allgroups[$gid]->name;
1183 // Enrolments
1184 $details['enrolments'] = array();
1185 foreach ($this->get_user_enrolments($user->id) as $ue) {
1186 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1187 $details['enrolments'][$ue->id] = array(
1188 'text' => $ue->enrolmentinstancename,
1189 'period' => null,
1190 'dimmed' => true,
1191 'actions' => array()
1193 continue;
1194 } else if ($ue->timestart and $ue->timeend) {
1195 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1196 $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1197 } else if ($ue->timestart) {
1198 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1199 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1200 } else if ($ue->timeend) {
1201 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1202 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1203 } else {
1204 // If there is no start or end show when user was enrolled.
1205 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1206 $periodoutside = false;
1208 $details['enrolments'][$ue->id] = array(
1209 'text' => $ue->enrolmentinstancename,
1210 'period' => $period,
1211 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1212 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1215 $userdetails[$user->id] = $details;
1217 return $userdetails;
1221 * Prepare a user record for display
1223 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1224 * prepare user fields for display
1226 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1228 * @param object $user The user record
1229 * @param array $extrafields The list of fields as returned from \core_user\fields::get_identity_fields used to determine which
1230 * additional fields may be displayed
1231 * @param int $now The time used for lastaccess calculation
1232 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1233 * additional fields from $extrafields
1235 private function prepare_user_for_display($user, $extrafields, $now) {
1236 $details = array(
1237 'userid' => $user->id,
1238 'courseid' => $this->get_course()->id,
1239 'picture' => new user_picture($user),
1240 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1241 'lastaccess' => get_string('never'),
1242 'lastcourseaccess' => get_string('never'),
1245 foreach ($extrafields as $field) {
1246 $details[$field] = s($user->{$field});
1249 // Last time user has accessed the site.
1250 if (!empty($user->lastaccess)) {
1251 $details['lastaccess'] = format_time($now - $user->lastaccess);
1254 // Last time user has accessed the course.
1255 if (!empty($user->lastcourseaccess)) {
1256 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess);
1258 return $details;
1261 public function get_manual_enrol_buttons() {
1262 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1263 $buttons = array();
1264 foreach ($plugins as $plugin) {
1265 $newbutton = $plugin->get_manual_enrol_button($this);
1266 if (is_array($newbutton)) {
1267 $buttons += $newbutton;
1268 } else if ($newbutton instanceof enrol_user_button) {
1269 $buttons[] = $newbutton;
1272 return $buttons;
1275 public function has_instance($enrolpluginname) {
1276 // Make sure manual enrolments instance exists
1277 foreach ($this->get_enrolment_instances() as $instance) {
1278 if ($instance->enrol == $enrolpluginname) {
1279 return true;
1282 return false;
1286 * Returns the enrolment plugin that the course manager was being filtered to.
1288 * If no filter was being applied then this function returns false.
1290 * @return enrol_plugin
1292 public function get_filtered_enrolment_plugin() {
1293 $instances = $this->get_enrolment_instances();
1294 $plugins = $this->get_enrolment_plugins(false);
1296 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1297 return false;
1300 $instance = $instances[$this->instancefilter];
1301 return $plugins[$instance->enrol];
1305 * Returns and array of users + enrolment details.
1307 * Given an array of user id's this function returns and array of user enrolments for those users
1308 * as well as enough user information to display the users name and picture for each enrolment.
1310 * @global moodle_database $DB
1311 * @param array $userids
1312 * @return array
1314 public function get_users_enrolments(array $userids) {
1315 global $DB;
1317 $instances = $this->get_enrolment_instances();
1318 $plugins = $this->get_enrolment_plugins(false);
1320 if (!empty($this->instancefilter)) {
1321 $instancesql = ' = :instanceid';
1322 $instanceparams = array('instanceid' => $this->instancefilter);
1323 } else {
1324 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1327 $userfieldsapi = \core_user\fields::for_userpic();
1328 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1329 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1331 list($sort, $sortparams) = users_order_by_sql('u');
1333 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1334 FROM {user_enrolments} ue
1335 LEFT JOIN {user} u ON u.id = ue.userid
1336 WHERE ue.enrolid $instancesql AND
1337 u.id $idsql
1338 ORDER BY $sort";
1340 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1341 $users = array();
1342 foreach ($rs as $ue) {
1343 $user = user_picture::unalias($ue);
1344 $ue->id = $ue->ueid;
1345 unset($ue->ueid);
1346 if (!array_key_exists($user->id, $users)) {
1347 $user->enrolments = array();
1348 $users[$user->id] = $user;
1350 $ue->enrolmentinstance = $instances[$ue->enrolid];
1351 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1352 $users[$user->id]->enrolments[$ue->id] = $ue;
1354 $rs->close();
1355 return $users;
1360 * A button that is used to enrol users in a course
1362 * @copyright 2010 Sam Hemelryk
1363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1365 class enrol_user_button extends single_button {
1368 * An array containing JS YUI modules required by this button
1369 * @var array
1371 protected $jsyuimodules = array();
1374 * An array containing JS initialisation calls required by this button
1375 * @var array
1377 protected $jsinitcalls = array();
1380 * An array strings required by JS for this button
1381 * @var array
1383 protected $jsstrings = array();
1386 * Initialises the new enrol_user_button
1388 * @staticvar int $count The number of enrol user buttons already created
1389 * @param moodle_url $url
1390 * @param string $label The text to display in the button
1391 * @param string $method Either post or get
1393 public function __construct(moodle_url $url, $label, $method = 'post') {
1394 static $count = 0;
1395 $count ++;
1396 parent::__construct($url, $label, $method);
1397 $this->class = 'singlebutton enrolusersbutton';
1398 $this->formid = 'enrolusersbutton-'.$count;
1402 * Adds a YUI module call that will be added to the page when the button is used.
1404 * @param string|array $modules One or more modules to require
1405 * @param string $function The JS function to call
1406 * @param array $arguments An array of arguments to pass to the function
1407 * @param string $galleryversion Deprecated: The gallery version to use
1408 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1410 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1411 if ($galleryversion != null) {
1412 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1415 $js = new stdClass;
1416 $js->modules = (array)$modules;
1417 $js->function = $function;
1418 $js->arguments = $arguments;
1419 $js->ondomready = $ondomready;
1420 $this->jsyuimodules[] = $js;
1424 * Adds a JS initialisation call to the page when the button is used.
1426 * @param string $function The function to call
1427 * @param array $extraarguments An array of arguments to pass to the function
1428 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1429 * @param array $module A module definition
1431 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1432 $js = new stdClass;
1433 $js->function = $function;
1434 $js->extraarguments = $extraarguments;
1435 $js->ondomready = $ondomready;
1436 $js->module = $module;
1437 $this->jsinitcalls[] = $js;
1441 * Requires strings for JS that will be loaded when the button is used.
1443 * @param type $identifiers
1444 * @param string $component
1445 * @param mixed $a
1447 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1448 $string = new stdClass;
1449 $string->identifiers = (array)$identifiers;
1450 $string->component = $component;
1451 $string->a = $a;
1452 $this->jsstrings[] = $string;
1456 * Initialises the JS that is required by this button
1458 * @param moodle_page $page
1460 public function initialise_js(moodle_page $page) {
1461 foreach ($this->jsyuimodules as $js) {
1462 $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1464 foreach ($this->jsinitcalls as $js) {
1465 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1467 foreach ($this->jsstrings as $string) {
1468 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1474 * User enrolment action
1476 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1477 * a user enrolment.
1479 * @copyright 2011 Sam Hemelryk
1480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1482 class user_enrolment_action implements renderable {
1485 * The icon to display for the action
1486 * @var pix_icon
1488 protected $icon;
1491 * The title for the action
1492 * @var string
1494 protected $title;
1497 * The URL to the action
1498 * @var moodle_url
1500 protected $url;
1503 * An array of HTML attributes
1504 * @var array
1506 protected $attributes = array();
1509 * Constructor
1510 * @param pix_icon $icon
1511 * @param string $title
1512 * @param moodle_url $url
1513 * @param array $attributes
1515 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1516 $this->icon = $icon;
1517 $this->title = $title;
1518 $this->url = new moodle_url($url);
1519 if (!empty($attributes)) {
1520 $this->attributes = $attributes;
1522 $this->attributes['title'] = $title;
1526 * Returns the icon for this action
1527 * @return pix_icon
1529 public function get_icon() {
1530 return $this->icon;
1534 * Returns the title for this action
1535 * @return string
1537 public function get_title() {
1538 return $this->title;
1542 * Returns the URL for this action
1543 * @return moodle_url
1545 public function get_url() {
1546 return $this->url;
1550 * Returns the attributes to use for this action
1551 * @return array
1553 public function get_attributes() {
1554 return $this->attributes;
1558 class enrol_ajax_exception extends moodle_exception {
1560 * Constructor
1561 * @param string $errorcode The name of the string from error.php to print
1562 * @param string $module name of module
1563 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1564 * @param object $a Extra words and phrases that might be required in the error string
1565 * @param string $debuginfo optional debugging information
1567 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1568 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1573 * This class is used to manage a bulk operations for enrolment plugins.
1575 * @copyright 2011 Sam Hemelryk
1576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1578 abstract class enrol_bulk_enrolment_operation {
1581 * The course enrolment manager
1582 * @var course_enrolment_manager
1584 protected $manager;
1587 * The enrolment plugin to which this operation belongs
1588 * @var enrol_plugin
1590 protected $plugin;
1593 * Contructor
1594 * @param course_enrolment_manager $manager
1595 * @param stdClass $plugin
1597 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1598 $this->manager = $manager;
1599 $this->plugin = $plugin;
1603 * Returns a moodleform used for this operation, or false if no form is required and the action
1604 * should be immediatly processed.
1606 * @param moodle_url|string $defaultaction
1607 * @param mixed $defaultcustomdata
1608 * @return enrol_bulk_enrolment_change_form|moodleform|false
1610 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1611 return false;
1615 * Returns the title to use for this bulk operation
1617 * @return string
1619 abstract public function get_title();
1622 * Returns the identifier for this bulk operation.
1623 * This should be the same identifier used by the plugins function when returning
1624 * all of its bulk operations.
1626 * @return string
1628 abstract public function get_identifier();
1631 * Processes the bulk operation on the given users
1633 * @param course_enrolment_manager $manager
1634 * @param array $users
1635 * @param stdClass $properties
1637 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);