.
/**
* Code for ajax user selectors.
*
* @package core_user
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* The default size of a user selector.
*/
define('USER_SELECTOR_DEFAULT_ROWS', 20);
/**
* Base class for user selectors.
*
* In your theme, you must give each user-selector a defined width. If the
* user selector has name="myid", then the div myid_wrapper must have a width
* specified.
*
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class user_selector_base {
/** @var string The control name (and id) in the HTML. */
protected $name;
/** @var array Extra fields to search on and return in addition to firstname and lastname. */
protected $extrafields;
/** @var object Context used for capability checks regarding this selector (does
* not necessarily restrict user list) */
protected $accesscontext;
/** @var boolean Whether the conrol should allow selection of many users, or just one. */
protected $multiselect = true;
/** @var int The height this control should have, in rows. */
protected $rows = USER_SELECTOR_DEFAULT_ROWS;
/** @var array A list of userids that should not be returned by this control. */
protected $exclude = array();
/** @var array|null A list of the users who are selected. */
protected $selected = null;
/** @var boolean When the search changes, do we keep previously selected options that do
* not match the new search term? */
protected $preserveselected = false;
/** @var boolean If only one user matches the search, should we select them automatically. */
protected $autoselectunique = false;
/** @var boolean When searching, do we only match the starts of fields (better performance)
* or do we match occurrences anywhere? */
protected $searchanywhere = false;
/** @var mixed This is used by get selected users */
protected $validatinguserids = null;
/** @var boolean Used to ensure we only output the search options for one user selector on
* each page. */
private static $searchoptionsoutput = false;
/** @var array JavaScript YUI3 Module definition */
protected static $jsmodule = array(
'name' => 'user_selector',
'fullpath' => '/user/selector/module.js',
'requires' => array('node', 'event-custom', 'datasource', 'json', 'moodle-core-notification'),
'strings' => array(
array('previouslyselectedusers', 'moodle', '%%SEARCHTERM%%'),
array('nomatchingusers', 'moodle', '%%SEARCHTERM%%'),
array('none', 'moodle')
));
/** @var int this is used to define maximum number of users visible in list */
public $maxusersperpage = 100;
/**
* Constructor. Each subclass must have a constructor with this signature.
*
* @param string $name the control name/id for use in the HTML.
* @param array $options other options needed to construct this selector.
* You must be able to clone a userselector by doing new get_class($us)($us->get_name(), $us->get_options());
*/
public function __construct($name, $options = array()) {
global $CFG, $PAGE;
// Initialise member variables from constructor arguments.
$this->name = $name;
// Use specified context for permission checks, system context if not specified.
if (isset($options['accesscontext'])) {
$this->accesscontext = $options['accesscontext'];
} else {
$this->accesscontext = context_system::instance();
}
if (isset($options['extrafields'])) {
$this->extrafields = $options['extrafields'];
} else if (!empty($CFG->showuseridentity) &&
has_capability('moodle/site:viewuseridentity', $this->accesscontext)) {
$this->extrafields = explode(',', $CFG->showuseridentity);
} else {
$this->extrafields = array();
}
if (isset($options['exclude']) && is_array($options['exclude'])) {
$this->exclude = $options['exclude'];
}
if (isset($options['multiselect'])) {
$this->multiselect = $options['multiselect'];
}
// Read the user prefs / optional_params that we use.
$this->preserveselected = $this->initialise_option('userselector_preserveselected', $this->preserveselected);
$this->autoselectunique = $this->initialise_option('userselector_autoselectunique', $this->autoselectunique);
$this->searchanywhere = $this->initialise_option('userselector_searchanywhere', $this->searchanywhere);
if (!empty($CFG->maxusersperpage)) {
$this->maxusersperpage = $CFG->maxusersperpage;
}
}
/**
* All to the list of user ids that this control will not select.
*
* For example, on the role assign page, we do not list the users who already have the role in question.
*
* @param array $arrayofuserids the user ids to exclude.
*/
public function exclude($arrayofuserids) {
$this->exclude = array_unique(array_merge($this->exclude, $arrayofuserids));
}
/**
* Clear the list of excluded user ids.
*/
public function clear_exclusions() {
$this->exclude = array();
}
/**
* Returns the list of user ids that this control will not select.
*
* @return array the list of user ids that this control will not select.
*/
public function get_exclusions() {
return clone($this->exclude);
}
/**
* The users that were selected.
*
* This is a more sophisticated version of optional_param($this->name, array(), PARAM_INT) that validates the
* returned list of ids against the rules for this user selector.
*
* @return array of user objects.
*/
public function get_selected_users() {
// Do a lazy load.
if (is_null($this->selected)) {
$this->selected = $this->load_selected_users();
}
return $this->selected;
}
/**
* Convenience method for when multiselect is false (throws an exception if not).
*
* @throws moodle_exception
* @return object the selected user object, or null if none.
*/
public function get_selected_user() {
if ($this->multiselect) {
throw new moodle_exception('cannotcallusgetselecteduser');
}
$users = $this->get_selected_users();
if (count($users) == 1) {
return reset($users);
} else if (count($users) == 0) {
return null;
} else {
throw new moodle_exception('userselectortoomany');
}
}
/**
* Invalidates the list of selected users.
*
* If you update the database in such a way that it is likely to change the
* list of users that this component is allowed to select from, then you
* must call this method. For example, on the role assign page, after you have
* assigned some roles to some users, you should call this.
*/
public function invalidate_selected_users() {
$this->selected = null;
}
/**
* Output this user_selector as HTML.
*
* @param boolean $return if true, return the HTML as a string instead of outputting it.
* @return mixed if $return is true, returns the HTML as a string, otherwise returns nothing.
*/
public function display($return = false) {
global $PAGE;
// Get the list of requested users.
$search = optional_param($this->name . '_searchtext', '', PARAM_RAW);
if (optional_param($this->name . '_clearbutton', false, PARAM_BOOL)) {
$search = '';
}
$groupedusers = $this->find_users($search);
// Output the select.
$name = $this->name;
$multiselect = '';
if ($this->multiselect) {
$name .= '[]';
$multiselect = 'multiple="multiple" ';
}
$output = '
\n\n";
// Initialise the ajax functionality.
$output .= $this->initialise_javascript($search);
// Return or output it.
if ($return) {
return $output;
} else {
echo $output;
}
}
/**
* The height this control will be displayed, in rows.
*
* @param integer $numrows the desired height.
*/
public function set_rows($numrows) {
$this->rows = $numrows;
}
/**
* Returns the number of rows to display in this control.
*
* @return integer the height this control will be displayed, in rows.
*/
public function get_rows() {
return $this->rows;
}
/**
* Whether this control will allow selection of many, or just one user.
*
* @param boolean $multiselect true = allow multiple selection.
*/
public function set_multiselect($multiselect) {
$this->multiselect = $multiselect;
}
/**
* Returns true is multiselect should be allowed.
*
* @return boolean whether this control will allow selection of more than one user.
*/
public function is_multiselect() {
return $this->multiselect;
}
/**
* Returns the id/name of this control.
*
* @return string the id/name that this control will have in the HTML.
*/
public function get_name() {
return $this->name;
}
/**
* Set the user fields that are displayed in the selector in addition to the user's name.
*
* @param array $fields a list of field names that exist in the user table.
*/
public function set_extra_fields($fields) {
$this->extrafields = $fields;
}
/**
* Search the database for users matching the $search string, and any other
* conditions that apply. The SQL for testing whether a user matches the
* search string should be obtained by calling the search_sql method.
*
* This method is used both when getting the list of choices to display to
* the user, and also when validating a list of users that was selected.
*
* When preparing a list of users to choose from ($this->is_validating()
* return false) you should probably have an maximum number of users you will
* return, and if more users than this match your search, you should instead
* return a message generated by the too_many_results() method. However, you
* should not do this when validating.
*
* If you are writing a new user_selector subclass, I strongly recommend you
* look at some of the subclasses later in this file and in admin/roles/lib.php.
* They should help you see exactly what you have to do.
*
* @param string $search the search string.
* @return array An array of arrays of users. The array keys of the outer
* array should be the string names of optgroups. The keys of the inner
* arrays should be userids, and the values should be user objects
* containing at least the list of fields returned by the method
* required_fields_sql(). If a user object has a ->disabled property
* that is true, then that option will be displayed greyed out, and
* will not be returned by get_selected_users.
*/
public abstract function find_users($search);
/**
*
* Note: this function must be implemented if you use the search ajax field
* (e.g. set $options['file'] = '/admin/filecontainingyourclass.php';)
* @return array the options needed to recreate this user_selector.
*/
protected function get_options() {
return array(
'class' => get_class($this),
'name' => $this->name,
'exclude' => $this->exclude,
'extrafields' => $this->extrafields,
'multiselect' => $this->multiselect,
'accesscontext' => $this->accesscontext,
);
}
/**
* Returns true if this control is validating a list of users.
*
* @return boolean if true, we are validating a list of selected users,
* rather than preparing a list of uesrs to choose from.
*/
protected function is_validating() {
return !is_null($this->validatinguserids);
}
/**
* Get the list of users that were selected by doing optional_param then validating the result.
*
* @return array of user objects.
*/
protected function load_selected_users() {
// See if we got anything.
if ($this->multiselect) {
$userids = optional_param_array($this->name, array(), PARAM_INT);
} else if ($userid = optional_param($this->name, 0, PARAM_INT)) {
$userids = array($userid);
}
// If there are no users there is nobody to load.
if (empty($userids)) {
return array();
}
// If we did, use the find_users method to validate the ids.
$this->validatinguserids = $userids;
$groupedusers = $this->find_users('');
$this->validatinguserids = null;
// Aggregate the resulting list back into a single one.
$users = array();
foreach ($groupedusers as $group) {
foreach ($group as $user) {
if (!isset($users[$user->id]) && empty($user->disabled) && in_array($user->id, $userids)) {
$users[$user->id] = $user;
}
}
}
// If we are only supposed to be selecting a single user, make sure we do.
if (!$this->multiselect && count($users) > 1) {
$users = array_slice($users, 0, 1);
}
return $users;
}
/**
* Returns SQL to select required fields.
*
* @param string $u the table alias for the user table in the query being
* built. May be ''.
* @return string fragment of SQL to go in the select list of the query.
*/
protected function required_fields_sql($u) {
// Raw list of fields.
$fields = array('id');
// Add additional name fields.
$fields = array_merge($fields, get_all_user_name_fields(), $this->extrafields);
// Prepend the table alias.
if ($u) {
foreach ($fields as &$field) {
$field = $u . '.' . $field;
}
}
return implode(',', $fields);
}
/**
* Returns an array with SQL to perform a search and the params that go into it.
*
* @param string $search the text to search for.
* @param string $u the table alias for the user table in the query being
* built. May be ''.
* @return array an array with two elements, a fragment of SQL to go in the
* where clause the query, and an array containing any required parameters.
* this uses ? style placeholders.
*/
protected function search_sql($search, $u) {
return users_search_sql($search, $u, $this->searchanywhere, $this->extrafields,
$this->exclude, $this->validatinguserids);
}
/**
* Used to generate a nice message when there are too many users to show.
*
* The message includes the number of users that currently match, and the
* text of the message depends on whether the search term is non-blank.
*
* @param string $search the search term, as passed in to the find users method.
* @param int $count the number of users that currently match.
* @return array in the right format to return from the find_users method.
*/
protected function too_many_results($search, $count) {
if ($search) {
$a = new stdClass;
$a->count = $count;
$a->search = $search;
return array(get_string('toomanyusersmatchsearch', '', $a) => array(),
get_string('pleasesearchmore') => array());
} else {
return array(get_string('toomanyuserstoshow', '', $count) => array(),
get_string('pleaseusesearch') => array());
}
}
/**
* Output the list of