Skip to content

Commit

Permalink
MDL-67748 user: Add a new core_user_search_identity external function
Browse files Browse the repository at this point in the history
The purpose of this external function is to provide data for
asynchronous user selectors and similar widgets. It allows to search
users matching the given query in their name or other available identity
fields.
  • Loading branch information
mudrd8mz committed Mar 15, 2021
1 parent 614036d commit f51d3a8
Show file tree
Hide file tree
Showing 5 changed files with 293 additions and 2 deletions.
11 changes: 10 additions & 1 deletion lib/db/services.php
Expand Up @@ -1740,12 +1740,21 @@
'methodname' => 'get_users_by_field',
'classpath' => 'user/externallib.php',
'description' => 'Retrieve users\' information for a specified unique field - If you want to do a user search, use '
. 'core_user_get_users()',
. 'core_user_get_users() or core_user_search_identity().',
'type' => 'read',
'capabilities' => 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update',
'ajax' => true,
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE),
),
'core_user_search_identity' => array(
'classname' => '\core_user\external\search_identity',
'methodname' => 'execute',
'description' => 'Return list of users identities matching the given criteria in their name or other identity fields.',
'type' => 'read',
'capabilities' => 'moodle/user:viewalldetails',
'ajax' => true,
'loginrequired' => true,
),
'core_user_remove_user_device' => array(
'classname' => 'core_user_external',
'methodname' => 'remove_user_device',
Expand Down
131 changes: 131 additions & 0 deletions user/classes/external/search_identity.php
@@ -0,0 +1,131 @@
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.

namespace core_user\external;

/**
* Provides the core_user_search_identity external function.
*
* @package core_user
* @category external
* @copyright 2021 David Mudrák <david@moodle.com>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class search_identity extends \external_api {

/**
* Describes the external function parameters.
*
* @return external_function_parameters
*/
public static function execute_parameters(): \external_function_parameters {

return new \external_function_parameters([
'query' => new \external_value(PARAM_TEXT, 'The search query', VALUE_REQUIRED),
]);
}

/**
* Finds users with the identity matching the given query.
*
* @param string $query The search request.
* @return array
*/
public static function execute(string $query): array {
global $DB, $CFG;

$params = \external_api::validate_parameters(self::execute_parameters(), [
'query' => $query,
]);
$query = $params['query'];

// Validate context.
$context = \context_system::instance();
self::validate_context($context);
require_capability('moodle/user:viewalldetails', $context);

$hasviewfullnames = has_capability('moodle/site:viewfullnames', $context);

$fields = \core\user_fields::for_name()->with_identity($context, false);
$extrafields = $fields->get_required_fields([\core\user_fields::PURPOSE_IDENTITY]);

list($searchsql, $searchparams) = users_search_sql($query, '', true, $extrafields);
list($sortsql, $sortparams) = users_order_by_sql('', $query, $context);
$params = array_merge($searchparams, $sortparams);

$rs = $DB->get_recordset_select('user', $searchsql, $params, $sortsql,
'id' . $fields->get_sql()->selects, 0, $CFG->maxusersperpage + 1);

$count = 0;
$list = [];

foreach ($rs as $record) {
$user = (object)[
'id' => $record->id,
'fullname' => fullname($record, $hasviewfullnames),
'extrafields' => [],
];

foreach ($extrafields as $extrafield) {
// Sanitize the extra fields to prevent potential XSS exploit.
$user->extrafields[] = (object)[
'name' => $extrafield,
'value' => s($record->$extrafield)
];
}

$count++;

if ($count <= $CFG->maxusersperpage) {
$list[$record->id] = $user;
}
}

$rs->close();

return [
'list' => $list,
'maxusersperpage' => $CFG->maxusersperpage,
'overflow' => ($count > $CFG->maxusersperpage),
];
}

/**
* Describes the external function result value.
*
* @return external_description
*/
public static function execute_returns(): \external_description {

return new \external_single_structure([
'list' => new \external_multiple_structure(
new \external_single_structure([
'id' => new \external_value(\core_user::get_property_type('id'), 'ID of the user'),
// The output of the {@see fullname()} can contain formatting HTML such as <ruby> tags.
// So we need PARAM_RAW here and the caller is supposed to render it appropriately.
'fullname' => new \external_value(PARAM_RAW, 'The fullname of the user'),
'extrafields' => new \external_multiple_structure(
new \external_single_structure([
'name' => new \external_value(PARAM_TEXT, 'Name of the extrafield.'),
'value' => new \external_value(PARAM_TEXT, 'Value of the extrafield.'),
]), 'List of extra fields', VALUE_OPTIONAL)
])
),
'maxusersperpage' => new \external_value(PARAM_INT, 'Configured maximum users per page.'),
'overflow' => new \external_value(PARAM_BOOL, 'Were there more records than maxusersperpage found?'),
]);
}
}
145 changes: 145 additions & 0 deletions user/tests/externallib_test.php
Expand Up @@ -1538,4 +1538,149 @@ public function test_get_private_files_info_missing_permissions() {
// Try to retrieve other user private files info.
core_user_external::get_private_files_info($user2->id);
}

/**
* Test the functionality of the {@see \core_user\external\search_identity} class.
*/
public function test_external_search_identity() {
global $CFG;

$this->resetAfterTest(true);
$this->setAdminUser();

$user1 = self::getDataGenerator()->create_user([
'firstname' => 'Firstone',
'lastname' => 'Lastone',
'username' => 'usernameone',
'idnumber' => 'idnumberone',
'email' => 'userone@example.com',
'phone1' => 'tel1',
'phone2' => 'tel2',
'department' => 'Department Foo',
'institution' => 'Institution Foo',
'city' => 'City One',
'country' => 'AU',
]);

$user2 = self::getDataGenerator()->create_user([
'firstname' => 'Firsttwo',
'lastname' => 'Lasttwo',
'username' => 'usernametwo',
'idnumber' => 'idnumbertwo',
'email' => 'usertwo@example.com',
'phone1' => 'tel1',
'phone2' => 'tel2',
'department' => 'Department Foo',
'institution' => 'Institution Foo',
'city' => 'City One',
'country' => 'AU',
]);

$user3 = self::getDataGenerator()->create_user([
'firstname' => 'Firstthree',
'lastname' => 'Lastthree',
'username' => 'usernamethree',
'idnumber' => 'idnumberthree',
'email' => 'userthree@example.com',
'phone1' => 'tel1',
'phone2' => 'tel2',
'department' => 'Department Foo',
'institution' => 'Institution Foo',
'city' => 'City One',
'country' => 'AU',
]);

$CFG->showuseridentity = 'email,idnumber,city';
$CFG->maxusersperpage = 3;

$result = \core_user\external\search_identity::execute('Lastt');
$result = external_api::clean_returnvalue(\core_user\external\search_identity::execute_returns(), $result);

$this->assertEquals(2, count($result['list']));
$this->assertEquals(3, $result['maxusersperpage']);
$this->assertEquals(false, $result['overflow']);

foreach ($result['list'] as $user) {
$this->assertEquals(3, count($user['extrafields']));
$this->assertEquals('email', $user['extrafields'][0]['name']);
$this->assertEquals('idnumber', $user['extrafields'][1]['name']);
$this->assertEquals('city', $user['extrafields'][2]['name']);
}

$CFG->showuseridentity = 'username';
$CFG->maxusersperpage = 2;

$result = \core_user\external\search_identity::execute('Firstt');
$result = external_api::clean_returnvalue(\core_user\external\search_identity::execute_returns(), $result);

$this->assertEquals(2, count($result['list']));
$this->assertEquals(2, $result['maxusersperpage']);
$this->assertEquals(false, $result['overflow']);

foreach ($result['list'] as $user) {
$this->assertEquals(1, count($user['extrafields']));
$this->assertEquals('username', $user['extrafields'][0]['name']);
}

$CFG->showuseridentity = 'email';
$CFG->maxusersperpage = 2;

$result = \core_user\external\search_identity::execute('City One');
$result = external_api::clean_returnvalue(\core_user\external\search_identity::execute_returns(), $result);

$this->assertEquals(0, count($result['list']));
$this->assertEquals(2, $result['maxusersperpage']);
$this->assertEquals(false, $result['overflow']);

$CFG->showuseridentity = 'city';
$CFG->maxusersperpage = 2;

foreach ($result['list'] as $user) {
$this->assertEquals(1, count($user['extrafields']));
$this->assertEquals('username', $user['extrafields'][0]['name']);
}

$result = \core_user\external\search_identity::execute('City One');
$result = external_api::clean_returnvalue(\core_user\external\search_identity::execute_returns(), $result);

$this->assertEquals(2, count($result['list']));
$this->assertEquals(2, $result['maxusersperpage']);
$this->assertEquals(true, $result['overflow']);
}

/**
* Test functionality of the {@see \core_user\external\search_identity} class with alternativefullnameformat defined.
*/
public function test_external_search_identity_with_alternativefullnameformat() {
global $CFG;

$this->resetAfterTest(true);
$this->setAdminUser();

$user1 = self::getDataGenerator()->create_user([
'lastname' => '小柳',
'lastnamephonetic' => 'Koyanagi',
'firstname' => '秋',
'firstnamephonetic' => 'Aki',
'email' => 'koyanagiaki@example.com',
'country' => 'JP',
]);

$CFG->showuseridentity = 'email';
$CFG->maxusersperpage = 3;
$CFG->alternativefullnameformat =
'<ruby>lastname firstname <rp>(</rp><rt>lastnamephonetic firstnamephonetic</rt><rp>)</rp></ruby>';

$result = \core_user\external\search_identity::execute('Ak');
$result = external_api::clean_returnvalue(\core_user\external\search_identity::execute_returns(), $result);

$this->assertEquals(1, count($result['list']));
$this->assertEquals(3, $result['maxusersperpage']);
$this->assertEquals(false, $result['overflow']);

foreach ($result['list'] as $user) {
$this->assertEquals(1, count($user['extrafields']));
$this->assertEquals('email', $user['extrafields'][0]['name']);
}
}
}
6 changes: 6 additions & 0 deletions user/upgrade.txt
@@ -1,5 +1,11 @@
This files describes API changes for code that uses the user API.

=== 3.11 ===

* Added new external function core_user_external::search_identity(). The main purpose of this external function is to
provide data for asynchronous user selectors and similar widgets. It allows to search users matching the given query
in their name or other available identity fields.

=== 3.9 ===

* The unified filter has been replaced by the participants filter. The following have therefore been deprecated:
Expand Down
2 changes: 1 addition & 1 deletion version.php
Expand Up @@ -29,7 +29,7 @@

defined('MOODLE_INTERNAL') || die();

$version = 2021052500.68; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2021052500.69; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '4.0dev (Build: 20210312)'; // Human-friendly version name
Expand Down

0 comments on commit f51d3a8

Please sign in to comment.