MDL-33468 css_optimiser: Improved consolidation of background styles and fixed orderi...
[moodle.git] / admin / roles / lib.php
blobd57233ff1a2243ddc35eb401ad20706c31229b7a
1 <?php
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.
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/>.
18 /**
19 * Library code used by the roles administration interfaces.
21 * Responds to actions:
22 * add - add a new role
23 * duplicate - like add, only initialise the new role by using an existing one.
24 * edit - edit the definition of a role
25 * view - view the definition of a role
27 * @package core
28 * @subpackage role
29 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 require_once($CFG->libdir.'/adminlib.php');
34 require_once($CFG->dirroot.'/user/selector/lib.php');
36 // Classes for producing tables with one row per capability ====================
38 /**
39 * This class represents a table with one row for each of a list of capabilities
40 * where the first cell in the row contains the capability name, and there is
41 * arbitrary stuff in the rest of the row. This class is used by
42 * admin/roles/manage.php, override.php and check.php.
44 * An ajaxy search UI shown at the top, if JavaScript is on.
46 abstract class capability_table_base {
47 /** The context this table relates to. */
48 protected $context;
50 /** The capabilities to display. Initialised as fetch_context_capabilities($context). */
51 protected $capabilities = array();
53 /** Added as an id="" attribute to the table on output. */
54 protected $id;
56 /** Added to the class="" attribute on output. */
57 protected $classes = array('rolecap');
59 /** Default number of capabilities in the table for the search UI to be shown. */
60 const NUM_CAPS_FOR_SEARCH = 12;
62 /**
63 * Constructor
64 * @param object $context the context this table relates to.
65 * @param string $id what to put in the id="" attribute.
67 public function __construct($context, $id) {
68 $this->context = $context;
69 $this->capabilities = fetch_context_capabilities($context);
70 $this->id = $id;
73 /**
74 * Use this to add class="" attributes to the table. You get the rolecap by
75 * default.
76 * @param array $classnames of class names.
78 public function add_classes($classnames) {
79 $this->classes = array_unique(array_merge($this->classes, $classnames));
82 /**
83 * Display the table.
85 public function display() {
86 if (count($this->capabilities) > capability_table_base::NUM_CAPS_FOR_SEARCH) {
87 global $PAGE;
88 $PAGE->requires->strings_for_js(array('filter','clear'),'moodle');
89 $PAGE->requires->js_init_call('M.core_role.init_cap_table_filter', array($this->id, $this->context->id));
91 echo '<table class="' . implode(' ', $this->classes) . '" id="' . $this->id . '">' . "\n<thead>\n";
92 echo '<tr><th class="name" align="left" scope="col">' . get_string('capability','role') . '</th>';
93 $this->add_header_cells();
94 echo "</tr>\n</thead>\n<tbody>\n";
96 /// Loop over capabilities.
97 $contextlevel = 0;
98 $component = '';
99 foreach ($this->capabilities as $capability) {
100 if ($this->skip_row($capability)) {
101 continue;
104 /// Prints a breaker if component or name or context level has changed
105 if (component_level_changed($capability, $component, $contextlevel)) {
106 $this->print_heading_row($capability);
108 $contextlevel = $capability->contextlevel;
109 $component = $capability->component;
111 /// Start the row.
112 echo '<tr class="' . implode(' ', array_unique(array_merge(array('rolecap'),
113 $this->get_row_classes($capability)))) . '">';
115 /// Table cell for the capability name.
116 echo '<th scope="row" class="name"><span class="cap-desc">' . get_capability_docs_link($capability) .
117 '<span class="cap-name">' . $capability->name . '</span></span></th>';
119 /// Add the cells specific to this table.
120 $this->add_row_cells($capability);
122 /// End the row.
123 echo "</tr>\n";
126 /// End of the table.
127 echo "</tbody>\n</table>\n";
131 * Used to output a heading rows when the context level or component changes.
132 * @param object $capability gives the new component and contextlevel.
134 protected function print_heading_row($capability) {
135 echo '<tr class="rolecapheading header"><td colspan="' . (1 + $this->num_extra_columns()) . '" class="header"><strong>' .
136 get_component_string($capability->component, $capability->contextlevel) .
137 '</strong></td></tr>';
141 /** For subclasses to override, output header cells, after the initial capability one. */
142 protected abstract function add_header_cells();
144 /** For subclasses to override, return the number of cells that add_header_cells/add_row_cells output. */
145 protected abstract function num_extra_columns();
148 * For subclasses to override. Allows certain capabilties
149 * to be left out of the table.
151 * @param object $capability the capability this row relates to.
152 * @return boolean. If true, this row is omitted from the table.
154 protected function skip_row($capability) {
155 return false;
159 * For subclasses to override. A change to reaturn class names that are added
160 * to the class="" attribute on the &lt;tr> for this capability.
162 * @param object $capability the capability this row relates to.
163 * @return array of class name strings.
165 protected function get_row_classes($capability) {
166 return array();
170 * For subclasses to override. Output the data cells for this capability. The
171 * capability name cell will already have been output.
173 * You can rely on get_row_classes always being called before add_row_cells.
175 * @param object $capability the capability this row relates to.
177 protected abstract function add_row_cells($capability);
181 * Subclass of capability_table_base for use on the Check permissions page.
183 * We have one additional column, Allowed, which contains yes/no.
185 class check_capability_table extends capability_table_base {
186 protected $user;
187 protected $fullname;
188 protected $contextname;
189 protected $stryes;
190 protected $strno;
191 private $hascap;
194 * Constructor
195 * @param object $context the context this table relates to.
196 * @param object $user the user we are generating the results for.
197 * @param string $contextname print_context_name($context) - to save recomputing.
199 public function __construct($context, $user, $contextname) {
200 global $CFG;
201 parent::__construct($context, 'explaincaps');
202 $this->user = $user;
203 $this->fullname = fullname($user);
204 $this->contextname = $contextname;
205 $this->stryes = get_string('yes');
206 $this->strno = get_string('no');
209 protected function add_header_cells() {
210 echo '<th>' . get_string('allowed', 'role') . '</th>';
213 protected function num_extra_columns() {
214 return 1;
217 protected function get_row_classes($capability) {
218 $this->hascap = has_capability($capability->name, $this->context, $this->user->id);
219 if ($this->hascap) {
220 return array('yes');
221 } else {
222 return array('no');
226 protected function add_row_cells($capability) {
227 global $OUTPUT;
228 if ($this->hascap) {
229 $result = $this->stryes;
230 } else {
231 $result = $this->strno;
233 $a = new stdClass;
234 $a->fullname = $this->fullname;
235 $a->capability = $capability->name;
236 $a->context = $this->contextname;
237 echo '<td>' . $result . '</td>';
243 * Subclass of capability_table_base for use on the Permissions page.
245 class permissions_table extends capability_table_base {
246 protected $contextname;
247 protected $allowoverrides;
248 protected $allowsafeoverrides;
249 protected $overridableroles;
250 protected $roles;
251 protected $icons = array();
254 * Constructor
255 * @param object $context the context this table relates to.
256 * @param string $contextname print_context_name($context) - to save recomputing.
258 public function __construct($context, $contextname, $allowoverrides, $allowsafeoverrides, $overridableroles) {
259 global $DB;
261 parent::__construct($context, 'permissions');
262 $this->contextname = $contextname;
263 $this->allowoverrides = $allowoverrides;
264 $this->allowsafeoverrides = $allowsafeoverrides;
265 $this->overridableroles = $overridableroles;
267 $roles = $DB->get_records('role', null, 'sortorder DESC');
268 foreach ($roles as $roleid=>$role) {
269 $roles[$roleid] = $role->name;
271 $this->roles = role_fix_names($roles, $context);
275 protected function add_header_cells() {
276 echo '<th>' . get_string('risks', 'role') . '</th>';
277 echo '<th>' . get_string('neededroles', 'role') . '</th>';
278 echo '<th>' . get_string('prohibitedroles', 'role') . '</th>';
281 protected function num_extra_columns() {
282 return 3;
285 protected function add_row_cells($capability) {
286 global $OUTPUT, $PAGE;
288 $context = $this->context;
289 $contextid = $this->context->id;
290 $allowoverrides = $this->allowoverrides;
291 $allowsafeoverrides = $this->allowsafeoverrides;
292 $overridableroles = $this->overridableroles;
293 $roles = $this->roles;
296 list($needed, $forbidden) = get_roles_with_cap_in_context($context, $capability->name);
297 $neededroles = array();
298 $forbiddenroles = array();
299 $allowable = $overridableroles;
300 $forbitable = $overridableroles;
301 foreach ($neededroles as $id=>$unused) {
302 unset($allowable[$id]);
304 foreach ($forbidden as $id=>$unused) {
305 unset($allowable[$id]);
306 unset($forbitable[$id]);
309 foreach ($roles as $id=>$name) {
310 if (isset($needed[$id])) {
311 $neededroles[$id] = $roles[$id];
312 if (isset($overridableroles[$id]) and ($allowoverrides or ($allowsafeoverrides and is_safe_capability($capability)))) {
313 $preventurl = new moodle_url($PAGE->url, array('contextid'=>$contextid, 'roleid'=>$id, 'capability'=>$capability->name, 'prevent'=>1));
314 $neededroles[$id] .= $OUTPUT->action_icon($preventurl, new pix_icon('t/delete', get_string('prevent', 'role')));
318 $neededroles = implode(', ', $neededroles);
319 foreach ($roles as $id=>$name) {
320 if (isset($forbidden[$id]) and ($allowoverrides or ($allowsafeoverrides and is_safe_capability($capability)))) {
321 $forbiddenroles[$id] = $roles[$id];
322 if (isset($overridableroles[$id]) and prohibit_is_removable($id, $context, $capability->name)) {
323 $unprohibiturl = new moodle_url($PAGE->url, array('contextid'=>$contextid, 'roleid'=>$id, 'capability'=>$capability->name, 'unprohibit'=>1));
324 $forbiddenroles[$id] .= $OUTPUT->action_icon($unprohibiturl, new pix_icon('t/delete', get_string('delete')));
328 $forbiddenroles = implode(', ', $forbiddenroles);
330 if ($allowable and ($allowoverrides or ($allowsafeoverrides and is_safe_capability($capability)))) {
331 $allowurl = new moodle_url($PAGE->url, array('contextid'=>$contextid, 'capability'=>$capability->name, 'allow'=>1));
332 $neededroles .= '<div class="allowmore">'.$OUTPUT->action_icon($allowurl, new pix_icon('t/add', get_string('allow', 'role'))).'</div>';
335 if ($forbitable and ($allowoverrides or ($allowsafeoverrides and is_safe_capability($capability)))) {
336 $prohibiturl = new moodle_url($PAGE->url, array('contextid'=>$contextid, 'capability'=>$capability->name, 'prohibit'=>1));
337 $forbiddenroles .= '<div class="prohibitmore">'.$OUTPUT->action_icon($prohibiturl, new pix_icon('t/add', get_string('prohibit', 'role'))).'</div>';
340 $risks = $this->get_risks($capability);
342 echo '<td>' . $risks . '</td>';
343 echo '<td>' . $neededroles . '</td>';
344 echo '<td>' . $forbiddenroles . '</td>';
347 protected function get_risks($capability) {
348 global $OUTPUT;
350 $allrisks = get_all_risks();
351 $risksurl = new moodle_url(get_docs_url(s(get_string('risks', 'role'))));
353 $return = '';
355 foreach ($allrisks as $type=>$risk) {
356 if ($risk & (int)$capability->riskbitmask) {
357 if (!isset($this->icons[$type])) {
358 $pixicon = new pix_icon('/i/' . str_replace('risk', 'risk_', $type), get_string($type . 'short', 'admin'));
359 $this->icons[$type] = $OUTPUT->action_icon($risksurl, $pixicon, new popup_action('click', $risksurl));
361 $return .= $this->icons[$type];
365 return $return;
371 * This subclass is the bases for both the define roles and override roles
372 * pages. As well as adding the risks columns, this also provides generic
373 * facilities for showing a certain number of permissions columns, and
374 * recording the current and submitted permissions for each capability.
376 abstract class capability_table_with_risks extends capability_table_base {
377 protected $allrisks;
378 protected $allpermissions; // We don't need perms ourselves, but all our subclasses do.
379 protected $strperms; // Language string cache.
380 protected $risksurl; // URL in moodledocs about risks.
381 protected $riskicons = array(); // Cache to avoid regenerating the HTML for each risk icon.
382 /** The capabilities to highlight as default/inherited. */
383 protected $parentpermissions;
384 protected $displaypermissions;
385 protected $permissions;
386 protected $changed;
387 protected $roleid;
389 public function __construct($context, $id, $roleid) {
390 parent::__construct($context, $id);
392 $this->allrisks = get_all_risks();
393 $this->risksurl = get_docs_url(s(get_string('risks', 'role')));
395 $this->allpermissions = array(
396 CAP_INHERIT => 'inherit',
397 CAP_ALLOW => 'allow',
398 CAP_PREVENT => 'prevent' ,
399 CAP_PROHIBIT => 'prohibit',
402 $this->strperms = array();
403 foreach ($this->allpermissions as $permname) {
404 $this->strperms[$permname] = get_string($permname, 'role');
407 $this->roleid = $roleid;
408 $this->load_current_permissions();
410 /// Fill in any blank permissions with an explicit CAP_INHERIT, and init a locked field.
411 foreach ($this->capabilities as $capid => $cap) {
412 if (!isset($this->permissions[$cap->name])) {
413 $this->permissions[$cap->name] = CAP_INHERIT;
415 $this->capabilities[$capid]->locked = false;
419 protected function load_current_permissions() {
420 global $DB;
422 /// Load the overrides/definition in this context.
423 if ($this->roleid) {
424 $this->permissions = $DB->get_records_menu('role_capabilities', array('roleid' => $this->roleid,
425 'contextid' => $this->context->id), '', 'capability,permission');
426 } else {
427 $this->permissions = array();
431 protected abstract function load_parent_permissions();
434 * Update $this->permissions based on submitted data, while making a list of
435 * changed capabilities in $this->changed.
437 public function read_submitted_permissions() {
438 $this->changed = array();
440 foreach ($this->capabilities as $cap) {
441 if ($cap->locked || $this->skip_row($cap)) {
442 /// The user is not allowed to change the permission for this capability
443 continue;
446 $permission = optional_param($cap->name, null, PARAM_PERMISSION);
447 if (is_null($permission)) {
448 /// A permission was not specified in submitted data.
449 continue;
452 /// If the permission has changed, update $this->permissions and
453 /// Record the fact there is data to save.
454 if ($this->permissions[$cap->name] != $permission) {
455 $this->permissions[$cap->name] = $permission;
456 $this->changed[] = $cap->name;
462 * Save the new values of any permissions that have been changed.
464 public function save_changes() {
465 /// Set the permissions.
466 foreach ($this->changed as $changedcap) {
467 assign_capability($changedcap, $this->permissions[$changedcap],
468 $this->roleid, $this->context->id, true);
471 /// Force accessinfo refresh for users visiting this context.
472 mark_context_dirty($this->context->path);
475 public function display() {
476 $this->load_parent_permissions();
477 foreach ($this->capabilities as $cap) {
478 if (!isset($this->parentpermissions[$cap->name])) {
479 $this->parentpermissions[$cap->name] = CAP_INHERIT;
482 parent::display();
485 protected function add_header_cells() {
486 global $OUTPUT;
487 echo '<th colspan="' . count($this->displaypermissions) . '" scope="col">' .
488 get_string('permission', 'role') . ' ' . $OUTPUT->help_icon('permission', 'role') . '</th>';
489 echo '<th class="risk" colspan="' . count($this->allrisks) . '" scope="col">' . get_string('risks','role') . '</th>';
492 protected function num_extra_columns() {
493 return count($this->displaypermissions) + count($this->allrisks);
496 protected function get_row_classes($capability) {
497 $rowclasses = array();
498 foreach ($this->allrisks as $riskname => $risk) {
499 if ($risk & (int)$capability->riskbitmask) {
500 $rowclasses[] = $riskname;
503 return $rowclasses;
506 protected abstract function add_permission_cells($capability);
508 protected function add_row_cells($capability) {
509 $this->add_permission_cells($capability);
510 /// One cell for each possible risk.
511 foreach ($this->allrisks as $riskname => $risk) {
512 echo '<td class="risk ' . str_replace('risk', '', $riskname) . '">';
513 if ($risk & (int)$capability->riskbitmask) {
514 echo $this->get_risk_icon($riskname);
516 echo '</td>';
521 * Print a risk icon, as a link to the Risks page on Moodle Docs.
523 * @param string $type the type of risk, will be one of the keys from the
524 * get_all_risks array. Must start with 'risk'.
526 function get_risk_icon($type) {
527 global $OUTPUT;
528 if (!isset($this->riskicons[$type])) {
529 $iconurl = $OUTPUT->pix_url('i/' . str_replace('risk', 'risk_', $type));
530 $text = '<img src="' . $iconurl . '" alt="' . get_string($type . 'short', 'admin') . '" />';
531 $action = new popup_action('click', $this->risksurl, 'docspopup');
532 $this->riskicons[$type] = $OUTPUT->action_link($this->risksurl, $text, $action, array('title'=>get_string($type, 'admin')));
534 return $this->riskicons[$type];
539 * As well as tracking the permissions information about the role we are creating
540 * or editing, we also track the other information about the role. (This class is
541 * starting to be more and more like a formslib form in some respects.)
543 class define_role_table_advanced extends capability_table_with_risks {
544 /** Used to store other information (besides permissions) about the role we are creating/editing. */
545 protected $role;
546 /** Used to store errors found when validating the data. */
547 protected $errors;
548 protected $contextlevels;
549 protected $allcontextlevels;
550 protected $disabled = '';
552 public function __construct($context, $roleid) {
553 $this->roleid = $roleid;
554 parent::__construct($context, 'defineroletable', $roleid);
555 $this->displaypermissions = $this->allpermissions;
556 $this->strperms[$this->allpermissions[CAP_INHERIT]] = get_string('notset', 'role');
558 $this->allcontextlevels = array(
559 CONTEXT_SYSTEM => get_string('coresystem'),
560 CONTEXT_USER => get_string('user'),
561 CONTEXT_COURSECAT => get_string('category'),
562 CONTEXT_COURSE => get_string('course'),
563 CONTEXT_MODULE => get_string('activitymodule'),
564 CONTEXT_BLOCK => get_string('block')
568 protected function load_current_permissions() {
569 global $DB;
570 if ($this->roleid) {
571 if (!$this->role = $DB->get_record('role', array('id' => $this->roleid))) {
572 throw new moodle_exception('invalidroleid');
574 $contextlevels = get_role_contextlevels($this->roleid);
575 // Put the contextlevels in the array keys, as well as the values.
576 if (!empty($contextlevels)) {
577 $this->contextlevels = array_combine($contextlevels, $contextlevels);
578 } else {
579 $this->contextlevels = array();
581 } else {
582 $this->role = new stdClass;
583 $this->role->name = '';
584 $this->role->shortname = '';
585 $this->role->description = '';
586 $this->role->archetype = '';
587 $this->contextlevels = array();
589 parent::load_current_permissions();
592 public function read_submitted_permissions() {
593 global $DB;
594 $this->errors = array();
596 // Role name.
597 $name = optional_param('name', null, PARAM_MULTILANG);
598 if (!is_null($name)) {
599 $this->role->name = $name;
600 if (html_is_blank($this->role->name)) {
601 $this->errors['name'] = get_string('errorbadrolename', 'role');
604 if ($DB->record_exists_select('role', 'name = ? and id <> ?', array($this->role->name, $this->roleid))) {
605 $this->errors['name'] = get_string('errorexistsrolename', 'role');
608 // Role short name. We clean this in a special way. We want to end up
609 // with only lowercase safe ASCII characters.
610 $shortname = optional_param('shortname', null, PARAM_RAW);
611 if (!is_null($shortname)) {
612 $this->role->shortname = $shortname;
613 $this->role->shortname = textlib::specialtoascii($this->role->shortname);
614 $this->role->shortname = textlib::strtolower(clean_param($this->role->shortname, PARAM_ALPHANUMEXT));
615 if (empty($this->role->shortname)) {
616 $this->errors['shortname'] = get_string('errorbadroleshortname', 'role');
619 if ($DB->record_exists_select('role', 'shortname = ? and id <> ?', array($this->role->shortname, $this->roleid))) {
620 $this->errors['shortname'] = get_string('errorexistsroleshortname', 'role');
623 // Description.
624 $description = optional_param('description', null, PARAM_RAW);
625 if (!is_null($description)) {
626 $this->role->description = $description;
629 // Legacy type.
630 $archetype = optional_param('archetype', null, PARAM_RAW);
631 if (isset($archetype)) {
632 $archetypes = get_role_archetypes();
633 if (isset($archetypes[$archetype])){
634 $this->role->archetype = $archetype;
635 } else {
636 $this->role->archetype = '';
640 // Assignable context levels.
641 foreach ($this->allcontextlevels as $cl => $notused) {
642 $assignable = optional_param('contextlevel' . $cl, null, PARAM_BOOL);
643 if (!is_null($assignable)) {
644 if ($assignable) {
645 $this->contextlevels[$cl] = $cl;
646 } else {
647 unset($this->contextlevels[$cl]);
652 // Now read the permissions for each capability.
653 parent::read_submitted_permissions();
656 public function is_submission_valid() {
657 return empty($this->errors);
661 * Call this after the table has been initialised, so to indicate that
662 * when save is called, we want to make a duplicate role.
664 public function make_copy() {
665 $this->roleid = 0;
666 unset($this->role->id);
667 $this->role->name .= ' ' . get_string('copyasnoun');
668 $this->role->shortname .= 'copy';
671 public function get_role_name() {
672 return $this->role->name;
675 public function get_role_id() {
676 return $this->role->id;
679 public function get_archetype() {
680 return $this->role->archetype;
683 protected function load_parent_permissions() {
684 $this->parentpermissions = get_default_capabilities($this->role->archetype);
687 public function save_changes() {
688 global $DB;
690 if (!$this->roleid) {
691 // Creating role
692 $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $this->role->archetype);
693 $this->roleid = $this->role->id; // Needed to make the parent::save_changes(); call work.
694 } else {
695 // Updating role
696 $DB->update_record('role', $this->role);
699 // Assignable contexts.
700 set_role_contextlevels($this->role->id, $this->contextlevels);
702 // Permissions.
703 parent::save_changes();
706 protected function get_name_field($id) {
707 return '<input type="text" id="' . $id . '" name="' . $id . '" maxlength="254" value="' . s($this->role->name) . '" />';
710 protected function get_shortname_field($id) {
711 return '<input type="text" id="' . $id . '" name="' . $id . '" maxlength="254" value="' . s($this->role->shortname) . '" />';
714 protected function get_description_field($id) {
715 return print_textarea(true, 10, 50, 50, 10, 'description', $this->role->description, 0, true);
718 protected function get_archetype_field($id) {
719 $options = array();
720 $options[''] = get_string('none');
721 foreach(get_role_archetypes() as $type) {
722 $options[$type] = get_string('archetype'.$type, 'role');
724 return html_writer::select($options, 'archetype', $this->role->archetype, false);
727 protected function get_assignable_levels_control() {
728 $output = '';
729 foreach ($this->allcontextlevels as $cl => $clname) {
730 $extraarguments = $this->disabled;
731 if (in_array($cl, $this->contextlevels)) {
732 $extraarguments .= 'checked="checked" ';
734 if (!$this->disabled) {
735 $output .= '<input type="hidden" name="contextlevel' . $cl . '" value="0" />';
737 $output .= '<input type="checkbox" id="cl' . $cl . '" name="contextlevel' . $cl .
738 '" value="1" ' . $extraarguments . '/> ';
739 $output .= '<label for="cl' . $cl . '">' . $clname . "</label><br />\n";
741 return $output;
744 protected function print_field($name, $caption, $field) {
745 global $OUTPUT;
746 // Attempt to generate HTML like formslib.
747 echo '<div class="fitem">';
748 echo '<div class="fitemtitle">';
749 if ($name) {
750 echo '<label for="' . $name . '">';
752 echo $caption;
753 if ($name) {
754 echo "</label>\n";
756 echo '</div>';
757 if (isset($this->errors[$name])) {
758 $extraclass = ' error';
759 } else {
760 $extraclass = '';
762 echo '<div class="felement' . $extraclass . '">';
763 if (isset($this->errors[$name])) {
764 echo $OUTPUT->error_text($this->errors[$name]);
766 echo $field;
767 echo '</div>';
768 echo '</div>';
771 protected function print_show_hide_advanced_button() {
772 echo '<p class="definenotice">' . get_string('highlightedcellsshowdefault', 'role') . ' </p>';
773 echo '<div class="advancedbutton">';
774 echo '<input type="submit" name="toggleadvanced" value="' . get_string('hideadvanced', 'form') . '" />';
775 echo '</div>';
778 public function display() {
779 global $OUTPUT;
780 // Extra fields at the top of the page.
781 echo '<div class="topfields clearfix">';
782 $this->print_field('name', get_string('rolefullname', 'role'), $this->get_name_field('name'));
783 $this->print_field('shortname', get_string('roleshortname', 'role'), $this->get_shortname_field('shortname'));
784 $this->print_field('edit-description', get_string('description'), $this->get_description_field('description'));
785 $this->print_field('menuarchetype', get_string('archetype', 'role').'&nbsp;'.$OUTPUT->help_icon('archetype', 'role'), $this->get_archetype_field('archetype'));
786 $this->print_field('', get_string('maybeassignedin', 'role'), $this->get_assignable_levels_control());
787 echo "</div>";
789 $this->print_show_hide_advanced_button();
791 // Now the permissions table.
792 parent::display();
795 protected function add_permission_cells($capability) {
796 /// One cell for each possible permission.
797 foreach ($this->displaypermissions as $perm => $permname) {
798 $strperm = $this->strperms[$permname];
799 $extraclass = '';
800 if ($perm == $this->parentpermissions[$capability->name]) {
801 $extraclass = ' capdefault';
803 $checked = '';
804 if ($this->permissions[$capability->name] == $perm) {
805 $checked = 'checked="checked" ';
807 echo '<td class="' . $permname . $extraclass . '">';
808 echo '<label><input type="radio" name="' . $capability->name .
809 '" value="' . $perm . '" ' . $checked . '/> ';
810 echo '<span class="note">' . $strperm . '</span>';
811 echo '</label></td>';
816 class define_role_table_basic extends define_role_table_advanced {
817 protected $stradvmessage;
818 protected $strallow;
820 public function __construct($context, $roleid) {
821 parent::__construct($context, $roleid);
822 $this->displaypermissions = array(CAP_ALLOW => $this->allpermissions[CAP_ALLOW]);
823 $this->stradvmessage = get_string('useshowadvancedtochange', 'role');
824 $this->strallow = $this->strperms[$this->allpermissions[CAP_ALLOW]];
827 protected function print_show_hide_advanced_button() {
828 echo '<div class="advancedbutton">';
829 echo '<input type="submit" name="toggleadvanced" value="' . get_string('showadvanced', 'form') . '" />';
830 echo '</div>';
833 protected function add_permission_cells($capability) {
834 $perm = $this->permissions[$capability->name];
835 $permname = $this->allpermissions[$perm];
836 $defaultperm = $this->allpermissions[$this->parentpermissions[$capability->name]];
837 echo '<td class="' . $permname . '">';
838 if ($perm == CAP_ALLOW || $perm == CAP_INHERIT) {
839 $checked = '';
840 if ($perm == CAP_ALLOW) {
841 $checked = 'checked="checked" ';
843 echo '<input type="hidden" name="' . $capability->name . '" value="' . CAP_INHERIT . '" />';
844 echo '<label><input type="checkbox" name="' . $capability->name .
845 '" value="' . CAP_ALLOW . '" ' . $checked . '/> ' . $this->strallow . '</label>';
846 } else {
847 echo '<input type="hidden" name="' . $capability->name . '" value="' . $perm . '" />';
848 echo $this->strperms[$permname] . '<span class="note">' . $this->stradvmessage . '</span>';
850 echo '</td>';
853 class view_role_definition_table extends define_role_table_advanced {
854 public function __construct($context, $roleid) {
855 parent::__construct($context, $roleid);
856 $this->displaypermissions = array(CAP_ALLOW => $this->allpermissions[CAP_ALLOW]);
857 $this->disabled = 'disabled="disabled" ';
860 public function save_changes() {
861 throw new moodle_exception('invalidaccess');
864 protected function get_name_field($id) {
865 return strip_tags(format_string($this->role->name));
868 protected function get_shortname_field($id) {
869 return $this->role->shortname;
872 protected function get_description_field($id) {
873 return format_text($this->role->description, FORMAT_HTML);
876 protected function get_archetype_field($id) {
877 if (empty($this->role->archetype)) {
878 return get_string('none');
879 } else {
880 return get_string('archetype'.$this->role->archetype, 'role');
884 protected function print_show_hide_advanced_button() {
885 // Do nothing.
888 protected function add_permission_cells($capability) {
889 $perm = $this->permissions[$capability->name];
890 $permname = $this->allpermissions[$perm];
891 $defaultperm = $this->allpermissions[$this->parentpermissions[$capability->name]];
892 if ($permname != $defaultperm) {
893 $default = get_string('defaultx', 'role', $this->strperms[$defaultperm]);
894 } else {
895 $default = "&#xa0;";
897 echo '<td class="' . $permname . '">' . $this->strperms[$permname] . '<span class="note">' .
898 $default . '</span></td>';
903 class override_permissions_table_advanced extends capability_table_with_risks {
904 protected $strnotset;
905 protected $haslockedcapabilities = false;
908 * Constructor
910 * This method loads loads all the information about the current state of
911 * the overrides, then updates that based on any submitted data. It also
912 * works out which capabilities should be locked for this user.
914 * @param object $context the context this table relates to.
915 * @param integer $roleid the role being overridden.
916 * @param boolean $safeoverridesonly If true, the user is only allowed to override
917 * capabilities with no risks.
919 public function __construct($context, $roleid, $safeoverridesonly) {
920 parent::__construct($context, 'overriderolestable', $roleid);
921 $this->displaypermissions = $this->allpermissions;
922 $this->strnotset = get_string('notset', 'role');
924 /// Determine which capabilities should be locked.
925 if ($safeoverridesonly) {
926 foreach ($this->capabilities as $capid => $cap) {
927 if (!is_safe_capability($cap)) {
928 $this->capabilities[$capid]->locked = true;
929 $this->haslockedcapabilities = true;
935 protected function load_parent_permissions() {
936 global $DB;
938 /// Get the capabilities from the parent context, so that can be shown in the interface.
939 $parentcontext = get_context_instance_by_id(get_parent_contextid($this->context));
940 $this->parentpermissions = role_context_capabilities($this->roleid, $parentcontext);
943 public function has_locked_capabilities() {
944 return $this->haslockedcapabilities;
947 protected function add_permission_cells($capability) {
948 $disabled = '';
949 if ($capability->locked || $this->parentpermissions[$capability->name] == CAP_PROHIBIT) {
950 $disabled = ' disabled="disabled"';
953 /// One cell for each possible permission.
954 foreach ($this->displaypermissions as $perm => $permname) {
955 $strperm = $this->strperms[$permname];
956 $extraclass = '';
957 if ($perm != CAP_INHERIT && $perm == $this->parentpermissions[$capability->name]) {
958 $extraclass = ' capcurrent';
960 $checked = '';
961 if ($this->permissions[$capability->name] == $perm) {
962 $checked = 'checked="checked" ';
964 echo '<td class="' . $permname . $extraclass . '">';
965 echo '<label><input type="radio" name="' . $capability->name .
966 '" value="' . $perm . '" ' . $checked . $disabled . '/> ';
967 if ($perm == CAP_INHERIT) {
968 $inherited = $this->parentpermissions[$capability->name];
969 if ($inherited == CAP_INHERIT) {
970 $inherited = $this->strnotset;
971 } else {
972 $inherited = $this->strperms[$this->allpermissions[$inherited]];
974 $strperm .= ' (' . $inherited . ')';
976 echo '<span class="note">' . $strperm . '</span>';
977 echo '</label></td>';
982 // User selectors for managing role assignments ================================
985 * Base class to avoid duplicating code.
987 abstract class role_assign_user_selector_base extends user_selector_base {
988 const MAX_USERS_PER_PAGE = 100;
990 protected $roleid;
991 protected $context;
994 * @param string $name control name
995 * @param array $options should have two elements with keys groupid and courseid.
997 public function __construct($name, $options) {
998 global $CFG;
999 if (isset($options['context'])) {
1000 $this->context = $options['context'];
1001 } else {
1002 $this->context = get_context_instance_by_id($options['contextid']);
1004 $options['accesscontext'] = $this->context;
1005 parent::__construct($name, $options);
1006 $this->roleid = $options['roleid'];
1007 require_once($CFG->dirroot . '/group/lib.php');
1010 protected function get_options() {
1011 global $CFG;
1012 $options = parent::get_options();
1013 $options['file'] = $CFG->admin . '/roles/lib.php';
1014 $options['roleid'] = $this->roleid;
1015 $options['contextid'] = $this->context->id;
1016 return $options;
1021 * User selector subclass for the list of potential users on the assign roles page,
1022 * when we are assigning in a context below the course level. (CONTEXT_MODULE and
1023 * some CONTEXT_BLOCK).
1025 * This returns only enrolled users in this context.
1027 class potential_assignees_below_course extends role_assign_user_selector_base {
1028 public function find_users($search) {
1029 global $DB;
1031 list($enrolsql, $eparams) = get_enrolled_sql($this->context);
1033 // Now we have to go to the database.
1034 list($wherecondition, $params) = $this->search_sql($search, 'u');
1035 $params = array_merge($params, $eparams);
1037 if ($wherecondition) {
1038 $wherecondition = ' AND ' . $wherecondition;
1041 $fields = 'SELECT ' . $this->required_fields_sql('u');
1042 $countfields = 'SELECT COUNT(u.id)';
1044 $sql = " FROM {user} u
1045 WHERE u.id IN ($enrolsql) $wherecondition
1046 AND u.id NOT IN (
1047 SELECT r.userid
1048 FROM {role_assignments} r
1049 WHERE r.contextid = :contextid
1050 AND r.roleid = :roleid)";
1051 $order = ' ORDER BY lastname ASC, firstname ASC';
1053 $params['contextid'] = $this->context->id;
1054 $params['roleid'] = $this->roleid;
1056 // Check to see if there are too many to show sensibly.
1057 if (!$this->is_validating()) {
1058 $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
1059 if ($potentialmemberscount > role_assign_user_selector_base::MAX_USERS_PER_PAGE) {
1060 return $this->too_many_results($search, $potentialmemberscount);
1064 // If not, show them.
1065 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
1067 if (empty($availableusers)) {
1068 return array();
1071 if ($search) {
1072 $groupname = get_string('potusersmatching', 'role', $search);
1073 } else {
1074 $groupname = get_string('potusers', 'role');
1077 return array($groupname => $availableusers);
1082 * User selector subclass for the list of potential users on the assign roles page,
1083 * when we are assigning in a context at or above the course level. In this case we
1084 * show all the users in the system who do not already have the role.
1086 class potential_assignees_course_and_above extends role_assign_user_selector_base {
1087 public function find_users($search) {
1088 global $DB;
1090 list($wherecondition, $params) = $this->search_sql($search, '');
1092 $fields = 'SELECT ' . $this->required_fields_sql('');
1093 $countfields = 'SELECT COUNT(1)';
1095 $sql = " FROM {user}
1096 WHERE $wherecondition
1097 AND id NOT IN (
1098 SELECT r.userid
1099 FROM {role_assignments} r
1100 WHERE r.contextid = :contextid
1101 AND r.roleid = :roleid)";
1102 $order = ' ORDER BY lastname ASC, firstname ASC';
1104 $params['contextid'] = $this->context->id;
1105 $params['roleid'] = $this->roleid;
1107 if (!$this->is_validating()) {
1108 $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
1109 if ($potentialmemberscount > role_assign_user_selector_base::MAX_USERS_PER_PAGE) {
1110 return $this->too_many_results($search, $potentialmemberscount);
1114 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
1116 if (empty($availableusers)) {
1117 return array();
1120 if ($search) {
1121 $groupname = get_string('potusersmatching', 'role', $search);
1122 } else {
1123 $groupname = get_string('potusers', 'role');
1126 return array($groupname => $availableusers);
1131 * User selector subclass for the list of users who already have the role in
1132 * question on the assign roles page.
1134 class existing_role_holders extends role_assign_user_selector_base {
1136 public function __construct($name, $options) {
1137 parent::__construct($name, $options);
1140 public function find_users($search) {
1141 global $DB;
1143 list($wherecondition, $params) = $this->search_sql($search, 'u');
1144 list($ctxcondition, $ctxparams) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
1145 $params = array_merge($params, $ctxparams);
1146 $params['roleid'] = $this->roleid;
1148 $sql = "SELECT ra.id as raid," . $this->required_fields_sql('u') . ",ra.contextid,ra.component
1149 FROM {role_assignments} ra
1150 JOIN {user} u ON u.id = ra.userid
1151 JOIN {context} ctx ON ra.contextid = ctx.id
1152 WHERE
1153 $wherecondition AND
1154 ctx.id $ctxcondition AND
1155 ra.roleid = :roleid
1156 ORDER BY ctx.depth DESC, ra.component, u.lastname, u.firstname";
1157 $contextusers = $DB->get_records_sql($sql, $params);
1159 // No users at all.
1160 if (empty($contextusers)) {
1161 return array();
1164 // We have users. Out put them in groups by context depth.
1165 // To help the loop below, tack a dummy user on the end of the results
1166 // array, to trigger output of the last group.
1167 $dummyuser = new stdClass;
1168 $dummyuser->contextid = 0;
1169 $dummyuser->id = 0;
1170 $dummyuser->component = '';
1171 $contextusers[] = $dummyuser;
1172 $results = array(); // The results array we are building up.
1173 $doneusers = array(); // Ensures we only list each user at most once.
1174 $currentcontextid = $this->context->id;
1175 $currentgroup = array();
1176 foreach ($contextusers as $user) {
1177 if (isset($doneusers[$user->id])) {
1178 continue;
1180 $doneusers[$user->id] = 1;
1181 if ($user->contextid != $currentcontextid) {
1182 // We have got to the end of the previous group. Add it to the results array.
1183 if ($currentcontextid == $this->context->id) {
1184 $groupname = $this->this_con_group_name($search, count($currentgroup));
1185 } else {
1186 $groupname = $this->parent_con_group_name($search, $currentcontextid);
1188 $results[$groupname] = $currentgroup;
1189 // Get ready for the next group.
1190 $currentcontextid = $user->contextid;
1191 $currentgroup = array();
1193 // Add this user to the group we are building up.
1194 unset($user->contextid);
1195 if ($currentcontextid != $this->context->id) {
1196 $user->disabled = true;
1198 if ($user->component !== '') {
1199 // bad luck, you can tweak only manual role assignments
1200 $user->disabled = true;
1202 unset($user->component);
1203 $currentgroup[$user->id] = $user;
1206 return $results;
1209 protected function this_con_group_name($search, $numusers) {
1210 if ($this->context->contextlevel == CONTEXT_SYSTEM) {
1211 // Special case in the System context.
1212 if ($search) {
1213 return get_string('extusersmatching', 'role', $search);
1214 } else {
1215 return get_string('extusers', 'role');
1218 $contexttype = get_contextlevel_name($this->context->contextlevel);
1219 if ($search) {
1220 $a = new stdClass;
1221 $a->search = $search;
1222 $a->contexttype = $contexttype;
1223 if ($numusers) {
1224 return get_string('usersinthisxmatching', 'role', $a);
1225 } else {
1226 return get_string('noneinthisxmatching', 'role', $a);
1228 } else {
1229 if ($numusers) {
1230 return get_string('usersinthisx', 'role', $contexttype);
1231 } else {
1232 return get_string('noneinthisx', 'role', $contexttype);
1237 protected function parent_con_group_name($search, $contextid) {
1238 $context = get_context_instance_by_id($contextid);
1239 $contextname = print_context_name($context, true, true);
1240 if ($search) {
1241 $a = new stdClass;
1242 $a->contextname = $contextname;
1243 $a->search = $search;
1244 return get_string('usersfrommatching', 'role', $a);
1245 } else {
1246 return get_string('usersfrom', 'role', $contextname);
1252 * Base class for managing the data in the grid of checkboxes on the role allow
1253 * allow/overrides/switch editing pages (allow.php).
1255 abstract class role_allow_role_page {
1256 protected $tablename;
1257 protected $targetcolname;
1258 protected $roles;
1259 protected $allowed = null;
1262 * @param string $tablename the table where our data is stored.
1263 * @param string $targetcolname the name of the target role id column.
1265 public function __construct($tablename, $targetcolname) {
1266 $this->tablename = $tablename;
1267 $this->targetcolname = $targetcolname;
1268 $this->load_required_roles();
1272 * Load information about all the roles we will need information about.
1274 protected function load_required_roles() {
1275 /// Get all roles
1276 $this->roles = get_all_roles();
1277 role_fix_names($this->roles, get_context_instance(CONTEXT_SYSTEM), ROLENAME_ORIGINAL);
1281 * Update the data with the new settings submitted by the user.
1283 public function process_submission() {
1284 global $DB;
1285 /// Delete all records, then add back the ones that should be allowed.
1286 $DB->delete_records($this->tablename);
1287 foreach ($this->roles as $fromroleid => $notused) {
1288 foreach ($this->roles as $targetroleid => $alsonotused) {
1289 if (optional_param('s_' . $fromroleid . '_' . $targetroleid, false, PARAM_BOOL)) {
1290 $this->set_allow($fromroleid, $targetroleid);
1297 * Set one allow in the database.
1298 * @param integer $fromroleid
1299 * @param integer $targetroleid
1301 protected abstract function set_allow($fromroleid, $targetroleid);
1304 * Load the current allows from the database.
1306 public function load_current_settings() {
1307 global $DB;
1308 /// Load the current settings
1309 $this->allowed = array();
1310 foreach ($this->roles as $role) {
1311 // Make an array $role->id => false. This is probably too clever for its own good.
1312 $this->allowed[$role->id] = array_combine(array_keys($this->roles), array_fill(0, count($this->roles), false));
1314 $rs = $DB->get_recordset($this->tablename);
1315 foreach ($rs as $allow) {
1316 $this->allowed[$allow->roleid][$allow->{$this->targetcolname}] = true;
1318 $rs->close();
1322 * @param integer $targetroleid a role id.
1323 * @return boolean whether the user should be allowed to select this role as a
1324 * target role.
1326 protected function is_allowed_target($targetroleid) {
1327 return true;
1331 * @return object a $table structure that can be passed to print_table, containing
1332 * one cell for each checkbox.
1334 public function get_table() {
1335 $table = new html_table();
1336 $table->tablealign = 'center';
1337 $table->cellpadding = 5;
1338 $table->cellspacing = 0;
1339 $table->width = '90%';
1340 $table->align = array('left');
1341 $table->rotateheaders = true;
1342 $table->head = array('&#xa0;');
1343 $table->colclasses = array('');
1345 /// Add role name headers.
1346 foreach ($this->roles as $targetrole) {
1347 $table->head[] = $targetrole->localname;
1348 $table->align[] = 'left';
1349 if ($this->is_allowed_target($targetrole->id)) {
1350 $table->colclasses[] = '';
1351 } else {
1352 $table->colclasses[] = 'dimmed_text';
1356 /// Now the rest of the table.
1357 foreach ($this->roles as $fromrole) {
1358 $row = array($fromrole->localname);
1359 foreach ($this->roles as $targetrole) {
1360 $checked = '';
1361 $disabled = '';
1362 if ($this->allowed[$fromrole->id][$targetrole->id]) {
1363 $checked = 'checked="checked" ';
1365 if (!$this->is_allowed_target($targetrole->id)) {
1366 $disabled = 'disabled="disabled" ';
1368 $name = 's_' . $fromrole->id . '_' . $targetrole->id;
1369 $tooltip = $this->get_cell_tooltip($fromrole, $targetrole);
1370 $row[] = '<input type="checkbox" name="' . $name . '" id="' . $name .
1371 '" title="' . $tooltip . '" value="1" ' . $checked . $disabled . '/>' .
1372 '<label for="' . $name . '" class="accesshide">' . $tooltip . '</label>';
1374 $table->data[] = $row;
1377 return $table;
1381 * Snippet of text displayed above the table, telling the admin what to do.
1382 * @return unknown_type
1384 public abstract function get_intro_text();
1388 * Subclass of role_allow_role_page for the Allow assigns tab.
1390 class role_allow_assign_page extends role_allow_role_page {
1391 public function __construct() {
1392 parent::__construct('role_allow_assign', 'allowassign');
1395 protected function set_allow($fromroleid, $targetroleid) {
1396 allow_assign($fromroleid, $targetroleid);
1399 protected function get_cell_tooltip($fromrole, $targetrole) {
1400 $a = new stdClass;
1401 $a->fromrole = $fromrole->localname;
1402 $a->targetrole = $targetrole->localname;
1403 return get_string('allowroletoassign', 'role', $a);
1406 public function get_intro_text() {
1407 return get_string('configallowassign', 'admin');
1412 * Subclass of role_allow_role_page for the Allow overrides tab.
1414 class role_allow_override_page extends role_allow_role_page {
1415 public function __construct() {
1416 parent::__construct('role_allow_override', 'allowoverride');
1419 protected function set_allow($fromroleid, $targetroleid) {
1420 allow_override($fromroleid, $targetroleid);
1423 protected function get_cell_tooltip($fromrole, $targetrole) {
1424 $a = new stdClass;
1425 $a->fromrole = $fromrole->localname;
1426 $a->targetrole = $targetrole->localname;
1427 return get_string('allowroletooverride', 'role', $a);
1430 public function get_intro_text() {
1431 return get_string('configallowoverride2', 'admin');
1436 * Subclass of role_allow_role_page for the Allow switches tab.
1438 class role_allow_switch_page extends role_allow_role_page {
1439 protected $allowedtargetroles;
1441 public function __construct() {
1442 parent::__construct('role_allow_switch', 'allowswitch');
1445 protected function load_required_roles() {
1446 global $DB;
1447 parent::load_required_roles();
1448 $this->allowedtargetroles = $DB->get_records_menu('role', NULL, 'id');
1451 protected function set_allow($fromroleid, $targetroleid) {
1452 allow_switch($fromroleid, $targetroleid);
1455 protected function is_allowed_target($targetroleid) {
1456 return isset($this->allowedtargetroles[$targetroleid]);
1459 protected function get_cell_tooltip($fromrole, $targetrole) {
1460 $a = new stdClass;
1461 $a->fromrole = $fromrole->localname;
1462 $a->targetrole = $targetrole->localname;
1463 return get_string('allowroletoswitch', 'role', $a);
1466 public function get_intro_text() {
1467 return get_string('configallowswitch', 'admin');
1472 * Get the potential assignees selector for a given context.
1474 * If this context is a course context, or inside a course context (module or
1475 * some blocks) then return a potential_assignees_below_course object. Otherwise
1476 * return a potential_assignees_course_and_above.
1478 * @param stdClass $context a context.
1479 * @param string $name passed to user selector constructor.
1480 * @param array $options to user selector constructor.
1481 * @return user_selector_base an appropriate user selector.
1483 function roles_get_potential_user_selector($context, $name, $options) {
1484 $blockinsidecourse = false;
1485 if ($context->contextlevel == CONTEXT_BLOCK) {
1486 $parentcontext = get_context_instance_by_id(get_parent_contextid($context));
1487 $blockinsidecourse = in_array($parentcontext->contextlevel, array(CONTEXT_MODULE, CONTEXT_COURSE));
1490 if (($context->contextlevel == CONTEXT_MODULE || $blockinsidecourse) &&
1491 !is_inside_frontpage($context)) {
1492 $potentialuserselector = new potential_assignees_below_course('addselect', $options);
1493 } else {
1494 $potentialuserselector = new potential_assignees_course_and_above('addselect', $options);
1496 return $potentialuserselector;
1499 class admins_potential_selector extends user_selector_base {
1501 * @param string $name control name
1502 * @param array $options should have two elements with keys groupid and courseid.
1504 public function __construct() {
1505 global $CFG, $USER;
1506 $admins = explode(',', $CFG->siteadmins);
1507 parent::__construct('addselect', array('multiselect'=>false, 'exclude'=>$admins));
1510 public function find_users($search) {
1511 global $CFG, $DB;
1512 list($wherecondition, $params) = $this->search_sql($search, '');
1514 $fields = 'SELECT ' . $this->required_fields_sql('');
1515 $countfields = 'SELECT COUNT(1)';
1517 $sql = " FROM {user}
1518 WHERE $wherecondition AND mnethostid = :localmnet";
1519 $order = ' ORDER BY lastname ASC, firstname ASC';
1520 $params['localmnet'] = $CFG->mnet_localhost_id; // it could be dangerous to make remote users admins and also this could lead to other problems
1522 // Check to see if there are too many to show sensibly.
1523 if (!$this->is_validating()) {
1524 $potentialcount = $DB->count_records_sql($countfields . $sql, $params);
1525 if ($potentialcount > 100) {
1526 return $this->too_many_results($search, $potentialcount);
1530 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
1532 if (empty($availableusers)) {
1533 return array();
1536 if ($search) {
1537 $groupname = get_string('potusersmatching', 'role', $search);
1538 } else {
1539 $groupname = get_string('potusers', 'role');
1542 return array($groupname => $availableusers);
1545 protected function get_options() {
1546 global $CFG;
1547 $options = parent::get_options();
1548 $options['file'] = $CFG->admin . '/roles/lib.php';
1549 return $options;
1553 class admins_existing_selector extends user_selector_base {
1555 * @param string $name control name
1556 * @param array $options should have two elements with keys groupid and courseid.
1558 public function __construct() {
1559 global $CFG, $USER;
1560 parent::__construct('removeselect', array('multiselect'=>false));
1563 public function find_users($search) {
1564 global $DB, $CFG;
1565 list($wherecondition, $params) = $this->search_sql($search, '');
1567 $fields = 'SELECT ' . $this->required_fields_sql('');
1568 $countfields = 'SELECT COUNT(1)';
1570 if ($wherecondition) {
1571 $wherecondition = "$wherecondition AND id IN ($CFG->siteadmins)";
1572 } else {
1573 $wherecondition = "id IN ($CFG->siteadmins)";
1575 $sql = " FROM {user}
1576 WHERE $wherecondition";
1577 $order = ' ORDER BY lastname ASC, firstname ASC';
1579 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
1581 if (empty($availableusers)) {
1582 return array();
1585 $mainadmin = array();
1586 $adminids = explode(',', $CFG->siteadmins);
1587 foreach ($adminids as $id) {
1588 if (isset($availableusers[$id])) {
1589 $mainadmin = array($id=>$availableusers[$id]);
1590 unset($availableusers[$id]);
1591 break;
1595 $result = array();
1596 if ($mainadmin) {
1597 $result[get_string('mainadmin', 'role')] = $mainadmin;
1600 if ($availableusers) {
1601 if ($search) {
1602 $groupname = get_string('extusersmatching', 'role', $search);
1603 } else {
1604 $groupname = get_string('extusers', 'role');
1606 $result[$groupname] = $availableusers;
1609 return $result;
1612 protected function get_options() {
1613 global $CFG;
1614 $options = parent::get_options();
1615 $options['file'] = $CFG->admin . '/roles/lib.php';
1616 return $options;