PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/user/externallib.php

https://github.com/dongsheng/moodle
PHP | 2029 lines | 1334 code | 212 blank | 483 comment | 121 complexity | 8e3531ca9c98122b32176bea7291d636 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * External user API
  18. *
  19. * @package core_user
  20. * @category external
  21. * @copyright 2009 Petr Skodak
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. require_once("$CFG->libdir/externallib.php");
  26. /**
  27. * User external functions
  28. *
  29. * @package core_user
  30. * @category external
  31. * @copyright 2011 Jerome Mouneyrac
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. * @since Moodle 2.2
  34. */
  35. class core_user_external extends external_api {
  36. /**
  37. * Returns description of method parameters
  38. *
  39. * @return external_function_parameters
  40. * @since Moodle 2.2
  41. */
  42. public static function create_users_parameters() {
  43. global $CFG;
  44. $userfields = [
  45. 'createpassword' => new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.',
  46. VALUE_OPTIONAL),
  47. // General.
  48. 'username' => new external_value(core_user::get_property_type('username'),
  49. 'Username policy is defined in Moodle security config.'),
  50. 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
  51. VALUE_DEFAULT, 'manual', core_user::get_property_null('auth')),
  52. 'password' => new external_value(core_user::get_property_type('password'),
  53. 'Plain text password consisting of any characters', VALUE_OPTIONAL),
  54. 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
  55. 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
  56. 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
  57. 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
  58. 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
  59. 'country' => new external_value(core_user::get_property_type('country'),
  60. 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
  61. 'timezone' => new external_value(core_user::get_property_type('timezone'),
  62. 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
  63. 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
  64. VALUE_OPTIONAL),
  65. // Additional names.
  66. 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
  67. 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
  68. 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
  69. 'The family name phonetically of the user', VALUE_OPTIONAL),
  70. 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
  71. VALUE_OPTIONAL),
  72. 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
  73. VALUE_OPTIONAL),
  74. // Interests.
  75. 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
  76. // Optional.
  77. 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
  78. 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''),
  79. 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
  80. 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
  81. 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
  82. 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
  83. 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
  84. // Other user preferences stored in the user table.
  85. 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
  86. VALUE_DEFAULT, core_user::get_property_default('lang'), core_user::get_property_null('lang')),
  87. 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
  88. 'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
  89. 'theme' => new external_value(core_user::get_property_type('theme'),
  90. 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
  91. 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
  92. 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
  93. // Custom user profile fields.
  94. 'customfields' => new external_multiple_structure(
  95. new external_single_structure(
  96. [
  97. 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
  98. 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
  99. ]
  100. ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
  101. // User preferences.
  102. 'preferences' => new external_multiple_structure(
  103. new external_single_structure(
  104. [
  105. 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
  106. 'value' => new external_value(PARAM_RAW, 'The value of the preference')
  107. ]
  108. ), 'User preferences', VALUE_OPTIONAL),
  109. ];
  110. return new external_function_parameters(
  111. [
  112. 'users' => new external_multiple_structure(
  113. new external_single_structure($userfields)
  114. )
  115. ]
  116. );
  117. }
  118. /**
  119. * Create one or more users.
  120. *
  121. * @throws invalid_parameter_exception
  122. * @param array $users An array of users to create.
  123. * @return array An array of arrays
  124. * @since Moodle 2.2
  125. */
  126. public static function create_users($users) {
  127. global $CFG, $DB;
  128. require_once($CFG->dirroot."/lib/weblib.php");
  129. require_once($CFG->dirroot."/user/lib.php");
  130. require_once($CFG->dirroot."/user/editlib.php");
  131. require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
  132. // Ensure the current user is allowed to run this function.
  133. $context = context_system::instance();
  134. self::validate_context($context);
  135. require_capability('moodle/user:create', $context);
  136. // Do basic automatic PARAM checks on incoming data, using params description.
  137. // If any problems are found then exceptions are thrown with helpful error messages.
  138. $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
  139. $availableauths = core_component::get_plugin_list('auth');
  140. unset($availableauths['mnet']); // These would need mnethostid too.
  141. unset($availableauths['webservice']); // We do not want new webservice users for now.
  142. $availablethemes = core_component::get_plugin_list('theme');
  143. $availablelangs = get_string_manager()->get_list_of_translations();
  144. $transaction = $DB->start_delegated_transaction();
  145. $userids = array();
  146. foreach ($params['users'] as $user) {
  147. // Make sure that the username, firstname and lastname are not blank.
  148. foreach (array('username', 'firstname', 'lastname') as $fieldname) {
  149. if (trim($user[$fieldname]) === '') {
  150. throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank');
  151. }
  152. }
  153. // Make sure that the username doesn't already exist.
  154. if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
  155. throw new invalid_parameter_exception('Username already exists: '.$user['username']);
  156. }
  157. // Make sure auth is valid.
  158. if (empty($availableauths[$user['auth']])) {
  159. throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
  160. }
  161. // Make sure lang is valid.
  162. if (empty($availablelangs[$user['lang']])) {
  163. throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
  164. }
  165. // Make sure lang is valid.
  166. if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
  167. // so no default value
  168. // We need to test if the client sent it
  169. // => !empty($user['theme']).
  170. throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
  171. }
  172. // Make sure we have a password or have to create one.
  173. $authplugin = get_auth_plugin($user['auth']);
  174. if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) {
  175. throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.');
  176. }
  177. $user['confirmed'] = true;
  178. $user['mnethostid'] = $CFG->mnet_localhost_id;
  179. // Start of user info validation.
  180. // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
  181. if (!validate_email($user['email'])) {
  182. throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
  183. } else if (empty($CFG->allowaccountssameemail)) {
  184. // Make a case-insensitive query for the given email address.
  185. $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
  186. $params = array(
  187. 'email' => $user['email'],
  188. 'mnethostid' => $user['mnethostid']
  189. );
  190. // If there are other user(s) that already have the same email, throw an error.
  191. if ($DB->record_exists_select('user', $select, $params)) {
  192. throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
  193. }
  194. }
  195. // End of user info validation.
  196. $createpassword = !empty($user['createpassword']);
  197. unset($user['createpassword']);
  198. $updatepassword = false;
  199. if ($authplugin->is_internal()) {
  200. if ($createpassword) {
  201. $user['password'] = '';
  202. } else {
  203. $updatepassword = true;
  204. }
  205. } else {
  206. $user['password'] = AUTH_PASSWORD_NOT_CACHED;
  207. }
  208. // Create the user data now!
  209. $user['id'] = user_create_user($user, $updatepassword, false);
  210. $userobject = (object)$user;
  211. // Set user interests.
  212. if (!empty($user['interests'])) {
  213. $trimmedinterests = array_map('trim', explode(',', $user['interests']));
  214. $interests = array_filter($trimmedinterests, function($value) {
  215. return !empty($value);
  216. });
  217. useredit_update_interests($userobject, $interests);
  218. }
  219. // Custom fields.
  220. if (!empty($user['customfields'])) {
  221. foreach ($user['customfields'] as $customfield) {
  222. // Profile_save_data() saves profile file it's expecting a user with the correct id,
  223. // and custom field to be named profile_field_"shortname".
  224. $user["profile_field_".$customfield['type']] = $customfield['value'];
  225. }
  226. profile_save_data((object) $user);
  227. }
  228. if ($createpassword) {
  229. setnew_password_and_mail($userobject);
  230. unset_user_preference('create_password', $userobject);
  231. set_user_preference('auth_forcepasswordchange', 1, $userobject);
  232. }
  233. // Trigger event.
  234. \core\event\user_created::create_from_userid($user['id'])->trigger();
  235. // Preferences.
  236. if (!empty($user['preferences'])) {
  237. $userpref = (object)$user;
  238. foreach ($user['preferences'] as $preference) {
  239. $userpref->{'preference_'.$preference['type']} = $preference['value'];
  240. }
  241. useredit_update_user_preference($userpref);
  242. }
  243. $userids[] = array('id' => $user['id'], 'username' => $user['username']);
  244. }
  245. $transaction->allow_commit();
  246. return $userids;
  247. }
  248. /**
  249. * Returns description of method result value
  250. *
  251. * @return external_description
  252. * @since Moodle 2.2
  253. */
  254. public static function create_users_returns() {
  255. return new external_multiple_structure(
  256. new external_single_structure(
  257. array(
  258. 'id' => new external_value(core_user::get_property_type('id'), 'user id'),
  259. 'username' => new external_value(core_user::get_property_type('username'), 'user name'),
  260. )
  261. )
  262. );
  263. }
  264. /**
  265. * Returns description of method parameters
  266. *
  267. * @return external_function_parameters
  268. * @since Moodle 2.2
  269. */
  270. public static function delete_users_parameters() {
  271. return new external_function_parameters(
  272. array(
  273. 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')),
  274. )
  275. );
  276. }
  277. /**
  278. * Delete users
  279. *
  280. * @throws moodle_exception
  281. * @param array $userids
  282. * @return null
  283. * @since Moodle 2.2
  284. */
  285. public static function delete_users($userids) {
  286. global $CFG, $DB, $USER;
  287. require_once($CFG->dirroot."/user/lib.php");
  288. // Ensure the current user is allowed to run this function.
  289. $context = context_system::instance();
  290. require_capability('moodle/user:delete', $context);
  291. self::validate_context($context);
  292. $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids));
  293. $transaction = $DB->start_delegated_transaction();
  294. foreach ($params['userids'] as $userid) {
  295. $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
  296. // Must not allow deleting of admins or self!!!
  297. if (is_siteadmin($user)) {
  298. throw new moodle_exception('useradminodelete', 'error');
  299. }
  300. if ($USER->id == $user->id) {
  301. throw new moodle_exception('usernotdeletederror', 'error');
  302. }
  303. user_delete_user($user);
  304. }
  305. $transaction->allow_commit();
  306. return null;
  307. }
  308. /**
  309. * Returns description of method result value
  310. *
  311. * @return null
  312. * @since Moodle 2.2
  313. */
  314. public static function delete_users_returns() {
  315. return null;
  316. }
  317. /**
  318. * Returns description of method parameters.
  319. *
  320. * @return external_function_parameters
  321. * @since Moodle 3.2
  322. */
  323. public static function update_user_preferences_parameters() {
  324. return new external_function_parameters(
  325. array(
  326. 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
  327. 'emailstop' => new external_value(core_user::get_property_type('emailstop'),
  328. 'Enable or disable notifications for this user', VALUE_DEFAULT, null),
  329. 'preferences' => new external_multiple_structure(
  330. new external_single_structure(
  331. array(
  332. 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
  333. 'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you
  334. want to remove (unset) the current value.', VALUE_DEFAULT, null),
  335. )
  336. ), 'User preferences', VALUE_DEFAULT, array()
  337. )
  338. )
  339. );
  340. }
  341. /**
  342. * Update the user's preferences.
  343. *
  344. * @param int $userid
  345. * @param bool|null $emailstop
  346. * @param array $preferences
  347. * @return null
  348. * @since Moodle 3.2
  349. */
  350. public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
  351. global $USER, $CFG;
  352. require_once($CFG->dirroot . '/user/lib.php');
  353. require_once($CFG->dirroot . '/user/editlib.php');
  354. require_once($CFG->dirroot . '/message/lib.php');
  355. if (empty($userid)) {
  356. $userid = $USER->id;
  357. }
  358. $systemcontext = context_system::instance();
  359. self::validate_context($systemcontext);
  360. $params = array(
  361. 'userid' => $userid,
  362. 'emailstop' => $emailstop,
  363. 'preferences' => $preferences
  364. );
  365. $params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
  366. $preferences = $params['preferences'];
  367. // Preferences.
  368. if (!empty($preferences)) {
  369. $userpref = ['id' => $userid];
  370. foreach ($preferences as $preference) {
  371. $userpref['preference_' . $preference['type']] = $preference['value'];
  372. }
  373. useredit_update_user_preference($userpref);
  374. }
  375. // Check if they want to update the email.
  376. if ($emailstop !== null) {
  377. $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
  378. core_user::require_active_user($otheruser);
  379. if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
  380. $user = new stdClass();
  381. $user->id = $userid;
  382. $user->emailstop = $emailstop;
  383. user_update_user($user);
  384. // Update the $USER if we should.
  385. if ($userid == $USER->id) {
  386. $USER->emailstop = $emailstop;
  387. }
  388. }
  389. }
  390. return null;
  391. }
  392. /**
  393. * Returns description of method result value
  394. *
  395. * @return null
  396. * @since Moodle 3.2
  397. */
  398. public static function update_user_preferences_returns() {
  399. return null;
  400. }
  401. /**
  402. * Returns description of method parameters
  403. *
  404. * @return external_function_parameters
  405. * @since Moodle 2.2
  406. */
  407. public static function update_users_parameters() {
  408. $userfields = [
  409. 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
  410. // General.
  411. 'username' => new external_value(core_user::get_property_type('username'),
  412. 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  413. 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc',
  414. VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  415. 'suspended' => new external_value(core_user::get_property_type('suspended'),
  416. 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
  417. 'password' => new external_value(core_user::get_property_type('password'),
  418. 'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  419. 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user',
  420. VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  421. 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user',
  422. VALUE_OPTIONAL),
  423. 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL,
  424. '', NULL_NOT_ALLOWED),
  425. 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email display', VALUE_OPTIONAL),
  426. 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
  427. 'country' => new external_value(core_user::get_property_type('country'),
  428. 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
  429. 'timezone' => new external_value(core_user::get_property_type('timezone'),
  430. 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
  431. 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML',
  432. VALUE_OPTIONAL),
  433. // User picture.
  434. 'userpicture' => new external_value(PARAM_INT,
  435. 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL),
  436. // Additional names.
  437. 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'),
  438. 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
  439. 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'),
  440. 'The family name phonetically of the user', VALUE_OPTIONAL),
  441. 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user',
  442. VALUE_OPTIONAL),
  443. 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user',
  444. VALUE_OPTIONAL),
  445. // Interests.
  446. 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL),
  447. // Optional.
  448. 'idnumber' => new external_value(core_user::get_property_type('idnumber'),
  449. 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
  450. 'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL),
  451. 'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL),
  452. 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL),
  453. 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL),
  454. 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
  455. // Other user preferences stored in the user table.
  456. 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server',
  457. VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  458. 'calendartype' => new external_value(core_user::get_property_type('calendartype'),
  459. 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED),
  460. 'theme' => new external_value(core_user::get_property_type('theme'),
  461. 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
  462. 'mailformat' => new external_value(core_user::get_property_type('mailformat'),
  463. 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
  464. // Custom user profile fields.
  465. 'customfields' => new external_multiple_structure(
  466. new external_single_structure(
  467. [
  468. 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
  469. 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
  470. ]
  471. ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
  472. // User preferences.
  473. 'preferences' => new external_multiple_structure(
  474. new external_single_structure(
  475. [
  476. 'type' => new external_value(PARAM_RAW, 'The name of the preference'),
  477. 'value' => new external_value(PARAM_RAW, 'The value of the preference')
  478. ]
  479. ), 'User preferences', VALUE_OPTIONAL),
  480. ];
  481. return new external_function_parameters(
  482. [
  483. 'users' => new external_multiple_structure(
  484. new external_single_structure($userfields)
  485. )
  486. ]
  487. );
  488. }
  489. /**
  490. * Update users
  491. *
  492. * @param array $users
  493. * @return null
  494. * @since Moodle 2.2
  495. */
  496. public static function update_users($users) {
  497. global $CFG, $DB, $USER;
  498. require_once($CFG->dirroot."/user/lib.php");
  499. require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
  500. require_once($CFG->dirroot.'/user/editlib.php');
  501. // Ensure the current user is allowed to run this function.
  502. $context = context_system::instance();
  503. require_capability('moodle/user:update', $context);
  504. self::validate_context($context);
  505. $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users));
  506. $filemanageroptions = array('maxbytes' => $CFG->maxbytes,
  507. 'subdirs' => 0,
  508. 'maxfiles' => 1,
  509. 'accepted_types' => 'optimised_image');
  510. $warnings = array();
  511. foreach ($params['users'] as $user) {
  512. // Catch any exception while updating a user and return it as a warning.
  513. try {
  514. $transaction = $DB->start_delegated_transaction();
  515. // First check the user exists.
  516. if (!$existinguser = core_user::get_user($user['id'])) {
  517. throw new moodle_exception('invaliduserid', '', '', null,
  518. 'Invalid user ID');
  519. }
  520. // Check if we are trying to update an admin.
  521. if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) {
  522. throw new moodle_exception('usernotupdatedadmin', '', '', null,
  523. 'Cannot update admin accounts');
  524. }
  525. // Other checks (deleted, remote or guest users).
  526. if ($existinguser->deleted) {
  527. throw new moodle_exception('usernotupdateddeleted', '', '', null,
  528. 'User is a deleted user');
  529. }
  530. if (is_mnet_remote_user($existinguser)) {
  531. throw new moodle_exception('usernotupdatedremote', '', '', null,
  532. 'User is a remote user');
  533. }
  534. if (isguestuser($existinguser->id)) {
  535. throw new moodle_exception('usernotupdatedguest', '', '', null,
  536. 'Cannot update guest account');
  537. }
  538. // Check duplicated emails.
  539. if (isset($user['email']) && $user['email'] !== $existinguser->email) {
  540. if (!validate_email($user['email'])) {
  541. throw new moodle_exception('useremailinvalid', '', '', null,
  542. 'Invalid email address');
  543. } else if (empty($CFG->allowaccountssameemail)) {
  544. // Make a case-insensitive query for the given email address
  545. // and make sure to exclude the user being updated.
  546. $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid';
  547. $params = array(
  548. 'email' => $user['email'],
  549. 'mnethostid' => $CFG->mnet_localhost_id,
  550. 'userid' => $user['id']
  551. );
  552. // Skip if there are other user(s) that already have the same email.
  553. if ($DB->record_exists_select('user', $select, $params)) {
  554. throw new moodle_exception('useremailduplicate', '', '', null,
  555. 'Duplicate email address');
  556. }
  557. }
  558. }
  559. user_update_user($user, true, false);
  560. $userobject = (object)$user;
  561. // Update user picture if it was specified for this user.
  562. if (empty($CFG->disableuserimages) && isset($user['userpicture'])) {
  563. $userobject->deletepicture = null;
  564. if ($user['userpicture'] == 0) {
  565. $userobject->deletepicture = true;
  566. } else {
  567. $userobject->imagefile = $user['userpicture'];
  568. }
  569. core_user::update_picture($userobject, $filemanageroptions);
  570. }
  571. // Update user interests.
  572. if (!empty($user['interests'])) {
  573. $trimmedinterests = array_map('trim', explode(',', $user['interests']));
  574. $interests = array_filter($trimmedinterests, function($value) {
  575. return !empty($value);
  576. });
  577. useredit_update_interests($userobject, $interests);
  578. }
  579. // Update user custom fields.
  580. if (!empty($user['customfields'])) {
  581. foreach ($user['customfields'] as $customfield) {
  582. // Profile_save_data() saves profile file it's expecting a user with the correct id,
  583. // and custom field to be named profile_field_"shortname".
  584. $user["profile_field_".$customfield['type']] = $customfield['value'];
  585. }
  586. profile_save_data((object) $user);
  587. }
  588. // Trigger event.
  589. \core\event\user_updated::create_from_userid($user['id'])->trigger();
  590. // Preferences.
  591. if (!empty($user['preferences'])) {
  592. $userpref = clone($existinguser);
  593. foreach ($user['preferences'] as $preference) {
  594. $userpref->{'preference_'.$preference['type']} = $preference['value'];
  595. }
  596. useredit_update_user_preference($userpref);
  597. }
  598. if (isset($user['suspended']) and $user['suspended']) {
  599. \core\session\manager::kill_user_sessions($user['id']);
  600. }
  601. $transaction->allow_commit();
  602. } catch (Exception $e) {
  603. try {
  604. $transaction->rollback($e);
  605. } catch (Exception $e) {
  606. $warning = [];
  607. $warning['item'] = 'user';
  608. $warning['itemid'] = $user['id'];
  609. if ($e instanceof moodle_exception) {
  610. $warning['warningcode'] = $e->errorcode;
  611. } else {
  612. $warning['warningcode'] = $e->getCode();
  613. }
  614. $warning['message'] = $e->getMessage();
  615. $warnings[] = $warning;
  616. }
  617. }
  618. }
  619. return ['warnings' => $warnings];
  620. }
  621. /**
  622. * Returns description of method result value
  623. *
  624. * @return external_description
  625. * @since Moodle 2.2
  626. */
  627. public static function update_users_returns() {
  628. return new external_single_structure(
  629. array(
  630. 'warnings' => new external_warnings()
  631. )
  632. );
  633. }
  634. /**
  635. * Returns description of method parameters
  636. *
  637. * @return external_function_parameters
  638. * @since Moodle 2.4
  639. */
  640. public static function get_users_by_field_parameters() {
  641. return new external_function_parameters(
  642. array(
  643. 'field' => new external_value(PARAM_ALPHA, 'the search field can be
  644. \'id\' or \'idnumber\' or \'username\' or \'email\''),
  645. 'values' => new external_multiple_structure(
  646. new external_value(PARAM_RAW, 'the value to match'))
  647. )
  648. );
  649. }
  650. /**
  651. * Get user information for a unique field.
  652. *
  653. * @throws coding_exception
  654. * @throws invalid_parameter_exception
  655. * @param string $field
  656. * @param array $values
  657. * @return array An array of arrays containg user profiles.
  658. * @since Moodle 2.4
  659. */
  660. public static function get_users_by_field($field, $values) {
  661. global $CFG, $USER, $DB;
  662. require_once($CFG->dirroot . "/user/lib.php");
  663. $params = self::validate_parameters(self::get_users_by_field_parameters(),
  664. array('field' => $field, 'values' => $values));
  665. // This array will keep all the users that are allowed to be searched,
  666. // according to the current user's privileges.
  667. $cleanedvalues = array();
  668. switch ($field) {
  669. case 'id':
  670. $paramtype = core_user::get_property_type('id');
  671. break;
  672. case 'idnumber':
  673. $paramtype = core_user::get_property_type('idnumber');
  674. break;
  675. case 'username':
  676. $paramtype = core_user::get_property_type('username');
  677. break;
  678. case 'email':
  679. $paramtype = core_user::get_property_type('email');
  680. break;
  681. default:
  682. throw new coding_exception('invalid field parameter',
  683. 'The search field \'' . $field . '\' is not supported, look at the web service documentation');
  684. }
  685. // Clean the values.
  686. foreach ($values as $value) {
  687. $cleanedvalue = clean_param($value, $paramtype);
  688. if ( $value != $cleanedvalue) {
  689. throw new invalid_parameter_exception('The field \'' . $field .
  690. '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')');
  691. }
  692. $cleanedvalues[] = $cleanedvalue;
  693. }
  694. // Retrieve the users.
  695. $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id');
  696. $context = context_system::instance();
  697. self::validate_context($context);
  698. // Finally retrieve each users information.
  699. $returnedusers = array();
  700. foreach ($users as $user) {
  701. $userdetails = user_get_user_details_courses($user);
  702. // Return the user only if the searched field is returned.
  703. // Otherwise it means that the $USER was not allowed to search the returned user.
  704. if (!empty($userdetails) and !empty($userdetails[$field])) {
  705. $returnedusers[] = $userdetails;
  706. }
  707. }
  708. return $returnedusers;
  709. }
  710. /**
  711. * Returns description of method result value
  712. *
  713. * @return external_multiple_structure
  714. * @since Moodle 2.4
  715. */
  716. public static function get_users_by_field_returns() {
  717. return new external_multiple_structure(self::user_description());
  718. }
  719. /**
  720. * Returns description of get_users() parameters.
  721. *
  722. * @return external_function_parameters
  723. * @since Moodle 2.5
  724. */
  725. public static function get_users_parameters() {
  726. return new external_function_parameters(
  727. array(
  728. 'criteria' => new external_multiple_structure(
  729. new external_single_structure(
  730. array(
  731. 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are:
  732. "id" (int) matching user id,
  733. "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!),
  734. "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!),
  735. "idnumber" (string) matching user idnumber,
  736. "username" (string) matching user username,
  737. "email" (string) user email (Note: you can use % for searching but it may be considerably slower!),
  738. "auth" (string) matching user auth plugin'),
  739. 'value' => new external_value(PARAM_RAW, 'the value to search')
  740. )
  741. ), 'the key/value pairs to be considered in user search. Values can not be empty.
  742. Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) -
  743. key occurences are forbidden.
  744. The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored,
  745. the search is still executed on the valid criterias.
  746. You can search without criteria, but the function is not designed for it.
  747. It could very slow or timeout. The function is designed to search some specific users.'
  748. )
  749. )
  750. );
  751. }
  752. /**
  753. * Retrieve matching user.
  754. *
  755. * @throws moodle_exception
  756. * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth.
  757. * @return array An array of arrays containing user profiles.
  758. * @since Moodle 2.5
  759. */
  760. public static function get_users($criteria = array()) {
  761. global $CFG, $USER, $DB;
  762. require_once($CFG->dirroot . "/user/lib.php");
  763. $params = self::validate_parameters(self::get_users_parameters(),
  764. array('criteria' => $criteria));
  765. // Validate the criteria and retrieve the users.
  766. $users = array();
  767. $warnings = array();
  768. $sqlparams = array();
  769. $usedkeys = array();
  770. // Do not retrieve deleted users.
  771. $sql = ' deleted = 0';
  772. foreach ($params['criteria'] as $criteriaindex => $criteria) {
  773. // Check that the criteria has never been used.
  774. if (array_key_exists($criteria['key'], $usedkeys)) {
  775. throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once');
  776. } else {
  777. $usedkeys[$criteria['key']] = true;
  778. }
  779. $invalidcriteria = false;
  780. // Clean the parameters.
  781. $paramtype = PARAM_RAW;
  782. switch ($criteria['key']) {
  783. case 'id':
  784. $paramtype = core_user::get_property_type('id');
  785. break;
  786. case 'idnumber':
  787. $paramtype = core_user::get_property_type('idnumber');
  788. break;
  789. case 'username':
  790. $paramtype = core_user::get_property_type('username');
  791. break;
  792. case 'email':
  793. // We use PARAM_RAW to allow searches with %.
  794. $paramtype = core_user::get_property_type('email');
  795. break;
  796. case 'auth':
  797. $paramtype = core_user::get_property_type('auth');
  798. break;
  799. case 'lastname':
  800. case 'firstname':
  801. $paramtype = core_user::get_property_type('firstname');
  802. break;
  803. default:
  804. // Send back a warning that this search key is not supported in this version.
  805. // This warning will make the function extandable without breaking clients.
  806. $warnings[] = array(
  807. 'item' => $criteria['key'],
  808. 'warningcode' => 'invalidfieldparameter',
  809. 'message' =>
  810. 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation'
  811. );
  812. // Do not add this invalid criteria to the created SQL request.
  813. $invalidcriteria = true;
  814. unset($params['criteria'][$criteriaindex]);
  815. break;
  816. }
  817. if (!$invalidcriteria) {
  818. $cleanedvalue = clean_param($criteria['value'], $paramtype);
  819. $sql .= ' AND ';
  820. // Create the SQL.
  821. switch ($criteria['key']) {
  822. case 'id':
  823. case 'idnumber':
  824. case 'username':
  825. case 'auth':
  826. $sql .= $criteria['key'] . ' = :' . $criteria['key'];
  827. $sqlparams[$criteria['key']] = $cleanedvalue;
  828. break;
  829. case 'email':
  830. case 'lastname':
  831. case 'firstname':
  832. $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false);
  833. $sqlparams[$criteria['key']] = $cleanedvalue;
  834. break;
  835. default:
  836. break;
  837. }
  838. }
  839. }
  840. $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC');
  841. // Finally retrieve each users information.
  842. $returnedusers = array();
  843. foreach ($users as $user) {
  844. $userdetails = user_get_user_details_courses($user);
  845. // Return the user only if all the searched fields are returned.
  846. // Otherwise it means that the $USER was not allowed to search the returned user.
  847. if (!empty($userdetails)) {
  848. $validuser = true;
  849. foreach ($params['criteria'] as $criteria) {
  850. if (empty($userdetails[$criteria['key']])) {
  851. $validuser = false;
  852. }
  853. }
  854. if ($validuser) {
  855. $returnedusers[] = $userdetails;
  856. }
  857. }
  858. }
  859. return array('users' => $returnedusers, 'warnings' => $warnings);
  860. }
  861. /**
  862. * Returns description of get_users result value.
  863. *
  864. * @return external_description
  865. * @since Moodle 2.5
  866. */
  867. public static function get_users_returns() {
  868. return new external_single_structure(
  869. array('users' => new external_multiple_structure(
  870. self::user_description()
  871. ),
  872. 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name')
  873. )
  874. );
  875. }
  876. /**
  877. * Returns description of method parameters
  878. *
  879. * @return external_function_parameters
  880. * @since Moodle 2.2
  881. */
  882. public static function get_course_user_profiles_parameters() {
  883. return new external_function_parameters(
  884. array(
  885. 'userlist' => new external_multiple_structure(
  886. new external_single_structure(
  887. array(
  888. 'userid' => new external_value(core_user::get_property_type('id'), 'userid'),
  889. 'courseid' => new external_value(PARAM_INT, 'courseid'),
  890. )
  891. )
  892. )
  893. )
  894. );
  895. }
  896. /**
  897. * Get course participant's details
  898. *
  899. * @param array $userlist array of user ids and according course ids
  900. * @return array An array of arrays describing course participants
  901. * @since Moodle 2.2
  902. */
  903. public static function get_course_user_profiles($userlist) {
  904. global $CFG, $USER, $DB;
  905. require_once($CFG->dirroot . "/user/lib.php");
  906. $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist));
  907. $userids = array();
  908. $courseids = array();
  909. foreach ($params['userlist'] as $value) {
  910. $userids[] = $value['userid'];
  911. $courseids[$value['userid']] = $value['courseid'];
  912. }
  913. // Cache all courses.
  914. $courses = array();
  915. list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED);
  916. $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  917. $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
  918. $params['contextlevel'] = CONTEXT_COURSE;
  919. $coursesql = "SELECT c.* $cselect
  920. FROM {course} c $cjoin
  921. WHERE c.id $sqlcourseids";
  922. $rs = $DB->get_recordset_sql($coursesql, $params);
  923. foreach ($rs as $course) {
  924. // Adding course contexts to cache.
  925. context_helper::preload_from_record($course);
  926. // Cache courses.
  927. $courses[$course->id] = $course;
  928. }
  929. $rs->close();
  930. list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
  931. $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  932. $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
  933. $params['contextlevel'] = CONTEXT_USER;
  934. $usersql = "SELECT u.* $uselect
  935. FROM {user} u $ujoin
  936. WHERE u.id $sqluserids";
  937. $users = $DB->get_recordset_sql($usersql, $params);
  938. $result = array();
  939. foreach ($users as $user) {
  940. if (!empty($user->deleted)) {
  941. continue;
  942. }
  943. context_helper::preload_from_record($user);
  944. $course = $courses[$courseids[$user->id]];
  945. $context = context_course::instance($courseids[$user->id], IGNORE_MISSING);
  946. self::validate_context($context);
  947. if ($userarray = user_get_user_details($user, $course)) {
  948. $result[] = $userarray;
  949. }
  950. }
  951. $users->close();
  952. return $result;
  953. }
  954. /**
  955. * Returns description of method result value
  956. *
  957. * @return external_description
  958. * @since Moodle 2.2
  959. */
  960. public static function get_course_user_profiles_returns() {
  961. $additionalfields = array(
  962. 'groups' => new external_multiple_structure(
  963. new external_single_structure(
  964. array(
  965. 'id' => new external_value(PARAM_INT, 'group id'),
  966. 'name' => new external_value(PARAM_RAW, 'group name'),
  967. 'description' => new external_value(PARAM_RAW, 'group description'),
  968. 'descriptionformat' => new external_format_value('description'),
  969. )
  970. ), 'user groups', VALUE_OPTIONAL),
  971. 'roles' => new external_multiple_structure(
  972. new external_single_structure(
  973. array(
  974. 'roleid' => new external_value(PARAM_INT, 'role id'),
  975. 'name' => new external_value(PARAM_RAW, 'role name'),
  976. 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
  977. 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
  978. )
  979. ), 'user roles', VALUE_OPTIONAL),
  980. 'enrolledcourses' => new external_multiple_structure(
  981. new external_single_structure(
  982. array(
  983. 'id' => new external_value(PARAM_INT, 'Id of the course'),
  984. 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
  985. 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
  986. )
  987. ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
  988. );
  989. return new external_mul

Large files files are truncated, but you can click here to view the full file