Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 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 * @copyright 2009 Moodle Pty Ltd (http://moodle.com) 22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 */ 24 25 define('USER_FILTER_ENROLMENT', 1); 26 define('USER_FILTER_GROUP', 2); 27 define('USER_FILTER_LAST_ACCESS', 3); 28 define('USER_FILTER_ROLE', 4); 29 define('USER_FILTER_STATUS', 5); 30 define('USER_FILTER_STRING', 6); 31 32 /** 33 * Creates a user 34 * 35 * @throws moodle_exception 36 * @param stdClass|array $user user to create 37 * @param bool $updatepassword if true, authentication plugin will update password. 38 * @param bool $triggerevent set false if user_created event should not be triggred. 39 * This will not affect user_password_updated event triggering. 40 * @return int id of the newly created user 41 */ 42 function user_create_user($user, $updatepassword = true, $triggerevent = true) { 43 global $DB; 44 45 // Set the timecreate field to the current time. 46 if (!is_object($user)) { 47 $user = (object) $user; 48 } 49 50 // Check username. 51 if (trim($user->username) === '') { 52 throw new moodle_exception('invalidusernameblank'); 53 } 54 55 if ($user->username !== core_text::strtolower($user->username)) { 56 throw new moodle_exception('usernamelowercase'); 57 } 58 59 if ($user->username !== core_user::clean_field($user->username, 'username')) { 60 throw new moodle_exception('invalidusername'); 61 } 62 63 // Save the password in a temp value for later. 64 if ($updatepassword && isset($user->password)) { 65 66 // Check password toward the password policy. 67 if (!check_password_policy($user->password, $errmsg, $user)) { 68 throw new moodle_exception($errmsg); 69 } 70 71 $userpassword = $user->password; 72 unset($user->password); 73 } 74 75 // Apply default values for user preferences that are stored in users table. 76 if (!isset($user->calendartype)) { 77 $user->calendartype = core_user::get_property_default('calendartype'); 78 } 79 if (!isset($user->maildisplay)) { 80 $user->maildisplay = core_user::get_property_default('maildisplay'); 81 } 82 if (!isset($user->mailformat)) { 83 $user->mailformat = core_user::get_property_default('mailformat'); 84 } 85 if (!isset($user->maildigest)) { 86 $user->maildigest = core_user::get_property_default('maildigest'); 87 } 88 if (!isset($user->autosubscribe)) { 89 $user->autosubscribe = core_user::get_property_default('autosubscribe'); 90 } 91 if (!isset($user->trackforums)) { 92 $user->trackforums = core_user::get_property_default('trackforums'); 93 } 94 if (!isset($user->lang)) { 95 $user->lang = core_user::get_property_default('lang'); 96 } 97 if (!isset($user->city)) { 98 $user->city = core_user::get_property_default('city'); 99 } 100 if (!isset($user->country)) { 101 // The default value of $CFG->country is 0, but that isn't a valid property for the user field, so switch to ''. 102 $user->country = core_user::get_property_default('country') ?: ''; 103 } 104 105 $user->timecreated = time(); 106 $user->timemodified = $user->timecreated; 107 108 // Validate user data object. 109 $uservalidation = core_user::validate($user); 110 if ($uservalidation !== true) { 111 foreach ($uservalidation as $field => $message) { 112 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER); 113 $user->$field = core_user::clean_field($user->$field, $field); 114 } 115 } 116 117 // Insert the user into the database. 118 $newuserid = $DB->insert_record('user', $user); 119 120 // Create USER context for this user. 121 $usercontext = context_user::instance($newuserid); 122 123 // Update user password if necessary. 124 if (isset($userpassword)) { 125 // Get full database user row, in case auth is default. 126 $newuser = $DB->get_record('user', array('id' => $newuserid)); 127 $authplugin = get_auth_plugin($newuser->auth); 128 $authplugin->user_update_password($newuser, $userpassword); 129 } 130 131 // Trigger event If required. 132 if ($triggerevent) { 133 \core\event\user_created::create_from_userid($newuserid)->trigger(); 134 } 135 136 // Purge the associated caches for the current user only. 137 $presignupcache = \cache::make('core', 'presignup'); 138 $presignupcache->purge_current_user(); 139 140 return $newuserid; 141 } 142 143 /** 144 * Update a user with a user object (will compare against the ID) 145 * 146 * @throws moodle_exception 147 * @param stdClass|array $user the user to update 148 * @param bool $updatepassword if true, authentication plugin will update password. 149 * @param bool $triggerevent set false if user_updated event should not be triggred. 150 * This will not affect user_password_updated event triggering. 151 */ 152 function user_update_user($user, $updatepassword = true, $triggerevent = true) { 153 global $DB; 154 155 // Set the timecreate field to the current time. 156 if (!is_object($user)) { 157 $user = (object) $user; 158 } 159 160 // Check username. 161 if (isset($user->username)) { 162 if ($user->username !== core_text::strtolower($user->username)) { 163 throw new moodle_exception('usernamelowercase'); 164 } else { 165 if ($user->username !== core_user::clean_field($user->username, 'username')) { 166 throw new moodle_exception('invalidusername'); 167 } 168 } 169 } 170 171 // Unset password here, for updating later, if password update is required. 172 if ($updatepassword && isset($user->password)) { 173 174 // Check password toward the password policy. 175 if (!check_password_policy($user->password, $errmsg, $user)) { 176 throw new moodle_exception($errmsg); 177 } 178 179 $passwd = $user->password; 180 unset($user->password); 181 } 182 183 // Make sure calendartype, if set, is valid. 184 if (empty($user->calendartype)) { 185 // Unset this variable, must be an empty string, which we do not want to update the calendartype to. 186 unset($user->calendartype); 187 } 188 189 $user->timemodified = time(); 190 191 // Validate user data object. 192 $uservalidation = core_user::validate($user); 193 if ($uservalidation !== true) { 194 foreach ($uservalidation as $field => $message) { 195 debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER); 196 $user->$field = core_user::clean_field($user->$field, $field); 197 } 198 } 199 200 $DB->update_record('user', $user); 201 202 if ($updatepassword) { 203 // Get full user record. 204 $updateduser = $DB->get_record('user', array('id' => $user->id)); 205 206 // If password was set, then update its hash. 207 if (isset($passwd)) { 208 $authplugin = get_auth_plugin($updateduser->auth); 209 if ($authplugin->can_change_password()) { 210 $authplugin->user_update_password($updateduser, $passwd); 211 } 212 } 213 } 214 // Trigger event if required. 215 if ($triggerevent) { 216 \core\event\user_updated::create_from_userid($user->id)->trigger(); 217 } 218 } 219 220 /** 221 * Marks user deleted in internal user database and notifies the auth plugin. 222 * Also unenrols user from all roles and does other cleanup. 223 * 224 * @todo Decide if this transaction is really needed (look for internal TODO:) 225 * @param object $user Userobject before delete (without system magic quotes) 226 * @return boolean success 227 */ 228 function user_delete_user($user) { 229 return delete_user($user); 230 } 231 232 /** 233 * Get users by id 234 * 235 * @param array $userids id of users to retrieve 236 * @return array 237 */ 238 function user_get_users_by_id($userids) { 239 global $DB; 240 return $DB->get_records_list('user', 'id', $userids); 241 } 242 243 /** 244 * Returns the list of default 'displayable' fields 245 * 246 * Contains database field names but also names used to generate information, such as enrolledcourses 247 * 248 * @return array of user fields 249 */ 250 function user_get_default_fields() { 251 return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email', 252 'address', 'phone1', 'phone2', 'department', 253 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed', 254 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat', 255 'city', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields', 256 'groups', 'roles', 'preferences', 'enrolledcourses', 'suspended', 'lastcourseaccess' 257 ); 258 } 259 260 /** 261 * 262 * Give user record from mdl_user, build an array contains all user details. 263 * 264 * Warning: description file urls are 'webservice/pluginfile.php' is use. 265 * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile 266 * 267 * @throws moodle_exception 268 * @param stdClass $user user record from mdl_user 269 * @param stdClass $course moodle course 270 * @param array $userfields required fields 271 * @return array|null 272 */ 273 function user_get_user_details($user, $course = null, array $userfields = array()) { 274 global $USER, $DB, $CFG, $PAGE; 275 require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library. 276 require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends. 277 278 $defaultfields = user_get_default_fields(); 279 280 if (empty($userfields)) { 281 $userfields = $defaultfields; 282 } 283 284 foreach ($userfields as $thefield) { 285 if (!in_array($thefield, $defaultfields)) { 286 throw new moodle_exception('invaliduserfield', 'error', '', $thefield); 287 } 288 } 289 290 // Make sure id and fullname are included. 291 if (!in_array('id', $userfields)) { 292 $userfields[] = 'id'; 293 } 294 295 if (!in_array('fullname', $userfields)) { 296 $userfields[] = 'fullname'; 297 } 298 299 if (!empty($course)) { 300 $context = context_course::instance($course->id); 301 $usercontext = context_user::instance($user->id); 302 $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext)); 303 } else { 304 $context = context_user::instance($user->id); 305 $usercontext = $context; 306 $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext); 307 } 308 309 $currentuser = ($user->id == $USER->id); 310 $isadmin = is_siteadmin($USER); 311 312 // This does not need to include custom profile fields as it is only used to check specific 313 // fields below. 314 $showuseridentityfields = \core_user\fields::get_identity_fields($context, false); 315 316 if (!empty($course)) { 317 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); 318 } else { 319 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context); 320 } 321 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context); 322 if (!empty($course)) { 323 $canviewuseremail = has_capability('moodle/course:useremail', $context); 324 } else { 325 $canviewuseremail = false; 326 } 327 $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id)); 328 if (!empty($course)) { 329 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); 330 } else { 331 $canaccessallgroups = false; 332 } 333 334 if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) { 335 // Skip this user details. 336 return null; 337 } 338 339 $userdetails = array(); 340 $userdetails['id'] = $user->id; 341 342 if (in_array('username', $userfields)) { 343 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) { 344 $userdetails['username'] = $user->username; 345 } 346 } 347 if ($isadmin or $canviewfullnames) { 348 if (in_array('firstname', $userfields)) { 349 $userdetails['firstname'] = $user->firstname; 350 } 351 if (in_array('lastname', $userfields)) { 352 $userdetails['lastname'] = $user->lastname; 353 } 354 } 355 $userdetails['fullname'] = fullname($user, $canviewfullnames); 356 357 if (in_array('customfields', $userfields)) { 358 $categories = profile_get_user_fields_with_data_by_category($user->id); 359 $userdetails['customfields'] = array(); 360 foreach ($categories as $categoryid => $fields) { 361 foreach ($fields as $formfield) { 362 if ($formfield->is_visible() and !$formfield->is_empty()) { 363 364 $userdetails['customfields'][] = [ 365 'name' => $formfield->field->name, 366 'value' => $formfield->data, 367 'displayvalue' => $formfield->display_data(), 368 'type' => $formfield->field->datatype, 369 'shortname' => $formfield->field->shortname 370 ]; 371 } 372 } 373 } 374 // Unset customfields if it's empty. 375 if (empty($userdetails['customfields'])) { 376 unset($userdetails['customfields']); 377 } 378 } 379 380 // Profile image. 381 if (in_array('profileimageurl', $userfields)) { 382 $userpicture = new user_picture($user); 383 $userpicture->size = 1; // Size f1. 384 $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); 385 } 386 if (in_array('profileimageurlsmall', $userfields)) { 387 if (!isset($userpicture)) { 388 $userpicture = new user_picture($user); 389 } 390 $userpicture->size = 0; // Size f2. 391 $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false); 392 } 393 394 // Hidden user field. 395 if ($canviewhiddenuserfields) { 396 $hiddenfields = array(); 397 } else { 398 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); 399 } 400 401 402 if (!empty($user->address) && (in_array('address', $userfields) 403 && in_array('address', $showuseridentityfields) || $isadmin)) { 404 $userdetails['address'] = $user->address; 405 } 406 if (!empty($user->phone1) && (in_array('phone1', $userfields) 407 && in_array('phone1', $showuseridentityfields) || $isadmin)) { 408 $userdetails['phone1'] = $user->phone1; 409 } 410 if (!empty($user->phone2) && (in_array('phone2', $userfields) 411 && in_array('phone2', $showuseridentityfields) || $isadmin)) { 412 $userdetails['phone2'] = $user->phone2; 413 } 414 415 if (isset($user->description) && 416 ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) { 417 if (in_array('description', $userfields)) { 418 // Always return the descriptionformat if description is requested. 419 list($userdetails['description'], $userdetails['descriptionformat']) = 420 \core_external\util::format_text($user->description, $user->descriptionformat, 421 $usercontext, 'user', 'profile', null); 422 } 423 } 424 425 if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) { 426 $userdetails['country'] = $user->country; 427 } 428 429 if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) { 430 $userdetails['city'] = $user->city; 431 } 432 433 if (in_array('timezone', $userfields) && (!isset($hiddenfields['timezone']) || $isadmin) && $user->timezone) { 434 $userdetails['timezone'] = $user->timezone; 435 } 436 437 if (in_array('suspended', $userfields) && (!isset($hiddenfields['suspended']) or $isadmin)) { 438 $userdetails['suspended'] = (bool)$user->suspended; 439 } 440 441 if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) { 442 if ($user->firstaccess) { 443 $userdetails['firstaccess'] = $user->firstaccess; 444 } else { 445 $userdetails['firstaccess'] = 0; 446 } 447 } 448 if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) { 449 if ($user->lastaccess) { 450 $userdetails['lastaccess'] = $user->lastaccess; 451 } else { 452 $userdetails['lastaccess'] = 0; 453 } 454 } 455 456 // Hidden fields restriction to lastaccess field applies to both site and course access time. 457 if (in_array('lastcourseaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) { 458 if (isset($user->lastcourseaccess)) { 459 $userdetails['lastcourseaccess'] = $user->lastcourseaccess; 460 } else { 461 $userdetails['lastcourseaccess'] = 0; 462 } 463 } 464 465 if (in_array('email', $userfields) && ( 466 $currentuser 467 or (!isset($hiddenfields['email']) and ( 468 $user->maildisplay == core_user::MAILDISPLAY_EVERYONE 469 or ($user->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY and enrol_sharing_course($user, $USER)) 470 or $canviewuseremail // TODO: Deprecate/remove for MDL-37479. 471 )) 472 or in_array('email', $showuseridentityfields) 473 )) { 474 $userdetails['email'] = $user->email; 475 } 476 477 if (in_array('interests', $userfields)) { 478 $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false); 479 if ($interests) { 480 $userdetails['interests'] = join(', ', $interests); 481 } 482 } 483 484 // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile. 485 if (in_array('idnumber', $userfields) && $user->idnumber) { 486 if (in_array('idnumber', $showuseridentityfields) or $currentuser or 487 has_capability('moodle/user:viewalldetails', $context)) { 488 $userdetails['idnumber'] = $user->idnumber; 489 } 490 } 491 if (in_array('institution', $userfields) && $user->institution) { 492 if (in_array('institution', $showuseridentityfields) or $currentuser or 493 has_capability('moodle/user:viewalldetails', $context)) { 494 $userdetails['institution'] = $user->institution; 495 } 496 } 497 // Isset because it's ok to have department 0. 498 if (in_array('department', $userfields) && isset($user->department)) { 499 if (in_array('department', $showuseridentityfields) or $currentuser or 500 has_capability('moodle/user:viewalldetails', $context)) { 501 $userdetails['department'] = $user->department; 502 } 503 } 504 505 if (in_array('roles', $userfields) && !empty($course)) { 506 // Not a big secret. 507 $roles = get_user_roles($context, $user->id, false); 508 $userdetails['roles'] = array(); 509 foreach ($roles as $role) { 510 $userdetails['roles'][] = array( 511 'roleid' => $role->roleid, 512 'name' => $role->name, 513 'shortname' => $role->shortname, 514 'sortorder' => $role->sortorder 515 ); 516 } 517 } 518 519 // Return user groups. 520 if (in_array('groups', $userfields) && !empty($course)) { 521 if ($usergroups = groups_get_all_groups($course->id, $user->id)) { 522 $userdetails['groups'] = []; 523 foreach ($usergroups as $group) { 524 if ($course->groupmode == SEPARATEGROUPS && !$canaccessallgroups && $user->id != $USER->id) { 525 // In separate groups, I only have to see the groups shared between both users. 526 if (!groups_is_member($group->id, $USER->id)) { 527 continue; 528 } 529 } 530 531 $userdetails['groups'][] = [ 532 'id' => $group->id, 533 'name' => format_string($group->name), 534 'description' => format_text($group->description, $group->descriptionformat, ['context' => $context]), 535 'descriptionformat' => $group->descriptionformat 536 ]; 537 } 538 } 539 } 540 // List of courses where the user is enrolled. 541 if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) { 542 $enrolledcourses = array(); 543 if ($mycourses = enrol_get_users_courses($user->id, true)) { 544 foreach ($mycourses as $mycourse) { 545 if ($mycourse->category) { 546 $coursecontext = context_course::instance($mycourse->id); 547 $enrolledcourse = array(); 548 $enrolledcourse['id'] = $mycourse->id; 549 $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext)); 550 $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); 551 $enrolledcourses[] = $enrolledcourse; 552 } 553 } 554 $userdetails['enrolledcourses'] = $enrolledcourses; 555 } 556 } 557 558 // User preferences. 559 if (in_array('preferences', $userfields) && $currentuser) { 560 $preferences = array(); 561 $userpreferences = get_user_preferences(); 562 foreach ($userpreferences as $prefname => $prefvalue) { 563 $preferences[] = array('name' => $prefname, 'value' => $prefvalue); 564 } 565 $userdetails['preferences'] = $preferences; 566 } 567 568 if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) { 569 $extrafields = ['auth', 'confirmed', 'lang', 'theme', 'mailformat']; 570 foreach ($extrafields as $extrafield) { 571 if (in_array($extrafield, $userfields) && isset($user->$extrafield)) { 572 $userdetails[$extrafield] = $user->$extrafield; 573 } 574 } 575 } 576 577 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs). 578 if (isset($userdetails['lang'])) { 579 $userdetails['lang'] = clean_param($userdetails['lang'], PARAM_LANG); 580 } 581 if (isset($userdetails['theme'])) { 582 $userdetails['theme'] = clean_param($userdetails['theme'], PARAM_THEME); 583 } 584 585 return $userdetails; 586 } 587 588 /** 589 * Tries to obtain user details, either recurring directly to the user's system profile 590 * or through one of the user's course enrollments (course profile). 591 * 592 * You can use the $userfields parameter to reduce the amount of a user record that is required by the method. 593 * The minimum user fields are: 594 * * id 595 * * deleted 596 * * all potential fullname fields 597 * 598 * @param stdClass $user The user. 599 * @param array $userfields An array of userfields to be returned, the values must be a 600 * subset of user_get_default_fields (optional) 601 * @return array if unsuccessful or the allowed user details. 602 */ 603 function user_get_user_details_courses($user, array $userfields = []) { 604 global $USER; 605 $userdetails = null; 606 607 $systemprofile = false; 608 if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) { 609 $systemprofile = true; 610 } 611 612 // Try using system profile. 613 if ($systemprofile) { 614 $userdetails = user_get_user_details($user, null, $userfields); 615 } else { 616 // Try through course profile. 617 // Get the courses that the user is enrolled in (only active). 618 $courses = enrol_get_users_courses($user->id, true); 619 foreach ($courses as $course) { 620 if (user_can_view_profile($user, $course)) { 621 $userdetails = user_get_user_details($user, $course, $userfields); 622 } 623 } 624 } 625 626 return $userdetails; 627 } 628 629 /** 630 * Check if $USER have the necessary capabilities to obtain user details. 631 * 632 * @param stdClass $user 633 * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile. 634 * @return bool true if $USER can view user details. 635 */ 636 function can_view_user_details_cap($user, $course = null) { 637 // Check $USER has the capability to view the user details at user context. 638 $usercontext = context_user::instance($user->id); 639 $result = has_capability('moodle/user:viewdetails', $usercontext); 640 // Otherwise can $USER see them at course context. 641 if (!$result && !empty($course)) { 642 $context = context_course::instance($course->id); 643 $result = has_capability('moodle/user:viewdetails', $context); 644 } 645 return $result; 646 } 647 648 /** 649 * Return a list of page types 650 * @param string $pagetype current page type 651 * @param stdClass $parentcontext Block's parent context 652 * @param stdClass $currentcontext Current context of block 653 * @return array 654 */ 655 function user_page_type_list($pagetype, $parentcontext, $currentcontext) { 656 return array('user-profile' => get_string('page-user-profile', 'pagetype')); 657 } 658 659 /** 660 * Count the number of failed login attempts for the given user, since last successful login. 661 * 662 * @param int|stdclass $user user id or object. 663 * @param bool $reset Resets failed login count, if set to true. 664 * 665 * @return int number of failed login attempts since the last successful login. 666 */ 667 function user_count_login_failures($user, $reset = true) { 668 global $DB; 669 670 if (!is_object($user)) { 671 $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST); 672 } 673 if ($user->deleted) { 674 // Deleted user, nothing to do. 675 return 0; 676 } 677 $count = get_user_preferences('login_failed_count_since_success', 0, $user); 678 if ($reset) { 679 set_user_preference('login_failed_count_since_success', 0, $user); 680 } 681 return $count; 682 } 683 684 /** 685 * Converts a string into a flat array of menu items, where each menu items is a 686 * stdClass with fields type, url, title. 687 * 688 * @param string $text the menu items definition 689 * @param moodle_page $page the current page 690 * @return array 691 */ 692 function user_convert_text_to_menu_items($text, $page) { 693 global $OUTPUT, $CFG; 694 695 $lines = explode("\n", $text); 696 $items = array(); 697 $lastchild = null; 698 $lastdepth = null; 699 $lastsort = 0; 700 $children = array(); 701 foreach ($lines as $line) { 702 $line = trim($line); 703 $bits = explode('|', $line, 2); 704 $itemtype = 'link'; 705 if (preg_match("/^#+$/", $line)) { 706 $itemtype = 'divider'; 707 } else if (!array_key_exists(0, $bits) or empty($bits[0])) { 708 // Every item must have a name to be valid. 709 continue; 710 } else { 711 $bits[0] = ltrim($bits[0], '-'); 712 } 713 714 // Create the child. 715 $child = new stdClass(); 716 $child->itemtype = $itemtype; 717 if ($itemtype === 'divider') { 718 // Add the divider to the list of children and skip link 719 // processing. 720 $children[] = $child; 721 continue; 722 } 723 724 // Name processing. 725 $namebits = explode(',', $bits[0], 2); 726 if (count($namebits) == 2) { 727 // Check the validity of the identifier part of the string. 728 if (clean_param($namebits[0], PARAM_STRINGID) !== '') { 729 // Treat this as a language string. 730 $child->title = get_string($namebits[0], $namebits[1]); 731 $child->titleidentifier = implode(',', $namebits); 732 } 733 } 734 if (empty($child->title)) { 735 // Use it as is, don't even clean it. 736 $child->title = $bits[0]; 737 $child->titleidentifier = str_replace(" ", "-", $bits[0]); 738 } 739 740 // URL processing. 741 if (!array_key_exists(1, $bits) or empty($bits[1])) { 742 // Set the url to null, and set the itemtype to invalid. 743 $bits[1] = null; 744 $child->itemtype = "invalid"; 745 } else { 746 // Nasty hack to replace the grades with the direct url. 747 if (strpos($bits[1], '/grade/report/mygrades.php') !== false) { 748 $bits[1] = user_mygrades_url(); 749 } 750 751 // Make sure the url is a moodle url. 752 $bits[1] = new moodle_url(trim($bits[1])); 753 } 754 $child->url = $bits[1]; 755 756 // Add this child to the list of children. 757 $children[] = $child; 758 } 759 return $children; 760 } 761 762 /** 763 * Get a list of essential user navigation items. 764 * 765 * @param stdclass $user user object. 766 * @param moodle_page $page page object. 767 * @param array $options associative array. 768 * options are: 769 * - avatarsize=35 (size of avatar image) 770 * @return stdClass $returnobj navigation information object, where: 771 * 772 * $returnobj->navitems array array of links where each link is a 773 * stdClass with fields url, title, and 774 * pix 775 * $returnobj->metadata array array of useful user metadata to be 776 * used when constructing navigation; 777 * fields include: 778 * 779 * ROLE FIELDS 780 * asotherrole bool whether viewing as another role 781 * rolename string name of the role 782 * 783 * USER FIELDS 784 * These fields are for the currently-logged in user, or for 785 * the user that the real user is currently logged in as. 786 * 787 * userid int the id of the user in question 788 * userfullname string the user's full name 789 * userprofileurl moodle_url the url of the user's profile 790 * useravatar string a HTML fragment - the rendered 791 * user_picture for this user 792 * userloginfail string an error string denoting the number 793 * of login failures since last login 794 * 795 * "REAL USER" FIELDS 796 * These fields are for when asotheruser is true, and 797 * correspond to the underlying "real user". 798 * 799 * asotheruser bool whether viewing as another user 800 * realuserid int the id of the user in question 801 * realuserfullname string the user's full name 802 * realuserprofileurl moodle_url the url of the user's profile 803 * realuseravatar string a HTML fragment - the rendered 804 * user_picture for this user 805 * 806 * MNET PROVIDER FIELDS 807 * asmnetuser bool whether viewing as a user from an 808 * MNet provider 809 * mnetidprovidername string name of the MNet provider 810 * mnetidproviderwwwroot string URL of the MNet provider 811 */ 812 function user_get_user_navigation_info($user, $page, $options = array()) { 813 global $OUTPUT, $DB, $SESSION, $CFG; 814 815 $returnobject = new stdClass(); 816 $returnobject->navitems = array(); 817 $returnobject->metadata = array(); 818 819 $guest = isguestuser(); 820 if (!isloggedin() || $guest) { 821 $returnobject->unauthenticateduser = [ 822 'guest' => $guest, 823 'content' => $guest ? 'loggedinasguest' : 'loggedinnot', 824 ]; 825 826 return $returnobject; 827 } 828 829 $course = $page->course; 830 831 // Query the environment. 832 $context = context_course::instance($course->id); 833 834 // Get basic user metadata. 835 $returnobject->metadata['userid'] = $user->id; 836 $returnobject->metadata['userfullname'] = fullname($user); 837 $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array( 838 'id' => $user->id 839 )); 840 841 $avataroptions = array('link' => false, 'visibletoscreenreaders' => false); 842 if (!empty($options['avatarsize'])) { 843 $avataroptions['size'] = $options['avatarsize']; 844 } 845 $returnobject->metadata['useravatar'] = $OUTPUT->user_picture ( 846 $user, $avataroptions 847 ); 848 // Build a list of items for a regular user. 849 850 // Query MNet status. 851 if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) { 852 $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid)); 853 $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name; 854 $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot; 855 } 856 857 // Did the user just log in? 858 if (isset($SESSION->justloggedin)) { 859 // Don't unset this flag as login_info still needs it. 860 if (!empty($CFG->displayloginfailures)) { 861 // Don't reset the count either, as login_info() still needs it too. 862 if ($count = user_count_login_failures($user, false)) { 863 864 // Get login failures string. 865 $a = new stdClass(); 866 $a->attempts = html_writer::tag('span', $count, array('class' => 'value mr-1 font-weight-bold')); 867 $returnobject->metadata['userloginfail'] = 868 get_string('failedloginattempts', '', $a); 869 870 } 871 } 872 } 873 874 $returnobject->metadata['asotherrole'] = false; 875 876 // Before we add the last items (usually a logout + switch role link), add any 877 // custom-defined items. 878 $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page); 879 $custommenucount = 0; 880 foreach ($customitems as $item) { 881 $returnobject->navitems[] = $item; 882 if ($item->itemtype !== 'divider' && $item->itemtype !== 'invalid') { 883 $custommenucount++; 884 } 885 } 886 887 if ($custommenucount > 0) { 888 // Only add a divider if we have customusermenuitems. 889 $divider = new stdClass(); 890 $divider->itemtype = 'divider'; 891 $returnobject->navitems[] = $divider; 892 } 893 894 // Links: Preferences. 895 $preferences = new stdClass(); 896 $preferences->itemtype = 'link'; 897 $preferences->url = new moodle_url('/user/preferences.php'); 898 $preferences->title = get_string('preferences'); 899 $preferences->titleidentifier = 'preferences,moodle'; 900 $returnobject->navitems[] = $preferences; 901 902 903 if (is_role_switched($course->id)) { 904 if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) { 905 // Build role-return link instead of logout link. 906 $rolereturn = new stdClass(); 907 $rolereturn->itemtype = 'link'; 908 $rolereturn->url = new moodle_url('/course/switchrole.php', array( 909 'id' => $course->id, 910 'sesskey' => sesskey(), 911 'switchrole' => 0, 912 'returnurl' => $page->url->out_as_local_url(false) 913 )); 914 $rolereturn->title = get_string('switchrolereturn'); 915 $rolereturn->titleidentifier = 'switchrolereturn,moodle'; 916 $returnobject->navitems[] = $rolereturn; 917 918 $returnobject->metadata['asotherrole'] = true; 919 $returnobject->metadata['rolename'] = role_get_name($role, $context); 920 921 } 922 } else { 923 // Build switch role link. 924 $roles = get_switchable_roles($context); 925 if (is_array($roles) && (count($roles) > 0)) { 926 $switchrole = new stdClass(); 927 $switchrole->itemtype = 'link'; 928 $switchrole->url = new moodle_url('/course/switchrole.php', array( 929 'id' => $course->id, 930 'switchrole' => -1, 931 'returnurl' => $page->url->out_as_local_url(false) 932 )); 933 $switchrole->title = get_string('switchroleto'); 934 $switchrole->titleidentifier = 'switchroleto,moodle'; 935 $returnobject->navitems[] = $switchrole; 936 } 937 } 938 939 if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) { 940 $realuser = \core\session\manager::get_realuser(); 941 942 // Save values for the real user, as $user will be full of data for the 943 // user is disguised as. 944 $returnobject->metadata['realuserid'] = $realuser->id; 945 $returnobject->metadata['realuserfullname'] = fullname($realuser); 946 $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', [ 947 'id' => $realuser->id 948 ]); 949 $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions); 950 951 // Build a user-revert link. 952 $userrevert = new stdClass(); 953 $userrevert->itemtype = 'link'; 954 $userrevert->url = new moodle_url('/course/loginas.php', [ 955 'id' => $course->id, 956 'sesskey' => sesskey() 957 ]); 958 $userrevert->title = get_string('logout'); 959 $userrevert->titleidentifier = 'logout,moodle'; 960 $returnobject->navitems[] = $userrevert; 961 } else { 962 // Build a logout link. 963 $logout = new stdClass(); 964 $logout->itemtype = 'link'; 965 $logout->url = new moodle_url('/login/logout.php', ['sesskey' => sesskey()]); 966 $logout->title = get_string('logout'); 967 $logout->titleidentifier = 'logout,moodle'; 968 $returnobject->navitems[] = $logout; 969 } 970 971 return $returnobject; 972 } 973 974 /** 975 * Add password to the list of used hashes for this user. 976 * 977 * This is supposed to be used from: 978 * 1/ change own password form 979 * 2/ password reset process 980 * 3/ user signup in auth plugins if password changing supported 981 * 982 * @param int $userid user id 983 * @param string $password plaintext password 984 * @return void 985 */ 986 function user_add_password_history($userid, $password) { 987 global $CFG, $DB; 988 989 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) { 990 return; 991 } 992 993 // Note: this is using separate code form normal password hashing because 994 // we need to have this under control in the future. Also the auth 995 // plugin might not store the passwords locally at all. 996 997 $record = new stdClass(); 998 $record->userid = $userid; 999 $record->hash = password_hash($password, PASSWORD_DEFAULT); 1000 $record->timecreated = time(); 1001 $DB->insert_record('user_password_history', $record); 1002 1003 $i = 0; 1004 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC'); 1005 foreach ($records as $record) { 1006 $i++; 1007 if ($i > $CFG->passwordreuselimit) { 1008 $DB->delete_records('user_password_history', array('id' => $record->id)); 1009 } 1010 } 1011 } 1012 1013 /** 1014 * Was this password used before on change or reset password page? 1015 * 1016 * The $CFG->passwordreuselimit setting determines 1017 * how many times different password needs to be used 1018 * before allowing previously used password again. 1019 * 1020 * @param int $userid user id 1021 * @param string $password plaintext password 1022 * @return bool true if password reused 1023 */ 1024 function user_is_previously_used_password($userid, $password) { 1025 global $CFG, $DB; 1026 1027 if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) { 1028 return false; 1029 } 1030 1031 $reused = false; 1032 1033 $i = 0; 1034 $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC'); 1035 foreach ($records as $record) { 1036 $i++; 1037 if ($i > $CFG->passwordreuselimit) { 1038 $DB->delete_records('user_password_history', array('id' => $record->id)); 1039 continue; 1040 } 1041 // NOTE: this is slow but we cannot compare the hashes directly any more. 1042 if (password_verify($password, $record->hash)) { 1043 $reused = true; 1044 } 1045 } 1046 1047 return $reused; 1048 } 1049 1050 /** 1051 * Remove a user device from the Moodle database (for PUSH notifications usually). 1052 * 1053 * @param string $uuid The device UUID. 1054 * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed. 1055 * @return bool true if removed, false if the device didn't exists in the database 1056 * @since Moodle 2.9 1057 */ 1058 function user_remove_user_device($uuid, $appid = "") { 1059 global $DB, $USER; 1060 1061 $conditions = array('uuid' => $uuid, 'userid' => $USER->id); 1062 if (!empty($appid)) { 1063 $conditions['appid'] = $appid; 1064 } 1065 1066 if (!$DB->count_records('user_devices', $conditions)) { 1067 return false; 1068 } 1069 1070 $DB->delete_records('user_devices', $conditions); 1071 1072 return true; 1073 } 1074 1075 /** 1076 * Trigger user_list_viewed event. 1077 * 1078 * @param stdClass $course course object 1079 * @param stdClass $context course context object 1080 * @since Moodle 2.9 1081 */ 1082 function user_list_view($course, $context) { 1083 1084 $event = \core\event\user_list_viewed::create(array( 1085 'objectid' => $course->id, 1086 'courseid' => $course->id, 1087 'context' => $context, 1088 'other' => array( 1089 'courseshortname' => $course->shortname, 1090 'coursefullname' => $course->fullname 1091 ) 1092 )); 1093 $event->trigger(); 1094 } 1095 1096 /** 1097 * Returns the url to use for the "Grades" link in the user navigation. 1098 * 1099 * @param int $userid The user's ID. 1100 * @param int $courseid The course ID if available. 1101 * @return mixed A URL to be directed to for "Grades". 1102 */ 1103 function user_mygrades_url($userid = null, $courseid = SITEID) { 1104 global $CFG, $USER; 1105 $url = null; 1106 if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') { 1107 if (isset($userid) && $USER->id != $userid) { 1108 // Send to the gradebook report. 1109 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php', 1110 array('id' => $courseid, 'userid' => $userid)); 1111 } else { 1112 $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php'); 1113 } 1114 } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external' 1115 && !empty($CFG->gradereport_mygradeurl)) { 1116 $url = $CFG->gradereport_mygradeurl; 1117 } else { 1118 $url = $CFG->wwwroot; 1119 } 1120 return $url; 1121 } 1122 1123 /** 1124 * Check if the current user has permission to view details of the supplied user. 1125 * 1126 * This function supports two modes: 1127 * If the optional $course param is omitted, then this function finds all shared courses and checks whether the current user has 1128 * permission in any of them, returning true if so. 1129 * If the $course param is provided, then this function checks permissions in ONLY that course. 1130 * 1131 * @param object $user The other user's details. 1132 * @param object $course if provided, only check permissions in this course. 1133 * @param context $usercontext The user context if available. 1134 * @return bool true for ability to view this user, else false. 1135 */ 1136 function user_can_view_profile($user, $course = null, $usercontext = null) { 1137 global $USER, $CFG; 1138 1139 if ($user->deleted) { 1140 return false; 1141 } 1142 1143 // Do we need to be logged in? 1144 if (empty($CFG->forceloginforprofiles)) { 1145 return true; 1146 } else { 1147 if (!isloggedin() || isguestuser()) { 1148 // User is not logged in and forceloginforprofile is set, we need to return now. 1149 return false; 1150 } 1151 } 1152 1153 // Current user can always view their profile. 1154 if ($USER->id == $user->id) { 1155 return true; 1156 } 1157 1158 // Use callbacks so that (primarily) local plugins can prevent or allow profile access. 1159 $forceallow = false; 1160 $plugintypes = get_plugins_with_function('control_view_profile'); 1161 foreach ($plugintypes as $plugins) { 1162 foreach ($plugins as $pluginfunction) { 1163 $result = $pluginfunction($user, $course, $usercontext); 1164 switch ($result) { 1165 case core_user::VIEWPROFILE_DO_NOT_PREVENT: 1166 // If the plugin doesn't stop access, just continue to next plugin or use 1167 // default behaviour. 1168 break; 1169 case core_user::VIEWPROFILE_FORCE_ALLOW: 1170 // Record that we are definitely going to allow it (unless another plugin 1171 // returns _PREVENT). 1172 $forceallow = true; 1173 break; 1174 case core_user::VIEWPROFILE_PREVENT: 1175 // If any plugin returns PREVENT then we return false, regardless of what 1176 // other plugins said. 1177 return false; 1178 } 1179 } 1180 } 1181 if ($forceallow) { 1182 return true; 1183 } 1184 1185 // Course contacts have visible profiles always. 1186 if (has_coursecontact_role($user->id)) { 1187 return true; 1188 } 1189 1190 // If we're only checking the capabilities in the single provided course. 1191 if (isset($course)) { 1192 // Confirm that $user is enrolled in the $course we're checking. 1193 if (is_enrolled(context_course::instance($course->id), $user)) { 1194 $userscourses = array($course); 1195 } 1196 } else { 1197 // Else we're checking whether the current user can view $user's profile anywhere, so check user context first. 1198 if (empty($usercontext)) { 1199 $usercontext = context_user::instance($user->id); 1200 } 1201 if (has_capability('moodle/user:viewdetails', $usercontext) || has_capability('moodle/user:viewalldetails', $usercontext)) { 1202 return true; 1203 } 1204 // This returns context information, so we can preload below. 1205 $userscourses = enrol_get_all_users_courses($user->id); 1206 } 1207 1208 if (empty($userscourses)) { 1209 return false; 1210 } 1211 1212 foreach ($userscourses as $userscourse) { 1213 context_helper::preload_from_record($userscourse); 1214 $coursecontext = context_course::instance($userscourse->id); 1215 if (has_capability('moodle/user:viewdetails', $coursecontext) || 1216 has_capability('moodle/user:viewalldetails', $coursecontext)) { 1217 if (!groups_user_groups_visible($userscourse, $user->id)) { 1218 // Not a member of the same group. 1219 continue; 1220 } 1221 return true; 1222 } 1223 } 1224 return false; 1225 } 1226 1227 /** 1228 * Returns users tagged with a specified tag. 1229 * 1230 * @param core_tag_tag $tag 1231 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag 1232 * are displayed on the page and the per-page limit may be bigger 1233 * @param int $fromctx context id where the link was displayed, may be used by callbacks 1234 * to display items in the same context first 1235 * @param int $ctx context id where to search for records 1236 * @param bool $rec search in subcontexts as well 1237 * @param int $page 0-based number of page being displayed 1238 * @return \core_tag\output\tagindex 1239 */ 1240 function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) { 1241 global $PAGE; 1242 1243 if ($ctx && $ctx != context_system::instance()->id) { 1244 $usercount = 0; 1245 } else { 1246 // Users can only be displayed in system context. 1247 $usercount = $tag->count_tagged_items('core', 'user', 1248 'it.deleted=:notdeleted', array('notdeleted' => 0)); 1249 } 1250 $perpage = $exclusivemode ? 24 : 5; 1251 $content = ''; 1252 $totalpages = ceil($usercount / $perpage); 1253 1254 if ($usercount) { 1255 $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage, 1256 'it.deleted=:notdeleted', array('notdeleted' => 0)); 1257 $renderer = $PAGE->get_renderer('core', 'user'); 1258 $content .= $renderer->user_list($userlist, $exclusivemode); 1259 } 1260 1261 return new core_tag\output\tagindex($tag, 'core', 'user', $content, 1262 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages); 1263 } 1264 1265 /** 1266 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access a course. 1267 * 1268 * @param int $accesssince The unix timestamp to compare to users' last access 1269 * @param string $tableprefix 1270 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional) 1271 * @return string 1272 */ 1273 function user_get_course_lastaccess_sql($accesssince = null, $tableprefix = 'ul', $haveaccessed = false) { 1274 return user_get_lastaccess_sql('timeaccess', $accesssince, $tableprefix, $haveaccessed); 1275 } 1276 1277 /** 1278 * Returns SQL that can be used to limit a query to a period where the user last accessed / did not access the system. 1279 * 1280 * @param int $accesssince The unix timestamp to compare to users' last access 1281 * @param string $tableprefix 1282 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional) 1283 * @return string 1284 */ 1285 function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u', $haveaccessed = false) { 1286 return user_get_lastaccess_sql('lastaccess', $accesssince, $tableprefix, $haveaccessed); 1287 } 1288 1289 /** 1290 * Returns SQL that can be used to limit a query to a period where the user last accessed or 1291 * did not access something recorded by a given table. 1292 * 1293 * @param string $columnname The name of the access column to check against 1294 * @param int $accesssince The unix timestamp to compare to users' last access 1295 * @param string $tableprefix The query prefix of the table to check 1296 * @param bool $haveaccessed Whether to match against users who HAVE accessed since $accesssince (optional) 1297 * @return string 1298 */ 1299 function user_get_lastaccess_sql($columnname, $accesssince, $tableprefix, $haveaccessed = false) { 1300 if (empty($accesssince)) { 1301 return ''; 1302 } 1303 1304 // Only users who have accessed since $accesssince. 1305 if ($haveaccessed) { 1306 if ($accesssince == -1) { 1307 // Include all users who have logged in at some point. 1308 $sql = "({$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0)"; 1309 } else { 1310 // Users who have accessed since the specified time. 1311 $sql = "{$tableprefix}.{$columnname} IS NOT NULL AND {$tableprefix}.{$columnname} != 0 1312 AND {$tableprefix}.{$columnname} >= {$accesssince}"; 1313 } 1314 } else { 1315 // Only users who have not accessed since $accesssince. 1316 1317 if ($accesssince == -1) { 1318 // Users who have never accessed. 1319 $sql = "({$tableprefix}.{$columnname} IS NULL OR {$tableprefix}.{$columnname} = 0)"; 1320 } else { 1321 // Users who have not accessed since the specified time. 1322 $sql = "({$tableprefix}.{$columnname} IS NULL 1323 OR ({$tableprefix}.{$columnname} != 0 AND {$tableprefix}.{$columnname} < {$accesssince}))"; 1324 } 1325 } 1326 1327 return $sql; 1328 } 1329 1330 /** 1331 * Callback for inplace editable API. 1332 * 1333 * @param string $itemtype - Only user_roles is supported. 1334 * @param string $itemid - Courseid and userid separated by a : 1335 * @param string $newvalue - json encoded list of roleids. 1336 * @return \core\output\inplace_editable|null 1337 */ 1338 function core_user_inplace_editable($itemtype, $itemid, $newvalue) { 1339 if ($itemtype === 'user_roles') { 1340 return \core_user\output\user_roles_editable::update($itemid, $newvalue); 1341 } 1342 } 1343 1344 /** 1345 * Map an internal field name to a valid purpose from: "https://www.w3.org/TR/WCAG21/#input-purposes" 1346 * 1347 * @param integer $userid 1348 * @param string $fieldname 1349 * @return string $purpose (empty string if there is no mapping). 1350 */ 1351 function user_edit_map_field_purpose($userid, $fieldname) { 1352 global $USER; 1353 1354 $currentuser = ($userid == $USER->id) && !\core\session\manager::is_loggedinas(); 1355 // These are the fields considered valid to map and auto fill from a browser. 1356 // We do not include fields that are in a collapsed section by default because 1357 // the browser could auto-fill the field and cause a new value to be saved when 1358 // that field was never visible. 1359 $validmappings = array( 1360 'username' => 'username', 1361 'password' => 'current-password', 1362 'firstname' => 'given-name', 1363 'lastname' => 'family-name', 1364 'middlename' => 'additional-name', 1365 'email' => 'email', 1366 'country' => 'country', 1367 'lang' => 'language' 1368 ); 1369 1370 $purpose = ''; 1371 // Only set a purpose when editing your own user details. 1372 if ($currentuser && isset($validmappings[$fieldname])) { 1373 $purpose = ' autocomplete="' . $validmappings[$fieldname] . '" '; 1374 } 1375 1376 return $purpose; 1377 } 1378 1379 /** 1380 * Update the users public key for the specified device and app. 1381 * 1382 * @param string $uuid The device UUID. 1383 * @param string $appid The app id, usually something like com.moodle.moodlemobile. 1384 * @param string $publickey The app generated public key. 1385 * @return bool 1386 * @since Moodle 4.2 1387 */ 1388 function user_update_device_public_key(string $uuid, string $appid, string $publickey): bool { 1389 global $USER, $DB; 1390 1391 if (!$DB->get_record('user_devices', 1392 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id] 1393 )) { 1394 return false; 1395 } 1396 1397 $DB->set_field('user_devices', 'publickey', $publickey, 1398 ['uuid' => $uuid, 'appid' => $appid, 'userid' => $USER->id] 1399 ); 1400 1401 return true; 1402 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body