MDL-36413 Added "this->" to exclude variable assignment
[moodle.git] / user / selector / lib.php
CommitLineData
aa6c1ced 1<?php
bbcf5711 2
456e4852
SH
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
bbcf5711 17
18/**
19 * Code for ajax user selectors.
20 *
456e4852
SH
21 * @package user
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
bbcf5711 24 */
25
26/**
27 * The default size of a user selector.
28 */
29define('USER_SELECTOR_DEFAULT_ROWS', 20);
30
31/**
32 * Base class for user selectors.
97873016 33 *
34 * In your theme, you must give each user-selector a defined width. If the
35 * user selector has name="myid", then the div myid_wrapper must have a width
36 * specified.
bbcf5711 37 */
38abstract class user_selector_base {
456e4852 39 /** @var string The control name (and id) in the HTML. */
bbcf5711 40 protected $name;
456e4852 41 /** @var array Extra fields to search on and return in addition to firstname and lastname. */
bbcf5711 42 protected $extrafields;
5c60a847 43 /** @var object Context used for capability checks regarding this selector (does
44 * not necessarily restrict user list) */
45 protected $accesscontext;
456e4852 46 /** @var boolean Whether the conrol should allow selection of many users, or just one. */
bbcf5711 47 protected $multiselect = true;
456e4852 48 /** @var int The height this control should have, in rows. */
bbcf5711 49 protected $rows = USER_SELECTOR_DEFAULT_ROWS;
456e4852 50 /** @var array A list of userids that should not be returned by this control. */
bbcf5711 51 protected $exclude = array();
456e4852 52 /** @var array|null A list of the users who are selected. */
bbcf5711 53 protected $selected = null;
456e4852 54 /** @var boolean When the search changes, do we keep previously selected options that do
904998d8 55 * not match the new search term? */
56 protected $preserveselected = false;
456e4852 57 /** @var boolean If only one user matches the search, should we select them automatically. */
904998d8 58 protected $autoselectunique = false;
df997f84 59 /** @var boolean When searching, do we only match the starts of fields (better performance)
904998d8 60 * or do we match occurrences anywhere? */
61 protected $searchanywhere = false;
456e4852 62 /** @var mixed This is used by get selected users */
c23c9009 63 protected $validatinguserids = null;
2f67a9b3 64
456e4852
SH
65 /** @var boolean Used to ensure we only output the search options for one user selector on
66 * each page. */
904998d8 67 private static $searchoptionsoutput = false;
df997f84 68
456e4852
SH
69 /** @var array JavaScript YUI3 Module definition */
70 protected static $jsmodule = array(
71 'name' => 'user_selector',
72 'fullpath' => '/user/selector/module.js',
73 'requires' => array('node', 'event-custom', 'datasource', 'json'),
74 'strings' => array(
75 array('previouslyselectedusers', 'moodle', '%%SEARCHTERM%%'),
76 array('nomatchingusers', 'moodle', '%%SEARCHTERM%%'),
77 array('none', 'moodle')
78 ));
bbcf5711 79
aa6c1ced 80
bbcf5711 81 // Public API ==============================================================
82
83 /**
f05c20fb 84 * Constructor. Each subclass must have a constructor with this signature.
bbcf5711 85 *
86 * @param string $name the control name/id for use in the HTML.
f05c20fb 87 * @param array $options other options needed to construct this selector.
88 * You must be able to clone a userselector by doing new get_class($us)($us->get_name(), $us->get_options());
bbcf5711 89 */
f05c20fb 90 public function __construct($name, $options = array()) {
cf615522 91 global $CFG, $PAGE;
cf0a341f 92
93 // Initialise member variables from constructor arguments.
bbcf5711 94 $this->name = $name;
5c60a847 95
96 // Use specified context for permission checks, system context if not
97 // specified
98 if (isset($options['accesscontext'])) {
99 $this->accesscontext = $options['accesscontext'];
100 } else {
101 $this->accesscontext = get_context_instance(CONTEXT_SYSTEM);
102 }
103
6cab02ac 104 if (isset($options['extrafields'])) {
105 $this->extrafields = $options['extrafields'];
5c60a847 106 } else if (!empty($CFG->showuseridentity) &&
107 has_capability('moodle/site:viewuseridentity', $this->accesscontext)) {
108 $this->extrafields = explode(',', $CFG->showuseridentity);
6cab02ac 109 } else {
110 $this->extrafields = array();
bbcf5711 111 }
f05c20fb 112 if (isset($options['exclude']) && is_array($options['exclude'])) {
113 $this->exclude = $options['exclude'];
114 }
8d89b401 115 if (isset($options['multiselect'])) {
116 $this->multiselect = $options['multiselect'];
117 }
cf0a341f 118
119 // Read the user prefs / optional_params that we use.
904998d8 120 $this->preserveselected = $this->initialise_option('userselector_preserveselected', $this->preserveselected);
121 $this->autoselectunique = $this->initialise_option('userselector_autoselectunique', $this->autoselectunique);
122 $this->searchanywhere = $this->initialise_option('userselector_searchanywhere', $this->searchanywhere);
bbcf5711 123 }
124
125 /**
126 * All to the list of user ids that this control will not select. For example,
127 * on the role assign page, we do not list the users who already have the role
128 * in question.
129 *
130 * @param array $arrayofuserids the user ids to exclude.
131 */
132 public function exclude($arrayofuserids) {
133 $this->exclude = array_unique(array_merge($this->exclude, $arrayofuserids));
134 }
135
136 /**
137 * Clear the list of excluded user ids.
138 */
139 public function clear_exclusions() {
3522c1dc 140 $this->exclude = array();
bbcf5711 141 }
142
143 /**
144 * @return array the list of user ids that this control will not select.
145 */
146 public function get_exclusions() {
147 return clone($this->exclude);
148 }
149
150 /**
6cab02ac 151 * @return array of user objects. The users that were selected. This is a more sophisticated version
bbcf5711 152 * of optional_param($this->name, array(), PARAM_INTEGER) that validates the
153 * returned list of ids against the rules for this user selector.
154 */
155 public function get_selected_users() {
156 // Do a lazy load.
157 if (is_null($this->selected)) {
158 $this->selected = $this->load_selected_users();
159 }
160 return $this->selected;
161 }
162
a6e7237a 163 /**
164 * Convenience method for when multiselect is false (throws an exception if not).
165 * @return object the selected user object, or null if none.
166 */
167 public function get_selected_user() {
168 if ($this->multiselect) {
169 throw new moodle_exception('cannotcallusgetselecteduser');
170 }
171 $users = $this->get_selected_users();
172 if (count($users) == 1) {
173 return reset($users);
174 } else if (count($users) == 0) {
175 return null;
176 } else {
177 throw new moodle_exception('userselectortoomany');
178 }
179 }
180
97873016 181 /**
182 * If you update the database in such a way that it is likely to change the
183 * list of users that this component is allowed to select from, then you
184 * must call this method. For example, on the role assign page, after you have
185 * assigned some roles to some users, you should call this.
186 */
187 public function invalidate_selected_users() {
188 $this->selected = null;
189 }
190
bbcf5711 191 /**
192 * Output this user_selector as HTML.
193 * @param boolean $return if true, return the HTML as a string instead of outputting it.
194 * @return mixed if $return is true, returns the HTML as a string, otherwise returns nothing.
195 */
196 public function display($return = false) {
cf615522 197 global $PAGE;
198
f771be27 199 // Get the list of requested users.
bbcf5711 200 $search = optional_param($this->name . '_searchtext', '', PARAM_RAW);
c9e4326c 201 if (optional_param($this->name . '_clearbutton', false, PARAM_BOOL)) {
202 $search = '';
203 }
bbcf5711 204 $groupedusers = $this->find_users($search);
bbcf5711 205
206 // Output the select.
207 $name = $this->name;
208 $multiselect = '';
209 if ($this->multiselect) {
210 $name .= '[]';
211 $multiselect = 'multiple="multiple" ';
212 }
213 $output = '<div class="userselector" id="' . $this->name . '_wrapper">' . "\n" .
214 '<select name="' . $name . '" id="' . $this->name . '" ' .
215 $multiselect . 'size="' . $this->rows . '">' . "\n";
d56f9e65 216
217 // Populate the select.
aa9671c9 218 $output .= $this->output_options($groupedusers, $search);
bbcf5711 219
220 // Output the search controls.
221 $output .= "</select>\n<div>\n";
222 $output .= '<input type="text" name="' . $this->name . '_searchtext" id="' .
c9e4326c 223 $this->name . '_searchtext" size="15" value="' . s($search) . '" />';
bbcf5711 224 $output .= '<input type="submit" name="' . $this->name . '_searchbutton" id="' .
225 $this->name . '_searchbutton" value="' . $this->search_button_caption() . '" />';
c9e4326c 226 $output .= '<input type="submit" name="' . $this->name . '_clearbutton" id="' .
227 $this->name . '_clearbutton" value="' . get_string('clear') . '" />';
904998d8 228
229 // And the search options.
230 $optionsoutput = false;
231 if (!user_selector_base::$searchoptionsoutput) {
232 $output .= print_collapsible_region_start('', 'userselector_options',
233 get_string('searchoptions'), 'userselector_optionscollapsed', true, true);
234 $output .= $this->option_checkbox('preserveselected', $this->preserveselected, get_string('userselectorpreserveselected'));
235 $output .= $this->option_checkbox('autoselectunique', $this->autoselectunique, get_string('userselectorautoselectunique'));
236 $output .= $this->option_checkbox('searchanywhere', $this->searchanywhere, get_string('userselectorsearchanywhere'));
237 $output .= print_collapsible_region_end(true);
cf615522 238
456e4852 239 $PAGE->requires->js_init_call('M.core_user.init_user_selector_options_tracker', array(), false, self::$jsmodule);
904998d8 240 user_selector_base::$searchoptionsoutput = true;
904998d8 241 }
bbcf5711 242 $output .= "</div>\n</div>\n\n";
243
d56f9e65 244 // Initialise the ajax functionality.
1acd8f50 245 $output .= $this->initialise_javascript($search);
f05c20fb 246
bbcf5711 247 // Return or output it.
248 if ($return) {
249 return $output;
250 } else {
251 echo $output;
252 }
253 }
254
255 /**
256 * The height this control will be displayed, in rows.
257 *
258 * @param integer $numrows the desired height.
259 */
260 public function set_rows($numrows) {
261 $this->rows = $numrows;
262 }
263
264 /**
265 * @return integer the height this control will be displayed, in rows.
266 */
267 public function get_rows() {
268 return $this->rows;
269 }
270
271 /**
272 * Whether this control will allow selection of many, or just one user.
273 *
274 * @param boolean $multiselect true = allow multiple selection.
275 */
276 public function set_multiselect($multiselect) {
277 $this->multiselect = $multiselect;
278 }
279
280 /**
281 * @return boolean whether this control will allow selection of more than one user.
282 */
283 public function is_multiselect() {
284 return $this->multiselect;
285 }
286
287 /**
288 * @return string the id/name that this control will have in the HTML.
289 */
290 public function get_name() {
291 return $this->name;
292 }
293
97873016 294 /**
295 * Set the user fields that are displayed in the selector in addition to the
296 * user's name.
297 *
298 * @param array $fields a list of field names that exist in the user table.
299 */
300 public function set_extra_fields($fields) {
301 $this->extrafields = $fields;
302 }
303
bbcf5711 304 // API for sublasses =======================================================
305
306 /**
307 * Search the database for users matching the $search string, and any other
308 * conditions that apply. The SQL for testing whether a user matches the
309 * search string should be obtained by calling the search_sql method.
310 *
deb39f43 311 * This method is used both when getting the list of choices to display to
312 * the user, and also when validating a list of users that was selected.
313 *
314 * When preparing a list of users to choose from ($this->is_validating()
315 * return false) you should probably have an maximum number of users you will
316 * return, and if more users than this match your search, you should instead
317 * return a message generated by the too_many_results() method. However, you
318 * should not do this when validating.
319 *
320 * If you are writing a new user_selector subclass, I strongly recommend you
1e8e4687 321 * look at some of the subclasses later in this file and in admin/roles/lib.php.
322 * They should help you see exactly what you have to do.
deb39f43 323 *
bbcf5711 324 * @param string $search the search string.
325 * @return array An array of arrays of users. The array keys of the outer
326 * array should be the string names of optgroups. The keys of the inner
327 * arrays should be userids, and the values should be user objects
328 * containing at least the list of fields returned by the method
6cab02ac 329 * required_fields_sql(). If a user object has a ->disabled property
330 * that is true, then that option will be displayed greyed out, and
331 * will not be returned by get_selected_users.
bbcf5711 332 */
f05c20fb 333 public abstract function find_users($search);
bbcf5711 334
f771be27 335 /**
aa6c1ced 336 *
234c18e4 337 * Note: this function must be implemented if you use the search ajax field
338 * (e.g. set $options['file'] = '/admin/filecontainingyourclass.php';)
f771be27 339 * @return array the options needed to recreate this user_selector.
340 */
bbcf5711 341 protected function get_options() {
342 return array(
343 'class' => get_class($this),
f05c20fb 344 'name' => $this->name,
bbcf5711 345 'exclude' => $this->exclude,
8d89b401 346 'extrafields' => $this->extrafields,
5c60a847 347 'multiselect' => $this->multiselect,
348 'accesscontext' => $this->accesscontext,
bbcf5711 349 );
350 }
351
352 // Inner workings ==========================================================
353
deb39f43 354 /**
355 * @return boolean if true, we are validating a list of selected users,
356 * rather than preparing a list of uesrs to choose from.
357 */
358 protected function is_validating() {
359 return !is_null($this->validatinguserids);
360 }
361
f771be27 362 /**
363 * Get the list of users that were selected by doing optional_param then
364 * validating the result.
365 *
366 * @return array of user objects.
367 */
bbcf5711 368 protected function load_selected_users() {
369 // See if we got anything.
409ac824 370 if ($this->multiselect) {
c600761b 371 $userids = optional_param_array($this->name, array(), PARAM_INTEGER);
3c2ed2d7 372 } else if ($userid = optional_param($this->name, 0, PARAM_INTEGER)) {
409ac824 373 $userids = array($userid);
f771be27 374 }
3c2ed2d7
MG
375 // If there are no users there is nobody to load
376 if (empty($userids)) {
377 return array();
378 }
bbcf5711 379
380 // If we did, use the find_users method to validate the ids.
381 $this->validatinguserids = $userids;
382 $groupedusers = $this->find_users('');
383 $this->validatinguserids = null;
384
385 // Aggregate the resulting list back into a single one.
386 $users = array();
387 foreach ($groupedusers as $group) {
6cab02ac 388 foreach ($group as $user) {
c23c9009 389 if (!isset($users[$user->id]) && empty($user->disabled) && in_array($user->id, $userids)) {
6cab02ac 390 $users[$user->id] = $user;
391 }
392 }
bbcf5711 393 }
f771be27 394
395 // If we are only supposed to be selecting a single user, make sure we do.
396 if (!$this->multiselect && count($users) > 1) {
397 $users = array_slice($users, 0, 1);
398 }
399
bbcf5711 400 return $users;
401 }
402
f771be27 403 /**
404 * @param string $u the table alias for the user table in the query being
405 * built. May be ''.
406 * @return string fragment of SQL to go in the select list of the query.
407 */
bbcf5711 408 protected function required_fields_sql($u) {
409 // Raw list of fields.
410 $fields = array('id', 'firstname', 'lastname');
411 $fields = array_merge($fields, $this->extrafields);
412
413 // Prepend the table alias.
414 if ($u) {
415 foreach ($fields as &$field) {
416 $field = $u . '.' . $field;
417 }
418 }
419 return implode(',', $fields);
420 }
421
f771be27 422 /**
423 * @param string $search the text to search for.
424 * @param string $u the table alias for the user table in the query being
425 * built. May be ''.
426 * @return array an array with two elements, a fragment of SQL to go in the
427 * where clause the query, and an array containing any required parameters.
428 * this uses ? style placeholders.
429 */
bbcf5711 430 protected function search_sql($search, $u) {
04aec3da 431 global $DB, $CFG;
bbcf5711 432 $params = array();
433 $tests = array();
434
6cab02ac 435 if ($u) {
436 $u .= '.';
437 }
438
bbcf5711 439 // If we have a $search string, put a field LIKE '$search%' condition on each field.
440 if ($search) {
441 $conditions = array(
6cab02ac 442 $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
443 $conditions[] = $u . 'lastname'
bbcf5711 444 );
445 foreach ($this->extrafields as $field) {
6cab02ac 446 $conditions[] = $u . $field;
bbcf5711 447 }
904998d8 448 if ($this->searchanywhere) {
449 $searchparam = '%' . $search . '%';
450 } else {
451 $searchparam = $search . '%';
452 }
4f0c2d00 453 $i = 0;
f63ac65a
PS
454 foreach ($conditions as $key=>$condition) {
455 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
4f0c2d00
PS
456 $params["con{$i}00"] = $searchparam;
457 $i++;
bbcf5711 458 }
459 $tests[] = '(' . implode(' OR ', $conditions) . ')';
460 }
461
6cab02ac 462 // Add some additional sensible conditions
04aec3da
PS
463 $tests[] = $u . "id <> :guestid";
464 $params['guestid'] = $CFG->siteguest;
6cab02ac 465 $tests[] = $u . 'deleted = 0';
466 $tests[] = $u . 'confirmed = 1';
467
bbcf5711 468 // If we are being asked to exclude any users, do that.
469 if (!empty($this->exclude)) {
cf717dc2 470 list($usertest, $userparams) = $DB->get_in_or_equal($this->exclude, SQL_PARAMS_NAMED, 'ex', false);
6cab02ac 471 $tests[] = $u . 'id ' . $usertest;
bbcf5711 472 $params = array_merge($params, $userparams);
473 }
474
475 // If we are validating a set list of userids, add an id IN (...) test.
476 if (!empty($this->validatinguserids)) {
cf717dc2 477 list($usertest, $userparams) = $DB->get_in_or_equal($this->validatinguserids, SQL_PARAMS_NAMED, 'val');
6cab02ac 478 $tests[] = $u . 'id ' . $usertest;
bbcf5711 479 $params = array_merge($params, $userparams);
480 }
481
482 if (empty($tests)) {
483 $tests[] = '1 = 1';
484 }
485
486 // Combing the conditions and return.
487 return array(implode(' AND ', $tests), $params);
488 }
489
deb39f43 490 /**
491 * Used to generate a nice message when there are too many users to show.
492 * The message includes the number of users that currently match, and the
493 * text of the message depends on whether the search term is non-blank.
494 *
495 * @param string $search the search term, as passed in to the find users method.
eab8ed9f 496 * @param int $count the number of users that currently match.
deb39f43 497 * @return array in the right format to return from the find_users method.
498 */
499 protected function too_many_results($search, $count) {
500 if ($search) {
501 $a = new stdClass;
502 $a->count = $count;
503 $a->search = $search;
504 return array(get_string('toomanyusersmatchsearch', '', $a) => array(),
505 get_string('pleasesearchmore') => array());
506 } else {
507 return array(get_string('toomanyuserstoshow', '', $count) => array(),
508 get_string('pleaseusesearch') => array());
509 }
510 }
511
d56f9e65 512 /**
513 * Output the list of <optgroup>s and <options>s that go inside the select.
514 * This method should do the same as the JavaScript method
515 * user_selector.prototype.handle_response.
516 *
f771be27 517 * @param array $groupedusers an array, as returned by find_users.
518 * @return string HTML code.
d56f9e65 519 */
aa9671c9 520 protected function output_options($groupedusers, $search) {
d56f9e65 521 $output = '';
522
523 // Ensure that the list of previously selected users is up to date.
524 $this->get_selected_users();
525
904998d8 526 // If $groupedusers is empty, make a 'no matching users' group. If there is
527 // only one selected user, set a flag to select them if that option is turned on.
f771be27 528 $select = false;
97873016 529 if (empty($groupedusers)) {
9d07ec29 530 if (!empty($search)) {
531 $groupedusers = array(get_string('nomatchingusers', '', $search) => array());
532 } else {
533 $groupedusers = array(get_string('none') => array());
534 }
904998d8 535 } else if ($this->autoselectunique && count($groupedusers) == 1 &&
536 count(reset($groupedusers)) == 1) {
f771be27 537 $select = true;
538 if (!$this->multiselect) {
539 $this->selected = array();
540 }
541 }
542
d56f9e65 543 // Output each optgroup.
544 foreach ($groupedusers as $groupname => $users) {
545 $output .= $this->output_optgroup($groupname, $users, $select);
546 }
547
548 // If there were previously selected users who do not match the search, show them too.
904998d8 549 if ($this->preserveselected && !empty($this->selected)) {
aa9671c9 550 $output .= $this->output_optgroup(get_string('previouslyselectedusers', '', $search), $this->selected, true);
d56f9e65 551 }
552
553 // This method trashes $this->selected, so clear the cache so it is
554 // rebuilt before anyone tried to use it again.
555 $this->selected = null;
556
557 return $output;
558 }
559
f771be27 560 /**
561 * Output one particular optgroup. Used by the preceding function output_options.
562 *
563 * @param string $groupname the label for this optgroup.
564 * @param array $users the users to put in this optgroup.
565 * @param boolean $select if true, select the users in this group.
566 * @return string HTML code.
567 */
bbcf5711 568 protected function output_optgroup($groupname, $users, $select) {
bbcf5711 569 if (!empty($users)) {
71ef6822 570 $output = ' <optgroup label="' . htmlspecialchars($groupname) . ' (' . count($users) . ')">' . "\n";
bbcf5711 571 foreach ($users as $user) {
6cab02ac 572 $attributes = '';
573 if (!empty($user->disabled)) {
574 $attributes .= ' disabled="disabled"';
575 } else if ($select || isset($this->selected[$user->id])) {
576 $attributes .= ' selected="selected"';
bbcf5711 577 }
578 unset($this->selected[$user->id]);
6cab02ac 579 $output .= ' <option' . $attributes . ' value="' . $user->id . '">' .
bbcf5711 580 $this->output_user($user) . "</option>\n";
581 }
582 } else {
71ef6822 583 $output = ' <optgroup label="' . htmlspecialchars($groupname) . '">' . "\n";
97873016 584 $output .= ' <option disabled="disabled">&nbsp;</option>' . "\n";
bbcf5711 585 }
97873016 586 $output .= " </optgroup>\n";
bbcf5711 587 return $output;
588 }
589
590 /**
d56f9e65 591 * Convert a user object to a string suitable for displaying as an option in the list box.
bbcf5711 592 *
593 * @param object $user the user to display.
d56f9e65 594 * @return string a string representation of the user.
bbcf5711 595 */
6cab02ac 596 public function output_user($user) {
5c60a847 597 $out = fullname($user);
598 if ($this->extrafields) {
599 $displayfields = array();
600 foreach ($this->extrafields as $field) {
601 $displayfields[] = $user->{$field};
602 }
603 $out .= ' (' . implode(', ', $displayfields) . ')';
bbcf5711 604 }
5c60a847 605 return $out;
bbcf5711 606 }
607
608 /**
609 * @return string the caption for the search button.
610 */
611 protected function search_button_caption() {
612 return get_string('search');
613 }
d56f9e65 614
904998d8 615 // Initialise one of the option checkboxes, either from
616 // the request, or failing that from the user_preferences table, or
617 // finally from the given default.
618 private function initialise_option($name, $default) {
619 $param = optional_param($name, null, PARAM_BOOL);
620 if (is_null($param)) {
621 return get_user_preferences($name, $default);
622 } else {
623 set_user_preference($name, $param);
624 return $param;
625 }
626 }
627
628 // Output one of the options checkboxes.
629 private function option_checkbox($name, $on, $label) {
630 if ($on) {
631 $checked = ' checked="checked"';
632 } else {
633 $checked = '';
634 }
635 $name = 'userselector_' . $name;
636 $output = '<p><input type="hidden" name="' . $name . '" value="0" />' .
1acd8f50 637 // For the benefit of brain-dead IE, the id must be different from the name of the hidden form field above.
638 // It seems that document.getElementById('frog') in IE will return and element with name="frog".
639 '<input type="checkbox" id="' . $name . 'id" name="' . $name . '" value="1"' . $checked . ' /> ' .
206dd861 640 '<label for="' . $name . 'id">' . $label . "</label></p>\n";
904998d8 641 user_preference_allow_ajax_update($name, PARAM_BOOL);
642 return $output;
643 }
644
d56f9e65 645 /**
904998d8 646 * @param boolean $optiontracker if true, initialise JavaScript for updating the user prefs.
f771be27 647 * @return any HTML needed here.
d56f9e65 648 */
1acd8f50 649 protected function initialise_javascript($search) {
ddedf979 650 global $USER, $PAGE, $OUTPUT;
d56f9e65 651 $output = '';
652
d56f9e65 653 // Put the options into the session, to allow search.php to respond to the ajax requests.
654 $options = $this->get_options();
655 $hash = md5(serialize($options));
656 $USER->userselectors[$hash] = $options;
657
658 // Initialise the selector.
456e4852 659 $PAGE->requires->js_init_call('M.core_user.init_user_selector', array($this->name, $hash, $this->extrafields, $search), false, self::$jsmodule);
d56f9e65 660 return $output;
661 }
662}
663
df997f84 664// User selectors for managing group members ==================================
6cab02ac 665
666/**
667 * Base class to avoid duplicating code.
668 */
97873016 669abstract class groups_user_selector_base extends user_selector_base {
670 protected $groupid;
671 protected $courseid;
672
673 /**
674 * @param string $name control name
675 * @param array $options should have two elements with keys groupid and courseid.
676 */
677 public function __construct($name, $options) {
678 global $CFG;
5c60a847 679 $options['accesscontext'] = get_context_instance(CONTEXT_COURSE, $options['courseid']);
97873016 680 parent::__construct($name, $options);
681 $this->groupid = $options['groupid'];
682 $this->courseid = $options['courseid'];
683 require_once($CFG->dirroot . '/group/lib.php');
684 }
685
686 protected function get_options() {
687 $options = parent::get_options();
688 $options['groupid'] = $this->groupid;
689 $options['courseid'] = $this->courseid;
690 return $options;
691 }
692
693 /**
97873016 694 * @param array $roles array in the format returned by groups_calculate_role_people.
695 * @return array array in the format find_users is supposed to return.
696 */
aa9671c9 697 protected function convert_array_format($roles, $search) {
97873016 698 if (empty($roles)) {
699 $roles = array();
700 }
701 $groupedusers = array();
702 foreach ($roles as $role) {
aa9671c9 703 if ($search) {
704 $a = new stdClass;
705 $a->role = $role->name;
706 $a->search = $search;
707 $groupname = get_string('matchingsearchandrole', '', $a);
708 } else {
709 $groupname = $role->name;
710 }
711 $groupedusers[$groupname] = $role->users;
712 foreach ($groupedusers[$groupname] as &$user) {
97873016 713 unset($user->roles);
714 $user->fullname = fullname($user);
715 }
716 }
717 return $groupedusers;
718 }
719}
720
721/**
722 * User selector subclass for the list of users who are in a certain group.
723 * Used on the add group memebers page.
724 */
725class group_members_selector extends groups_user_selector_base {
f05c20fb 726 public function find_users($search) {
97873016 727 list($wherecondition, $params) = $this->search_sql($search, 'u');
728 $roles = groups_get_members_by_role($this->groupid, $this->courseid,
729 $this->required_fields_sql('u'), 'u.lastname, u.firstname',
730 $wherecondition, $params);
aa9671c9 731 return $this->convert_array_format($roles, $search);
97873016 732 }
733}
734
735/**
736 * User selector subclass for the list of users who are not in a certain group.
bf1ac6d9 737 * Used on the add group members page.
97873016 738 */
739class group_non_members_selector extends groups_user_selector_base {
740 const MAX_USERS_PER_PAGE = 100;
741
bf1ac6d9
AD
742 /**
743 * An array of user ids populated by find_users() used in print_user_summaries()
744 */
745 private $potentialmembersids = array();
746
6cab02ac 747 public function output_user($user) {
97873016 748 return parent::output_user($user) . ' (' . $user->numgroups . ')';
749 }
750
f19497f2
SH
751 /**
752 * Returns the user selector JavaScript module
753 * @return array
754 */
755 public function get_js_module() {
756 return self::$jsmodule;
757 }
758
bf1ac6d9 759 /**
0b3f8547
SH
760 * Creates a global JS variable (userSummaries) that is used by the group selector
761 * to print related information when the user clicks on a user in the groups UI.
762 *
763 * Used by /group/clientlib.js
764 *
765 * @global moodle_database $DB
766 * @global moodle_page $PAGE
767 * @param int $courseid
bf1ac6d9
AD
768 */
769 public function print_user_summaries($courseid) {
0b3f8547 770 global $DB, $PAGE;
bf1ac6d9 771
0b3f8547 772 $usersummaries = array();
1c7a2f84 773
bf1ac6d9
AD
774 // Get other groups user already belongs to
775 $usergroups = array();
776 $potentialmembersids = $this->potentialmembersids;
777 if( empty($potentialmembersids)==false ) {
cf717dc2 778 list($membersidsclause, $params) = $DB->get_in_or_equal($potentialmembersids, SQL_PARAMS_NAMED, 'pm');
bf1ac6d9 779 $sql = "SELECT u.id AS userid, g.*
0b3f8547
SH
780 FROM {user} u
781 JOIN {groups_members} gm ON u.id = gm.userid
782 JOIN {groups} g ON gm.groupid = g.id
783 WHERE u.id $membersidsclause AND g.courseid = :courseid ";
bf1ac6d9 784 $params['courseid'] = $courseid;
cd5fdfd8
EL
785 $rs = $DB->get_recordset_sql($sql, $params);
786 foreach ($rs as $usergroup) {
787 $usergroups[$usergroup->userid][$usergroup->id] = $usergroup;
bf1ac6d9 788 }
cd5fdfd8 789 $rs->close();
bf1ac6d9 790
bf1ac6d9 791 foreach ($potentialmembersids as $userid) {
0b3f8547
SH
792 if (isset($usergroups[$userid])) {
793 $usergrouplist = html_writer::start_tag('ul');
794 foreach ($usergroups[$userid] as $groupitem) {
795 $usergrouplist .= html_writer::tag('li', format_string($groupitem->name));
796 }
797 $usergrouplist .= html_writer::end_tag('ul');
798 } else {
799 $usergrouplist = '';
800 }
801 $usersummaries[] = $usergrouplist;
bf1ac6d9
AD
802 }
803 }
0b3f8547
SH
804
805 $PAGE->requires->data_for_js('userSummaries', $usersummaries);
bf1ac6d9
AD
806 }
807
97873016 808 public function find_users($search) {
809 global $DB;
810
811 // Get list of allowed roles.
812 $context = get_context_instance(CONTEXT_COURSE, $this->courseid);
1c7a2f84 813 if ($validroleids = groups_get_possible_roles($context)) {
cf717dc2 814 list($roleids, $roleparams) = $DB->get_in_or_equal($validroleids, SQL_PARAMS_NAMED, 'r');
1c7a2f84
PS
815 } else {
816 $roleids = " = -1";
817 $roleparams = array();
97873016 818 }
97873016 819
820 // Get the search condition.
821 list($searchcondition, $searchparams) = $this->search_sql($search, 'u');
822
823 // Build the SQL
4f0c2d00
PS
824 list($enrolsql, $enrolparams) = get_enrolled_sql($context);
825 $fields = "SELECT r.id AS roleid, r.shortname AS roleshortname, r.name AS rolename, u.id AS userid,
826 " . $this->required_fields_sql('u') . ",
827 (SELECT count(igm.groupid)
828 FROM {groups_members} igm
829 JOIN {groups} ig ON igm.groupid = ig.id
830 WHERE igm.userid = u.id AND ig.courseid = :courseid) AS numgroups";
97873016 831 $sql = " FROM {user} u
4f0c2d00 832 JOIN ($enrolsql) e ON e.id = u.id
1c7a2f84
PS
833 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid " . get_related_contexts_string($context) . " AND ra.roleid $roleids)
834 LEFT JOIN {role} r ON r.id = ra.roleid
e3a5ed9d 835 LEFT JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)
1c7a2f84 836 WHERE u.deleted = 0
e3a5ed9d 837 AND gm.id IS NULL
97873016 838 AND $searchcondition";
4f0c2d00 839 $orderby = "ORDER BY u.lastname, u.firstname";
97873016 840
df997f84 841 $params = array_merge($searchparams, $roleparams, $enrolparams);
4f0c2d00 842 $params['courseid'] = $this->courseid;
df997f84 843 $params['groupid'] = $this->groupid;
97873016 844
deb39f43 845 if (!$this->is_validating()) {
4f0c2d00 846 $potentialmemberscount = $DB->count_records_sql("SELECT COUNT(DISTINCT u.id) $sql", $params);
deb39f43 847 if ($potentialmemberscount > group_non_members_selector::MAX_USERS_PER_PAGE) {
848 return $this->too_many_results($search, $potentialmemberscount);
849 }
97873016 850 }
851
4f0c2d00 852 $rs = $DB->get_recordset_sql("$fields $sql $orderby", $params);
97873016 853 $roles = groups_calculate_role_people($rs, $context);
854
bf1ac6d9 855 //don't hold onto user IDs if we're doing validation
df997f84 856 if (empty($this->validatinguserids) ) {
bf1ac6d9
AD
857 if($roles) {
858 foreach($roles as $k=>$v) {
859 if($v) {
860 foreach($v->users as $uid=>$userobject) {
861 $this->potentialmembersids[] = $uid;
862 }
863 }
864 }
865 }
866 }
867
aa9671c9 868 return $this->convert_array_format($roles, $search);
bbcf5711 869 }
870}