Differences Between: [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 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 namespace core_user; 18 19 use core_text; 20 21 /** 22 * Class for retrieving information about user fields that are needed for displaying user identity. 23 * 24 * @package core_user 25 */ 26 class fields { 27 /** @var string Prefix used to identify custom profile fields */ 28 const PROFILE_FIELD_PREFIX = 'profile_field_'; 29 /** @var string Regular expression used to match a field name against the prefix */ 30 const PROFILE_FIELD_REGEX = '~^' . self::PROFILE_FIELD_PREFIX . '(.*)$~'; 31 32 /** @var int All fields required to display user's identity, based on server configuration */ 33 const PURPOSE_IDENTITY = 0; 34 /** @var int All fields required to display a user picture */ 35 const PURPOSE_USERPIC = 1; 36 /** @var int All fields required for somebody's name */ 37 const PURPOSE_NAME = 2; 38 /** @var int Field required by custom include list */ 39 const CUSTOM_INCLUDE = 3; 40 41 /** @var \context|null Context in use */ 42 protected $context; 43 44 /** @var bool True to allow custom user fields */ 45 protected $allowcustom; 46 47 /** @var bool[] Array of purposes (from PURPOSE_xx to true/false) */ 48 protected $purposes; 49 50 /** @var string[] List of extra fields to include */ 51 protected $include; 52 53 /** @var string[] List of fields to exclude */ 54 protected $exclude; 55 56 /** @var int Unique identifier for different queries generated in same request */ 57 protected static $uniqueidentifier = 1; 58 59 /** @var array|null Associative array from field => array of purposes it was used for => true */ 60 protected $fields = null; 61 62 /** 63 * Protected constructor - use one of the for_xx methods to create an object. 64 * 65 * @param int $purpose Initial purpose for object or -1 for none 66 */ 67 protected function __construct(int $purpose = -1) { 68 $this->purposes = [ 69 self::PURPOSE_IDENTITY => false, 70 self::PURPOSE_USERPIC => false, 71 self::PURPOSE_NAME => false, 72 ]; 73 if ($purpose != -1) { 74 $this->purposes[$purpose] = true; 75 } 76 $this->include = []; 77 $this->exclude = []; 78 $this->context = null; 79 $this->allowcustom = true; 80 } 81 82 /** 83 * Constructs an empty user fields object to get arbitrary user fields. 84 * 85 * You can add fields to retrieve with the including() function. 86 * 87 * @return fields User fields object ready for use 88 */ 89 public static function empty(): fields { 90 return new fields(); 91 } 92 93 /** 94 * Constructs a user fields object to get identity information for display. 95 * 96 * The function does all the required capability checks to see if the current user is allowed 97 * to see them in the specified context. You can pass context null to get all the fields without 98 * checking permissions. 99 * 100 * If the code can only handle fields in the main user table, and not custom profile fields, 101 * then set $allowcustom to false. 102 * 103 * Note: After constructing the object you can use the ->with_xx, ->including, and ->excluding 104 * functions to control the required fields in more detail. For example: 105 * 106 * $fields = fields::for_identity($context)->with_userpic()->excluding('email'); 107 * 108 * @param \context|null $context Context; if supplied, includes only fields the current user should see 109 * @param bool $allowcustom If true, custom profile fields may be included 110 * @return fields User fields object ready for use 111 */ 112 public static function for_identity(?\context $context, bool $allowcustom = true): fields { 113 $fields = new fields(self::PURPOSE_IDENTITY); 114 $fields->context = $context; 115 $fields->allowcustom = $allowcustom; 116 return $fields; 117 } 118 119 /** 120 * Constructs a user fields object to get information required for displaying a user picture. 121 * 122 * Note: After constructing the object you can use the ->with_xx, ->including, and ->excluding 123 * functions to control the required fields in more detail. For example: 124 * 125 * $fields = fields::for_userpic()->with_name()->excluding('email'); 126 * 127 * @return fields User fields object ready for use 128 */ 129 public static function for_userpic(): fields { 130 return new fields(self::PURPOSE_USERPIC); 131 } 132 133 /** 134 * Constructs a user fields object to get information required for displaying a user full name. 135 * 136 * Note: After constructing the object you can use the ->with_xx, ->including, and ->excluding 137 * functions to control the required fields in more detail. For example: 138 * 139 * $fields = fields::for_name()->with_userpic()->excluding('email'); 140 * 141 * @return fields User fields object ready for use 142 */ 143 public static function for_name(): fields { 144 return new fields(self::PURPOSE_NAME); 145 } 146 147 /** 148 * On an existing fields object, adds the fields required for displaying user pictures. 149 * 150 * @return $this Same object for chaining function calls 151 */ 152 public function with_userpic(): fields { 153 $this->purposes[self::PURPOSE_USERPIC] = true; 154 return $this; 155 } 156 157 /** 158 * On an existing fields object, adds the fields required for displaying user full names. 159 * 160 * @return $this Same object for chaining function calls 161 */ 162 public function with_name(): fields { 163 $this->purposes[self::PURPOSE_NAME] = true; 164 return $this; 165 } 166 167 /** 168 * On an existing fields object, adds the fields required for displaying user identity. 169 * 170 * The function does all the required capability checks to see if the current user is allowed 171 * to see them in the specified context. You can pass context null to get all the fields without 172 * checking permissions. 173 * 174 * If the code can only handle fields in the main user table, and not custom profile fields, 175 * then set $allowcustom to false. 176 * 177 * @param \context|null Context; if supplied, includes only fields the current user should see 178 * @param bool $allowcustom If true, custom profile fields may be included 179 * @return $this Same object for chaining function calls 180 */ 181 public function with_identity(?\context $context, bool $allowcustom = true): fields { 182 $this->context = $context; 183 $this->allowcustom = $allowcustom; 184 $this->purposes[self::PURPOSE_IDENTITY] = true; 185 return $this; 186 } 187 188 /** 189 * On an existing fields object, adds extra fields to be retrieved. You can specify either 190 * fields from the user table e.g. 'email', or profile fields e.g. 'profile_field_height'. 191 * 192 * @param string ...$include One or more fields to add 193 * @return $this Same object for chaining function calls 194 */ 195 public function including(string ...$include): fields { 196 $this->include = array_merge($this->include, $include); 197 return $this; 198 } 199 200 /** 201 * On an existing fields object, excludes fields from retrieval. You can specify either 202 * fields from the user table e.g. 'email', or profile fields e.g. 'profile_field_height'. 203 * 204 * This is useful when constructing queries where your query already explicitly references 205 * certain fields, so you don't want to retrieve them twice. 206 * 207 * @param string ...$exclude One or more fields to exclude 208 * @return $this Same object for chaining function calls 209 */ 210 public function excluding(...$exclude): fields { 211 $this->exclude = array_merge($this->exclude, $exclude); 212 return $this; 213 } 214 215 /** 216 * Gets an array of all fields that are required for the specified purposes, also taking 217 * into account the $includes and $excludes settings. 218 * 219 * The results may include basic field names (columns from the 'user' database table) and, 220 * unless turned off, custom profile field names in the format 'profile_field_myfield'. 221 * 222 * You should not rely on the order of fields, with one exception: if there is an id field 223 * it will be returned first. This is in case it is used with get_records calls. 224 * 225 * The $limitpurposes parameter is useful if you want to get a different set of fields than the 226 * purposes in the constructor. For example, if you want to get SQL for identity + user picture 227 * fields, but you then want to only get the identity fields as a list. (You can only specify 228 * purposes that were also passed to the constructor i.e. it can only be used to restrict the 229 * list, not add to it.) 230 * 231 * @param array $limitpurposes If specified, gets fields only for these purposes 232 * @return string[] Array of required fields 233 * @throws \coding_exception If any unknown purpose is listed 234 */ 235 public function get_required_fields(array $limitpurposes = []): array { 236 // The first time this is called, actually work out the list. There is no way to 'un-cache' 237 // it, but these objects are designed to be short-lived so it doesn't need one. 238 if ($this->fields === null) { 239 // Add all the fields as array keys so that there are no duplicates. 240 $this->fields = []; 241 if ($this->purposes[self::PURPOSE_IDENTITY]) { 242 foreach (self::get_identity_fields($this->context, $this->allowcustom) as $field) { 243 $this->fields[$field] = [self::PURPOSE_IDENTITY => true]; 244 } 245 } 246 if ($this->purposes[self::PURPOSE_USERPIC]) { 247 foreach (self::get_picture_fields() as $field) { 248 if (!array_key_exists($field, $this->fields)) { 249 $this->fields[$field] = []; 250 } 251 $this->fields[$field][self::PURPOSE_USERPIC] = true; 252 } 253 } 254 if ($this->purposes[self::PURPOSE_NAME]) { 255 foreach (self::get_name_fields() as $field) { 256 if (!array_key_exists($field, $this->fields)) { 257 $this->fields[$field] = []; 258 } 259 $this->fields[$field][self::PURPOSE_NAME] = true; 260 } 261 } 262 foreach ($this->include as $field) { 263 if ($this->allowcustom || !preg_match(self::PROFILE_FIELD_REGEX, $field)) { 264 if (!array_key_exists($field, $this->fields)) { 265 $this->fields[$field] = []; 266 } 267 $this->fields[$field][self::CUSTOM_INCLUDE] = true; 268 } 269 } 270 foreach ($this->exclude as $field) { 271 unset($this->fields[$field]); 272 } 273 274 // If the id field is included, make sure it's first in the list. 275 if (array_key_exists('id', $this->fields)) { 276 $newfields = ['id' => $this->fields['id']]; 277 foreach ($this->fields as $field => $purposes) { 278 if ($field !== 'id') { 279 $newfields[$field] = $purposes; 280 } 281 } 282 $this->fields = $newfields; 283 } 284 } 285 286 if ($limitpurposes) { 287 // Check the value was legitimate. 288 foreach ($limitpurposes as $purpose) { 289 if ($purpose != self::CUSTOM_INCLUDE && empty($this->purposes[$purpose])) { 290 throw new \coding_exception('$limitpurposes can only include purposes defined in object'); 291 } 292 } 293 294 // Filter the fields to include only those matching the purposes. 295 $result = []; 296 foreach ($this->fields as $key => $purposes) { 297 foreach ($limitpurposes as $purpose) { 298 if (array_key_exists($purpose, $purposes)) { 299 $result[] = $key; 300 break; 301 } 302 } 303 } 304 return $result; 305 } else { 306 return array_keys($this->fields); 307 } 308 } 309 310 /** 311 * Gets fields required for user pictures. 312 * 313 * The results include only basic field names (columns from the 'user' database table). 314 * 315 * @return string[] All fields required for user pictures 316 */ 317 public static function get_picture_fields(): array { 318 return ['id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic', 319 'middlename', 'alternatename', 'imagealt', 'email']; 320 } 321 322 /** 323 * Gets fields required for user names. 324 * 325 * The results include only basic field names (columns from the 'user' database table). 326 * 327 * Fields are usually returned in a specific order, which the fullname() function depends on. 328 * If you specify 'true' to the $strangeorder flag, then the firstname and lastname fields 329 * are moved to the front; this is useful in a few places in existing code. New code should 330 * avoid requiring a particular order. 331 * 332 * @param bool $differentorder In a few places, a different order of fields is required 333 * @return string[] All fields used to display user names 334 */ 335 public static function get_name_fields(bool $differentorder = false): array { 336 $fields = ['firstnamephonetic', 'lastnamephonetic', 'middlename', 'alternatename', 337 'firstname', 'lastname']; 338 if ($differentorder) { 339 return array_merge(array_slice($fields, -2), array_slice($fields, 0, -2)); 340 } else { 341 return $fields; 342 } 343 } 344 345 /** 346 * Gets all fields required for user identity. These fields should be included in tables 347 * showing lists of users (in addition to the user's name which is included as standard). 348 * 349 * The results include basic field names (columns from the 'user' database table) and, unless 350 * turned off, custom profile field names in the format 'profile_field_myfield', note these 351 * fields will always be returned lower cased to match how they are returned by the DML library. 352 * 353 * This function does all the required capability checks to see if the current user is allowed 354 * to see them in the specified context. You can pass context null to get all the fields 355 * without checking permissions. 356 * 357 * @param \context|null $context Context; if not supplied, all fields will be included without checks 358 * @param bool $allowcustom If true, custom profile fields will be included 359 * @return string[] Array of required fields 360 * @throws \coding_exception 361 */ 362 public static function get_identity_fields(?\context $context, bool $allowcustom = true): array { 363 global $CFG; 364 365 // Only users with permission get the extra fields. 366 if ($context && !has_capability('moodle/site:viewuseridentity', $context)) { 367 return []; 368 } 369 370 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty). 371 $extra = array_filter(explode(',', $CFG->showuseridentity)); 372 373 // If there are any custom fields, remove them if necessary (either if allowcustom is false, 374 // or if the user doesn't have access to see them). 375 foreach ($extra as $key => $field) { 376 if (preg_match(self::PROFILE_FIELD_REGEX, $field, $matches)) { 377 $allowed = false; 378 if ($allowcustom) { 379 require_once($CFG->dirroot . '/user/profile/lib.php'); 380 $fieldinfo = profile_get_custom_field_data_by_shortname($matches[1]); 381 switch ($fieldinfo->visible ?? -1) { 382 case PROFILE_VISIBLE_NONE: 383 case PROFILE_VISIBLE_PRIVATE: 384 $allowed = !$context || has_capability('moodle/user:viewalldetails', $context); 385 break; 386 case PROFILE_VISIBLE_TEACHERS: 387 // This is actually defined (in user/profile/lib.php) based on whether 388 // you have moodle/site:viewuseridentity in context. We already checked 389 // that, so treat it as visible (fall through). 390 case PROFILE_VISIBLE_ALL: 391 $allowed = true; 392 break; 393 } 394 } 395 if (!$allowed) { 396 unset($extra[$key]); 397 } 398 } 399 } 400 401 // For standard user fields, access is controlled by the hiddenuserfields option and 402 // some different capabilities. Check and remove these if the user can't access them. 403 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields)); 404 $hiddenidentifiers = array_intersect($extra, $hiddenfields); 405 406 if ($hiddenidentifiers) { 407 if (!$context) { 408 $canviewhiddenuserfields = true; 409 } else if ($context->get_course_context(false)) { 410 // We are somewhere inside a course. 411 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); 412 } else { 413 // We are not inside a course. 414 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context); 415 } 416 417 if (!$canviewhiddenuserfields) { 418 // Remove hidden identifiers from the list. 419 $extra = array_diff($extra, $hiddenidentifiers); 420 } 421 } 422 423 // Re-index the entries and return. 424 $extra = array_values($extra); 425 return array_map([core_text::class, 'strtolower'], $extra); 426 } 427 428 /** 429 * Gets SQL that can be used in a query to get the necessary fields. 430 * 431 * The result of this function is an object with fields 'selects', 'joins', 'params', and 432 * 'mappings'. 433 * 434 * If not empty, the list of selects will begin with a comma and the list of joins will begin 435 * and end with a space. You can include the result in your existing query like this: 436 * 437 * SELECT (your existing fields) 438 * $selects 439 * FROM {user} u 440 * JOIN (your existing joins) 441 * $joins 442 * 443 * When there are no custom fields then the 'joins' result will always be an empty string, and 444 * 'params' will be an empty array. 445 * 446 * The $fieldmappings value is often not needed. It is an associative array from each field 447 * name to an SQL expression for the value of that field, e.g.: 448 * 'profile_field_frog' => 'uf1d_3.data' 449 * 'city' => 'u.city' 450 * This is helpful if you want to use the profile fields in a WHERE clause, becuase you can't 451 * refer to the aliases used in the SELECT list there. 452 * 453 * The leading comma is included because this makes it work in the pattern above even if there 454 * are no fields from the get_sql() data (which can happen if doing identity fields and none 455 * are selected). If you want the result without a leading comma, set $leadingcomma to false. 456 * 457 * If the 'id' field is included then it will always be first in the list. Otherwise, you 458 * should not rely on the field order. 459 * 460 * For identity fields, the function does all the required capability checks to see if the 461 * current user is allowed to see them in the specified context. You can pass context null 462 * to get all the fields without checking permissions. 463 * 464 * If your code for any reason cannot cope with custom fields then you can turn them off. 465 * 466 * You can have either named or ? params. If you use named params, they are of the form 467 * uf1s_2; the first number increments in each call using a static variable in this class and 468 * the second number refers to the field being queried. A similar pattern is used to make 469 * join aliases unique. 470 * 471 * If your query refers to the user table by an alias e.g. 'u' then specify this in the $alias 472 * parameter; otherwise it will use {user} (if there are any joins for custom profile fields) 473 * or simply refer to the field by name only (if there aren't). 474 * 475 * If you need to use a prefix on the field names (for example in case they might coincide with 476 * existing result columns from your query, or if you want a convenient way to split out all 477 * the user data into a separate object) then you can specify one here. For example, if you 478 * include name fields and the prefix is 'u_' then the results will include 'u_firstname'. 479 * 480 * If you don't want to prefix all the field names but only change the id field name, use 481 * the $renameid parameter. (When you use this parameter, it takes precedence over any prefix; 482 * the id field will not be prefixed, while all others will.) 483 * 484 * @param string $alias Optional (but recommended) alias for user table in query, e.g. 'u' 485 * @param bool $namedparams If true, uses named :parameters instead of indexed ? parameters 486 * @param string $prefix Optional prefix for all field names in result, e.g. 'u_' 487 * @param string $renameid Renames the 'id' field if specified, e.g. 'userid' 488 * @param bool $leadingcomma If true the 'selects' list will start with a comma 489 * @return \stdClass Object with necessary SQL components 490 */ 491 public function get_sql(string $alias = '', bool $namedparams = false, string $prefix = '', 492 string $renameid = '', bool $leadingcomma = true): \stdClass { 493 global $DB; 494 495 $fields = $this->get_required_fields(); 496 497 $selects = ''; 498 $joins = ''; 499 $params = []; 500 $mappings = []; 501 502 $unique = self::$uniqueidentifier++; 503 $fieldcount = 0; 504 505 if ($alias) { 506 $usertable = $alias . '.'; 507 } else { 508 // If there is no alias, we still need to use {user} to identify the table when there 509 // are joins with other tables. When there are no customfields then there are no joins 510 // so we can refer to the fields by name alone. 511 $gotcustomfields = false; 512 foreach ($fields as $field) { 513 if (preg_match(self::PROFILE_FIELD_REGEX, $field, $matches)) { 514 $gotcustomfields = true; 515 break; 516 } 517 } 518 if ($gotcustomfields) { 519 $usertable = '{user}.'; 520 } else { 521 $usertable = ''; 522 } 523 } 524 525 foreach ($fields as $field) { 526 if (preg_match(self::PROFILE_FIELD_REGEX, $field, $matches)) { 527 // Custom profile field. 528 $shortname = $matches[1]; 529 530 $fieldcount++; 531 532 $fieldalias = 'uf' . $unique . 'f_' . $fieldcount; 533 $dataalias = 'uf' . $unique . 'd_' . $fieldcount; 534 if ($namedparams) { 535 $withoutcolon = 'uf' . $unique . 's' . $fieldcount; 536 $placeholder = ':' . $withoutcolon; 537 $params[$withoutcolon] = $shortname; 538 } else { 539 $placeholder = '?'; 540 $params[] = $shortname; 541 } 542 $joins .= " JOIN {user_info_field} $fieldalias ON " . 543 $DB->sql_equal($fieldalias . '.shortname', $placeholder, false) . " 544 LEFT JOIN {user_info_data} $dataalias ON $dataalias.fieldid = $fieldalias.id 545 AND $dataalias.userid = {$usertable}id"; 546 // For Oracle we need to convert the field into a usable format. 547 $fieldsql = $DB->sql_compare_text($dataalias . '.data', 255); 548 $selects .= ", $fieldsql AS $prefix$field"; 549 $mappings[$field] = $fieldsql; 550 } else { 551 // Standard user table field. 552 $selects .= ", $usertable$field"; 553 if ($field === 'id' && $renameid && $renameid !== 'id') { 554 $selects .= " AS $renameid"; 555 } else if ($prefix) { 556 $selects .= " AS $prefix$field"; 557 } 558 $mappings[$field] = "$usertable$field"; 559 } 560 } 561 562 // Add a space to the end of the joins list; this means it can be appended directly into 563 // any existing query without worrying about whether the developer has remembered to add 564 // whitespace after it. 565 if ($joins) { 566 $joins .= ' '; 567 } 568 569 // Optionally remove the leading comma. 570 if (!$leadingcomma) { 571 $selects = ltrim($selects, ' ,'); 572 } 573 574 return (object)['selects' => $selects, 'joins' => $joins, 'params' => $params, 575 'mappings' => $mappings]; 576 } 577 578 /** 579 * Gets the display name of a given user field. 580 * 581 * Supports field names from the 'user' database table, and custom profile fields supplied in 582 * the format 'profile_field_xx'. 583 * 584 * @param string $field Field name in database 585 * @return string Field name for display to user 586 * @throws \coding_exception 587 */ 588 public static function get_display_name(string $field): string { 589 global $CFG; 590 591 // Custom fields have special handling. 592 if (preg_match(self::PROFILE_FIELD_REGEX, $field, $matches)) { 593 require_once($CFG->dirroot . '/user/profile/lib.php'); 594 $fieldinfo = profile_get_custom_field_data_by_shortname($matches[1], false); 595 // Use format_string so it can be translated with multilang filter if necessary. 596 return $fieldinfo ? format_string($fieldinfo->name) : $field; 597 } 598 599 // Some fields have language strings which are not the same as field name. 600 switch ($field) { 601 case 'picture' : { 602 return get_string('pictureofuser'); 603 } 604 } 605 // Otherwise just use the same lang string. 606 return get_string($field); 607 } 608 609 /** 610 * Resets the unique identifier used to ensure that multiple SQL fragments generated in the 611 * same request will have different identifiers for parameters and table aliases. 612 * 613 * This is intended only for use in unit testing. 614 */ 615 public static function reset_unique_identifier() { 616 self::$uniqueidentifier = 1; 617 } 618 619 /** 620 * Checks if a field name looks like a custom profile field i.e. it begins with profile_field_ 621 * (does not check if that profile field actually exists). 622 * 623 * @param string $fieldname Field name 624 * @return string Empty string if not a profile field, or profile field name (without profile_field_) 625 */ 626 public static function match_custom_field(string $fieldname): string { 627 if (preg_match(self::PROFILE_FIELD_REGEX, $fieldname, $matches)) { 628 return $matches[1]; 629 } else { 630 return ''; 631 } 632 } 633 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body