Merge branch 'MDL-46015_28' of git://github.com/jmvedrine/moodle into MOODLE_28_STABLE
[moodle.git] / user / editlib.php
blob62c114c78c79facae1d7cb673104df36c0ca5952
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 * This file contains function used when editing a users profile and preferences.
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_user
25 /**
26 * Cancels the requirement for a user to update their email address.
28 * @param int $userid
30 function cancel_email_update($userid) {
31 unset_user_preference('newemail', $userid);
32 unset_user_preference('newemailkey', $userid);
33 unset_user_preference('newemailattemptsleft', $userid);
36 /**
37 * Loads the given users preferences into the given user object.
39 * @param stdClass $user The user object, modified by reference.
40 * @param bool $reload
42 function useredit_load_preferences(&$user, $reload=true) {
43 global $USER;
45 if (!empty($user->id)) {
46 if ($reload and $USER->id == $user->id) {
47 // Reload preferences in case it was changed in other session.
48 unset($USER->preference);
51 if ($preferences = get_user_preferences(null, null, $user->id)) {
52 foreach ($preferences as $name => $value) {
53 $user->{'preference_'.$name} = $value;
59 /**
60 * Updates the user preferences for teh given user.
62 * @param stdClass|array $usernew
64 function useredit_update_user_preference($usernew) {
65 $ua = (array)$usernew;
66 foreach ($ua as $key => $value) {
67 if (strpos($key, 'preference_') === 0) {
68 $name = substr($key, strlen('preference_'));
69 set_user_preference($name, $value, $usernew->id);
74 /**
75 * Updates the provided users profile picture based upon the expected fields returned from the edit or edit_advanced forms.
77 * @global moodle_database $DB
78 * @param stdClass $usernew An object that contains some information about the user being updated
79 * @param moodleform $userform The form that was submitted to edit the form
80 * @param array $filemanageroptions
81 * @return bool True if the user was updated, false if it stayed the same.
83 function useredit_update_picture(stdClass $usernew, moodleform $userform, $filemanageroptions = array()) {
84 global $CFG, $DB;
85 require_once("$CFG->libdir/gdlib.php");
87 $context = context_user::instance($usernew->id, MUST_EXIST);
88 $user = $DB->get_record('user', array('id' => $usernew->id), 'id, picture', MUST_EXIST);
90 $newpicture = $user->picture;
91 // Get file_storage to process files.
92 $fs = get_file_storage();
93 if (!empty($usernew->deletepicture)) {
94 // The user has chosen to delete the selected users picture.
95 $fs->delete_area_files($context->id, 'user', 'icon'); // Drop all images in area.
96 $newpicture = 0;
98 } else {
99 // Save newly uploaded file, this will avoid context mismatch for newly created users.
100 file_save_draft_area_files($usernew->imagefile, $context->id, 'user', 'newicon', 0, $filemanageroptions);
101 if (($iconfiles = $fs->get_area_files($context->id, 'user', 'newicon')) && count($iconfiles) == 2) {
102 // Get file which was uploaded in draft area.
103 foreach ($iconfiles as $file) {
104 if (!$file->is_directory()) {
105 break;
108 // Copy file to temporary location and the send it for processing icon.
109 if ($iconfile = $file->copy_content_to_temp()) {
110 // There is a new image that has been uploaded.
111 // Process the new image and set the user to make use of it.
112 // NOTE: Uploaded images always take over Gravatar.
113 $newpicture = (int)process_new_icon($context, 'user', 'icon', 0, $iconfile);
114 // Delete temporary file.
115 @unlink($iconfile);
116 // Remove uploaded file.
117 $fs->delete_area_files($context->id, 'user', 'newicon');
118 } else {
119 // Something went wrong while creating temp file.
120 // Remove uploaded file.
121 $fs->delete_area_files($context->id, 'user', 'newicon');
122 return false;
127 if ($newpicture != $user->picture) {
128 $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id));
129 return true;
130 } else {
131 return false;
136 * Updates the user email bounce + send counts when the user is edited.
138 * @param stdClass $user The current user object.
139 * @param stdClass $usernew The updated user object.
141 function useredit_update_bounces($user, $usernew) {
142 if (!isset($usernew->email)) {
143 // Locked field.
144 return;
146 if (!isset($user->email) || $user->email !== $usernew->email) {
147 set_bounce_count($usernew, true);
148 set_send_count($usernew, true);
153 * Updates the forums a user is tracking when the user is edited.
155 * @param stdClass $user The original user object.
156 * @param stdClass $usernew The updated user object.
158 function useredit_update_trackforums($user, $usernew) {
159 global $CFG;
160 if (!isset($usernew->trackforums)) {
161 // Locked field.
162 return;
164 if ((!isset($user->trackforums) || ($usernew->trackforums != $user->trackforums)) and !$usernew->trackforums) {
165 require_once($CFG->dirroot.'/mod/forum/lib.php');
166 forum_tp_delete_read_records($usernew->id);
171 * Updates a users interests.
173 * @param stdClass $user
174 * @param array $interests
176 function useredit_update_interests($user, $interests) {
177 tag_set('user', $user->id, $interests, 'core', context_user::instance($user->id)->id);
181 * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
183 * @param moodleform $mform
184 * @param array|null $editoroptions
185 * @param array|null $filemanageroptions
187 function useredit_shared_definition(&$mform, $editoroptions = null, $filemanageroptions = null) {
188 global $CFG, $USER, $DB;
190 $user = $DB->get_record('user', array('id' => $USER->id));
191 useredit_load_preferences($user, false);
193 $strrequired = get_string('required');
195 // Add the necessary names.
196 foreach (useredit_get_required_name_fields() as $fullname) {
197 $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"');
198 $mform->addRule($fullname, $strrequired, 'required', null, 'client');
199 $mform->setType($fullname, PARAM_NOTAGS);
202 $enabledusernamefields = useredit_get_enabled_name_fields();
203 // Add the enabled additional name fields.
204 foreach ($enabledusernamefields as $addname) {
205 $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"');
206 $mform->setType($addname, PARAM_NOTAGS);
209 // Do not show email field if change confirmation is pending.
210 if (!empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
211 $notice = get_string('emailchangepending', 'auth', $user);
212 $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
213 . get_string('emailchangecancel', 'auth') . '</a>';
214 $mform->addElement('static', 'emailpending', get_string('email'), $notice);
215 } else {
216 $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
217 $mform->addRule('email', $strrequired, 'required', null, 'client');
218 $mform->setType('email', PARAM_EMAIL);
221 $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
222 $mform->setType('city', PARAM_TEXT);
223 if (!empty($CFG->defaultcity)) {
224 $mform->setDefault('city', $CFG->defaultcity);
227 $choices = get_string_manager()->get_list_of_countries();
228 $choices = array('' => get_string('selectacountry') . '...') + $choices;
229 $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
230 if (!empty($CFG->country)) {
231 $mform->setDefault('country', $CFG->country);
234 $choices = get_list_of_timezones();
235 $choices['99'] = get_string('serverlocaltime');
236 if ($CFG->forcetimezone != 99) {
237 $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
238 } else {
239 $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
240 $mform->setDefault('timezone', '99');
243 // Multi-Calendar Support - see MDL-18375.
244 $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
245 // We do not want to show this option unless there is more than one calendar type to display.
246 if (count($calendartypes) > 1) {
247 $mform->addElement('select', 'calendartype', get_string('preferredcalendar', 'calendar'), $calendartypes);
248 $mform->setDefault('calendartype', $CFG->calendartype);
251 if (!empty($CFG->allowuserthemes)) {
252 $choices = array();
253 $choices[''] = get_string('default');
254 $themes = get_list_of_themes();
255 foreach ($themes as $key => $theme) {
256 if (empty($theme->hidefromselector)) {
257 $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
260 $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
263 $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
264 $mform->setType('description_editor', PARAM_CLEANHTML);
265 $mform->addHelpButton('description_editor', 'userdescription');
267 $mform->addElement('header', 'moodle_userpreferences', get_string('preferences'));
268 useredit_shared_definition_preferences($user, $mform, $editoroptions, $filemanageroptions);
270 if (empty($USER->newadminuser)) {
271 $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
273 if (!empty($CFG->enablegravatar)) {
274 $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
277 $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
279 $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
280 $mform->setDefault('deletepicture', 0);
282 $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
283 $mform->addHelpButton('imagefile', 'newpicture');
285 $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
286 $mform->setType('imagealt', PARAM_TEXT);
290 // Display user name fields that are not currenlty enabled here if there are any.
291 $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
292 if (count($disabledusernamefields) > 0) {
293 $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
294 foreach ($disabledusernamefields as $allname) {
295 $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
296 $mform->setType($allname, PARAM_NOTAGS);
300 if (!empty($CFG->usetags) and empty($USER->newadminuser)) {
301 $mform->addElement('header', 'moodle_interests', get_string('interests'));
302 $mform->addElement('tags', 'interests', get_string('interestslist'), array('display' => 'noofficial'));
303 $mform->addHelpButton('interests', 'interestslist');
306 // Moodle optional fields.
307 $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
309 $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
310 $mform->setType('url', PARAM_URL);
312 $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
313 $mform->setType('icq', PARAM_NOTAGS);
315 $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
316 $mform->setType('skype', PARAM_NOTAGS);
318 $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
319 $mform->setType('aim', PARAM_NOTAGS);
321 $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
322 $mform->setType('yahoo', PARAM_NOTAGS);
324 $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
325 $mform->setType('msn', PARAM_NOTAGS);
327 $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
328 $mform->setType('idnumber', PARAM_NOTAGS);
330 $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
331 $mform->setType('institution', PARAM_TEXT);
333 $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
334 $mform->setType('department', PARAM_TEXT);
336 $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
337 $mform->setType('phone1', PARAM_NOTAGS);
339 $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
340 $mform->setType('phone2', PARAM_NOTAGS);
342 $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
343 $mform->setType('address', PARAM_TEXT);
347 * Adds user preferences elements to user edit form.
349 * @param stdClass $user
350 * @param moodleform $mform
351 * @param array|null $editoroptions
352 * @param array|null $filemanageroptions
354 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
355 global $CFG;
357 $choices = array();
358 $choices['0'] = get_string('emaildisplayno');
359 $choices['1'] = get_string('emaildisplayyes');
360 $choices['2'] = get_string('emaildisplaycourse');
361 $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
362 $mform->setDefault('maildisplay', $CFG->defaultpreference_maildisplay);
364 $choices = array();
365 $choices['0'] = get_string('textformat');
366 $choices['1'] = get_string('htmlformat');
367 $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
368 $mform->setDefault('mailformat', $CFG->defaultpreference_mailformat);
370 if (!empty($CFG->allowusermailcharset)) {
371 $choices = array();
372 $charsets = get_list_of_charsets();
373 if (!empty($CFG->sitemailcharset)) {
374 $choices['0'] = get_string('site').' ('.$CFG->sitemailcharset.')';
375 } else {
376 $choices['0'] = get_string('site').' (UTF-8)';
378 $choices = array_merge($choices, $charsets);
379 $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
382 $choices = array();
383 $choices['0'] = get_string('emaildigestoff');
384 $choices['1'] = get_string('emaildigestcomplete');
385 $choices['2'] = get_string('emaildigestsubjects');
386 $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
387 $mform->setDefault('maildigest', $CFG->defaultpreference_maildigest);
388 $mform->addHelpButton('maildigest', 'emaildigest');
390 $choices = array();
391 $choices['1'] = get_string('autosubscribeyes');
392 $choices['0'] = get_string('autosubscribeno');
393 $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
394 $mform->setDefault('autosubscribe', $CFG->defaultpreference_autosubscribe);
396 if (!empty($CFG->forum_trackreadposts)) {
397 $choices = array();
398 $choices['0'] = get_string('trackforumsno');
399 $choices['1'] = get_string('trackforumsyes');
400 $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
401 $mform->setDefault('trackforums', $CFG->defaultpreference_trackforums);
404 $editors = editors_get_enabled();
405 if (count($editors) > 1) {
406 $choices = array('' => get_string('defaulteditor'));
407 $firsteditor = '';
408 foreach (array_keys($editors) as $editor) {
409 if (!$firsteditor) {
410 $firsteditor = $editor;
412 $choices[$editor] = get_string('pluginname', 'editor_' . $editor);
414 $mform->addElement('select', 'preference_htmleditor', get_string('textediting'), $choices);
415 $mform->setDefault('preference_htmleditor', '');
416 } else {
417 // Empty string means use the first chosen text editor.
418 $mform->addElement('hidden', 'preference_htmleditor');
419 $mform->setDefault('preference_htmleditor', '');
420 $mform->setType('preference_htmleditor', PARAM_PLUGIN);
423 $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
424 $mform->setDefault('lang', $CFG->lang);
429 * Return required user name fields for forms.
431 * @return array required user name fields in order according to settings.
433 function useredit_get_required_name_fields() {
434 global $CFG;
436 // Get the name display format.
437 $nameformat = $CFG->fullnamedisplay;
439 // Names that are required fields on user forms.
440 $necessarynames = array('firstname', 'lastname');
441 $languageformat = get_string('fullnamedisplay');
443 // Check that the language string and the $nameformat contain the necessary names.
444 foreach ($necessarynames as $necessaryname) {
445 $pattern = "/$necessaryname\b/";
446 if (!preg_match($pattern, $languageformat)) {
447 // If the language string has been altered then fall back on the below order.
448 $languageformat = 'firstname lastname';
450 if (!preg_match($pattern, $nameformat)) {
451 // If the nameformat doesn't contain the necessary name fields then use the languageformat.
452 $nameformat = $languageformat;
456 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
457 $necessarynames = order_in_string($necessarynames, $nameformat);
458 return $necessarynames;
462 * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
464 * @return array Enabled user name fields.
466 function useredit_get_enabled_name_fields() {
467 global $CFG;
469 // Get all of the other name fields which are not ranked as necessary.
470 $additionalusernamefields = array_diff(get_all_user_name_fields(), array('firstname', 'lastname'));
471 // Find out which additional name fields are actually being used from the fullnamedisplay setting.
472 $enabledadditionalusernames = array();
473 foreach ($additionalusernamefields as $enabledname) {
474 if (strpos($CFG->fullnamedisplay, $enabledname) !== false) {
475 $enabledadditionalusernames[] = $enabledname;
479 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
480 $enabledadditionalusernames = order_in_string($enabledadditionalusernames, $CFG->fullnamedisplay);
481 return $enabledadditionalusernames;
485 * Gets user name fields not enabled from the setting fullnamedisplay.
487 * @param array $enabledadditionalusernames Current enabled additional user name fields.
488 * @return array Disabled user name fields.
490 function useredit_get_disabled_name_fields($enabledadditionalusernames = null) {
491 // If we don't have enabled additional user name information then go and fetch it (try to avoid).
492 if (!isset($enabledadditionalusernames)) {
493 $enabledadditionalusernames = useredit_get_enabled_name_fields();
496 // These are the additional fields that are not currently enabled.
497 $nonusednamefields = array_diff(get_all_user_name_fields(),
498 array_merge(array('firstname', 'lastname'), $enabledadditionalusernames));
499 return $nonusednamefields;