weekly release 3.2dev
[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
479fa47d
DW
36/**
37 * Performs the common access checks and page setup for all
38 * user preference pages.
39 *
40 * @param int $userid The user id to edit taken from the page params.
41 * @param int $courseid The optional course id if we came from a course context.
42 * @return array containing the user and course records.
43 */
44function useredit_setup_preference_page($userid, $courseid) {
45 global $PAGE, $SESSION, $DB, $CFG, $OUTPUT, $USER;
46
47 // Guest can not edit.
48 if (isguestuser()) {
49 print_error('guestnoeditprofile');
50 }
51
52 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
53 print_error('invalidcourseid');
54 }
55
56 if ($course->id != SITEID) {
57 require_login($course);
58 } else if (!isloggedin()) {
59 if (empty($SESSION->wantsurl)) {
60 $SESSION->wantsurl = $CFG->httpswwwroot.'/user/preferences.php';
61 }
62 redirect(get_login_url());
63 } else {
64 $PAGE->set_context(context_system::instance());
65 }
66
67 // The user profile we are editing.
68 if (!$user = $DB->get_record('user', array('id' => $userid))) {
69 print_error('invaliduserid');
70 }
71
72 // Guest can not be edited.
73 if (isguestuser($user)) {
74 print_error('guestnoeditprofile');
75 }
76
77 // Remote users cannot be edited.
78 if (is_mnet_remote_user($user)) {
79 if (user_not_fully_set_up($user)) {
80 $hostwwwroot = $DB->get_field('mnet_host', 'wwwroot', array('id' => $user->mnethostid));
81 print_error('usernotfullysetup', 'mnet', '', $hostwwwroot);
82 }
83 redirect($CFG->wwwroot . "/user/view.php?course={$course->id}");
84 }
85
86 $systemcontext = context_system::instance();
87 $personalcontext = context_user::instance($user->id);
88
89 // Check access control.
90 if ($user->id == $USER->id) {
91 // Editing own profile - require_login() MUST NOT be used here, it would result in infinite loop!
92 if (!has_capability('moodle/user:editownprofile', $systemcontext)) {
93 print_error('cannotedityourprofile');
94 }
95
96 } else {
97 // Teachers, parents, etc.
98 require_capability('moodle/user:editprofile', $personalcontext);
45367bdf 99
479fa47d
DW
100 // No editing of primary admin!
101 if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
102 print_error('useradmineditadmin');
103 }
104 }
105
106 if ($user->deleted) {
107 echo $OUTPUT->header();
108 echo $OUTPUT->heading(get_string('userdeleted'));
109 echo $OUTPUT->footer();
110 die;
111 }
112
113 $PAGE->set_pagelayout('admin');
114 $PAGE->set_context($personalcontext);
115 if ($USER->id != $user->id) {
116 $PAGE->navigation->extend_for_user($user);
117 } else {
118 if ($node = $PAGE->navigation->find('myprofile', navigation_node::TYPE_ROOTNODE)) {
119 $node->force_open();
120 }
121 }
122
123 return array($user, $course);
124}
125
a2ed6e69
SH
126/**
127 * Loads the given users preferences into the given user object.
128 *
129 * @param stdClass $user The user object, modified by reference.
130 * @param bool $reload
131 */
05c38e2b 132function useredit_load_preferences(&$user, $reload=true) {
133 global $USER;
14a6b7e1 134
05c38e2b 135 if (!empty($user->id)) {
136 if ($reload and $USER->id == $user->id) {
a2ed6e69 137 // Reload preferences in case it was changed in other session.
05c38e2b 138 unset($USER->preference);
139 }
aa6c1ced 140
05c38e2b 141 if ($preferences = get_user_preferences(null, null, $user->id)) {
a2ed6e69 142 foreach ($preferences as $name => $value) {
05c38e2b 143 $user->{'preference_'.$name} = $value;
144 }
14a6b7e1 145 }
146 }
147}
148
a2ed6e69
SH
149/**
150 * Updates the user preferences for teh given user.
151 *
152 * @param stdClass|array $usernew
153 */
14a6b7e1 154function useredit_update_user_preference($usernew) {
155 $ua = (array)$usernew;
a2ed6e69 156 foreach ($ua as $key => $value) {
14a6b7e1 157 if (strpos($key, 'preference_') === 0) {
158 $name = substr($key, strlen('preference_'));
159 set_user_preference($name, $value, $usernew->id);
160 }
161 }
162}
163
4125bdc1 164/**
a2ed6e69 165 * Updates the provided users profile picture based upon the expected fields returned from the edit or edit_advanced forms.
4125bdc1
SH
166 *
167 * @global moodle_database $DB
168 * @param stdClass $usernew An object that contains some information about the user being updated
169 * @param moodleform $userform The form that was submitted to edit the form
a2ed6e69 170 * @param array $filemanageroptions
4125bdc1
SH
171 * @return bool True if the user was updated, false if it stayed the same.
172 */
4e782b32 173function useredit_update_picture(stdClass $usernew, moodleform $userform, $filemanageroptions = array()) {
a5d424df 174 global $CFG, $DB;
e88dd876 175 require_once("$CFG->libdir/gdlib.php");
9d85247d 176
43731030 177 $context = context_user::instance($usernew->id, MUST_EXIST);
a2ed6e69 178 $user = $DB->get_record('user', array('id' => $usernew->id), 'id, picture', MUST_EXIST);
4d254790
PS
179
180 $newpicture = $user->picture;
4e782b32
RT
181 // Get file_storage to process files.
182 $fs = get_file_storage();
4125bdc1 183 if (!empty($usernew->deletepicture)) {
a2ed6e69
SH
184 // The user has chosen to delete the selected users picture.
185 $fs->delete_area_files($context->id, 'user', 'icon'); // Drop all images in area.
4d254790
PS
186 $newpicture = 0;
187
4e782b32
RT
188 } else {
189 // Save newly uploaded file, this will avoid context mismatch for newly created users.
190 file_save_draft_area_files($usernew->imagefile, $context->id, 'user', 'newicon', 0, $filemanageroptions);
191 if (($iconfiles = $fs->get_area_files($context->id, 'user', 'newicon')) && count($iconfiles) == 2) {
a2ed6e69 192 // Get file which was uploaded in draft area.
4e782b32
RT
193 foreach ($iconfiles as $file) {
194 if (!$file->is_directory()) {
195 break;
196 }
197 }
a2ed6e69 198 // Copy file to temporary location and the send it for processing icon.
4e782b32 199 if ($iconfile = $file->copy_content_to_temp()) {
a2ed6e69 200 // There is a new image that has been uploaded.
4e782b32 201 // Process the new image and set the user to make use of it.
a2ed6e69 202 // NOTE: Uploaded images always take over Gravatar.
4e782b32 203 $newpicture = (int)process_new_icon($context, 'user', 'icon', 0, $iconfile);
a2ed6e69 204 // Delete temporary file.
4e782b32
RT
205 @unlink($iconfile);
206 // Remove uploaded file.
207 $fs->delete_area_files($context->id, 'user', 'newicon');
208 } else {
209 // Something went wrong while creating temp file.
210 // Remove uploaded file.
211 $fs->delete_area_files($context->id, 'user', 'newicon');
212 return false;
213 }
214 }
14a6b7e1 215 }
4125bdc1 216
4d254790
PS
217 if ($newpicture != $user->picture) {
218 $DB->set_field('user', 'picture', $newpicture, array('id' => $user->id));
4125bdc1 219 return true;
4d254790
PS
220 } else {
221 return false;
4125bdc1 222 }
14a6b7e1 223}
224
a2ed6e69
SH
225/**
226 * Updates the user email bounce + send counts when the user is edited.
227 *
228 * @param stdClass $user The current user object.
229 * @param stdClass $usernew The updated user object.
230 */
14a6b7e1 231function useredit_update_bounces($user, $usernew) {
232 if (!isset($usernew->email)) {
a2ed6e69 233 // Locked field.
14a6b7e1 234 return;
d8734783 235 }
a9457b54 236 if (!isset($user->email) || $user->email !== $usernew->email) {
a2ed6e69
SH
237 set_bounce_count($usernew, true);
238 set_send_count($usernew, true);
14a6b7e1 239 }
240}
241
a2ed6e69
SH
242/**
243 * Updates the forums a user is tracking when the user is edited.
244 *
245 * @param stdClass $user The original user object.
246 * @param stdClass $usernew The updated user object.
247 */
14a6b7e1 248function useredit_update_trackforums($user, $usernew) {
249 global $CFG;
250 if (!isset($usernew->trackforums)) {
a2ed6e69 251 // Locked field.
14a6b7e1 252 return;
253 }
a9457b54 254 if ((!isset($user->trackforums) || ($usernew->trackforums != $user->trackforums)) and !$usernew->trackforums) {
14a6b7e1 255 require_once($CFG->dirroot.'/mod/forum/lib.php');
256 forum_tp_delete_read_records($usernew->id);
257 }
258}
259
a2ed6e69
SH
260/**
261 * Updates a users interests.
262 *
263 * @param stdClass $user
264 * @param array $interests
265 */
c060fc6a 266function useredit_update_interests($user, $interests) {
c4e868d5
MG
267 core_tag_tag::set_item_tags('core', 'user', $user->id,
268 context_user::instance($user->id), $interests);
1e1c51a3 269}
270
a2ed6e69
SH
271/**
272 * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
273 *
274 * @param moodleform $mform
d6e7a63d
PS
275 * @param array $editoroptions
276 * @param array $filemanageroptions
277 * @param stdClass $user
a2ed6e69 278 */
d6e7a63d 279function useredit_shared_definition(&$mform, $editoroptions, $filemanageroptions, $user) {
d6ace123 280 global $CFG, $USER, $DB;
281
d6e7a63d
PS
282 if ($user->id > 0) {
283 useredit_load_preferences($user, false);
284 }
14a6b7e1 285
286 $strrequired = get_string('required');
e9c27d1e 287 $stringman = get_string_manager();
d8734783 288
1cc3a9ae
AG
289 // Add the necessary names.
290 foreach (useredit_get_required_name_fields() as $fullname) {
a327f25e 291 $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"');
e9c27d1e
DM
292 if ($stringman->string_exists('missing'.$fullname, 'core')) {
293 $strmissingfield = get_string('missing'.$fullname, 'core');
294 } else {
295 $strmissingfield = $strrequired;
296 }
297 $mform->addRule($fullname, $strmissingfield, 'required', null, 'client');
a327f25e
AG
298 $mform->setType($fullname, PARAM_NOTAGS);
299 }
d8734783 300
1cc3a9ae
AG
301 $enabledusernamefields = useredit_get_enabled_name_fields();
302 // Add the enabled additional name fields.
303 foreach ($enabledusernamefields as $addname) {
a327f25e
AG
304 $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"');
305 $mform->setType($addname, PARAM_NOTAGS);
306 }
d8734783 307
a2ed6e69 308 // Do not show email field if change confirmation is pending.
d6e7a63d 309 if ($user->id > 0 and !empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
c6a074f8 310 $notice = get_string('emailchangepending', 'auth', $user);
d6ace123 311 $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
c6a074f8 312 . get_string('emailchangecancel', 'auth') . '</a>';
d6ace123 313 $mform->addElement('static', 'emailpending', get_string('email'), $notice);
314 } else {
315 $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
316 $mform->addRule('email', $strrequired, 'required', null, 'client');
947ab40b 317 $mform->setType('email', PARAM_RAW_TRIMMED);
d6ace123 318 }
d8734783 319
479fa47d
DW
320 $choices = array();
321 $choices['0'] = get_string('emaildisplayno');
322 $choices['1'] = get_string('emaildisplayyes');
323 $choices['2'] = get_string('emaildisplaycourse');
324 $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
ac9768fc 325 $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
479fa47d 326
c5c0d2ff 327 $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
071e68f9 328 $mform->setType('city', PARAM_TEXT);
fa7f750c
PS
329 if (!empty($CFG->defaultcity)) {
330 $mform->setDefault('city', $CFG->defaultcity);
331 }
d8734783 332
0aa759b0 333 $choices = get_string_manager()->get_list_of_countries();
a2ed6e69 334 $choices = array('' => get_string('selectacountry') . '...') + $choices;
d8734783 335 $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
d8734783 336 if (!empty($CFG->country)) {
ac9768fc 337 $mform->setDefault('country', core_user::get_property_default('country'));
d8734783 338 }
339
d6e7a63d
PS
340 if (isset($CFG->forcetimezone) and $CFG->forcetimezone != 99) {
341 $choices = core_date::get_list_of_timezones($CFG->forcetimezone);
d8734783 342 $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
d6e7a63d 343 $mform->addElement('hidden', 'timezone');
ac9768fc 344 $mform->setType('timezone', core_user::get_property_type('timezone'));
d8734783 345 } else {
d6e7a63d 346 $choices = core_date::get_list_of_timezones($user->timezone, true);
d8734783 347 $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
d8734783 348 }
349
2f00e1b2 350 // Multi-Calendar Support - see MDL-18375.
df5d27d8
MN
351 $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
352 // We do not want to show this option unless there is more than one calendar type to display.
353 if (count($calendartypes) > 1) {
354 $mform->addElement('select', 'calendartype', get_string('preferredcalendar', 'calendar'), $calendartypes);
8bf0f207 355 $mform->setDefault('calendartype', $CFG->calendartype);
df5d27d8 356 }
6dd59aab 357
d8734783 358 if (!empty($CFG->allowuserthemes)) {
ad6226fb 359 $choices = array();
d8734783 360 $choices[''] = get_string('default');
36798745 361 $themes = get_list_of_themes();
a2ed6e69 362 foreach ($themes as $key => $theme) {
36798745 363 if (empty($theme->hidefromselector)) {
d609d962 364 $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
36798745
SH
365 }
366 }
c3ed4a5a 367 $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
d8734783 368 }
ad6226fb 369
8bdc9cac
SH
370 $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
371 $mform->setType('description_editor', PARAM_CLEANHTML);
27d1a27c 372 $mform->addHelpButton('description_editor', 'userdescription');
ad6226fb 373
689096bc 374 if (empty($USER->newadminuser)) {
757e89d2 375 $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
80ef91ef 376 $mform->setExpanded('moodle_picture', true);
ad6226fb 377
4125bdc1 378 if (!empty($CFG->enablegravatar)) {
ed9e0cb6 379 $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
4125bdc1
SH
380 }
381
d8734783 382 $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
ad6226fb 383
d8734783 384 $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
edfd6a5e 385 $mform->setDefault('deletepicture', 0);
ad6226fb 386
4e782b32 387 $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
27d1a27c 388 $mform->addHelpButton('imagefile', 'newpicture');
ad6226fb 389
d8734783 390 $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
071e68f9 391 $mform->setType('imagealt', PARAM_TEXT);
ad6226fb 392
d8734783 393 }
ad6226fb 394
1cc3a9ae
AG
395 // Display user name fields that are not currenlty enabled here if there are any.
396 $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
b63f542d 397 if (count($disabledusernamefields) > 0) {
a327f25e 398 $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
1cc3a9ae
AG
399 foreach ($disabledusernamefields as $allname) {
400 $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
401 $mform->setType($allname, PARAM_NOTAGS);
a327f25e 402 }
a327f25e
AG
403 }
404
c4e868d5 405 if (core_tag_tag::is_enabled('core', 'user') and empty($USER->newadminuser)) {
1e1c51a3 406 $mform->addElement('header', 'moodle_interests', get_string('interests'));
c4e868d5 407 $mform->addElement('tags', 'interests', get_string('interestslist'),
4be9c7ad 408 array('itemtype' => 'user', 'component' => 'core'));
27d1a27c 409 $mform->addHelpButton('interests', 'interestslist');
1e1c51a3 410 }
d6ace123 411
a2ed6e69 412 // Moodle optional fields.
c3ed4a5a 413 $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
ad6226fb 414
d8734783 415 $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
ac9768fc 416 $mform->setType('url', core_user::get_property_type('url'));
ad6226fb 417
d8734783 418 $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
ac9768fc 419 $mform->setType('icq', core_user::get_property_type('icq'));
ad6226fb 420
d8734783 421 $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
ac9768fc 422 $mform->setType('skype', core_user::get_property_type('skype'));
ad6226fb 423
d8734783 424 $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
ac9768fc 425 $mform->setType('aim', core_user::get_property_type('aim'));
ad6226fb 426
d8734783 427 $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
ac9768fc 428 $mform->setType('yahoo', core_user::get_property_type('yahoo'));
ad6226fb 429
d8734783 430 $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
ac9768fc 431 $mform->setType('msn', core_user::get_property_type('msn'));
ad6226fb 432
8b9cfac4 433 $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
ac9768fc 434 $mform->setType('idnumber', core_user::get_property_type('idnumber'));
ad6226fb 435
a8fd33b0 436 $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
ac9768fc 437 $mform->setType('institution', core_user::get_property_type('institution'));
ad6226fb 438
a8fd33b0 439 $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
ac9768fc 440 $mform->setType('department', core_user::get_property_type('department'));
ad6226fb 441
70fb46c8 442 $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
ac9768fc 443 $mform->setType('phone1', core_user::get_property_type('phone1'));
ad6226fb 444
55ac3d6f 445 $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
ac9768fc 446 $mform->setType('phone2', core_user::get_property_type('phone2'));
ad6226fb 447
a8fd33b0 448 $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
ac9768fc 449 $mform->setType('address', core_user::get_property_type('address'));
14a6b7e1 450}
ad6226fb 451
1cc3a9ae
AG
452/**
453 * Return required user name fields for forms.
454 *
455 * @return array required user name fields in order according to settings.
456 */
457function useredit_get_required_name_fields() {
458 global $CFG;
459
460 // Get the name display format.
461 $nameformat = $CFG->fullnamedisplay;
462
463 // Names that are required fields on user forms.
464 $necessarynames = array('firstname', 'lastname');
465 $languageformat = get_string('fullnamedisplay');
466
467 // Check that the language string and the $nameformat contain the necessary names.
468 foreach ($necessarynames as $necessaryname) {
469 $pattern = "/$necessaryname\b/";
470 if (!preg_match($pattern, $languageformat)) {
471 // If the language string has been altered then fall back on the below order.
472 $languageformat = 'firstname lastname';
473 }
474 if (!preg_match($pattern, $nameformat)) {
475 // If the nameformat doesn't contain the necessary name fields then use the languageformat.
476 $nameformat = $languageformat;
477 }
478 }
479
480 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
481 $necessarynames = order_in_string($necessarynames, $nameformat);
482 return $necessarynames;
483}
484
485/**
486 * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
487 *
488 * @return array Enabled user name fields.
489 */
490function useredit_get_enabled_name_fields() {
491 global $CFG;
492
493 // Get all of the other name fields which are not ranked as necessary.
494 $additionalusernamefields = array_diff(get_all_user_name_fields(), array('firstname', 'lastname'));
495 // Find out which additional name fields are actually being used from the fullnamedisplay setting.
496 $enabledadditionalusernames = array();
497 foreach ($additionalusernamefields as $enabledname) {
498 if (strpos($CFG->fullnamedisplay, $enabledname) !== false) {
499 $enabledadditionalusernames[] = $enabledname;
500 }
501 }
502
503 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
504 $enabledadditionalusernames = order_in_string($enabledadditionalusernames, $CFG->fullnamedisplay);
505 return $enabledadditionalusernames;
506}
507
508/**
509 * Gets user name fields not enabled from the setting fullnamedisplay.
510 *
511 * @param array $enabledadditionalusernames Current enabled additional user name fields.
512 * @return array Disabled user name fields.
513 */
514function useredit_get_disabled_name_fields($enabledadditionalusernames = null) {
515 // If we don't have enabled additional user name information then go and fetch it (try to avoid).
516 if (!isset($enabledadditionalusernames)) {
517 $enabledadditionalusernames = useredit_get_enabled_name_fields();
518 }
519
520 // These are the additional fields that are not currently enabled.
521 $nonusednamefields = array_diff(get_all_user_name_fields(),
522 array_merge(array('firstname', 'lastname'), $enabledadditionalusernames));
523 return $nonusednamefields;
524}