Merge branch 'MDL-47990_27' of git://github.com/timhunt/moodle into MOODLE_27_STABLE
[moodle.git] / user / editlib.php
blob55c8de2ae9a7ef99745de2204af13b856dbc4a7b
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 $choices = array();
222 $choices['0'] = get_string('emaildisplayno');
223 $choices['1'] = get_string('emaildisplayyes');
224 $choices['2'] = get_string('emaildisplaycourse');
225 $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
226 $mform->setDefault('maildisplay', 2);
228 $choices = array();
229 $choices['0'] = get_string('textformat');
230 $choices['1'] = get_string('htmlformat');
231 $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
232 $mform->setDefault('mailformat', 1);
234 if (!empty($CFG->allowusermailcharset)) {
235 $choices = array();
236 $charsets = get_list_of_charsets();
237 if (!empty($CFG->sitemailcharset)) {
238 $choices['0'] = get_string('site').' ('.$CFG->sitemailcharset.')';
239 } else {
240 $choices['0'] = get_string('site').' (UTF-8)';
242 $choices = array_merge($choices, $charsets);
243 $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
246 $choices = array();
247 $choices['0'] = get_string('emaildigestoff');
248 $choices['1'] = get_string('emaildigestcomplete');
249 $choices['2'] = get_string('emaildigestsubjects');
250 $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
251 $mform->setDefault('maildigest', 0);
252 $mform->addHelpButton('maildigest', 'emaildigest');
254 $choices = array();
255 $choices['1'] = get_string('autosubscribeyes');
256 $choices['0'] = get_string('autosubscribeno');
257 $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
258 $mform->setDefault('autosubscribe', 1);
260 if (!empty($CFG->forum_trackreadposts)) {
261 $choices = array();
262 $choices['0'] = get_string('trackforumsno');
263 $choices['1'] = get_string('trackforumsyes');
264 $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
265 $mform->setDefault('trackforums', 0);
268 $editors = editors_get_enabled();
269 if (count($editors) > 1) {
270 $choices = array('' => get_string('defaulteditor'));
271 $firsteditor = '';
272 foreach (array_keys($editors) as $editor) {
273 if (!$firsteditor) {
274 $firsteditor = $editor;
276 $choices[$editor] = get_string('pluginname', 'editor_' . $editor);
278 $mform->addElement('select', 'preference_htmleditor', get_string('textediting'), $choices);
279 $mform->setDefault('preference_htmleditor', '');
280 } else {
281 // Empty string means use the first chosen text editor.
282 $mform->addElement('hidden', 'preference_htmleditor');
283 $mform->setDefault('preference_htmleditor', '');
284 $mform->setType('preference_htmleditor', PARAM_PLUGIN);
287 $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
288 $mform->setType('city', PARAM_TEXT);
289 if (!empty($CFG->defaultcity)) {
290 $mform->setDefault('city', $CFG->defaultcity);
293 $choices = get_string_manager()->get_list_of_countries();
294 $choices = array('' => get_string('selectacountry') . '...') + $choices;
295 $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
296 if (!empty($CFG->country)) {
297 $mform->setDefault('country', $CFG->country);
300 $choices = get_list_of_timezones();
301 $choices['99'] = get_string('serverlocaltime');
302 if ($CFG->forcetimezone != 99) {
303 $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
304 } else {
305 $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
306 $mform->setDefault('timezone', '99');
309 $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
310 $mform->setDefault('lang', $CFG->lang);
312 // Multi-Calendar Support - see MDL-18375.
313 $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
314 // We do not want to show this option unless there is more than one calendar type to display.
315 if (count($calendartypes) > 1) {
316 $mform->addElement('select', 'calendartype', get_string('preferredcalendar', 'calendar'), $calendartypes);
317 $mform->setDefault('calendartype', $CFG->calendartype);
320 if (!empty($CFG->allowuserthemes)) {
321 $choices = array();
322 $choices[''] = get_string('default');
323 $themes = get_list_of_themes();
324 foreach ($themes as $key => $theme) {
325 if (empty($theme->hidefromselector)) {
326 $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
329 $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
332 $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
333 $mform->setType('description_editor', PARAM_CLEANHTML);
334 $mform->addHelpButton('description_editor', 'userdescription');
336 if (empty($USER->newadminuser)) {
337 $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
339 if (!empty($CFG->enablegravatar)) {
340 $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
343 $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
345 $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
346 $mform->setDefault('deletepicture', 0);
348 $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
349 $mform->addHelpButton('imagefile', 'newpicture');
351 $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
352 $mform->setType('imagealt', PARAM_TEXT);
356 // Display user name fields that are not currenlty enabled here if there are any.
357 $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
358 if (count($disabledusernamefields) > 0) {
359 $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
360 foreach ($disabledusernamefields as $allname) {
361 $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
362 $mform->setType($allname, PARAM_NOTAGS);
366 if (!empty($CFG->usetags) and empty($USER->newadminuser)) {
367 $mform->addElement('header', 'moodle_interests', get_string('interests'));
368 $mform->addElement('tags', 'interests', get_string('interestslist'), array('display' => 'noofficial'));
369 $mform->addHelpButton('interests', 'interestslist');
372 // Moodle optional fields.
373 $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
375 $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
376 $mform->setType('url', PARAM_URL);
378 $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
379 $mform->setType('icq', PARAM_NOTAGS);
381 $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
382 $mform->setType('skype', PARAM_NOTAGS);
384 $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
385 $mform->setType('aim', PARAM_NOTAGS);
387 $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
388 $mform->setType('yahoo', PARAM_NOTAGS);
390 $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
391 $mform->setType('msn', PARAM_NOTAGS);
393 $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
394 $mform->setType('idnumber', PARAM_NOTAGS);
396 $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
397 $mform->setType('institution', PARAM_TEXT);
399 $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
400 $mform->setType('department', PARAM_TEXT);
402 $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
403 $mform->setType('phone1', PARAM_NOTAGS);
405 $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
406 $mform->setType('phone2', PARAM_NOTAGS);
408 $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
409 $mform->setType('address', PARAM_TEXT);
413 * Return required user name fields for forms.
415 * @return array required user name fields in order according to settings.
417 function useredit_get_required_name_fields() {
418 global $CFG;
420 // Get the name display format.
421 $nameformat = $CFG->fullnamedisplay;
423 // Names that are required fields on user forms.
424 $necessarynames = array('firstname', 'lastname');
425 $languageformat = get_string('fullnamedisplay');
427 // Check that the language string and the $nameformat contain the necessary names.
428 foreach ($necessarynames as $necessaryname) {
429 $pattern = "/$necessaryname\b/";
430 if (!preg_match($pattern, $languageformat)) {
431 // If the language string has been altered then fall back on the below order.
432 $languageformat = 'firstname lastname';
434 if (!preg_match($pattern, $nameformat)) {
435 // If the nameformat doesn't contain the necessary name fields then use the languageformat.
436 $nameformat = $languageformat;
440 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
441 $necessarynames = order_in_string($necessarynames, $nameformat);
442 return $necessarynames;
446 * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
448 * @return array Enabled user name fields.
450 function useredit_get_enabled_name_fields() {
451 global $CFG;
453 // Get all of the other name fields which are not ranked as necessary.
454 $additionalusernamefields = array_diff(get_all_user_name_fields(), array('firstname', 'lastname'));
455 // Find out which additional name fields are actually being used from the fullnamedisplay setting.
456 $enabledadditionalusernames = array();
457 foreach ($additionalusernamefields as $enabledname) {
458 if (strpos($CFG->fullnamedisplay, $enabledname) !== false) {
459 $enabledadditionalusernames[] = $enabledname;
463 // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
464 $enabledadditionalusernames = order_in_string($enabledadditionalusernames, $CFG->fullnamedisplay);
465 return $enabledadditionalusernames;
469 * Gets user name fields not enabled from the setting fullnamedisplay.
471 * @param array $enabledadditionalusernames Current enabled additional user name fields.
472 * @return array Disabled user name fields.
474 function useredit_get_disabled_name_fields($enabledadditionalusernames = null) {
475 // If we don't have enabled additional user name information then go and fetch it (try to avoid).
476 if (!isset($enabledadditionalusernames)) {
477 $enabledadditionalusernames = useredit_get_enabled_name_fields();
480 // These are the additional fields that are not currently enabled.
481 $nonusednamefields = array_diff(get_all_user_name_fields(),
482 array_merge(array('firstname', 'lastname'), $enabledadditionalusernames));
483 return $nonusednamefields;