Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
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 /** 18 * External user API 19 * 20 * @package core_user 21 * @category external 22 * @copyright 2009 Petr Skodak 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 24 */ 25 26 defined('MOODLE_INTERNAL') || die(); 27 28 require_once("$CFG->libdir/externallib.php"); 29 30 /** 31 * User external functions 32 * 33 * @package core_user 34 * @category external 35 * @copyright 2011 Jerome Mouneyrac 36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 37 * @since Moodle 2.2 38 */ 39 class core_user_external extends external_api { 40 41 /** 42 * Returns description of method parameters 43 * 44 * @return external_function_parameters 45 * @since Moodle 2.2 46 */ 47 public static function create_users_parameters() { 48 global $CFG; 49 $userfields = [ 50 'createpassword' => new external_value(PARAM_BOOL, 'True if password should be created and mailed to user.', 51 VALUE_OPTIONAL), 52 // General. 53 'username' => new external_value(core_user::get_property_type('username'), 54 'Username policy is defined in Moodle security config.'), 55 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', 56 VALUE_DEFAULT, 'manual', core_user::get_property_null('auth')), 57 'password' => new external_value(core_user::get_property_type('password'), 58 'Plain text password consisting of any characters', VALUE_OPTIONAL), 59 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'), 60 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'), 61 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'), 62 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email visibility', VALUE_OPTIONAL), 63 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL), 64 'country' => new external_value(core_user::get_property_type('country'), 65 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL), 66 'timezone' => new external_value(core_user::get_property_type('timezone'), 67 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL), 68 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', 69 VALUE_OPTIONAL), 70 // Additional names. 71 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'), 72 'The first name(s) phonetically of the user', VALUE_OPTIONAL), 73 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'), 74 'The family name phonetically of the user', VALUE_OPTIONAL), 75 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', 76 VALUE_OPTIONAL), 77 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', 78 VALUE_OPTIONAL), 79 // Interests. 80 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL), 81 // Optional. 82 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 83 'An arbitrary ID code number perhaps from the institution', VALUE_DEFAULT, ''), 84 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL), 85 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL), 86 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL), 87 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL), 88 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL), 89 // Other user preferences stored in the user table. 90 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', 91 VALUE_DEFAULT, core_user::get_property_default('lang'), core_user::get_property_null('lang')), 92 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 93 'Calendar type such as "gregorian", must exist on server', VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL), 94 'theme' => new external_value(core_user::get_property_type('theme'), 95 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL), 96 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 97 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL), 98 // Custom user profile fields. 99 'customfields' => new external_multiple_structure( 100 new external_single_structure( 101 [ 102 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'), 103 'value' => new external_value(PARAM_RAW, 'The value of the custom field') 104 ] 105 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL), 106 // User preferences. 107 'preferences' => new external_multiple_structure( 108 new external_single_structure( 109 [ 110 'type' => new external_value(PARAM_RAW, 'The name of the preference'), 111 'value' => new external_value(PARAM_RAW, 'The value of the preference') 112 ] 113 ), 'User preferences', VALUE_OPTIONAL), 114 ]; 115 return new external_function_parameters( 116 [ 117 'users' => new external_multiple_structure( 118 new external_single_structure($userfields) 119 ) 120 ] 121 ); 122 } 123 124 /** 125 * Create one or more users. 126 * 127 * @throws invalid_parameter_exception 128 * @param array $users An array of users to create. 129 * @return array An array of arrays 130 * @since Moodle 2.2 131 */ 132 public static function create_users($users) { 133 global $CFG, $DB; 134 require_once($CFG->dirroot."/lib/weblib.php"); 135 require_once($CFG->dirroot."/user/lib.php"); 136 require_once($CFG->dirroot."/user/editlib.php"); 137 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function. 138 139 // Ensure the current user is allowed to run this function. 140 $context = context_system::instance(); 141 self::validate_context($context); 142 require_capability('moodle/user:create', $context); 143 144 // Do basic automatic PARAM checks on incoming data, using params description. 145 // If any problems are found then exceptions are thrown with helpful error messages. 146 $params = self::validate_parameters(self::create_users_parameters(), array('users' => $users)); 147 148 $availableauths = core_component::get_plugin_list('auth'); 149 unset($availableauths['mnet']); // These would need mnethostid too. 150 unset($availableauths['webservice']); // We do not want new webservice users for now. 151 152 $availablethemes = core_component::get_plugin_list('theme'); 153 $availablelangs = get_string_manager()->get_list_of_translations(); 154 155 $transaction = $DB->start_delegated_transaction(); 156 157 $userids = array(); 158 foreach ($params['users'] as $user) { 159 // Make sure that the username, firstname and lastname are not blank. 160 foreach (array('username', 'firstname', 'lastname') as $fieldname) { 161 if (trim($user[$fieldname]) === '') { 162 throw new invalid_parameter_exception('The field '.$fieldname.' cannot be blank'); 163 } 164 } 165 166 // Make sure that the username doesn't already exist. 167 if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) { 168 throw new invalid_parameter_exception('Username already exists: '.$user['username']); 169 } 170 171 // Make sure auth is valid. 172 if (empty($availableauths[$user['auth']])) { 173 throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']); 174 } 175 176 // Make sure lang is valid. 177 if (empty($availablelangs[$user['lang']])) { 178 throw new invalid_parameter_exception('Invalid language code: '.$user['lang']); 179 } 180 181 // Make sure lang is valid. 182 if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL, 183 // so no default value 184 // We need to test if the client sent it 185 // => !empty($user['theme']). 186 throw new invalid_parameter_exception('Invalid theme: '.$user['theme']); 187 } 188 189 // Make sure we have a password or have to create one. 190 $authplugin = get_auth_plugin($user['auth']); 191 if ($authplugin->is_internal() && empty($user['password']) && empty($user['createpassword'])) { 192 throw new invalid_parameter_exception('Invalid password: you must provide a password, or set createpassword.'); 193 } 194 195 $user['confirmed'] = true; 196 $user['mnethostid'] = $CFG->mnet_localhost_id; 197 198 // Start of user info validation. 199 // Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation(). 200 if (!validate_email($user['email'])) { 201 throw new invalid_parameter_exception('Email address is invalid: '.$user['email']); 202 } else if (empty($CFG->allowaccountssameemail)) { 203 // Make a case-insensitive query for the given email address. 204 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid'; 205 $params = array( 206 'email' => $user['email'], 207 'mnethostid' => $user['mnethostid'] 208 ); 209 // If there are other user(s) that already have the same email, throw an error. 210 if ($DB->record_exists_select('user', $select, $params)) { 211 throw new invalid_parameter_exception('Email address already exists: '.$user['email']); 212 } 213 } 214 // End of user info validation. 215 216 $createpassword = !empty($user['createpassword']); 217 unset($user['createpassword']); 218 $updatepassword = false; 219 if ($authplugin->is_internal()) { 220 if ($createpassword) { 221 $user['password'] = ''; 222 } else { 223 $updatepassword = true; 224 } 225 } else { 226 $user['password'] = AUTH_PASSWORD_NOT_CACHED; 227 } 228 229 // Create the user data now! 230 $user['id'] = user_create_user($user, $updatepassword, false); 231 232 $userobject = (object)$user; 233 234 // Set user interests. 235 if (!empty($user['interests'])) { 236 $trimmedinterests = array_map('trim', explode(',', $user['interests'])); 237 $interests = array_filter($trimmedinterests, function($value) { 238 return !empty($value); 239 }); 240 useredit_update_interests($userobject, $interests); 241 } 242 243 // Custom fields. 244 if (!empty($user['customfields'])) { 245 foreach ($user['customfields'] as $customfield) { 246 // Profile_save_data() saves profile file it's expecting a user with the correct id, 247 // and custom field to be named profile_field_"shortname". 248 $user["profile_field_".$customfield['type']] = $customfield['value']; 249 } 250 profile_save_data((object) $user); 251 } 252 253 if ($createpassword) { 254 setnew_password_and_mail($userobject); 255 unset_user_preference('create_password', $userobject); 256 set_user_preference('auth_forcepasswordchange', 1, $userobject); 257 } 258 259 // Trigger event. 260 \core\event\user_created::create_from_userid($user['id'])->trigger(); 261 262 // Preferences. 263 if (!empty($user['preferences'])) { 264 $userpref = (object)$user; 265 foreach ($user['preferences'] as $preference) { 266 $userpref->{'preference_'.$preference['type']} = $preference['value']; 267 } 268 useredit_update_user_preference($userpref); 269 } 270 271 $userids[] = array('id' => $user['id'], 'username' => $user['username']); 272 } 273 274 $transaction->allow_commit(); 275 276 return $userids; 277 } 278 279 /** 280 * Returns description of method result value 281 * 282 * @return external_description 283 * @since Moodle 2.2 284 */ 285 public static function create_users_returns() { 286 return new external_multiple_structure( 287 new external_single_structure( 288 array( 289 'id' => new external_value(core_user::get_property_type('id'), 'user id'), 290 'username' => new external_value(core_user::get_property_type('username'), 'user name'), 291 ) 292 ) 293 ); 294 } 295 296 297 /** 298 * Returns description of method parameters 299 * 300 * @return external_function_parameters 301 * @since Moodle 2.2 302 */ 303 public static function delete_users_parameters() { 304 return new external_function_parameters( 305 array( 306 'userids' => new external_multiple_structure(new external_value(core_user::get_property_type('id'), 'user ID')), 307 ) 308 ); 309 } 310 311 /** 312 * Delete users 313 * 314 * @throws moodle_exception 315 * @param array $userids 316 * @return null 317 * @since Moodle 2.2 318 */ 319 public static function delete_users($userids) { 320 global $CFG, $DB, $USER; 321 require_once($CFG->dirroot."/user/lib.php"); 322 323 // Ensure the current user is allowed to run this function. 324 $context = context_system::instance(); 325 require_capability('moodle/user:delete', $context); 326 self::validate_context($context); 327 328 $params = self::validate_parameters(self::delete_users_parameters(), array('userids' => $userids)); 329 330 $transaction = $DB->start_delegated_transaction(); 331 332 foreach ($params['userids'] as $userid) { 333 $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST); 334 // Must not allow deleting of admins or self!!! 335 if (is_siteadmin($user)) { 336 throw new moodle_exception('useradminodelete', 'error'); 337 } 338 if ($USER->id == $user->id) { 339 throw new moodle_exception('usernotdeletederror', 'error'); 340 } 341 user_delete_user($user); 342 } 343 344 $transaction->allow_commit(); 345 346 return null; 347 } 348 349 /** 350 * Returns description of method result value 351 * 352 * @return null 353 * @since Moodle 2.2 354 */ 355 public static function delete_users_returns() { 356 return null; 357 } 358 359 /** 360 * Returns description of method parameters. 361 * 362 * @return external_function_parameters 363 * @since Moodle 3.2 364 */ 365 public static function update_user_preferences_parameters() { 366 return new external_function_parameters( 367 array( 368 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0), 369 'emailstop' => new external_value(core_user::get_property_type('emailstop'), 370 'Enable or disable notifications for this user', VALUE_DEFAULT, null), 371 'preferences' => new external_multiple_structure( 372 new external_single_structure( 373 array( 374 'type' => new external_value(PARAM_RAW, 'The name of the preference'), 375 'value' => new external_value(PARAM_RAW, 'The value of the preference, do not set this field if you 376 want to remove (unset) the current value.', VALUE_DEFAULT, null), 377 ) 378 ), 'User preferences', VALUE_DEFAULT, array() 379 ) 380 ) 381 ); 382 } 383 384 /** 385 * Update the user's preferences. 386 * 387 * @param int $userid 388 * @param bool|null $emailstop 389 * @param array $preferences 390 * @return null 391 * @since Moodle 3.2 392 */ 393 public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) { 394 global $USER, $CFG; 395 396 require_once($CFG->dirroot . '/user/lib.php'); 397 require_once($CFG->dirroot . '/user/editlib.php'); 398 require_once($CFG->dirroot . '/message/lib.php'); 399 400 if (empty($userid)) { 401 $userid = $USER->id; 402 } 403 404 $systemcontext = context_system::instance(); 405 self::validate_context($systemcontext); 406 $params = array( 407 'userid' => $userid, 408 'emailstop' => $emailstop, 409 'preferences' => $preferences 410 ); 411 $params = self::validate_parameters(self::update_user_preferences_parameters(), $params); 412 $preferences = $params['preferences']; 413 414 // Preferences. 415 if (!empty($preferences)) { 416 $userpref = ['id' => $userid]; 417 foreach ($preferences as $preference) { 418 419 /* 420 * Rename user message provider preferences to avoid orphan settings on old app versions. 421 * @todo Remove this "translation" block on MDL-73284. 422 */ 423 if (preg_match('/message_provider_.*_loggedin/', $preference['type']) || 424 preg_match('/message_provider_.*_loggedoff/', $preference['type'])) { 425 $nameparts = explode('_', $preference['type']); 426 array_pop($nameparts); 427 $preference['type'] = implode('_', $nameparts).'_enabled'; 428 } 429 430 $userpref['preference_' . $preference['type']] = $preference['value']; 431 } 432 useredit_update_user_preference($userpref); 433 } 434 435 // Check if they want to update the email. 436 if ($emailstop !== null) { 437 $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST); 438 core_user::require_active_user($otheruser); 439 if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) { 440 $user = new stdClass(); 441 $user->id = $userid; 442 $user->emailstop = $emailstop; 443 user_update_user($user); 444 445 // Update the $USER if we should. 446 if ($userid == $USER->id) { 447 $USER->emailstop = $emailstop; 448 } 449 } 450 } 451 452 return null; 453 } 454 455 /** 456 * Returns description of method result value 457 * 458 * @return null 459 * @since Moodle 3.2 460 */ 461 public static function update_user_preferences_returns() { 462 return null; 463 } 464 465 /** 466 * Returns description of method parameters 467 * 468 * @return external_function_parameters 469 * @since Moodle 2.2 470 */ 471 public static function update_users_parameters() { 472 $userfields = [ 473 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'), 474 // General. 475 'username' => new external_value(core_user::get_property_type('username'), 476 'Username policy is defined in Moodle security config.', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 477 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', 478 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 479 'suspended' => new external_value(core_user::get_property_type('suspended'), 480 'Suspend user account, either false to enable user login or true to disable it', VALUE_OPTIONAL), 481 'password' => new external_value(core_user::get_property_type('password'), 482 'Plain text password consisting of any characters', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 483 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', 484 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 485 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', 486 VALUE_OPTIONAL), 487 'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address', VALUE_OPTIONAL, 488 '', NULL_NOT_ALLOWED), 489 'maildisplay' => new external_value(core_user::get_property_type('maildisplay'), 'Email visibility', VALUE_OPTIONAL), 490 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL), 491 'country' => new external_value(core_user::get_property_type('country'), 492 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL), 493 'timezone' => new external_value(core_user::get_property_type('timezone'), 494 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL), 495 'description' => new external_value(core_user::get_property_type('description'), 'User profile description, no HTML', 496 VALUE_OPTIONAL), 497 // User picture. 498 'userpicture' => new external_value(PARAM_INT, 499 'The itemid where the new user picture has been uploaded to, 0 to delete', VALUE_OPTIONAL), 500 // Additional names. 501 'firstnamephonetic' => new external_value(core_user::get_property_type('firstnamephonetic'), 502 'The first name(s) phonetically of the user', VALUE_OPTIONAL), 503 'lastnamephonetic' => new external_value(core_user::get_property_type('lastnamephonetic'), 504 'The family name phonetically of the user', VALUE_OPTIONAL), 505 'middlename' => new external_value(core_user::get_property_type('middlename'), 'The middle name of the user', 506 VALUE_OPTIONAL), 507 'alternatename' => new external_value(core_user::get_property_type('alternatename'), 'The alternate name of the user', 508 VALUE_OPTIONAL), 509 // Interests. 510 'interests' => new external_value(PARAM_TEXT, 'User interests (separated by commas)', VALUE_OPTIONAL), 511 // Optional. 512 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 513 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL), 514 'institution' => new external_value(core_user::get_property_type('institution'), 'Institution', VALUE_OPTIONAL), 515 'department' => new external_value(core_user::get_property_type('department'), 'Department', VALUE_OPTIONAL), 516 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone', VALUE_OPTIONAL), 517 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Mobile phone', VALUE_OPTIONAL), 518 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL), 519 // Other user preferences stored in the user table. 520 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', 521 VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 522 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 523 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL, '', NULL_NOT_ALLOWED), 524 'theme' => new external_value(core_user::get_property_type('theme'), 525 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL), 526 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 527 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL), 528 // Custom user profile fields. 529 'customfields' => new external_multiple_structure( 530 new external_single_structure( 531 [ 532 'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'), 533 'value' => new external_value(PARAM_RAW, 'The value of the custom field') 534 ] 535 ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL), 536 // User preferences. 537 'preferences' => new external_multiple_structure( 538 new external_single_structure( 539 [ 540 'type' => new external_value(PARAM_RAW, 'The name of the preference'), 541 'value' => new external_value(PARAM_RAW, 'The value of the preference') 542 ] 543 ), 'User preferences', VALUE_OPTIONAL), 544 ]; 545 return new external_function_parameters( 546 [ 547 'users' => new external_multiple_structure( 548 new external_single_structure($userfields) 549 ) 550 ] 551 ); 552 } 553 554 /** 555 * Update users 556 * 557 * @param array $users 558 * @return null 559 * @since Moodle 2.2 560 */ 561 public static function update_users($users) { 562 global $CFG, $DB, $USER; 563 require_once($CFG->dirroot."/user/lib.php"); 564 require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function. 565 require_once($CFG->dirroot.'/user/editlib.php'); 566 567 // Ensure the current user is allowed to run this function. 568 $context = context_system::instance(); 569 require_capability('moodle/user:update', $context); 570 self::validate_context($context); 571 572 $params = self::validate_parameters(self::update_users_parameters(), array('users' => $users)); 573 574 $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 575 'subdirs' => 0, 576 'maxfiles' => 1, 577 'accepted_types' => 'optimised_image'); 578 579 $warnings = array(); 580 foreach ($params['users'] as $user) { 581 // Catch any exception while updating a user and return it as a warning. 582 try { 583 $transaction = $DB->start_delegated_transaction(); 584 585 // First check the user exists. 586 if (!$existinguser = core_user::get_user($user['id'])) { 587 throw new moodle_exception('invaliduserid', '', '', null, 588 'Invalid user ID'); 589 } 590 // Check if we are trying to update an admin. 591 if ($existinguser->id != $USER->id and is_siteadmin($existinguser) and !is_siteadmin($USER)) { 592 throw new moodle_exception('usernotupdatedadmin', '', '', null, 593 'Cannot update admin accounts'); 594 } 595 // Other checks (deleted, remote or guest users). 596 if ($existinguser->deleted) { 597 throw new moodle_exception('usernotupdateddeleted', '', '', null, 598 'User is a deleted user'); 599 } 600 if (is_mnet_remote_user($existinguser)) { 601 throw new moodle_exception('usernotupdatedremote', '', '', null, 602 'User is a remote user'); 603 } 604 if (isguestuser($existinguser->id)) { 605 throw new moodle_exception('usernotupdatedguest', '', '', null, 606 'Cannot update guest account'); 607 } 608 // Check duplicated emails. 609 if (isset($user['email']) && $user['email'] !== $existinguser->email) { 610 if (!validate_email($user['email'])) { 611 throw new moodle_exception('useremailinvalid', '', '', null, 612 'Invalid email address'); 613 } else if (empty($CFG->allowaccountssameemail)) { 614 // Make a case-insensitive query for the given email address 615 // and make sure to exclude the user being updated. 616 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid AND id <> :userid'; 617 $params = array( 618 'email' => $user['email'], 619 'mnethostid' => $CFG->mnet_localhost_id, 620 'userid' => $user['id'] 621 ); 622 // Skip if there are other user(s) that already have the same email. 623 if ($DB->record_exists_select('user', $select, $params)) { 624 throw new moodle_exception('useremailduplicate', '', '', null, 625 'Duplicate email address'); 626 } 627 } 628 } 629 630 user_update_user($user, true, false); 631 632 $userobject = (object)$user; 633 634 // Update user picture if it was specified for this user. 635 if (empty($CFG->disableuserimages) && isset($user['userpicture'])) { 636 $userobject->deletepicture = null; 637 638 if ($user['userpicture'] == 0) { 639 $userobject->deletepicture = true; 640 } else { 641 $userobject->imagefile = $user['userpicture']; 642 } 643 644 core_user::update_picture($userobject, $filemanageroptions); 645 } 646 647 // Update user interests. 648 if (!empty($user['interests'])) { 649 $trimmedinterests = array_map('trim', explode(',', $user['interests'])); 650 $interests = array_filter($trimmedinterests, function($value) { 651 return !empty($value); 652 }); 653 useredit_update_interests($userobject, $interests); 654 } 655 656 // Update user custom fields. 657 if (!empty($user['customfields'])) { 658 659 foreach ($user['customfields'] as $customfield) { 660 // Profile_save_data() saves profile file it's expecting a user with the correct id, 661 // and custom field to be named profile_field_"shortname". 662 $user["profile_field_".$customfield['type']] = $customfield['value']; 663 } 664 profile_save_data((object) $user); 665 } 666 667 // Trigger event. 668 \core\event\user_updated::create_from_userid($user['id'])->trigger(); 669 670 // Preferences. 671 if (!empty($user['preferences'])) { 672 $userpref = clone($existinguser); 673 foreach ($user['preferences'] as $preference) { 674 $userpref->{'preference_'.$preference['type']} = $preference['value']; 675 } 676 useredit_update_user_preference($userpref); 677 } 678 if (isset($user['suspended']) and $user['suspended']) { 679 \core\session\manager::kill_user_sessions($user['id']); 680 } 681 682 $transaction->allow_commit(); 683 } catch (Exception $e) { 684 try { 685 $transaction->rollback($e); 686 } catch (Exception $e) { 687 $warning = []; 688 $warning['item'] = 'user'; 689 $warning['itemid'] = $user['id']; 690 if ($e instanceof moodle_exception) { 691 $warning['warningcode'] = $e->errorcode; 692 } else { 693 $warning['warningcode'] = $e->getCode(); 694 } 695 $warning['message'] = $e->getMessage(); 696 $warnings[] = $warning; 697 } 698 } 699 } 700 701 return ['warnings' => $warnings]; 702 } 703 704 /** 705 * Returns description of method result value 706 * 707 * @return external_description 708 * @since Moodle 2.2 709 */ 710 public static function update_users_returns() { 711 return new external_single_structure( 712 array( 713 'warnings' => new external_warnings() 714 ) 715 ); 716 } 717 718 /** 719 * Returns description of method parameters 720 * 721 * @return external_function_parameters 722 * @since Moodle 2.4 723 */ 724 public static function get_users_by_field_parameters() { 725 return new external_function_parameters( 726 array( 727 'field' => new external_value(PARAM_ALPHA, 'the search field can be 728 \'id\' or \'idnumber\' or \'username\' or \'email\''), 729 'values' => new external_multiple_structure( 730 new external_value(PARAM_RAW, 'the value to match')) 731 ) 732 ); 733 } 734 735 /** 736 * Get user information for a unique field. 737 * 738 * @throws coding_exception 739 * @throws invalid_parameter_exception 740 * @param string $field 741 * @param array $values 742 * @return array An array of arrays containg user profiles. 743 * @since Moodle 2.4 744 */ 745 public static function get_users_by_field($field, $values) { 746 global $CFG, $USER, $DB; 747 require_once($CFG->dirroot . "/user/lib.php"); 748 749 $params = self::validate_parameters(self::get_users_by_field_parameters(), 750 array('field' => $field, 'values' => $values)); 751 752 // This array will keep all the users that are allowed to be searched, 753 // according to the current user's privileges. 754 $cleanedvalues = array(); 755 756 switch ($field) { 757 case 'id': 758 $paramtype = core_user::get_property_type('id'); 759 break; 760 case 'idnumber': 761 $paramtype = core_user::get_property_type('idnumber'); 762 break; 763 case 'username': 764 $paramtype = core_user::get_property_type('username'); 765 break; 766 case 'email': 767 $paramtype = core_user::get_property_type('email'); 768 break; 769 default: 770 throw new coding_exception('invalid field parameter', 771 'The search field \'' . $field . '\' is not supported, look at the web service documentation'); 772 } 773 774 // Clean the values. 775 foreach ($values as $value) { 776 $cleanedvalue = clean_param($value, $paramtype); 777 if ( $value != $cleanedvalue) { 778 throw new invalid_parameter_exception('The field \'' . $field . 779 '\' value is invalid: ' . $value . '(cleaned value: '.$cleanedvalue.')'); 780 } 781 $cleanedvalues[] = $cleanedvalue; 782 } 783 784 // Retrieve the users. 785 $users = $DB->get_records_list('user', $field, $cleanedvalues, 'id'); 786 787 $context = context_system::instance(); 788 self::validate_context($context); 789 790 // Finally retrieve each users information. 791 $returnedusers = array(); 792 foreach ($users as $user) { 793 $userdetails = user_get_user_details_courses($user); 794 795 // Return the user only if the searched field is returned. 796 // Otherwise it means that the $USER was not allowed to search the returned user. 797 if (!empty($userdetails) and !empty($userdetails[$field])) { 798 $returnedusers[] = $userdetails; 799 } 800 } 801 802 return $returnedusers; 803 } 804 805 /** 806 * Returns description of method result value 807 * 808 * @return external_multiple_structure 809 * @since Moodle 2.4 810 */ 811 public static function get_users_by_field_returns() { 812 return new external_multiple_structure(self::user_description()); 813 } 814 815 816 /** 817 * Returns description of get_users() parameters. 818 * 819 * @return external_function_parameters 820 * @since Moodle 2.5 821 */ 822 public static function get_users_parameters() { 823 return new external_function_parameters( 824 array( 825 'criteria' => new external_multiple_structure( 826 new external_single_structure( 827 array( 828 'key' => new external_value(PARAM_ALPHA, 'the user column to search, expected keys (value format) are: 829 "id" (int) matching user id, 830 "lastname" (string) user last name (Note: you can use % for searching but it may be considerably slower!), 831 "firstname" (string) user first name (Note: you can use % for searching but it may be considerably slower!), 832 "idnumber" (string) matching user idnumber, 833 "username" (string) matching user username, 834 "email" (string) user email (Note: you can use % for searching but it may be considerably slower!), 835 "auth" (string) matching user auth plugin'), 836 'value' => new external_value(PARAM_RAW, 'the value to search') 837 ) 838 ), 'the key/value pairs to be considered in user search. Values can not be empty. 839 Specify different keys only once (fullname => \'user1\', auth => \'manual\', ...) - 840 key occurences are forbidden. 841 The search is executed with AND operator on the criterias. Invalid criterias (keys) are ignored, 842 the search is still executed on the valid criterias. 843 You can search without criteria, but the function is not designed for it. 844 It could very slow or timeout. The function is designed to search some specific users.' 845 ) 846 ) 847 ); 848 } 849 850 /** 851 * Retrieve matching user. 852 * 853 * @throws moodle_exception 854 * @param array $criteria the allowed array keys are id/lastname/firstname/idnumber/username/email/auth. 855 * @return array An array of arrays containing user profiles. 856 * @since Moodle 2.5 857 */ 858 public static function get_users($criteria = array()) { 859 global $CFG, $USER, $DB; 860 861 require_once($CFG->dirroot . "/user/lib.php"); 862 863 $params = self::validate_parameters(self::get_users_parameters(), 864 array('criteria' => $criteria)); 865 866 // Validate the criteria and retrieve the users. 867 $users = array(); 868 $warnings = array(); 869 $sqlparams = array(); 870 $usedkeys = array(); 871 872 // Do not retrieve deleted users. 873 $sql = ' deleted = 0'; 874 875 foreach ($params['criteria'] as $criteriaindex => $criteria) { 876 877 // Check that the criteria has never been used. 878 if (array_key_exists($criteria['key'], $usedkeys)) { 879 throw new moodle_exception('keyalreadyset', '', '', null, 'The key ' . $criteria['key'] . ' can only be sent once'); 880 } else { 881 $usedkeys[$criteria['key']] = true; 882 } 883 884 $invalidcriteria = false; 885 // Clean the parameters. 886 $paramtype = PARAM_RAW; 887 switch ($criteria['key']) { 888 case 'id': 889 $paramtype = core_user::get_property_type('id'); 890 break; 891 case 'idnumber': 892 $paramtype = core_user::get_property_type('idnumber'); 893 break; 894 case 'username': 895 $paramtype = core_user::get_property_type('username'); 896 break; 897 case 'email': 898 // We use PARAM_RAW to allow searches with %. 899 $paramtype = core_user::get_property_type('email'); 900 break; 901 case 'auth': 902 $paramtype = core_user::get_property_type('auth'); 903 break; 904 case 'lastname': 905 case 'firstname': 906 $paramtype = core_user::get_property_type('firstname'); 907 break; 908 default: 909 // Send back a warning that this search key is not supported in this version. 910 // This warning will make the function extandable without breaking clients. 911 $warnings[] = array( 912 'item' => $criteria['key'], 913 'warningcode' => 'invalidfieldparameter', 914 'message' => 915 'The search key \'' . $criteria['key'] . '\' is not supported, look at the web service documentation' 916 ); 917 // Do not add this invalid criteria to the created SQL request. 918 $invalidcriteria = true; 919 unset($params['criteria'][$criteriaindex]); 920 break; 921 } 922 923 if (!$invalidcriteria) { 924 $cleanedvalue = clean_param($criteria['value'], $paramtype); 925 926 $sql .= ' AND '; 927 928 // Create the SQL. 929 switch ($criteria['key']) { 930 case 'id': 931 case 'idnumber': 932 case 'username': 933 case 'auth': 934 $sql .= $criteria['key'] . ' = :' . $criteria['key']; 935 $sqlparams[$criteria['key']] = $cleanedvalue; 936 break; 937 case 'email': 938 case 'lastname': 939 case 'firstname': 940 $sql .= $DB->sql_like($criteria['key'], ':' . $criteria['key'], false); 941 $sqlparams[$criteria['key']] = $cleanedvalue; 942 break; 943 default: 944 break; 945 } 946 } 947 } 948 949 $users = $DB->get_records_select('user', $sql, $sqlparams, 'id ASC'); 950 951 // Finally retrieve each users information. 952 $returnedusers = array(); 953 foreach ($users as $user) { 954 $userdetails = user_get_user_details_courses($user); 955 956 // Return the user only if all the searched fields are returned. 957 // Otherwise it means that the $USER was not allowed to search the returned user. 958 if (!empty($userdetails)) { 959 $validuser = true; 960 961 foreach ($params['criteria'] as $criteria) { 962 if (empty($userdetails[$criteria['key']])) { 963 $validuser = false; 964 } 965 } 966 967 if ($validuser) { 968 $returnedusers[] = $userdetails; 969 } 970 } 971 } 972 973 return array('users' => $returnedusers, 'warnings' => $warnings); 974 } 975 976 /** 977 * Returns description of get_users result value. 978 * 979 * @return external_description 980 * @since Moodle 2.5 981 */ 982 public static function get_users_returns() { 983 return new external_single_structure( 984 array('users' => new external_multiple_structure( 985 self::user_description() 986 ), 987 'warnings' => new external_warnings('always set to \'key\'', 'faulty key name') 988 ) 989 ); 990 } 991 992 /** 993 * Returns description of method parameters 994 * 995 * @return external_function_parameters 996 * @since Moodle 2.2 997 */ 998 public static function get_course_user_profiles_parameters() { 999 return new external_function_parameters( 1000 array( 1001 'userlist' => new external_multiple_structure( 1002 new external_single_structure( 1003 array( 1004 'userid' => new external_value(core_user::get_property_type('id'), 'userid'), 1005 'courseid' => new external_value(PARAM_INT, 'courseid'), 1006 ) 1007 ) 1008 ) 1009 ) 1010 ); 1011 } 1012 1013 /** 1014 * Get course participant's details 1015 * 1016 * @param array $userlist array of user ids and according course ids 1017 * @return array An array of arrays describing course participants 1018 * @since Moodle 2.2 1019 */ 1020 public static function get_course_user_profiles($userlist) { 1021 global $CFG, $USER, $DB; 1022 require_once($CFG->dirroot . "/user/lib.php"); 1023 $params = self::validate_parameters(self::get_course_user_profiles_parameters(), array('userlist' => $userlist)); 1024 1025 $userids = array(); 1026 $courseids = array(); 1027 foreach ($params['userlist'] as $value) { 1028 $userids[] = $value['userid']; 1029 $courseids[$value['userid']] = $value['courseid']; 1030 } 1031 1032 // Cache all courses. 1033 $courses = array(); 1034 list($sqlcourseids, $params) = $DB->get_in_or_equal(array_unique($courseids), SQL_PARAMS_NAMED); 1035 $cselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 1036 $cjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 1037 $params['contextlevel'] = CONTEXT_COURSE; 1038 $coursesql = "SELECT c.* $cselect 1039 FROM {course} c $cjoin 1040 WHERE c.id $sqlcourseids"; 1041 $rs = $DB->get_recordset_sql($coursesql, $params); 1042 foreach ($rs as $course) { 1043 // Adding course contexts to cache. 1044 context_helper::preload_from_record($course); 1045 // Cache courses. 1046 $courses[$course->id] = $course; 1047 } 1048 $rs->close(); 1049 1050 list($sqluserids, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED); 1051 $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 1052 $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)"; 1053 $params['contextlevel'] = CONTEXT_USER; 1054 $usersql = "SELECT u.* $uselect 1055 FROM {user} u $ujoin 1056 WHERE u.id $sqluserids"; 1057 $users = $DB->get_recordset_sql($usersql, $params); 1058 $result = array(); 1059 foreach ($users as $user) { 1060 if (!empty($user->deleted)) { 1061 continue; 1062 } 1063 context_helper::preload_from_record($user); 1064 $course = $courses[$courseids[$user->id]]; 1065 $context = context_course::instance($courseids[$user->id], IGNORE_MISSING); 1066 self::validate_context($context); 1067 if ($userarray = user_get_user_details($user, $course)) { 1068 $result[] = $userarray; 1069 } 1070 } 1071 1072 $users->close(); 1073 1074 return $result; 1075 } 1076 1077 /** 1078 * Returns description of method result value 1079 * 1080 * @return external_description 1081 * @since Moodle 2.2 1082 */ 1083 public static function get_course_user_profiles_returns() { 1084 $additionalfields = array( 1085 'groups' => new external_multiple_structure( 1086 new external_single_structure( 1087 array( 1088 'id' => new external_value(PARAM_INT, 'group id'), 1089 'name' => new external_value(PARAM_RAW, 'group name'), 1090 'description' => new external_value(PARAM_RAW, 'group description'), 1091 'descriptionformat' => new external_format_value('description'), 1092 ) 1093 ), 'user groups', VALUE_OPTIONAL), 1094 'roles' => new external_multiple_structure( 1095 new external_single_structure( 1096 array( 1097 'roleid' => new external_value(PARAM_INT, 'role id'), 1098 'name' => new external_value(PARAM_RAW, 'role name'), 1099 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'), 1100 'sortorder' => new external_value(PARAM_INT, 'role sortorder') 1101 ) 1102 ), 'user roles', VALUE_OPTIONAL), 1103 'enrolledcourses' => new external_multiple_structure( 1104 new external_single_structure( 1105 array( 1106 'id' => new external_value(PARAM_INT, 'Id of the course'), 1107 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'), 1108 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course') 1109 ) 1110 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL) 1111 ); 1112 1113 return new external_multiple_structure(self::user_description($additionalfields)); 1114 } 1115 1116 /** 1117 * Create user return value description. 1118 * 1119 * @param array $additionalfields some additional field 1120 * @return single_structure_description 1121 */ 1122 public static function user_description($additionalfields = array()) { 1123 $userfields = array( 1124 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'), 1125 'username' => new external_value(core_user::get_property_type('username'), 'The username', VALUE_OPTIONAL), 1126 'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user', VALUE_OPTIONAL), 1127 'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user', VALUE_OPTIONAL), 1128 'fullname' => new external_value(core_user::get_property_type('firstname'), 'The fullname of the user'), 1129 'email' => new external_value(core_user::get_property_type('email'), 'An email address - allow email as root@localhost', VALUE_OPTIONAL), 1130 'address' => new external_value(core_user::get_property_type('address'), 'Postal address', VALUE_OPTIONAL), 1131 'phone1' => new external_value(core_user::get_property_type('phone1'), 'Phone 1', VALUE_OPTIONAL), 1132 'phone2' => new external_value(core_user::get_property_type('phone2'), 'Phone 2', VALUE_OPTIONAL), 1133 'department' => new external_value(core_user::get_property_type('department'), 'department', VALUE_OPTIONAL), 1134 'institution' => new external_value(core_user::get_property_type('institution'), 'institution', VALUE_OPTIONAL), 1135 'idnumber' => new external_value(core_user::get_property_type('idnumber'), 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL), 1136 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL), 1137 'firstaccess' => new external_value(core_user::get_property_type('firstaccess'), 'first access to the site (0 if never)', VALUE_OPTIONAL), 1138 'lastaccess' => new external_value(core_user::get_property_type('lastaccess'), 'last access to the site (0 if never)', VALUE_OPTIONAL), 1139 'auth' => new external_value(core_user::get_property_type('auth'), 'Auth plugins include manual, ldap, etc', VALUE_OPTIONAL), 1140 '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), 1141 'confirmed' => new external_value(core_user::get_property_type('confirmed'), 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL), 1142 'lang' => new external_value(core_user::get_property_type('lang'), 'Language code such as "en", must exist on server', VALUE_OPTIONAL), 1143 'calendartype' => new external_value(core_user::get_property_type('calendartype'), 'Calendar type such as "gregorian", must exist on server', VALUE_OPTIONAL), 1144 'theme' => new external_value(core_user::get_property_type('theme'), 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL), 1145 'timezone' => new external_value(core_user::get_property_type('timezone'), 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL), 1146 'mailformat' => new external_value(core_user::get_property_type('mailformat'), 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL), 1147 'description' => new external_value(core_user::get_property_type('description'), 'User profile description', VALUE_OPTIONAL), 1148 'descriptionformat' => new external_format_value(core_user::get_property_type('descriptionformat'), VALUE_OPTIONAL), 1149 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_OPTIONAL), 1150 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL), 1151 'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'), 1152 'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'), 1153 'customfields' => new external_multiple_structure( 1154 new external_single_structure( 1155 array( 1156 'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'), 1157 'value' => new external_value(PARAM_RAW, 'The value of the custom field'), 1158 'name' => new external_value(PARAM_RAW, 'The name of the custom field'), 1159 'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'), 1160 ) 1161 ), 'User custom fields (also known as user profile fields)', VALUE_OPTIONAL), 1162 'preferences' => new external_multiple_structure( 1163 new external_single_structure( 1164 array( 1165 'name' => new external_value(PARAM_RAW, 'The name of the preferences'), 1166 'value' => new external_value(PARAM_RAW, 'The value of the preference'), 1167 ) 1168 ), 'Users preferences', VALUE_OPTIONAL) 1169 ); 1170 if (!empty($additionalfields)) { 1171 $userfields = array_merge($userfields, $additionalfields); 1172 } 1173 return new external_single_structure($userfields); 1174 } 1175 1176 /** 1177 * Returns description of method parameters 1178 * 1179 * @return external_function_parameters 1180 * @since Moodle 2.6 1181 */ 1182 public static function add_user_private_files_parameters() { 1183 return new external_function_parameters( 1184 array( 1185 'draftid' => new external_value(PARAM_INT, 'draft area id') 1186 ) 1187 ); 1188 } 1189 1190 /** 1191 * Copy files from a draft area to users private files area. 1192 * 1193 * @throws invalid_parameter_exception 1194 * @throws moodle_exception 1195 * @param int $draftid Id of a draft area containing files. 1196 * @return array An array of warnings 1197 * @since Moodle 2.6 1198 */ 1199 public static function add_user_private_files($draftid) { 1200 global $CFG, $USER; 1201 require_once($CFG->libdir . "/filelib.php"); 1202 1203 $params = self::validate_parameters(self::add_user_private_files_parameters(), array('draftid' => $draftid)); 1204 1205 if (isguestuser()) { 1206 throw new invalid_parameter_exception('Guest users cannot upload files'); 1207 } 1208 1209 $context = context_user::instance($USER->id); 1210 require_capability('moodle/user:manageownfiles', $context); 1211 1212 $maxbytes = $CFG->userquota; 1213 $maxareabytes = $CFG->userquota; 1214 if (has_capability('moodle/user:ignoreuserquota', $context)) { 1215 $maxbytes = USER_CAN_IGNORE_FILE_SIZE_LIMITS; 1216 $maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED; 1217 } else { 1218 // Get current used space for this user (private files only). 1219 $fileareainfo = file_get_file_area_info($context->id, 'user', 'private'); 1220 $usedspace = $fileareainfo['filesize_without_references']; 1221 1222 // Get the total size of the new files we want to add to private files. 1223 $newfilesinfo = file_get_draft_area_info($params['draftid']); 1224 1225 if (($newfilesinfo['filesize_without_references'] + $usedspace) > $maxareabytes) { 1226 throw new moodle_exception('maxareabytes'); 1227 } 1228 } 1229 1230 $options = array('subdirs' => 1, 1231 'maxbytes' => $maxbytes, 1232 'maxfiles' => -1, 1233 'areamaxbytes' => $maxareabytes); 1234 1235 file_merge_files_from_draft_area_into_filearea($draftid, $context->id, 'user', 'private', 0, $options); 1236 1237 return null; 1238 } 1239 1240 /** 1241 * Returns description of method result value 1242 * 1243 * @return external_description 1244 * @since Moodle 2.2 1245 */ 1246 public static function add_user_private_files_returns() { 1247 return null; 1248 } 1249 1250 /** 1251 * Returns description of method parameters. 1252 * 1253 * @return external_function_parameters 1254 * @since Moodle 2.6 1255 */ 1256 public static function add_user_device_parameters() { 1257 return new external_function_parameters( 1258 array( 1259 'appid' => new external_value(PARAM_NOTAGS, 'the app id, usually something like com.moodle.moodlemobile'), 1260 'name' => new external_value(PARAM_NOTAGS, 'the device name, \'occam\' or \'iPhone\' etc.'), 1261 'model' => new external_value(PARAM_NOTAGS, 'the device model \'Nexus4\' or \'iPad1,1\' etc.'), 1262 'platform' => new external_value(PARAM_NOTAGS, 'the device platform \'iOS\' or \'Android\' etc.'), 1263 'version' => new external_value(PARAM_NOTAGS, 'the device version \'6.1.2\' or \'4.2.2\' etc.'), 1264 'pushid' => new external_value(PARAM_RAW, 'the device PUSH token/key/identifier/registration id'), 1265 'uuid' => new external_value(PARAM_RAW, 'the device UUID') 1266 ) 1267 ); 1268 } 1269 1270 /** 1271 * Add a user device in Moodle database (for PUSH notifications usually). 1272 * 1273 * @throws moodle_exception 1274 * @param string $appid The app id, usually something like com.moodle.moodlemobile. 1275 * @param string $name The device name, occam or iPhone etc. 1276 * @param string $model The device model Nexus4 or iPad1.1 etc. 1277 * @param string $platform The device platform iOs or Android etc. 1278 * @param string $version The device version 6.1.2 or 4.2.2 etc. 1279 * @param string $pushid The device PUSH token/key/identifier/registration id. 1280 * @param string $uuid The device UUID. 1281 * @return array List of possible warnings. 1282 * @since Moodle 2.6 1283 */ 1284 public static function add_user_device($appid, $name, $model, $platform, $version, $pushid, $uuid) { 1285 global $CFG, $USER, $DB; 1286 require_once($CFG->dirroot . "/user/lib.php"); 1287 1288 $params = self::validate_parameters(self::add_user_device_parameters(), 1289 array('appid' => $appid, 1290 'name' => $name, 1291 'model' => $model, 1292 'platform' => $platform, 1293 'version' => $version, 1294 'pushid' => $pushid, 1295 'uuid' => $uuid 1296 )); 1297 1298 $warnings = array(); 1299 1300 // Prevent duplicate keys for users. 1301 if ($DB->get_record('user_devices', array('pushid' => $params['pushid'], 'userid' => $USER->id))) { 1302 $warnings['warning'][] = array( 1303 'item' => $params['pushid'], 1304 'warningcode' => 'existingkeyforthisuser', 1305 'message' => 'This key is already stored for this user' 1306 ); 1307 return $warnings; 1308 } 1309 1310 // Notice that we can have multiple devices because previously it was allowed to have repeated ones. 1311 // Since we don't have a clear way to decide which one is the more appropiate, we update all. 1312 if ($userdevices = $DB->get_records('user_devices', array('uuid' => $params['uuid'], 1313 'appid' => $params['appid'], 'userid' => $USER->id))) { 1314 1315 foreach ($userdevices as $userdevice) { 1316 $userdevice->version = $params['version']; // Maybe the user upgraded the device. 1317 $userdevice->pushid = $params['pushid']; 1318 $userdevice->timemodified = time(); 1319 $DB->update_record('user_devices', $userdevice); 1320 } 1321 1322 } else { 1323 $userdevice = new stdclass; 1324 $userdevice->userid = $USER->id; 1325 $userdevice->appid = $params['appid']; 1326 $userdevice->name = $params['name']; 1327 $userdevice->model = $params['model']; 1328 $userdevice->platform = $params['platform']; 1329 $userdevice->version = $params['version']; 1330 $userdevice->pushid = $params['pushid']; 1331 $userdevice->uuid = $params['uuid']; 1332 $userdevice->timecreated = time(); 1333 $userdevice->timemodified = $userdevice->timecreated; 1334 1335 if (!$DB->insert_record('user_devices', $userdevice)) { 1336 throw new moodle_exception("There was a problem saving in the database the device with key: " . $params['pushid']); 1337 } 1338 } 1339 1340 return $warnings; 1341 } 1342 1343 /** 1344 * Returns description of method result value. 1345 * 1346 * @return external_multiple_structure 1347 * @since Moodle 2.6 1348 */ 1349 public static function add_user_device_returns() { 1350 return new external_multiple_structure( 1351 new external_warnings() 1352 ); 1353 } 1354 1355 /** 1356 * Returns description of method parameters. 1357 * 1358 * @return external_function_parameters 1359 * @since Moodle 2.9 1360 */ 1361 public static function remove_user_device_parameters() { 1362 return new external_function_parameters( 1363 array( 1364 'uuid' => new external_value(PARAM_RAW, 'the device UUID'), 1365 'appid' => new external_value(PARAM_NOTAGS, 1366 'the app id, if empty devices matching the UUID for the user will be removed', 1367 VALUE_DEFAULT, ''), 1368 ) 1369 ); 1370 } 1371 1372 /** 1373 * Remove a user device from the Moodle database (for PUSH notifications usually). 1374 * 1375 * @param string $uuid The device UUID. 1376 * @param string $appid The app id, opitonal parameter. If empty all the devices fmatching the UUID or the user will be removed. 1377 * @return array List of possible warnings and removal status. 1378 * @since Moodle 2.9 1379 */ 1380 public static function remove_user_device($uuid, $appid = "") { 1381 global $CFG; 1382 require_once($CFG->dirroot . "/user/lib.php"); 1383 1384 $params = self::validate_parameters(self::remove_user_device_parameters(), array('uuid' => $uuid, 'appid' => $appid)); 1385 1386 $context = context_system::instance(); 1387 self::validate_context($context); 1388 1389 // Warnings array, it can be empty at the end but is mandatory. 1390 $warnings = array(); 1391 1392 $removed = user_remove_user_device($params['uuid'], $params['appid']); 1393 1394 if (!$removed) { 1395 $warnings[] = array( 1396 'item' => $params['uuid'], 1397 'warningcode' => 'devicedoesnotexist', 1398 'message' => 'The device doesn\'t exists in the database' 1399 ); 1400 } 1401 1402 $result = array( 1403 'removed' => $removed, 1404 'warnings' => $warnings 1405 ); 1406 1407 return $result; 1408 } 1409 1410 /** 1411 * Returns description of method result value. 1412 * 1413 * @return external_multiple_structure 1414 * @since Moodle 2.9 1415 */ 1416 public static function remove_user_device_returns() { 1417 return new external_single_structure( 1418 array( 1419 'removed' => new external_value(PARAM_BOOL, 'True if removed, false if not removed because it doesn\'t exists'), 1420 'warnings' => new external_warnings(), 1421 ) 1422 ); 1423 } 1424 1425 /** 1426 * Returns description of method parameters 1427 * 1428 * @return external_function_parameters 1429 * @since Moodle 2.9 1430 */ 1431 public static function view_user_list_parameters() { 1432 return new external_function_parameters( 1433 array( 1434 'courseid' => new external_value(PARAM_INT, 'id of the course, 0 for site') 1435 ) 1436 ); 1437 } 1438 1439 /** 1440 * Trigger the user_list_viewed event. 1441 * 1442 * @param int $courseid id of course 1443 * @return array of warnings and status result 1444 * @since Moodle 2.9 1445 * @throws moodle_exception 1446 */ 1447 public static function view_user_list($courseid) { 1448 global $CFG; 1449 require_once($CFG->dirroot . "/user/lib.php"); 1450 require_once($CFG->dirroot . '/course/lib.php'); 1451 1452 $params = self::validate_parameters(self::view_user_list_parameters(), 1453 array( 1454 'courseid' => $courseid 1455 )); 1456 1457 $warnings = array(); 1458 1459 if (empty($params['courseid'])) { 1460 $params['courseid'] = SITEID; 1461 } 1462 1463 $course = get_course($params['courseid']); 1464 1465 if ($course->id == SITEID) { 1466 $context = context_system::instance(); 1467 } else { 1468 $context = context_course::instance($course->id); 1469 } 1470 self::validate_context($context); 1471 1472 course_require_view_participants($context); 1473 1474 user_list_view($course, $context); 1475 1476 $result = array(); 1477 $result['status'] = true; 1478 $result['warnings'] = $warnings; 1479 return $result; 1480 } 1481 1482 /** 1483 * Returns description of method result value 1484 * 1485 * @return external_description 1486 * @since Moodle 2.9 1487 */ 1488 public static function view_user_list_returns() { 1489 return new external_single_structure( 1490 array( 1491 'status' => new external_value(PARAM_BOOL, 'status: true if success'), 1492 'warnings' => new external_warnings() 1493 ) 1494 ); 1495 } 1496 1497 /** 1498 * Returns description of method parameters 1499 * 1500 * @return external_function_parameters 1501 * @since Moodle 2.9 1502 */ 1503 public static function view_user_profile_parameters() { 1504 return new external_function_parameters( 1505 array( 1506 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED), 1507 'courseid' => new external_value(PARAM_INT, 'id of the course, default site course', VALUE_DEFAULT, 0) 1508 ) 1509 ); 1510 } 1511 1512 /** 1513 * Trigger the user profile viewed event. 1514 * 1515 * @param int $userid id of user 1516 * @param int $courseid id of course 1517 * @return array of warnings and status result 1518 * @since Moodle 2.9 1519 * @throws moodle_exception 1520 */ 1521 public static function view_user_profile($userid, $courseid = 0) { 1522 global $CFG, $USER; 1523 require_once($CFG->dirroot . "/user/profile/lib.php"); 1524 1525 $params = self::validate_parameters(self::view_user_profile_parameters(), 1526 array( 1527 'userid' => $userid, 1528 'courseid' => $courseid 1529 )); 1530 1531 $warnings = array(); 1532 1533 if (empty($params['userid'])) { 1534 $params['userid'] = $USER->id; 1535 } 1536 1537 if (empty($params['courseid'])) { 1538 $params['courseid'] = SITEID; 1539 } 1540 1541 $course = get_course($params['courseid']); 1542 $user = core_user::get_user($params['userid'], '*', MUST_EXIST); 1543 core_user::require_active_user($user); 1544 1545 if ($course->id == SITEID) { 1546 $coursecontext = context_system::instance();; 1547 } else { 1548 $coursecontext = context_course::instance($course->id); 1549 } 1550 self::validate_context($coursecontext); 1551 1552 $currentuser = $USER->id == $user->id; 1553 $usercontext = context_user::instance($user->id); 1554 1555 if (!$currentuser and 1556 !has_capability('moodle/user:viewdetails', $coursecontext) and 1557 !has_capability('moodle/user:viewdetails', $usercontext)) { 1558 throw new moodle_exception('cannotviewprofile'); 1559 } 1560 1561 // Case like user/profile.php. 1562 if ($course->id == SITEID) { 1563 profile_view($user, $usercontext); 1564 } else { 1565 // Case like user/view.php. 1566 if (!$currentuser and !can_access_course($course, $user, '', true)) { 1567 throw new moodle_exception('notenrolledprofile'); 1568 } 1569 1570 profile_view($user, $coursecontext, $course); 1571 } 1572 1573 $result = array(); 1574 $result['status'] = true; 1575 $result['warnings'] = $warnings; 1576 return $result; 1577 } 1578 1579 /** 1580 * Returns description of method result value 1581 * 1582 * @return external_description 1583 * @since Moodle 2.9 1584 */ 1585 public static function view_user_profile_returns() { 1586 return new external_single_structure( 1587 array( 1588 'status' => new external_value(PARAM_BOOL, 'status: true if success'), 1589 'warnings' => new external_warnings() 1590 ) 1591 ); 1592 } 1593 1594 /** 1595 * Returns description of method parameters 1596 * 1597 * @return external_function_parameters 1598 * @since Moodle 3.2 1599 */ 1600 public static function get_user_preferences_parameters() { 1601 return new external_function_parameters( 1602 array( 1603 'name' => new external_value(PARAM_RAW, 'preference name, empty for all', VALUE_DEFAULT, ''), 1604 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0) 1605 ) 1606 ); 1607 } 1608 1609 /** 1610 * Return user preferences. 1611 * 1612 * @param string $name preference name, empty for all 1613 * @param int $userid id of the user, 0 for current user 1614 * @return array of warnings and preferences 1615 * @since Moodle 3.2 1616 * @throws moodle_exception 1617 */ 1618 public static function get_user_preferences($name = '', $userid = 0) { 1619 global $USER; 1620 1621 $params = self::validate_parameters(self::get_user_preferences_parameters(), 1622 array( 1623 'name' => $name, 1624 'userid' => $userid 1625 )); 1626 $preferences = array(); 1627 $warnings = array(); 1628 1629 $context = context_system::instance(); 1630 self::validate_context($context); 1631 1632 if (empty($params['name'])) { 1633 $name = null; 1634 } 1635 if (empty($params['userid'])) { 1636 $user = null; 1637 } else { 1638 $user = core_user::get_user($params['userid'], '*', MUST_EXIST); 1639 core_user::require_active_user($user); 1640 if ($user->id != $USER->id) { 1641 // Only admins can retrieve other users preferences. 1642 require_capability('moodle/site:config', $context); 1643 } 1644 } 1645 1646 $userpreferences = get_user_preferences($name, null, $user); 1647 // Check if we received just one preference. 1648 if (!is_array($userpreferences)) { 1649 $userpreferences = array($name => $userpreferences); 1650 } 1651 1652 foreach ($userpreferences as $name => $value) { 1653 $preferences[] = array( 1654 'name' => $name, 1655 'value' => $value, 1656 ); 1657 } 1658 1659 $result = array(); 1660 $result['preferences'] = $preferences; 1661 $result['warnings'] = $warnings; 1662 return $result; 1663 } 1664 1665 /** 1666 * Returns description of method result value 1667 * 1668 * @return external_description 1669 * @since Moodle 3.2 1670 */ 1671 public static function get_user_preferences_returns() { 1672 return new external_single_structure( 1673 array( 1674 'preferences' => new external_multiple_structure( 1675 new external_single_structure( 1676 array( 1677 'name' => new external_value(PARAM_RAW, 'The name of the preference'), 1678 'value' => new external_value(PARAM_RAW, 'The value of the preference'), 1679 ) 1680 ), 1681 'User custom fields (also known as user profile fields)' 1682 ), 1683 'warnings' => new external_warnings() 1684 ) 1685 ); 1686 } 1687 1688 /** 1689 * Returns description of method parameters 1690 * 1691 * @return external_function_parameters 1692 * @since Moodle 3.2 1693 */ 1694 public static function update_picture_parameters() { 1695 return new external_function_parameters( 1696 array( 1697 'draftitemid' => new external_value(PARAM_INT, 'Id of the user draft file to use as image'), 1698 'delete' => new external_value(PARAM_BOOL, 'If we should delete the user picture', VALUE_DEFAULT, false), 1699 'userid' => new external_value(PARAM_INT, 'Id of the user, 0 for current user', VALUE_DEFAULT, 0) 1700 ) 1701 ); 1702 } 1703 1704 /** 1705 * Update or delete the user picture in the site 1706 * 1707 * @param int $draftitemid id of the user draft file to use as image 1708 * @param bool $delete if we should delete the user picture 1709 * @param int $userid id of the user, 0 for current user 1710 * @return array warnings and success status 1711 * @since Moodle 3.2 1712 * @throws moodle_exception 1713 */ 1714 public static function update_picture($draftitemid, $delete = false, $userid = 0) { 1715 global $CFG, $USER, $PAGE; 1716 1717 $params = self::validate_parameters( 1718 self::update_picture_parameters(), 1719 array( 1720 'draftitemid' => $draftitemid, 1721 'delete' => $delete, 1722 'userid' => $userid 1723 ) 1724 ); 1725 1726 $context = context_system::instance(); 1727 self::validate_context($context); 1728 1729 if (!empty($CFG->disableuserimages)) { 1730 throw new moodle_exception('userimagesdisabled', 'admin'); 1731 } 1732 1733 if (empty($params['userid']) or $params['userid'] == $USER->id) { 1734 $user = $USER; 1735 require_capability('moodle/user:editownprofile', $context); 1736 } else { 1737 $user = core_user::get_user($params['userid'], '*', MUST_EXIST); 1738 core_user::require_active_user($user); 1739 $personalcontext = context_user::instance($user->id); 1740 1741 require_capability('moodle/user:editprofile', $personalcontext); 1742 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins. 1743 throw new moodle_exception('useradmineditadmin'); 1744 } 1745 } 1746 1747 // Load the appropriate auth plugin. 1748 $userauth = get_auth_plugin($user->auth); 1749 if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) { 1750 throw new moodle_exception('noprofileedit', 'auth'); 1751 } 1752 1753 $filemanageroptions = array( 1754 'maxbytes' => $CFG->maxbytes, 1755 'subdirs' => 0, 1756 'maxfiles' => 1, 1757 'accepted_types' => 'optimised_image' 1758 ); 1759 $user->deletepicture = $params['delete']; 1760 $user->imagefile = $params['draftitemid']; 1761 $success = core_user::update_picture($user, $filemanageroptions); 1762 1763 $result = array( 1764 'success' => $success, 1765 'warnings' => array(), 1766 ); 1767 if ($success) { 1768 $userpicture = new user_picture(core_user::get_user($user->id)); 1769 $userpicture->size = 1; // Size f1. 1770 $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); 1771 } 1772 return $result; 1773 } 1774 1775 /** 1776 * Returns description of method result value 1777 * 1778 * @return external_description 1779 * @since Moodle 3.2 1780 */ 1781 public static function update_picture_returns() { 1782 return new external_single_structure( 1783 array( 1784 'success' => new external_value(PARAM_BOOL, 'True if the image was updated, false otherwise.'), 1785 'profileimageurl' => new external_value(PARAM_URL, 'New profile user image url', VALUE_OPTIONAL), 1786 'warnings' => new external_warnings() 1787 ) 1788 ); 1789 } 1790 1791 /** 1792 * Returns description of method parameters 1793 * 1794 * @return external_function_parameters 1795 * @since Moodle 3.2 1796 */ 1797 public static function set_user_preferences_parameters() { 1798 return new external_function_parameters( 1799 array( 1800 'preferences' => new external_multiple_structure( 1801 new external_single_structure( 1802 array( 1803 'name' => new external_value(PARAM_RAW, 'The name of the preference'), 1804 'value' => new external_value(PARAM_RAW, 'The value of the preference'), 1805 'userid' => new external_value(PARAM_INT, 'Id of the user to set the preference'), 1806 ) 1807 ) 1808 ) 1809 ) 1810 ); 1811 } 1812 1813 /** 1814 * Set user preferences. 1815 * 1816 * @param array $preferences list of preferences including name, value and userid 1817 * @return array of warnings and preferences saved 1818 * @since Moodle 3.2 1819 * @throws moodle_exception 1820 */ 1821 public static function set_user_preferences($preferences) { 1822 global $USER; 1823 1824 $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences)); 1825 $warnings = array(); 1826 $saved = array(); 1827 1828 $context = context_system::instance(); 1829 self::validate_context($context); 1830 1831 $userscache = array(); 1832 foreach ($params['preferences'] as $pref) { 1833 // Check to which user set the preference. 1834 if (!empty($userscache[$pref['userid']])) { 1835 $user = $userscache[$pref['userid']]; 1836 } else { 1837 try { 1838 $user = core_user::get_user($pref['userid'], '*', MUST_EXIST); 1839 core_user::require_active_user($user); 1840 $userscache[$pref['userid']] = $user; 1841 } catch (Exception $e) { 1842 $warnings[] = array( 1843 'item' => 'user', 1844 'itemid' => $pref['userid'], 1845 'warningcode' => 'invaliduser', 1846 'message' => $e->getMessage() 1847 ); 1848 continue; 1849 } 1850 } 1851 1852 try { 1853 if (core_user::can_edit_preference($pref['name'], $user)) { 1854 $value = core_user::clean_preference($pref['value'], $pref['name']); 1855 set_user_preference($pref['name'], $value, $user->id); 1856 $saved[] = array( 1857 'name' => $pref['name'], 1858 'userid' => $user->id, 1859 ); 1860 } else { 1861 $warnings[] = array( 1862 'item' => 'user', 1863 'itemid' => $user->id, 1864 'warningcode' => 'nopermission', 1865 'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id 1866 ); 1867 } 1868 } catch (Exception $e) { 1869 $warnings[] = array( 1870 'item' => 'user', 1871 'itemid' => $user->id, 1872 'warningcode' => 'errorsavingpreference', 1873 'message' => $e->getMessage() 1874 ); 1875 } 1876 } 1877 1878 $result = array(); 1879 $result['saved'] = $saved; 1880 $result['warnings'] = $warnings; 1881 return $result; 1882 } 1883 1884 /** 1885 * Returns description of method result value 1886 * 1887 * @return external_description 1888 * @since Moodle 3.2 1889 */ 1890 public static function set_user_preferences_returns() { 1891 return new external_single_structure( 1892 array( 1893 'saved' => new external_multiple_structure( 1894 new external_single_structure( 1895 array( 1896 'name' => new external_value(PARAM_RAW, 'The name of the preference'), 1897 'userid' => new external_value(PARAM_INT, 'The user the preference was set for'), 1898 ) 1899 ), 'Preferences saved' 1900 ), 1901 'warnings' => new external_warnings() 1902 ) 1903 ); 1904 } 1905 1906 /** 1907 * Returns description of method parameters. 1908 * 1909 * @return external_function_parameters 1910 * @since Moodle 3.2 1911 */ 1912 public static function agree_site_policy_parameters() { 1913 return new external_function_parameters(array()); 1914 } 1915 1916 /** 1917 * Agree the site policy for the current user. 1918 * 1919 * @return array of warnings and status result 1920 * @since Moodle 3.2 1921 * @throws moodle_exception 1922 */ 1923 public static function agree_site_policy() { 1924 global $CFG, $DB, $USER; 1925 1926 $warnings = array(); 1927 1928 $context = context_system::instance(); 1929 try { 1930 // We expect an exception here since the user didn't agree the site policy yet. 1931 self::validate_context($context); 1932 } catch (Exception $e) { 1933 // We are expecting only a sitepolicynotagreed exception. 1934 if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') { 1935 // In case we receive a different exception, throw it. 1936 throw $e; 1937 } 1938 } 1939 1940 $manager = new \core_privacy\local\sitepolicy\manager(); 1941 if (!empty($USER->policyagreed)) { 1942 $status = false; 1943 $warnings[] = array( 1944 'item' => 'user', 1945 'itemid' => $USER->id, 1946 'warningcode' => 'alreadyagreed', 1947 'message' => 'The user already agreed the site policy.' 1948 ); 1949 } else if (!$manager->is_defined()) { 1950 $status = false; 1951 $warnings[] = array( 1952 'item' => 'user', 1953 'itemid' => $USER->id, 1954 'warningcode' => 'nositepolicy', 1955 'message' => 'The site does not have a site policy configured.' 1956 ); 1957 } else { 1958 $status = $manager->accept(); 1959 } 1960 1961 $result = array(); 1962 $result['status'] = $status; 1963 $result['warnings'] = $warnings; 1964 return $result; 1965 } 1966 1967 /** 1968 * Returns description of method result value. 1969 * 1970 * @return external_description 1971 * @since Moodle 3.2 1972 */ 1973 public static function agree_site_policy_returns() { 1974 return new external_single_structure( 1975 array( 1976 'status' => new external_value(PARAM_BOOL, 'Status: true only if we set the policyagreed to 1 for the user'), 1977 'warnings' => new external_warnings() 1978 ) 1979 ); 1980 } 1981 1982 /** 1983 * Returns description of method parameters. 1984 * 1985 * @return external_function_parameters 1986 * @since Moodle 3.4 1987 */ 1988 public static function get_private_files_info_parameters() { 1989 return new external_function_parameters( 1990 array( 1991 'userid' => new external_value(PARAM_INT, 'Id of the user, default to current user.', VALUE_DEFAULT, 0) 1992 ) 1993 ); 1994 } 1995 1996 /** 1997 * Returns general information about files in the user private files area. 1998 * 1999 * @param int $userid Id of the user, default to current user. 2000 * @return array of warnings and file area information 2001 * @since Moodle 3.4 2002 * @throws moodle_exception 2003 */ 2004 public static function get_private_files_info($userid = 0) { 2005 global $CFG, $USER; 2006 require_once($CFG->libdir . '/filelib.php'); 2007 2008 $params = self::validate_parameters(self::get_private_files_info_parameters(), array('userid' => $userid)); 2009 $warnings = array(); 2010 2011 $context = context_system::instance(); 2012 self::validate_context($context); 2013 2014 if (empty($params['userid']) || $params['userid'] == $USER->id) { 2015 $usercontext = context_user::instance($USER->id); 2016 require_capability('moodle/user:manageownfiles', $usercontext); 2017 } else { 2018 $user = core_user::get_user($params['userid'], '*', MUST_EXIST); 2019 core_user::require_active_user($user); 2020 // Only admins can retrieve other users information. 2021 require_capability('moodle/site:config', $context); 2022 $usercontext = context_user::instance($user->id); 2023 } 2024 2025 $fileareainfo = file_get_file_area_info($usercontext->id, 'user', 'private'); 2026 2027 $result = array(); 2028 $result['filecount'] = $fileareainfo['filecount']; 2029 $result['foldercount'] = $fileareainfo['foldercount']; 2030 $result['filesize'] = $fileareainfo['filesize']; 2031 $result['filesizewithoutreferences'] = $fileareainfo['filesize_without_references']; 2032 $result['warnings'] = $warnings; 2033 return $result; 2034 } 2035 2036 /** 2037 * Returns description of method result value. 2038 * 2039 * @return external_description 2040 * @since Moodle 3.4 2041 */ 2042 public static function get_private_files_info_returns() { 2043 return new external_single_structure( 2044 array( 2045 'filecount' => new external_value(PARAM_INT, 'Number of files in the area.'), 2046 'foldercount' => new external_value(PARAM_INT, 'Number of folders in the area.'), 2047 'filesize' => new external_value(PARAM_INT, 'Total size of the files in the area.'), 2048 'filesizewithoutreferences' => new external_value(PARAM_INT, 'Total size of the area excluding file references'), 2049 'warnings' => new external_warnings() 2050 ) 2051 ); 2052 } 2053 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body