PageRenderTime 32ms CodeModel.GetById 30ms RepoModel.GetById 0ms 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
  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_multiple_structure(self::user_description($additionalfields));
  990. }
  991. /**
  992. * Create user return value description.
  993. *
  994. * @param array $additionalfields some additional field
  995. * @return single_structure_description
  996. */
  997. public static function user_description($additionalfields = array()) {
  998. $userfields = array(
  999. 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
  1000. 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL),
  1001. 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL),
  1002. 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL),
  1003. 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'),
  1004. 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
  1005. 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL),
  1006. 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL),
  1007. 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL),
  1008. 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL),
  1009. 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL),
  1010. 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
  1011. 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
  1012. 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL),
  1013. 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL),
  1014. 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL),
  1015. 'suspended' => new external_value(core_user::get_property_type('suspended'), 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL),
  1016. 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
  1017. 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
  1018. 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL),
  1019. 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
  1020. 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
  1021. 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
  1022. 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL),
  1023. 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL),
  1024. 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL),
  1025. 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
  1026. 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
  1027. 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
  1028. 'customfields' => new external_multiple_structure(
  1029. new external_single_structure(
  1030. array(
  1031. 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
  1032. 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
  1033. 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
  1034. 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
  1035. )
  1036. ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL),
  1037. 'preferences' => new external_multiple_structure(
  1038. new external_single_structure(
  1039. array(
  1040. 'name' => new external_value(PARAM_RAW, 'The name of the preferences'),
  1041. 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
  1042. )
  1043. ), 'Users preferences', VALUE_OPTIONAL)
  1044. );
  1045. if (!empty($additionalfields)) {
  1046. $userfields = array_merge($userfields, $additionalfields);
  1047. }
  1048. return new external_single_structure($userfields);
  1049. }
  1050. /**
  1051. * Returns description of method parameters
  1052. *
  1053. * @return external_function_parameters
  1054. * @since Moodle 2.6
  1055. */
  1056. public static function add_user_private_files_parameters() {
  1057. return new external_function_parameters(
  1058. array(
  1059. 'draftid' => new external_value(PARAM_INT, 'draft area id')
  1060. )
  1061. );
  1062. }
  1063. /**
  1064. * Copy files from a draft area to users private files area.
  1065. *
  1066. * @throws invalid_parameter_exception
  1067. * @param int $draftid Id of a draft area containing files.
  1068. * @return array An array of warnings
  1069. * @since Moodle 2.6
  1070. */
  1071. public static function add_user_private_files($draftid) {
  1072. global $CFG, $USER;
  1073. require_once($CFG->libdir . "/filelib.php");
  1074. $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid));
  1075. if (isguestuser()) {
  1076. throw new invalid_parameter_exception('Guest users cannot upload files');
  1077. }
  1078. $context = context_user::instance($USER->id);
  1079. require_capability('moodle/user:manageownfiles', $context);
  1080. $maxbytes = $CFG->userquota;
  1081. $maxareabytes = $CFG->userquota;
  1082. if (has_capability('moodle/user:ignoreuserquota', $context)) {
  1083. $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS;
  1084. $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
  1085. }
  1086. $options = array('subdirs' => 1,
  1087. 'maxbytes' => $maxbytes,
  1088. 'maxfiles' => -1,
  1089. 'areamaxbytes' => $maxareabytes);
  1090. file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options);
  1091. return null;
  1092. }
  1093. /**
  1094. * Returns description of method result value
  1095. *
  1096. * @return external_description
  1097. * @since Moodle 2.2
  1098. */
  1099. public static function add_user_private_files_returns() {
  1100. return null;
  1101. }
  1102. /**
  1103. * Returns description of method parameters.
  1104. *
  1105. * @return external_function_parameters
  1106. * @since Moodle 2.6
  1107. */
  1108. public static function add_user_device_parameters() {
  1109. return new external_function_parameters(
  1110. array(
  1111. 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'),
  1112. 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'),
  1113. 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'),
  1114. 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'),
  1115. 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'),
  1116. 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'),
  1117. 'uuid' => new external_value(PARAM_RAW, 'the device UUID')
  1118. )
  1119. );
  1120. }
  1121. /**
  1122. * Add a user device in Moodle database (for PUSH notifications usually).
  1123. *
  1124. * @throws moodle_exception
  1125. * @param string $appid The app id, usually something like com.moodle.moodlemobile.
  1126. * @param string $name The device name, occam or iPhone etc.
  1127. * @param string $model The device model Nexus4 or iPad1.1 etc.
  1128. * @param string $platform The device platform iOs or Android etc.
  1129. * @param string $version The device version 6.1.2 or 4.2.2 etc.
  1130. * @param string $pushid The device PUSH token/key/identifier/registration id.
  1131. * @param string $uuid The device UUID.
  1132. * @return array List of possible warnings.
  1133. * @since Moodle 2.6
  1134. */
  1135. public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) {
  1136. global $CFG, $USER, $DB;
  1137. require_once($CFG->dirroot . "/user/lib.php");
  1138. $params = self::validate_parameters(self::add_user_device_parameters(),
  1139. array('appid' => $appid,
  1140. 'name' => $name,
  1141. 'model' => $model,
  1142. 'platform' => $platform,
  1143. 'version' => $version,
  1144. 'pushid' => $pushid,
  1145. 'uuid' => $uuid
  1146. ));
  1147. $warnings = array();
  1148. // Prevent duplicate keys for users.
  1149. if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) {
  1150. $warnings['warning'][] = array(
  1151. 'item' => $params['pushid'],
  1152. 'warningcode' => 'existingkeyforthisuser',
  1153. 'message' => 'This key is already stored for this user'
  1154. );
  1155. return $warnings;
  1156. }
  1157. // Notice that we can have multiple devices because previously it was allowed to have repeated ones.
  1158. // Since we don't have a clear way to decide which one is the more appropiate, we update all.
  1159. if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'],
  1160. 'appid' => $params['appid'], 'userid' => $USER->id))) {
  1161. foreach ($userdevices as $userdevice) {
  1162. $userdevice->version = $params['version']; // Maybe the user upgraded the device.
  1163. $userdevice->pushid = $params['pushid'];
  1164. $userdevice->timemodified = time();
  1165. $DB->update_record('user_devices', $userdevice);
  1166. }
  1167. } else {
  1168. $userdevice = new stdclass;
  1169. $userdevice->userid = $USER->id;
  1170. $userdevice->appid = $params['appid'];
  1171. $userdevice->name = $params['name'];
  1172. $userdevice->model = $params['model'];
  1173. $userdevice->platform = $params['platform'];
  1174. $userdevice->version = $params['version'];
  1175. $userdevice->pushid = $params['pushid'];
  1176. $userdevice->uuid = $params['uuid'];
  1177. $userdevice->timecreated = time();
  1178. $userdevice->timemodified = $userdevice->timecreated;
  1179. if (!$DB->insert_record('user_devices', $userdevice)) {
  1180. throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']);
  1181. }
  1182. }
  1183. return $warnings;
  1184. }
  1185. /**
  1186. * Returns description of method result value.
  1187. *
  1188. * @return external_multiple_structure
  1189. * @since Moodle 2.6
  1190. */
  1191. public static function add_user_device_returns() {
  1192. return new external_multiple_structure(
  1193. new external_warnings()
  1194. );
  1195. }
  1196. /**
  1197. * Returns description of method parameters.
  1198. *
  1199. * @return external_function_parameters
  1200. * @since Moodle 2.9
  1201. */
  1202. public static function remove_user_device_parameters() {
  1203. return new external_function_parameters(
  1204. array(
  1205. 'uuid' => new external_value(PARAM_RAW, 'the device UUID'),
  1206. 'appid' => new external_value(PARAM_NOTAGS,
  1207. 'the app id, if empty devices matching the UUID for the user will be removed',
  1208. VALUE_DEFAULT, ''),
  1209. )
  1210. );
  1211. }
  1212. /**
  1213. * Remove a user device from the Moodle database (for PUSH notifications usually).
  1214. *
  1215. * @param string $uuid The device UUID.
  1216. * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed.
  1217. * @return array List of possible warnings and removal status.
  1218. * @since Moodle 2.9
  1219. */
  1220. public static function remove_user_device($uuid, $appid = "") {
  1221. global $CFG;
  1222. require_once($CFG->dirroot . "/user/lib.php");
  1223. $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid));
  1224. $context = context_system::instance();
  1225. self::validate_context($context);
  1226. // Warnings array, it can be empty at the end but is mandatory.
  1227. $warnings = array();
  1228. $removed = user_remove_user_device($params['uuid'], $params['appid']);
  1229. if (!$removed) {
  1230. $warnings[] = array(
  1231. 'item' => $params['uuid'],
  1232. 'warningcode' => 'devicedoesnotexist',
  1233. 'message' => 'The device doesn\'t exists in the database'
  1234. );
  1235. }
  1236. $result = array(
  1237. 'removed' => $removed,
  1238. 'warnings' => $warnings
  1239. );
  1240. return $result;
  1241. }
  1242. /**
  1243. * Returns description of method result value.
  1244. *
  1245. * @return external_multiple_structure
  1246. * @since Moodle 2.9
  1247. */
  1248. public static function remove_user_device_returns() {
  1249. return new external_single_structure(
  1250. array(
  1251. 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'),
  1252. 'warnings' => new external_warnings(),
  1253. )
  1254. );
  1255. }
  1256. /**
  1257. * Returns description of method parameters
  1258. *
  1259. * @return external_function_parameters
  1260. * @since Moodle 2.9
  1261. */
  1262. public static function view_user_list_parameters() {
  1263. return new external_function_parameters(
  1264. array(
  1265. 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site')
  1266. )
  1267. );
  1268. }
  1269. /**
  1270. * Trigger the user_list_viewed event.
  1271. *
  1272. * @param int $courseid id of course
  1273. * @return array of warnings and status result
  1274. * @since Moodle 2.9
  1275. * @throws moodle_exception
  1276. */
  1277. public static function view_user_list($courseid) {
  1278. global $CFG;
  1279. require_once($CFG->dirroot . "/user/lib.php");
  1280. require_once($CFG->dirroot . '/course/lib.php');
  1281. $params = self::validate_parameters(self::view_user_list_parameters(),
  1282. array(
  1283. 'courseid' => $courseid
  1284. ));
  1285. $warnings = array();
  1286. if (empty($params['courseid'])) {
  1287. $params['courseid'] = SITEID;
  1288. }
  1289. $course = get_course($params['courseid']);
  1290. if ($course->id == SITEID) {
  1291. $context = context_system::instance();
  1292. } else {
  1293. $context = context_course::instance($course->id);
  1294. }
  1295. self::validate_context($context);
  1296. course_require_view_participants($context);
  1297. user_list_view($course, $context);
  1298. $result = array();
  1299. $result['status'] = true;
  1300. $result['warnings'] = $warnings;
  1301. return $result;
  1302. }
  1303. /**
  1304. * Returns description of method result value
  1305. *
  1306. * @return external_description
  1307. * @since Moodle 2.9
  1308. */
  1309. public static function view_user_list_returns() {
  1310. return new external_single_structure(
  1311. array(
  1312. 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
  1313. 'warnings' => new external_warnings()
  1314. )
  1315. );
  1316. }
  1317. /**
  1318. * Returns description of method parameters
  1319. *
  1320. * @return external_function_parameters
  1321. * @since Moodle 2.9
  1322. */
  1323. public static function view_user_profile_parameters() {
  1324. return new external_function_parameters(
  1325. array(
  1326. 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
  1327. 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0)
  1328. )
  1329. );
  1330. }
  1331. /**
  1332. * Trigger the user profile viewed event.
  1333. *
  1334. * @param int $userid id of user
  1335. * @param int $courseid id of course
  1336. * @return array of warnings and status result
  1337. * @since Moodle 2.9
  1338. * @throws moodle_exception
  1339. */
  1340. public static function view_user_profile($userid, $courseid = 0) {
  1341. global $CFG, $USER;
  1342. require_once($CFG->dirroot . "/user/profile/lib.php");
  1343. $params = self::validate_parameters(self::view_user_profile_parameters(),
  1344. array(
  1345. 'userid' => $userid,
  1346. 'courseid' => $courseid
  1347. ));
  1348. $warnings = array();
  1349. if (empty($params['userid'])) {
  1350. $params['userid'] = $USER->id;
  1351. }
  1352. if (empty($params['courseid'])) {
  1353. $params['courseid'] = SITEID;
  1354. }
  1355. $course = get_course($params['courseid']);
  1356. $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
  1357. core_user::require_active_user($user);
  1358. if ($course->id == SITEID) {
  1359. $coursecontext = context_system::instance();;
  1360. } else {
  1361. $coursecontext = context_course::instance($course->id);
  1362. }
  1363. self::validate_context($coursecontext);
  1364. $currentuser = $USER->id == $user->id;
  1365. $usercontext = context_user::instance($user->id);
  1366. if (!$currentuser and
  1367. !has_capability('moodle/user:viewdetails', $coursecontext) and
  1368. !has_capability('moodle/user:viewdetails', $usercontext)) {
  1369. throw new moodle_exception('cannotviewprofile');
  1370. }
  1371. // Case like user/profile.php.
  1372. if ($course->id == SITEID) {
  1373. profile_view($user, $usercontext);
  1374. } else {
  1375. // Case like user/view.php.
  1376. if (!$currentuser and !can_access_course($course, $user, '', true)) {
  1377. throw new moodle_exception('notenrolledprofile');
  1378. }
  1379. profile_view($user, $coursecontext, $course);
  1380. }
  1381. $result = array();
  1382. $result['status'] = true;
  1383. $result['warnings'] = $warnings;
  1384. return $result;
  1385. }
  1386. /**
  1387. * Returns description of method result value
  1388. *
  1389. * @return external_description
  1390. * @since Moodle 2.9
  1391. */
  1392. public static function view_user_profile_returns() {
  1393. return new external_single_structure(
  1394. array(
  1395. 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
  1396. 'warnings' => new external_warnings()
  1397. )
  1398. );
  1399. }
  1400. /**
  1401. * Returns description of method parameters
  1402. *
  1403. * @return external_function_parameters
  1404. * @since Moodle 3.2
  1405. */
  1406. public static function get_user_preferences_parameters() {
  1407. return new external_function_parameters(
  1408. array(
  1409. 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''),
  1410. 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0)
  1411. )
  1412. );
  1413. }
  1414. /**
  1415. * Return user preferences.
  1416. *
  1417. * @param string $name preference name, empty for all
  1418. * @param int $userid id of the user, 0 for current user
  1419. * @return array of warnings and preferences
  1420. * @since Moodle 3.2
  1421. * @throws moodle_exception
  1422. */
  1423. public static function get_user_preferences($name = '', $userid = 0) {
  1424. global $USER;
  1425. $params = self::validate_parameters(self::get_user_preferences_parameters(),
  1426. array(
  1427. 'name' => $name,
  1428. 'userid' => $userid
  1429. ));
  1430. $preferences = array();
  1431. $warnings = array();
  1432. $context = context_system::instance();
  1433. self::validate_context($context);
  1434. if (empty($params['name'])) {
  1435. $name = null;
  1436. }
  1437. if (empty($params['userid'])) {
  1438. $user = null;
  1439. } else {
  1440. $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
  1441. core_user::require_active_user($user);
  1442. if ($user->id != $USER->id) {
  1443. // Only admins can retrieve other users preferences.
  1444. require_capability('moodle/site:config', $context);
  1445. }
  1446. }
  1447. $userpreferences = get_user_preferences($name, null, $user);
  1448. // Check if we received just one preference.
  1449. if (!is_array($userpreferences)) {
  1450. $userpreferences = array($name => $userpreferences);
  1451. }
  1452. foreach ($userpreferences as $name => $value) {
  1453. $preferences[] = array(
  1454. 'name' => $name,
  1455. 'value' => $value,
  1456. );
  1457. }
  1458. $result = array();
  1459. $result['preferences'] = $preferences;
  1460. $result['warnings'] = $warnings;
  1461. return $result;
  1462. }
  1463. /**
  1464. * Returns description of method result value
  1465. *
  1466. * @return external_description
  1467. * @since Moodle 3.2
  1468. */
  1469. public static function get_user_preferences_returns() {
  1470. return new external_single_structure(
  1471. array(
  1472. 'preferences' => new external_multiple_structure(
  1473. new external_single_structure(
  1474. array(
  1475. 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
  1476. 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
  1477. )
  1478. ),
  1479. 'User custom fields (also known as user profile fields)'
  1480. ),
  1481. 'warnings' => new external_warnings()
  1482. )
  1483. );
  1484. }
  1485. /**
  1486. * Returns description of method parameters
  1487. *
  1488. * @return external_function_parameters
  1489. * @since Moodle 3.2
  1490. */
  1491. public static function update_picture_parameters() {
  1492. return new external_function_parameters(
  1493. array(
  1494. 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'),
  1495. 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false),
  1496. 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0)
  1497. )
  1498. );
  1499. }
  1500. /**
  1501. * Update or delete the user picture in the site
  1502. *
  1503. * @param int $draftitemid id of the user draft file to use as image
  1504. * @param bool $delete if we should delete the user picture
  1505. * @param int $userid id of the user, 0 for current user
  1506. * @return array warnings and success status
  1507. * @since Moodle 3.2
  1508. * @throws moodle_exception
  1509. */
  1510. public static function update_picture($draftitemid, $delete = false, $userid = 0) {
  1511. global $CFG, $USER, $PAGE;
  1512. $params = self::validate_parameters(
  1513. self::update_picture_parameters(),
  1514. array(
  1515. 'draftitemid' => $draftitemid,
  1516. 'delete' => $delete,
  1517. 'userid' => $userid
  1518. )
  1519. );
  1520. $context = context_system::instance();
  1521. self::validate_context($context);
  1522. if (!empty($CFG->disableuserimages)) {
  1523. throw new moodle_exception('userimagesdisabled', 'admin');
  1524. }
  1525. if (empty($params['userid']) or $params['userid'] == $USER->id) {
  1526. $user = $USER;
  1527. require_capability('moodle/user:editownprofile', $context);
  1528. } else {
  1529. $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
  1530. core_user::require_active_user($user);
  1531. $personalcontext = context_user::instance($user->id);
  1532. require_capability('moodle/user:editprofile', $personalcontext);
  1533. if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
  1534. throw new moodle_exception('useradmineditadmin');
  1535. }
  1536. }
  1537. // Load the appropriate auth plugin.
  1538. $userauth = get_auth_plugin($user->auth);
  1539. if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
  1540. throw new moodle_exception('noprofileedit', 'auth');
  1541. }
  1542. $filemanageroptions = array(
  1543. 'maxbytes' => $CFG->maxbytes,
  1544. 'subdirs' => 0,
  1545. 'maxfiles' => 1,
  1546. 'accepted_types' => 'optimised_image'
  1547. );
  1548. $user->deletepicture = $params['delete'];
  1549. $user->imagefile = $params['draftitemid'];
  1550. $success = core_user::update_picture($user, $filemanageroptions);
  1551. $result = array(
  1552. 'success' => $success,
  1553. 'warnings' => array(),
  1554. );
  1555. if ($success) {
  1556. $userpicture = new user_picture(core_user::get_user($user->id));
  1557. $userpicture->size = 1; // Size f1.
  1558. $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
  1559. }
  1560. return $result;
  1561. }
  1562. /**
  1563. * Returns description of method result value
  1564. *
  1565. * @return external_description
  1566. * @since Moodle 3.2
  1567. */
  1568. public static function update_picture_returns() {
  1569. return new external_single_structure(
  1570. array(
  1571. 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'),
  1572. 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL),
  1573. 'warnings' => new external_warnings()
  1574. )
  1575. );
  1576. }
  1577. /**
  1578. * Returns description of method parameters
  1579. *
  1580. * @return external_function_parameters
  1581. * @since Moodle 3.2
  1582. */
  1583. public static function set_user_preferences_parameters() {
  1584. return new external_function_parameters(
  1585. array(
  1586. 'preferences' => new external_multiple_structure(
  1587. new external_single_structure(
  1588. array(
  1589. 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
  1590. 'value' => new external_value(PARAM_RAW, 'The value of the preference'),
  1591. 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'),
  1592. )
  1593. )
  1594. )
  1595. )
  1596. );
  1597. }
  1598. /**
  1599. * Set user preferences.
  1600. *
  1601. * @param array $preferences list of preferences including name, value and userid
  1602. * @return array of warnings and preferences saved
  1603. * @since Moodle 3.2
  1604. * @throws moodle_exception
  1605. */
  1606. public static function set_user_preferences($preferences) {
  1607. global $USER;
  1608. $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
  1609. $warnings = array();
  1610. $saved = array();
  1611. $context = context_system::instance();
  1612. self::validate_context($context);
  1613. $userscache = array();
  1614. foreach ($params['preferences'] as $pref) {
  1615. // Check to which user set the preference.
  1616. if (!empty($userscache[$pref['userid']])) {
  1617. $user = $userscache[$pref['userid']];
  1618. } else {
  1619. try {
  1620. $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
  1621. core_user::require_active_user($user);
  1622. $userscache[$pref['userid']] = $user;
  1623. } catch (Exception $e) {
  1624. $warnings[] = array(
  1625. 'item' => 'user',
  1626. 'itemid' => $pref['userid'],
  1627. 'warningcode' => 'invaliduser',
  1628. 'message' => $e->getMessage()
  1629. );
  1630. continue;
  1631. }
  1632. }
  1633. try {
  1634. if (core_user::can_edit_preference($pref['name'], $user)) {
  1635. $value = core_user::clean_preference($pref['value'], $pref['name']);
  1636. set_user_preference($pref['name'], $value, $user->id);
  1637. $saved[] = array(
  1638. 'name' => $pref['name'],
  1639. 'userid' => $user->id,
  1640. );
  1641. } else {
  1642. $warnings[] = array(
  1643. 'item' => 'user',
  1644. 'itemid' => $user->id,
  1645. 'warningcode' => 'nopermission',
  1646. 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
  1647. );
  1648. }
  1649. } catch (Exception $e) {
  1650. $warnings[] = array(
  1651. 'item' => 'user',
  1652. 'itemid' => $user->id,
  1653. 'warningcode' => 'errorsavingpreference',
  1654. 'message' => $e->getMessage()
  1655. );
  1656. }
  1657. }
  1658. $result = array();
  1659. $result['saved'] = $saved;
  1660. $result['warnings'] = $warnings;
  1661. return $result;
  1662. }
  1663. /**
  1664. * Returns description of method result value
  1665. *
  1666. * @return external_description
  1667. * @since Moodle 3.2
  1668. */
  1669. public static function set_user_preferences_returns() {
  1670. return new external_single_structure(
  1671. array(
  1672. 'saved' => new external_multiple_structure(
  1673. new external_single_structure(
  1674. array(
  1675. 'name' => new external_value(PARAM_RAW, 'The name of the preference'),
  1676. 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'),
  1677. )
  1678. ), 'Preferences saved'
  1679. ),
  1680. 'warnings' => new external_warnings()
  1681. )
  1682. );
  1683. }
  1684. /**
  1685. * Returns description of method parameters.
  1686. *
  1687. * @return external_function_parameters
  1688. * @since Moodle 3.2
  1689. */
  1690. public static function agree_site_policy_parameters() {
  1691. return new external_function_parameters(array());
  1692. }
  1693. /**
  1694. * Agree the site policy for the current user.
  1695. *
  1696. * @return array of warnings and status result
  1697. * @since Moodle 3.2
  1698. * @throws moodle_exception
  1699. */
  1700. public static function agree_site_policy() {
  1701. global $CFG, $DB, $USER;
  1702. $warnings = array();
  1703. $context = context_system::instance();
  1704. try {
  1705. // We expect an exception here since the user didn't agree the site policy yet.
  1706. self::validate_context($context);
  1707. } catch (Exception $e) {
  1708. // We are expecting only a sitepolicynotagreed exception.
  1709. if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
  1710. // In case we receive a different exception, throw it.
  1711. throw $e;
  1712. }
  1713. }
  1714. $manager = new \core_privacy\local\sitepolicy\manager();
  1715. if (!empty($USER->policyagreed)) {
  1716. $status = false;
  1717. $warnings[] = array(
  1718. 'item' => 'user',
  1719. 'itemid' => $USER->id,
  1720. 'warningcode' => 'alreadyagreed',
  1721. 'message' => 'The user already agreed the site policy.'
  1722. );
  1723. } else if (!$manager->is_defined()) {
  1724. $status = false;
  1725. $warnings[] = array(
  1726. 'item' => 'user',
  1727. 'itemid' => $USER->id,
  1728. 'warningcode' => 'nositepolicy',
  1729. 'message' => 'The site does not have a site policy configured.'
  1730. );
  1731. } else {
  1732. $status = $manager->accept();
  1733. }
  1734. $result = array();
  1735. $result['status'] = $status;
  1736. $result['warnings'] = $warnings;
  1737. return $result;
  1738. }
  1739. /**
  1740. * Returns description of method result value.
  1741. *
  1742. * @return external_description
  1743. * @since Moodle 3.2
  1744. */
  1745. public static function agree_site_policy_returns() {
  1746. return new external_single_structure(
  1747. array(
  1748. 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'),
  1749. 'warnings' => new external_warnings()
  1750. )
  1751. );
  1752. }
  1753. /**
  1754. * Returns description of method parameters.
  1755. *
  1756. * @return external_function_parameters
  1757. * @since Moodle 3.4
  1758. */
  1759. public static function get_private_files_info_parameters() {
  1760. return new external_function_parameters(
  1761. array(
  1762. 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0)
  1763. )
  1764. );
  1765. }
  1766. /**
  1767. * Returns general information about files in the user private files area.
  1768. *
  1769. * @param int $userid Id of the user, default to current user.
  1770. * @return array of warnings and file area information
  1771. * @since Moodle 3.4
  1772. * @throws moodle_exception
  1773. */
  1774. public static function get_private_files_info($userid = 0) {
  1775. global $CFG, $USER;
  1776. require_once($CFG->libdir . '/filelib.php');
  1777. $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid));
  1778. $warnings = array();
  1779. $context = context_system::instance();
  1780. self::validate_context($context);
  1781. if (empty($params['userid']) || $params['userid'] == $USER->id) {
  1782. $usercontext = context_user::instance($USER->id);
  1783. require_capability('moodle/user:manageownfiles', $usercontext);
  1784. } else {
  1785. $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
  1786. core_user::require_active_user($user);
  1787. // Only admins can retrieve other users information.
  1788. require_capability('moodle/site:config', $context);
  1789. $usercontext = context_user::instance($user->id);
  1790. }
  1791. $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private');
  1792. $result = array();
  1793. $result['filecount'] = $fileareainfo['filecount'];
  1794. $result['foldercount'] = $fileareainfo['foldercount'];
  1795. $result['filesize'] = $fileareainfo['filesize'];
  1796. $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references'];
  1797. $result['warnings'] = $warnings;
  1798. return $result;
  1799. }
  1800. /**
  1801. * Returns description of method result value.
  1802. *
  1803. * @return external_description
  1804. * @since Moodle 3.4
  1805. */
  1806. public static function get_private_files_info_returns() {
  1807. return new external_single_structure(
  1808. array(
  1809. 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'),
  1810. 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'),
  1811. 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'),
  1812. 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'),
  1813. 'warnings' => new external_warnings()
  1814. )
  1815. );
  1816. }
  1817. }