Skip to content

Instantly share code, notes, and snippets.

@fabiomsouto
Created May 7, 2012 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fabiomsouto/2628358 to your computer and use it in GitHub Desktop.
Save fabiomsouto/2628358 to your computer and use it in GitHub Desktop.
get_users attempt with fullname/email search
<?php
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.3
*/
public static function get_users_parameters() {
return new external_function_parameters(
array(
'criteria' => new external_multiple_structure(
new external_single_structure(
array(
'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
"id" (int) the user id,
"firstname" (string) the user first name (ATTENTION: searching by name can be extremely slow!),
"lastname" (string) the user last name (ATTENTION: searching by name can be extremely slow!)
"idnumber" (string) the user idnumber,
"username" (string) the user username,
"email" (string) the user email,
"auth" (plugin) the user auth plugin'),
'value' => new external_value(PARAM_RAW, 'the value to match')
)
), VALUE_DEFAULT, array()
, 'the key/value pairs to be considered in user search. If several are specified, they will be AND\'ed together')
)
);
}
/**
* Get user information, filtered by key/value pairs.
* If several key/value pairs are specified, the underlying query will join search for them
* AND'ed together.
*
* @param array $criteria key/value pairs to consider in user search, AND'ed together.
* @return array An array of arrays containg user profiles that match the given criteria.
* @since Moodle 2.3
*/
public static function get_users($criteria = array()) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
$params = self::validate_parameters(self::get_users_parameters(), array('criteria' => $criteria));
// This array will keep all the users that are allowed to be searched, according to the current user's privileges.
$allowedusers = array();
// This array will keep the results to be returned.
$result = array();
if (!empty($params['criteria'])) {
$conditions = array();
$wheres = array();
$siteadmin = is_siteadmin($USER);
// First we build a list of users that are allowed to be searched.
foreach ($params['criteria'] as $crit) {
$key = trim($crit['key']);
// Trying to avoid duplicate keys.
if (!isset($conditions[$key])) {
$value = null;
switch($key) {
case 'id':
$value = clean_param($crit['value'], PARAM_INT);
// We add the users since later the function that gets user details will perform complex capability checks.
$returnedusers = $DB->get_records('user', array('id' => $value));
$allowedusers = $allowedusers + $returnedusers;
break;
case 'idnumber':
if (has_capability('moodle/user:update', context_system::instance())) {
$value = clean_param($crit['value'], PARAM_RAW);
$returnedusers = $DB->get_records('user', array('idnumber' => $value));
$allowedusers = $allowedusers + $returnedusers;
}
else {
throw new moodle_exception('nocapabilitytouseparameter', 'webservice', '', $key);
}
break;
case 'username':
if ($siteadmin || ($USER->username == $value)) {
$value = clean_param($crit['value'], PARAM_USERNAME);
$returnedusers = $DB->get_records('user', array('username' => $value));
$allowedusers = $allowedusers + $returnedusers;
}
else {
throw new moodle_exception('nocapabilitytouseparameter', 'webservice', '', $key);
}
break;
case 'fullname':
// Do not set value because search by fullname is a special case.
$searchfullname = clean_param($crit['value'], PARAM_NOTAGS);
$fullname = $DB->sql_fullname();
$returnedusers = $DB->get_records_select('user', $DB->sql_like($fullname, ':searchfullname', false), array('searchfullname' => "$searchfullname%"));
$allowedusers = $allowedusers + $returnedusers;
break;
case 'email':
// Do not set value because search by username is a special case.
$searchemail = clean_param($crit['value'], PARAM_EMAIL);
// We add the users since later the function that gets user details will perform complex capability checks.
$returnedusers = $DB->get_records_select('user', $DB->sql_like('email', ':searchemail', false), array('searchemail' => "$searchemail%"));
$allowedusers = $allowedusers + $returnedusers;
break;
case 'auth':
if (has_capability('moodle/user:update', context_system::instance())) {
$value = clean_param($crit['value'], PARAM_PLUGIN);
$returnedusers = $DB->get_records('user', array('idnumber' => $value));
$allowedusers = $allowedusers + $returnedusers;
}
else {
throw new moodle_exception('nocapabilitytouseparameter', 'webservice', '', $key);
}
break;
default:
throw new moodle_exception('invalidextparam', 'webservice', '', $key);
}
if (isset($value)) {
$conditions[$key] = $crit['value'];
$wheres[] = $key . " = :" . $key;
}
}
}
}
// The following query is performed to save multiple get_context_instance SQL requests.
list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
if (!empty($wheres)) {
$wheres = implode(" AND ", $wheres);
list($uin, $uparams) = $DB->get_in_or_equal(array_keys($allowedusers), SQL_PARAMS_NAMED);
$conditions = array_merge($conditions, $uparams);
$usersql = "SELECT u.* $uselect
FROM {user} u $ujoin
WHERE u.id $uin AND $wheres";
if (!empty($searchemail)) {
$searchemail = trim($searchemail);
$usersql .= " AND ".$DB->sql_like('email', ':searchemail', false);
$conditions['searchemail'] = "$searchemail%";
}
if (!empty($searchfullname)) {
$fullname = $DB->sql_fullname();
$searchfullname = trim($searchfullname);
$usersql .= " AND ".$DB->sql_like($fullname, ':searchfullname', false);
$conditions['searchfullname'] = "$searchfullname%";
}
$usersql .= " ORDER BY u.username ASC";
} else {
$usersql = "SELECT u.* $uselect
FROM {user} u $ujoin
ORDER BY username ASC";
}
$users = $DB->get_recordset_sql($usersql, $conditions);
foreach ($users as $user) {
context_helper::preload_from_record($user);
$usercontext = context_user::instance($user->id);
self::validate_context($usercontext);
$userdetails = user_get_user_details_courses($user);
if ($userdetails != null) {
// Fields matching permissions from /user/editadvanced.php.
$hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
$currentuser = ($user->id == $USER->id);
if ($currentuser or $hasuserupdatecap) {
$userarray['auth'] = $user->auth;
$userarray['confirmed'] = $user->confirmed;
$userarray['idnumber'] = $user->idnumber;
$userarray['lang'] = $user->lang;
$userarray['theme'] = $user->theme;
$userarray['timezone'] = $user->timezone;
$userarray['mailformat'] = $user->mailformat;
}
$result[] = $userdetails;
}
}
return $result;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.3
*/
public static function get_users_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
'confirmed' => new external_value(PARAM_NUMBER, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
'customfields' => new external_multiple_structure(
new external_single_structure(
array(
'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
)
), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
'preferences' => new external_multiple_structure(
new external_single_structure(
array(
'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
)
), 'User preferences', VALUE_OPTIONAL)
)
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment