Merge branch 'MDL-74638-master-test' of https://github.com/rezaies/moodle
[moodle.git] / user / profile / lib.php
blobd1a64098c98d9f3eab1c148ca66e0d1f203e11f6
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.
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/>.
17 /**
18 * Profile field API library file.
20 * @package core_user
21 * @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 /**
26 * Visible to anyone who has the moodle/site:viewuseridentity permission.
27 * Editable by the profile owner if they have the moodle/user:editownprofile capability
28 * or any user with the moodle/user:update capability.
30 define('PROFILE_VISIBLE_TEACHERS', '3');
32 /**
33 * Visible to anyone who can view the user.
34 * Editable by the profile owner if they have the moodle/user:editownprofile capability
35 * or any user with the moodle/user:update capability.
37 define('PROFILE_VISIBLE_ALL', '2');
38 /**
39 * Visible to the profile owner or anyone with the moodle/user:viewalldetails capability.
40 * Editable by the profile owner if they have the moodle/user:editownprofile capability
41 * or any user with moodle/user:viewalldetails and moodle/user:update capabilities.
43 define('PROFILE_VISIBLE_PRIVATE', '1');
44 /**
45 * Only visible to users with the moodle/user:viewalldetails capability.
46 * Only editable by users with the moodle/user:viewalldetails and moodle/user:update capabilities.
48 define('PROFILE_VISIBLE_NONE', '0');
50 /**
51 * Base class for the customisable profile fields.
53 * @package core_user
54 * @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 class profile_field_base {
59 // These 2 variables are really what we're interested in.
60 // Everything else can be extracted from them.
62 /** @var int */
63 public $fieldid;
65 /** @var int */
66 public $userid;
68 /** @var stdClass */
69 public $field;
71 /** @var string */
72 public $inputname;
74 /** @var mixed */
75 public $data;
77 /** @var string */
78 public $dataformat;
80 /** @var string name of the user profile category */
81 protected $categoryname;
83 /**
84 * Constructor method.
85 * @param int $fieldid id of the profile from the user_info_field table
86 * @param int $userid id of the user for whom we are displaying data
87 * @param stdClass $fielddata optional data for the field object plus additional fields 'hasuserdata', 'data' and 'dataformat'
88 * with user data. (If $fielddata->hasuserdata is empty, user data is not available and we should use default data).
89 * If this parameter is passed, constructor will not call load_data() at all.
91 public function __construct($fieldid=0, $userid=0, $fielddata=null) {
92 global $CFG;
94 if ($CFG->debugdeveloper) {
95 // In Moodle 3.4 the new argument $fielddata was added to the constructor. Make sure that
96 // plugin constructor properly passes this argument.
97 $backtrace = debug_backtrace();
98 if (isset($backtrace[1]['class']) && $backtrace[1]['function'] === '__construct' &&
99 in_array(self::class, class_parents($backtrace[1]['class']))) {
100 // If this constructor is called from the constructor of the plugin make sure that the third argument was passed through.
101 if (count($backtrace[1]['args']) >= 3 && count($backtrace[0]['args']) < 3) {
102 debugging($backtrace[1]['class'].'::__construct() must support $fielddata as the third argument ' .
103 'and pass it to the parent constructor', DEBUG_DEVELOPER);
108 $this->set_fieldid($fieldid);
109 $this->set_userid($userid);
110 if ($fielddata) {
111 $this->set_field($fielddata);
112 if ($userid > 0 && !empty($fielddata->hasuserdata)) {
113 $this->set_user_data($fielddata->data, $fielddata->dataformat);
115 } else {
116 $this->load_data();
121 * Old syntax of class constructor. Deprecated in PHP7.
123 * @deprecated since Moodle 3.1
125 public function profile_field_base($fieldid=0, $userid=0) {
126 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
127 self::__construct($fieldid, $userid);
131 * Abstract method: Adds the profile field to the moodle form class
132 * @abstract The following methods must be overwritten by child classes
133 * @param MoodleQuickForm $mform instance of the moodleform class
135 public function edit_field_add($mform) {
136 throw new \moodle_exception('mustbeoveride', 'debug', '', 'edit_field_add');
140 * Display the data for this field
141 * @return string
143 public function display_data() {
144 $options = new stdClass();
145 $options->para = false;
146 return format_text($this->data, FORMAT_MOODLE, $options);
150 * Print out the form field in the edit profile page
151 * @param MoodleQuickForm $mform instance of the moodleform class
152 * @return bool
154 public function edit_field($mform) {
155 if (!$this->is_editable()) {
156 return false;
159 $this->edit_field_add($mform);
160 $this->edit_field_set_default($mform);
161 $this->edit_field_set_required($mform);
162 return true;
166 * Tweaks the edit form
167 * @param MoodleQuickForm $mform instance of the moodleform class
168 * @return bool
170 public function edit_after_data($mform) {
171 if (!$this->is_editable()) {
172 return false;
175 $this->edit_field_set_locked($mform);
176 return true;
180 * Saves the data coming from form
181 * @param stdClass $usernew data coming from the form
183 public function edit_save_data($usernew) {
184 global $DB;
186 if (!isset($usernew->{$this->inputname})) {
187 // Field not present in form, probably locked and invisible - skip it.
188 return;
191 $data = new stdClass();
193 $usernew->{$this->inputname} = $this->edit_save_data_preprocess($usernew->{$this->inputname}, $data);
194 if (!isset($usernew->{$this->inputname})) {
195 // Field cannot be set to null, set the default value.
196 $usernew->{$this->inputname} = $this->field->defaultdata;
199 $data->userid = $usernew->id;
200 $data->fieldid = $this->field->id;
201 $data->data = $usernew->{$this->inputname};
203 if ($dataid = $DB->get_field('user_info_data', 'id', array('userid' => $data->userid, 'fieldid' => $data->fieldid))) {
204 $data->id = $dataid;
205 $DB->update_record('user_info_data', $data);
206 } else {
207 $DB->insert_record('user_info_data', $data);
212 * Validate the form field from profile page
214 * @param stdClass $usernew
215 * @return array error messages for the form validation
217 public function edit_validate_field($usernew) {
218 global $DB;
220 $errors = array();
221 // Get input value.
222 if (isset($usernew->{$this->inputname})) {
223 if (is_array($usernew->{$this->inputname}) && isset($usernew->{$this->inputname}['text'])) {
224 $value = $usernew->{$this->inputname}['text'];
225 } else {
226 $value = $usernew->{$this->inputname};
228 } else {
229 $value = '';
232 // Check for uniqueness of data if required.
233 if ($this->is_unique() && (($value !== '') || $this->is_required())) {
234 $data = $DB->get_records_sql('
235 SELECT id, userid
236 FROM {user_info_data}
237 WHERE fieldid = ?
238 AND ' . $DB->sql_compare_text('data', 255) . ' = ' . $DB->sql_compare_text('?', 255),
239 array($this->field->id, $value));
240 if ($data) {
241 $existing = false;
242 foreach ($data as $v) {
243 if ($v->userid == $usernew->id) {
244 $existing = true;
245 break;
248 if (!$existing) {
249 $errors[$this->inputname] = get_string('valuealreadyused');
253 return $errors;
257 * Sets the default data for the field in the form object
258 * @param MoodleQuickForm $mform instance of the moodleform class
260 public function edit_field_set_default($mform) {
261 if (!empty($this->field->defaultdata)) {
262 $mform->setDefault($this->inputname, $this->field->defaultdata);
267 * Sets the required flag for the field in the form object
269 * @param MoodleQuickForm $mform instance of the moodleform class
271 public function edit_field_set_required($mform) {
272 global $USER;
273 if ($this->is_required() && ($this->userid == $USER->id || isguestuser())) {
274 $mform->addRule($this->inputname, get_string('required'), 'required', null, 'client');
279 * HardFreeze the field if locked.
280 * @param MoodleQuickForm $mform instance of the moodleform class
282 public function edit_field_set_locked($mform) {
283 if (!$mform->elementExists($this->inputname)) {
284 return;
286 if ($this->is_locked() and !has_capability('moodle/user:update', context_system::instance())) {
287 $mform->hardFreeze($this->inputname);
288 $mform->setConstant($this->inputname, $this->data);
293 * Hook for child classess to process the data before it gets saved in database
294 * @param stdClass $data
295 * @param stdClass $datarecord The object that will be used to save the record
296 * @return mixed
298 public function edit_save_data_preprocess($data, $datarecord) {
299 return $data;
303 * Loads a user object with data for this field ready for the edit profile
304 * form
305 * @param stdClass $user a user object
307 public function edit_load_user_data($user) {
308 if ($this->data !== null) {
309 $user->{$this->inputname} = $this->data;
314 * Check if the field data should be loaded into the user object
315 * By default it is, but for field types where the data may be potentially
316 * large, the child class should override this and return false
317 * @return bool
319 public function is_user_object_data() {
320 return true;
324 * Accessor method: set the userid for this instance
325 * @internal This method should not generally be overwritten by child classes.
326 * @param integer $userid id from the user table
328 public function set_userid($userid) {
329 $this->userid = $userid;
333 * Accessor method: set the fieldid for this instance
334 * @internal This method should not generally be overwritten by child classes.
335 * @param integer $fieldid id from the user_info_field table
337 public function set_fieldid($fieldid) {
338 $this->fieldid = $fieldid;
342 * Sets the field object and default data and format into $this->data and $this->dataformat
344 * This method should be called before {@link self::set_user_data}
346 * @param stdClass $field
347 * @throws coding_exception
349 public function set_field($field) {
350 global $CFG;
351 if ($CFG->debugdeveloper) {
352 $properties = ['id', 'shortname', 'name', 'datatype', 'description', 'descriptionformat', 'categoryid', 'sortorder',
353 'required', 'locked', 'visible', 'forceunique', 'signup', 'defaultdata', 'defaultdataformat', 'param1', 'param2',
354 'param3', 'param4', 'param5'];
355 foreach ($properties as $property) {
356 if (!property_exists($field, $property)) {
357 debugging('The \'' . $property . '\' property must be set.', DEBUG_DEVELOPER);
361 if ($this->fieldid && $this->fieldid != $field->id) {
362 throw new coding_exception('Can not set field object after a different field id was set');
364 $this->fieldid = $field->id;
365 $this->field = $field;
366 $this->inputname = 'profile_field_' . $this->field->shortname;
367 $this->data = $this->field->defaultdata;
368 $this->dataformat = FORMAT_HTML;
372 * Sets user id and user data for the field
374 * @param mixed $data
375 * @param int $dataformat
377 public function set_user_data($data, $dataformat) {
378 $this->data = $data;
379 $this->dataformat = $dataformat;
383 * Set the name for the profile category where this field is
385 * @param string $categoryname
387 public function set_category_name($categoryname) {
388 $this->categoryname = $categoryname;
392 * Return field short name
394 * @return string
396 public function get_shortname(): string {
397 return $this->field->shortname;
401 * Returns the name of the profile category where this field is
403 * @return string
405 public function get_category_name() {
406 global $DB;
407 if ($this->categoryname === null) {
408 $this->categoryname = $DB->get_field('user_info_category', 'name', ['id' => $this->field->categoryid]);
410 return $this->categoryname;
414 * Accessor method: Load the field record and user data associated with the
415 * object's fieldid and userid
417 * @internal This method should not generally be overwritten by child classes.
419 public function load_data() {
420 global $DB;
422 // Load the field object.
423 if (($this->fieldid == 0) or (!($field = $DB->get_record('user_info_field', array('id' => $this->fieldid))))) {
424 $this->field = null;
425 $this->inputname = '';
426 } else {
427 $this->set_field($field);
430 if (!empty($this->field) && $this->userid > 0) {
431 $params = array('userid' => $this->userid, 'fieldid' => $this->fieldid);
432 if ($data = $DB->get_record('user_info_data', $params, 'data, dataformat')) {
433 $this->set_user_data($data->data, $data->dataformat);
435 } else {
436 $this->data = null;
441 * Check if the field data is visible to the current user
442 * @internal This method should not generally be overwritten by child classes.
443 * @return bool
445 public function is_visible() {
446 global $USER, $COURSE;
448 $context = ($this->userid > 0) ? context_user::instance($this->userid) : context_system::instance();
450 switch ($this->field->visible) {
451 case PROFILE_VISIBLE_TEACHERS:
452 if ($this->is_signup_field() && (empty($this->userid) || isguestuser($this->userid))) {
453 return true;
454 } else if ($this->userid == $USER->id) {
455 return true;
456 } else if ($this->userid > 0) {
457 return has_capability('moodle/user:viewalldetails', $context);
458 } else {
459 $coursecontext = context_course::instance($COURSE->id);
460 return has_capability('moodle/site:viewuseridentity', $coursecontext);
462 case PROFILE_VISIBLE_ALL:
463 return true;
464 case PROFILE_VISIBLE_PRIVATE:
465 if ($this->is_signup_field() && (empty($this->userid) || isguestuser($this->userid))) {
466 return true;
467 } else if ($this->userid == $USER->id) {
468 return true;
469 } else {
470 return has_capability('moodle/user:viewalldetails', $context);
472 default:
473 // PROFILE_VISIBLE_NONE, so let's check capabilities at system level.
474 if ($this->userid > 0) {
475 $context = context_system::instance();
477 return has_capability('moodle/user:viewalldetails', $context);
482 * Check if the field data is editable for the current user
483 * This method should not generally be overwritten by child classes.
484 * @return bool
486 public function is_editable() {
487 global $USER;
489 if (!$this->is_visible()) {
490 return false;
493 if ($this->is_signup_field() && (empty($this->userid) || isguestuser($this->userid))) {
494 // Allow editing the field on the signup page.
495 return true;
498 $systemcontext = context_system::instance();
500 if ($this->userid == $USER->id && has_capability('moodle/user:editownprofile', $systemcontext)) {
501 return true;
504 if (has_capability('moodle/user:update', $systemcontext)) {
505 return true;
508 // Checking for mentors have capability to edit user's profile.
509 if ($this->userid > 0) {
510 $usercontext = context_user::instance($this->userid);
511 if ($this->userid != $USER->id && has_capability('moodle/user:editprofile', $usercontext, $USER->id)) {
512 return true;
516 return false;
520 * Check if the field data is considered empty
521 * @internal This method should not generally be overwritten by child classes.
522 * @return boolean
524 public function is_empty() {
525 return ( ($this->data != '0') and empty($this->data));
529 * Check if the field is required on the edit profile page
530 * @internal This method should not generally be overwritten by child classes.
531 * @return bool
533 public function is_required() {
534 return (boolean)$this->field->required;
538 * Check if the field is locked on the edit profile page
539 * @internal This method should not generally be overwritten by child classes.
540 * @return bool
542 public function is_locked() {
543 return (boolean)$this->field->locked;
547 * Check if the field data should be unique
548 * @internal This method should not generally be overwritten by child classes.
549 * @return bool
551 public function is_unique() {
552 return (boolean)$this->field->forceunique;
556 * Check if the field should appear on the signup page
557 * @internal This method should not generally be overwritten by child classes.
558 * @return bool
560 public function is_signup_field() {
561 return (boolean)$this->field->signup;
565 * Return the field settings suitable to be exported via an external function.
566 * By default it return all the field settings.
568 * @return array all the settings
569 * @since Moodle 3.2
571 public function get_field_config_for_external() {
572 return (array) $this->field;
576 * Return the field type and null properties.
577 * This will be used for validating the data submitted by a user.
579 * @return array the param type and null property
580 * @since Moodle 3.2
582 public function get_field_properties() {
583 return array(PARAM_RAW, NULL_NOT_ALLOWED);
588 * Returns an array of all custom field records with any defined data (or empty data), for the specified user id.
589 * @param int $userid
590 * @return profile_field_base[]
592 function profile_get_user_fields_with_data(int $userid): array {
593 global $DB, $CFG;
595 // Join any user info data present with each user info field for the user object.
596 $sql = 'SELECT uif.*, uic.name AS categoryname ';
597 if ($userid > 0) {
598 $sql .= ', uind.id AS hasuserdata, uind.data, uind.dataformat ';
600 $sql .= 'FROM {user_info_field} uif ';
601 $sql .= 'LEFT JOIN {user_info_category} uic ON uif.categoryid = uic.id ';
602 if ($userid > 0) {
603 $sql .= 'LEFT JOIN {user_info_data} uind ON uif.id = uind.fieldid AND uind.userid = :userid ';
605 $sql .= 'ORDER BY uic.sortorder ASC, uif.sortorder ASC ';
606 $fields = $DB->get_records_sql($sql, ['userid' => $userid]);
607 $data = [];
608 foreach ($fields as $field) {
609 require_once($CFG->dirroot . '/user/profile/field/' . $field->datatype . '/field.class.php');
610 $classname = 'profile_field_' . $field->datatype;
611 $field->hasuserdata = !empty($field->hasuserdata);
612 /** @var profile_field_base $fieldobject */
613 $fieldobject = new $classname($field->id, $userid, $field);
614 $fieldobject->set_category_name($field->categoryname);
615 unset($field->categoryname);
616 $data[] = $fieldobject;
618 return $data;
622 * Returns an array of all custom field records with any defined data (or empty data), for the specified user id, by category.
623 * @param int $userid
624 * @return profile_field_base[][]
626 function profile_get_user_fields_with_data_by_category(int $userid): array {
627 $fields = profile_get_user_fields_with_data($userid);
628 $data = [];
629 foreach ($fields as $field) {
630 $data[$field->field->categoryid][] = $field;
632 return $data;
636 * Loads user profile field data into the user object.
637 * @param stdClass $user
639 function profile_load_data(stdClass $user): void {
640 $fields = profile_get_user_fields_with_data($user->id);
641 foreach ($fields as $formfield) {
642 $formfield->edit_load_user_data($user);
647 * Print out the customisable categories and fields for a users profile
649 * @param MoodleQuickForm $mform instance of the moodleform class
650 * @param int $userid id of user whose profile is being edited or 0 for the new user
652 function profile_definition(MoodleQuickForm $mform, int $userid = 0): void {
653 $categories = profile_get_user_fields_with_data_by_category($userid);
654 foreach ($categories as $categoryid => $fields) {
655 // Check first if *any* fields will be displayed.
656 $fieldstodisplay = [];
658 foreach ($fields as $formfield) {
659 if ($formfield->is_editable()) {
660 $fieldstodisplay[] = $formfield;
664 if (empty($fieldstodisplay)) {
665 continue;
668 // Display the header and the fields.
669 $mform->addElement('header', 'category_'.$categoryid, format_string($fields[0]->get_category_name()));
670 foreach ($fieldstodisplay as $formfield) {
671 $formfield->edit_field($mform);
677 * Adds profile fields to user edit forms.
678 * @param MoodleQuickForm $mform
679 * @param int $userid
681 function profile_definition_after_data(MoodleQuickForm $mform, int $userid): void {
682 $userid = ($userid < 0) ? 0 : (int)$userid;
684 $fields = profile_get_user_fields_with_data($userid);
685 foreach ($fields as $formfield) {
686 $formfield->edit_after_data($mform);
691 * Validates profile data.
692 * @param stdClass $usernew
693 * @param array $files
694 * @return array array of errors, same as in {@see moodleform::validation()}
696 function profile_validation(stdClass $usernew, array $files): array {
697 $err = array();
698 $fields = profile_get_user_fields_with_data($usernew->id);
699 foreach ($fields as $formfield) {
700 $err += $formfield->edit_validate_field($usernew, $files);
702 return $err;
706 * Saves profile data for a user.
707 * @param stdClass $usernew
709 function profile_save_data(stdClass $usernew): void {
710 global $CFG;
712 $fields = profile_get_user_fields_with_data($usernew->id);
713 foreach ($fields as $formfield) {
714 $formfield->edit_save_data($usernew);
719 * Display profile fields.
721 * @deprecated since Moodle 3.11 MDL-71051 - please do not use this function any more.
722 * @todo MDL-71413 This will be deleted in Moodle 4.3.
724 * @param int $userid
726 function profile_display_fields($userid) {
727 debugging('Function profile_display_fields() is deprecated because it is no longer used and will be '.
728 'removed in future versions of Moodle', DEBUG_DEVELOPER);
730 $categories = profile_get_user_fields_with_data_by_category($userid);
731 foreach ($categories as $categoryid => $fields) {
732 foreach ($fields as $formfield) {
733 if ($formfield->is_visible() and !$formfield->is_empty()) {
734 echo html_writer::tag('dt', format_string($formfield->field->name));
735 echo html_writer::tag('dd', $formfield->display_data());
742 * Retrieves a list of profile fields that must be displayed in the sign-up form.
744 * @return array list of profile fields info
745 * @since Moodle 3.2
747 function profile_get_signup_fields(): array {
748 $profilefields = array();
749 $fieldobjects = profile_get_user_fields_with_data(0);
750 foreach ($fieldobjects as $fieldobject) {
751 $field = (object)$fieldobject->get_field_config_for_external();
752 if ($fieldobject->get_category_name() !== null && $fieldobject->is_signup_field() && $field->visible <> 0) {
753 $profilefields[] = (object) array(
754 'categoryid' => $field->categoryid,
755 'categoryname' => $fieldobject->get_category_name(),
756 'fieldid' => $field->id,
757 'datatype' => $field->datatype,
758 'object' => $fieldobject
762 return $profilefields;
766 * Adds code snippet to a moodle form object for custom profile fields that
767 * should appear on the signup page
768 * @param MoodleQuickForm $mform moodle form object
770 function profile_signup_fields(MoodleQuickForm $mform): void {
772 if ($fields = profile_get_signup_fields()) {
773 foreach ($fields as $field) {
774 // Check if we change the categories.
775 if (!isset($currentcat) || $currentcat != $field->categoryid) {
776 $currentcat = $field->categoryid;
777 $mform->addElement('header', 'category_'.$field->categoryid, format_string($field->categoryname));
779 $field->object->edit_field($mform);
785 * Returns an object with the custom profile fields set for the given user
786 * @param int $userid
787 * @param bool $onlyinuserobject True if you only want the ones in $USER.
788 * @return stdClass object where properties names are shortnames of custom profile fields
790 function profile_user_record(int $userid, bool $onlyinuserobject = true): stdClass {
791 $usercustomfields = new stdClass();
793 $fields = profile_get_user_fields_with_data($userid);
794 foreach ($fields as $formfield) {
795 if (!$onlyinuserobject || $formfield->is_user_object_data()) {
796 $usercustomfields->{$formfield->field->shortname} = $formfield->data;
800 return $usercustomfields;
804 * Obtains a list of all available custom profile fields, indexed by id.
806 * Some profile fields are not included in the user object data (see
807 * profile_user_record function above). Optionally, you can obtain only those
808 * fields that are included in the user object.
810 * To be clear, this function returns the available fields, and does not
811 * return the field values for a particular user.
813 * @param bool $onlyinuserobject True if you only want the ones in $USER
814 * @return array Array of field objects from database (indexed by id)
815 * @since Moodle 2.7.1
817 function profile_get_custom_fields(bool $onlyinuserobject = false): array {
818 $fieldobjects = profile_get_user_fields_with_data(0);
819 $fields = [];
820 foreach ($fieldobjects as $fieldobject) {
821 if (!$onlyinuserobject || $fieldobject->is_user_object_data()) {
822 $fields[$fieldobject->fieldid] = (object)$fieldobject->get_field_config_for_external();
825 ksort($fields);
826 return $fields;
830 * Load custom profile fields into user object
832 * @param stdClass $user user object
834 function profile_load_custom_fields($user) {
835 $user->profile = (array)profile_user_record($user->id);
839 * Save custom profile fields for a user.
841 * @param int $userid The user id
842 * @param array $profilefields The fields to save
844 function profile_save_custom_fields($userid, $profilefields) {
845 global $DB;
847 $fields = profile_get_user_fields_with_data(0);
848 if ($fields) {
849 foreach ($fields as $fieldobject) {
850 $field = (object)$fieldobject->get_field_config_for_external();
851 if (isset($profilefields[$field->shortname])) {
852 $conditions = array('fieldid' => $field->id, 'userid' => $userid);
853 $id = $DB->get_field('user_info_data', 'id', $conditions);
854 $data = $profilefields[$field->shortname];
855 if ($id) {
856 $DB->set_field('user_info_data', 'data', $data, array('id' => $id));
857 } else {
858 $record = array('fieldid' => $field->id, 'userid' => $userid, 'data' => $data);
859 $DB->insert_record('user_info_data', $record);
867 * Gets basic data about custom profile fields. This is minimal data that is cached within the
868 * current request for all fields so that it can be used quickly.
870 * @param string $shortname Shortname of custom profile field
871 * @param bool $casesensitive Whether to perform case-sensitive matching of shortname. Note current limitations of custom profile
872 * fields allow the same shortname to exist differing only by it's case
873 * @return stdClass|null Object with properties id, shortname, name, visible, datatype, categoryid, etc
875 function profile_get_custom_field_data_by_shortname(string $shortname, bool $casesensitive = true): ?stdClass {
876 $cache = \cache::make_from_params(cache_store::MODE_REQUEST, 'core_profile', 'customfields',
877 [], ['simplekeys' => true, 'simpledata' => true]);
878 $data = $cache->get($shortname);
879 if ($data === false) {
880 // If we don't have data, we get and cache it for all fields to avoid multiple DB requests.
881 $fields = profile_get_custom_fields();
882 $data = null;
883 foreach ($fields as $field) {
884 $cache->set($field->shortname, $field);
886 // Perform comparison according to case sensitivity parameter.
887 $shortnamematch = $casesensitive
888 ? strcmp($field->shortname, $shortname) === 0
889 : strcasecmp($field->shortname, $shortname) === 0;
891 if ($shortnamematch) {
892 $data = $field;
897 return $data;
901 * Trigger a user profile viewed event.
903 * @param stdClass $user user object
904 * @param stdClass $context context object (course or user)
905 * @param stdClass $course course object
906 * @since Moodle 2.9
908 function profile_view($user, $context, $course = null) {
910 $eventdata = array(
911 'objectid' => $user->id,
912 'relateduserid' => $user->id,
913 'context' => $context
916 if (!empty($course)) {
917 $eventdata['courseid'] = $course->id;
918 $eventdata['other'] = array(
919 'courseid' => $course->id,
920 'courseshortname' => $course->shortname,
921 'coursefullname' => $course->fullname
925 $event = \core\event\user_profile_viewed::create($eventdata);
926 $event->add_record_snapshot('user', $user);
927 $event->trigger();
931 * Does the user have all required custom fields set?
933 * Internal, to be exclusively used by {@link user_not_fully_set_up()} only.
935 * Note that if users have no way to fill a required field via editing their
936 * profiles (e.g. the field is not visible or it is locked), we still return true.
937 * So this is actually checking if we should redirect the user to edit their
938 * profile, rather than whether there is a value in the database.
940 * @param int $userid
941 * @return bool
943 function profile_has_required_custom_fields_set($userid) {
944 $profilefields = profile_get_user_fields_with_data($userid);
945 foreach ($profilefields as $profilefield) {
946 if ($profilefield->is_required() && !$profilefield->is_locked() &&
947 $profilefield->is_empty() && $profilefield->get_field_config_for_external()['visible']) {
948 return false;
952 return true;