MDL-49684 timezones: add BC unit test first
[moodle.git] / user / editlib.php
CommitLineData
8bdc9cac 1<?php
a2ed6e69
SH
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/>.
ad6226fb 16
a2ed6e69
SH
17/**
18 * This file contains function used when editing a users profile and preferences.
19 *
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
23 */
24
25/**
26 * Cancels the requirement for a user to update their email address.
27 *
28 * @param int $userid
29 */
05c38e2b 30function cancel_email_update($userid) {
31 unset_user_preference('newemail', $userid);
32 unset_user_preference('newemailkey', $userid);
33 unset_user_preference('newemailattemptsleft', $userid);
34}
35
a2ed6e69
SH
36/**
37 * Loads the given users preferences into the given user object.
38 *
39 * @param stdClass $user The user object, modified by reference.
40 * @param bool $reload
41 */
05c38e2b 42function useredit_load_preferences(&$user, $reload=true) {
43 global $USER;
14a6b7e1 44
05c38e2b 45 if (!empty($user->id)) {
46 if ($reload and $USER->id == $user->id) {
a2ed6e69 47 // Reload preferences in case it was changed in other session.
05c38e2b 48 unset($USER->preference);
49 }
aa6c1ced 50
05c38e2b 51 if ($preferences = get_user_preferences(null, null, $user->id)) {
a2ed6e69 52 foreach ($preferences as $name => $value) {
05c38e2b 53 $user->{'preference_'.$name} = $value;
54 }
14a6b7e1 55 }
56 }
57}
58
a2ed6e69
SH
59/**
60 * Updates the user preferences for teh given user.
61 *
62 * @param stdClass|array $usernew
63 */
14a6b7e1 64function useredit_update_user_preference($usernew) {
65 $ua = (array)$usernew;
a2ed6e69 66 foreach ($ua as $key => $value) {
14a6b7e1 67 if (strpos($key, 'preference_') === 0) {
68 $name = substr($key, strlen('preference_'));
69 set_user_preference($name, $value, $usernew->id);
70 }
71 }
72}
73
4125bdc1 74/**
a2ed6e69 75 * Updates the provided users profile picture based upon the expected fields returned from the edit or edit_advanced forms.
4125bdc1
SH
76 *
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
a2ed6e69 80 * @param array $filemanageroptions
4125bdc1
SH
81 * @return bool True if the user was updated, false if it stayed the same.
82 */
4e782b32 83function useredit_update_picture(stdClass $usernew, moodleform $userform, $filemanageroptions = array()) {
a5d424df 84 global $CFG, $DB;
e88dd876 85 require_once("$CFG->libdir/gdlib.php");
9d85247d 86
43731030 87 $context = context_user::instance($usernew->id, MUST_EXIST);
a2ed6e69 88 $user = $DB->get_record('user', array('id' => $usernew->id), 'id, picture', MUST_EXIST);
4d254790
PS
89
90 $newpicture = $user->picture;
4e782b32
RT
91 // Get file_storage to process files.
92 $fs = get_file_storage();
4125bdc1 93 if (!empty($usernew->deletepicture)) {
a2ed6e69
SH
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.
4d254790
PS
96 $newpicture = 0;
97
4e782b32
RT
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) {
a2ed6e69 102 // Get file which was uploaded in draft area.
4e782b32
RT
103 foreach ($iconfiles as $file) {
104 if (!$file->is_directory()) {
105 break;
106 }
107 }
a2ed6e69 108 // Copy file to temporary location and the send it for processing icon.
4e782b32 109 if ($iconfile = $file->copy_content_to_temp()) {
a2ed6e69 110 // There is a new image that has been uploaded.
4e782b32 111 // Process the new image and set the user to make use of it.
a2ed6e69 112 // NOTE: Uploaded images always take over Gravatar.
4e782b32 113 $newpicture = (int)process_new_icon($context, 'user', 'icon', 0, $iconfile);
a2ed6e69 114 // Delete temporary file.
4e782b32
RT
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;
123 }
124 }
14a6b7e1 125 }
4125bdc1 126
4d254790
PS
127 if ($newpicture != $user->picture) {
128 $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id));
4125bdc1 129 return true;
4d254790
PS
130 } else {
131 return false;
4125bdc1 132 }
14a6b7e1 133}
134
a2ed6e69
SH
135/**
136 * Updates the user email bounce + send counts when the user is edited.
137 *
138 * @param stdClass $user The current user object.
139 * @param stdClass $usernew The updated user object.
140 */
14a6b7e1 141function useredit_update_bounces($user, $usernew) {
142 if (!isset($usernew->email)) {
a2ed6e69 143 // Locked field.
14a6b7e1 144 return;
d8734783 145 }
a9457b54 146 if (!isset($user->email) || $user->email !== $usernew->email) {
a2ed6e69
SH
147 set_bounce_count($usernew, true);
148 set_send_count($usernew, true);
14a6b7e1 149 }
150}
151
a2ed6e69
SH
152/**
153 * Updates the forums a user is tracking when the user is edited.
154 *
155 * @param stdClass $user The original user object.
156 * @param stdClass $usernew The updated user object.
157 */
14a6b7e1 158function useredit_update_trackforums($user, $usernew) {
159 global $CFG;
160 if (!isset($usernew->trackforums)) {
a2ed6e69 161 // Locked field.
14a6b7e1 162 return;
163 }
a9457b54 164 if ((!isset($user->trackforums) || ($usernew->trackforums != $user->trackforums)) and !$usernew->trackforums) {
14a6b7e1 165 require_once($CFG->dirroot.'/mod/forum/lib.php');
166 forum_tp_delete_read_records($usernew->id);
167 }
168}
169
a2ed6e69
SH
170/**
171 * Updates a users interests.
172 *
173 * @param stdClass $user
174 * @param array $interests
175 */
c060fc6a 176function useredit_update_interests($user, $interests) {
cc033d48 177 tag_set('user', $user->id, $interests, 'core', context_user::instance($user->id)->id);
1e1c51a3 178}
179
a2ed6e69
SH
180/**
181 * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
182 *
183 * @param moodleform $mform
184 * @param array|null $editoroptions
185 * @param array|null $filemanageroptions
186 */
4e782b32 187function useredit_shared_definition(&$mform, $editoroptions = null, $filemanageroptions = null) {
d6ace123 188 global $CFG, $USER, $DB;
189
190 $user = $DB->get_record('user', array('id' => $USER->id));
05c38e2b 191 useredit_load_preferences($user, false);
14a6b7e1 192
193 $strrequired = get_string('required');
d8734783 194
1cc3a9ae
AG
195 // Add the necessary names.
196 foreach (useredit_get_required_name_fields() as $fullname) {
a327f25e 197 $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"');
1cc3a9ae 198 $mform->addRule($fullname, $strrequired, 'required', null, 'client');
a327f25e
AG
199 $mform->setType($fullname, PARAM_NOTAGS);
200 }
d8734783 201
1cc3a9ae
AG
202 $enabledusernamefields = useredit_get_enabled_name_fields();
203 // Add the enabled additional name fields.
204 foreach ($enabledusernamefields as $addname) {
a327f25e
AG
205 $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"');
206 $mform->setType($addname, PARAM_NOTAGS);
207 }
d8734783 208
a2ed6e69 209 // Do not show email field if change confirmation is pending.
775f811a 210 if (!empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
c6a074f8 211 $notice = get_string('emailchangepending', 'auth', $user);
d6ace123 212 $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
c6a074f8 213 . get_string('emailchangecancel', 'auth') . '</a>';
d6ace123 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');
947ab40b 218 $mform->setType('email', PARAM_RAW_TRIMMED);
d6ace123 219 }
d8734783 220
c5c0d2ff 221 $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
071e68f9 222 $mform->setType('city', PARAM_TEXT);
fa7f750c
PS
223 if (!empty($CFG->defaultcity)) {
224 $mform->setDefault('city', $CFG->defaultcity);
225 }
d8734783 226
0aa759b0 227 $choices = get_string_manager()->get_list_of_countries();
a2ed6e69 228 $choices = array('' => get_string('selectacountry') . '...') + $choices;
d8734783 229 $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
d8734783 230 if (!empty($CFG->country)) {
231 $mform->setDefault('country', $CFG->country);
232 }
233
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');
241 }
242
2f00e1b2 243 // Multi-Calendar Support - see MDL-18375.
df5d27d8
MN
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);
8bf0f207 248 $mform->setDefault('calendartype', $CFG->calendartype);
df5d27d8 249 }
6dd59aab 250
d8734783 251 if (!empty($CFG->allowuserthemes)) {
ad6226fb 252 $choices = array();
d8734783 253 $choices[''] = get_string('default');
36798745 254 $themes = get_list_of_themes();
a2ed6e69 255 foreach ($themes as $key => $theme) {
36798745 256 if (empty($theme->hidefromselector)) {
d609d962 257 $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
36798745
SH
258 }
259 }
c3ed4a5a 260 $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
d8734783 261 }
ad6226fb 262
8bdc9cac
SH
263 $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
264 $mform->setType('description_editor', PARAM_CLEANHTML);
27d1a27c 265 $mform->addHelpButton('description_editor', 'userdescription');
ad6226fb 266
7a0bf1bd
MG
267 $mform->addElement('header', 'moodle_userpreferences', get_string('preferences'));
268 useredit_shared_definition_preferences($user, $mform, $editoroptions, $filemanageroptions);
269
689096bc 270 if (empty($USER->newadminuser)) {
757e89d2 271 $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
ad6226fb 272
4125bdc1 273 if (!empty($CFG->enablegravatar)) {
ed9e0cb6 274 $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
4125bdc1
SH
275 }
276
d8734783 277 $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
ad6226fb 278
d8734783 279 $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
edfd6a5e 280 $mform->setDefault('deletepicture', 0);
ad6226fb 281
4e782b32 282 $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
27d1a27c 283 $mform->addHelpButton('imagefile', 'newpicture');
ad6226fb 284
d8734783 285 $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
071e68f9 286 $mform->setType('imagealt', PARAM_TEXT);
ad6226fb 287
d8734783 288 }
ad6226fb 289
1cc3a9ae
AG
290 // Display user name fields that are not currenlty enabled here if there are any.
291 $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
b63f542d 292 if (count($disabledusernamefields) > 0) {
a327f25e 293 $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
1cc3a9ae
AG
294 foreach ($disabledusernamefields as $allname) {
295 $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
296 $mform->setType($allname, PARAM_NOTAGS);
a327f25e 297 }
a327f25e
AG
298 }
299
de2d81fa 300 if (!empty($CFG->usetags) and empty($USER->newadminuser)) {
1e1c51a3 301 $mform->addElement('header', 'moodle_interests', get_string('interests'));
c060fc6a 302 $mform->addElement('tags', 'interests', get_string('interestslist'), array('display' => 'noofficial'));
27d1a27c 303 $mform->addHelpButton('interests', 'interestslist');
1e1c51a3 304 }
d6ace123 305
a2ed6e69 306 // Moodle optional fields.
c3ed4a5a 307 $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
ad6226fb 308
d8734783 309 $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
310 $mform->setType('url', PARAM_URL);
ad6226fb 311
d8734783 312 $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
93de0ac2 313 $mform->setType('icq', PARAM_NOTAGS);
ad6226fb 314
d8734783 315 $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
93de0ac2 316 $mform->setType('skype', PARAM_NOTAGS);
ad6226fb 317
d8734783 318 $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
93de0ac2 319 $mform->setType('aim', PARAM_NOTAGS);
ad6226fb 320
d8734783 321 $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
93de0ac2 322 $mform->setType('yahoo', PARAM_NOTAGS);
ad6226fb 323
d8734783 324 $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
93de0ac2 325 $mform->setType('msn', PARAM_NOTAGS);
ad6226fb 326
8b9cfac4 327 $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
93de0ac2 328 $mform->setType('idnumber', PARAM_NOTAGS);
ad6226fb 329
a8fd33b0 330 $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
071e68f9 331 $mform->setType('institution', PARAM_TEXT);
ad6226fb 332
a8fd33b0 333 $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
071e68f9 334 $mform->setType('department', PARAM_TEXT);
ad6226fb 335
d8734783 336 $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
93de0ac2 337 $mform->setType('phone1', PARAM_NOTAGS);
ad6226fb 338
55ac3d6f 339 $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
93de0ac2 340 $mform->setType('phone2', PARAM_NOTAGS);
ad6226fb 341
a8fd33b0 342 $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
071e68f9 343 $mform->setType('address', PARAM_TEXT);
14a6b7e1 344}
ad6226fb 345
7a0bf1bd
MG
346/**
347 * Adds user preferences elements to user edit form.
348 *
349 * @param stdClass $user
350 * @param moodleform $mform
351 * @param array|null $editoroptions
352 * @param array|null $filemanageroptions
353 */
354function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
355 global $CFG;
356
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);
747dac69 362 $mform->setDefault('maildisplay', $CFG->defaultpreference_maildisplay);
7a0bf1bd
MG
363
364 $choices = array();
365 $choices['0'] = get_string('textformat');
366 $choices['1'] = get_string('htmlformat');
367 $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
747dac69 368 $mform->setDefault('mailformat', $CFG->defaultpreference_mailformat);
7a0bf1bd
MG
369
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)';
377 }
378 $choices = array_merge($choices, $charsets);
379 $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
380 }
381
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);
747dac69 387 $mform->setDefault('maildigest', $CFG->defaultpreference_maildigest);
7a0bf1bd
MG
388 $mform->addHelpButton('maildigest', 'emaildigest');
389
390 $choices = array();
391 $choices['1'] = get_string('autosubscribeyes');
392 $choices['0'] = get_string('autosubscribeno');
393 $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
747dac69 394 $mform->setDefault('autosubscribe', $CFG->defaultpreference_autosubscribe);
7a0bf1bd
MG
395
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);
747dac69 401 $mform->setDefault('trackforums', $CFG->defaultpreference_trackforums);
7a0bf1bd
MG
402 }
403
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;
411 }
412 $choices[$editor] = get_string('pluginname', 'editor_' . $editor);
413 }
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);
421 }
422
423 $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
424 $mform->setDefault('lang', $CFG->lang);
425
426}
427
1cc3a9ae
AG
428/**
429 * Return required user name fields for forms.
430 *
431 * @return array required user name fields in order according to settings.
432 */
433function useredit_get_required_name_fields() {
434 global $CFG;
435
436 // Get the name display format.
437 $nameformat = $CFG->fullnamedisplay;
438
439 // Names that are required fields on user forms.
440 $necessarynames = array('firstname', 'lastname');
441 $languageformat = get_string('fullnamedisplay');
442
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';
449 }
450 if (!preg_match($pattern, $nameformat)) {
451 // If the nameformat doesn't contain the necessary name fields then use the languageformat.
452 $nameformat = $languageformat;
453 }
454 }
455
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;
459}
460
461/**
462 * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
463 *
464 * @return array Enabled user name fields.
465 */
466function useredit_get_enabled_name_fields() {
467 global $CFG;
468
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;
476 }
477 }
478
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;
482}
483
484/**
485 * Gets user name fields not enabled from the setting fullnamedisplay.
486 *
487 * @param array $enabledadditionalusernames Current enabled additional user name fields.
488 * @return array Disabled user name fields.
489 */
490function 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();
494 }
495
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;
500}