Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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.
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/>.
16
 
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
require_once($CFG->dirroot . '/user/lib.php');
26
 
27
/**
28
 * Cancels the requirement for a user to update their email address.
29
 *
30
 * @param int $userid
31
 */
32
function cancel_email_update($userid) {
33
    unset_user_preference('newemail', $userid);
34
    unset_user_preference('newemailattemptsleft', $userid);
1441 ariadna 35
    delete_user_key('core_user/email_change', $userid);
1 efrain 36
}
37
 
38
/**
39
 * Performs the common access checks and page setup for all
40
 * user preference pages.
41
 *
42
 * @param int $userid The user id to edit taken from the page params.
43
 * @param int $courseid The optional course id if we came from a course context.
44
 * @return array containing the user and course records.
45
 */
46
function useredit_setup_preference_page($userid, $courseid) {
47
    global $PAGE, $SESSION, $DB, $CFG, $OUTPUT, $USER;
48
 
49
    // Guest can not edit.
50
    if (isguestuser()) {
51
        throw new \moodle_exception('guestnoeditprofile');
52
    }
53
 
54
    if (!$course = $DB->get_record('course', array('id' => $courseid))) {
55
        throw new \moodle_exception('invalidcourseid');
56
    }
57
 
58
    if ($course->id != SITEID) {
59
        require_login($course);
60
    } else if (!isloggedin()) {
61
        if (empty($SESSION->wantsurl)) {
62
            $SESSION->wantsurl = $CFG->wwwroot.'/user/preferences.php';
63
        }
64
        redirect(get_login_url());
65
    } else {
66
        $PAGE->set_context(context_system::instance());
67
    }
68
 
69
    // The user profile we are editing.
70
    if (!$user = $DB->get_record('user', array('id' => $userid))) {
71
        throw new \moodle_exception('invaliduserid');
72
    }
73
 
74
    // Guest can not be edited.
75
    if (isguestuser($user)) {
76
        throw new \moodle_exception('guestnoeditprofile');
77
    }
78
 
79
    // Remote users cannot be edited.
80
    if (is_mnet_remote_user($user)) {
81
        if (user_not_fully_set_up($user, false)) {
82
            $hostwwwroot = $DB->get_field('mnet_host', 'wwwroot', array('id' => $user->mnethostid));
83
            throw new \moodle_exception('usernotfullysetup', 'mnet', '', $hostwwwroot);
84
        }
85
        redirect($CFG->wwwroot . "/user/view.php?course={$course->id}");
86
    }
87
 
88
    $systemcontext   = context_system::instance();
89
    $personalcontext = context_user::instance($user->id);
90
 
91
    // Check access control.
92
    if ($user->id == $USER->id) {
93
        // Editing own profile - require_login() MUST NOT be used here, it would result in infinite loop!
94
        if (!has_capability('moodle/user:editownprofile', $systemcontext)) {
95
            throw new \moodle_exception('cannotedityourprofile');
96
        }
97
 
98
    } else {
99
        // Teachers, parents, etc.
100
        require_capability('moodle/user:editprofile', $personalcontext);
101
 
102
        // No editing of primary admin!
103
        if (is_siteadmin($user) and !is_siteadmin($USER)) {  // Only admins may edit other admins.
104
            throw new \moodle_exception('useradmineditadmin');
105
        }
106
    }
107
 
108
    if ($user->deleted) {
109
        echo $OUTPUT->header();
110
        echo $OUTPUT->heading(get_string('userdeleted'));
111
        echo $OUTPUT->footer();
112
        die;
113
    }
114
 
115
    $PAGE->set_pagelayout('admin');
116
    $PAGE->add_body_class('limitedwidth');
117
    $PAGE->set_context($personalcontext);
118
    if ($USER->id != $user->id) {
119
        $PAGE->navigation->extend_for_user($user);
120
    } else {
121
        if ($node = $PAGE->navigation->find('myprofile', navigation_node::TYPE_ROOTNODE)) {
122
            $node->force_open();
123
        }
124
    }
125
 
126
    return array($user, $course);
127
}
128
 
129
/**
130
 * Loads the given users preferences into the given user object.
131
 *
132
 * @param stdClass $user The user object, modified by reference.
133
 * @param bool $reload
134
 */
135
function useredit_load_preferences(&$user, $reload=true) {
136
    global $USER;
137
 
138
    if (!empty($user->id)) {
139
        if ($reload and $USER->id == $user->id) {
140
            // Reload preferences in case it was changed in other session.
141
            unset($USER->preference);
142
        }
143
 
144
        if ($preferences = get_user_preferences(null, null, $user->id)) {
145
            foreach ($preferences as $name => $value) {
146
                $user->{'preference_'.$name} = $value;
147
            }
148
        }
149
    }
150
}
151
 
152
/**
153
 * Updates the user preferences for the given user
154
 *
155
 * Only preference that can be updated directly will be updated here. This method is called from various WS
156
 * updating users and should be used when updating user details. Plugins may list preferences that can
157
 * be updated by defining 'user_preferences' callback, {@see core_user::fill_preferences_cache()}
158
 *
159
 * Some parts of code may use user preference table to store internal data, in these cases it is acceptable
160
 * to call set_user_preference()
161
 *
162
 * @param stdClass|array $usernew object or array that has user preferences as attributes with keys starting with preference_
163
 */
164
function useredit_update_user_preference($usernew) {
165
    global $USER;
166
    $ua = (array)$usernew;
167
    if (is_object($usernew) && isset($usernew->id) && isset($usernew->deleted) && isset($usernew->confirmed)) {
168
        // This is already a full user object, maybe not completely full but these fields are enough.
169
        $user = $usernew;
170
    } else if (empty($ua['id']) || $ua['id'] == $USER->id) {
171
        // We are updating current user.
172
        $user = $USER;
173
    } else {
174
        // Retrieve user object.
175
        $user = core_user::get_user($ua['id'], '*', MUST_EXIST);
176
    }
177
 
178
    foreach ($ua as $key => $value) {
179
        if (strpos($key, 'preference_') === 0) {
180
            $name = substr($key, strlen('preference_'));
181
            if (core_user::can_edit_preference($name, $user)) {
182
                $value = core_user::clean_preference($value, $name);
183
                set_user_preference($name, $value, $user->id);
184
            }
185
        }
186
    }
187
}
188
 
189
/**
190
 * Updates the user email bounce + send counts when the user is edited.
191
 *
192
 * @param stdClass $user The current user object.
193
 * @param stdClass $usernew The updated user object.
194
 */
195
function useredit_update_bounces($user, $usernew) {
196
    if (!isset($usernew->email)) {
197
        // Locked field.
198
        return;
199
    }
200
    if (!isset($user->email) || $user->email !== $usernew->email) {
201
        set_bounce_count($usernew, true);
202
        set_send_count($usernew, true);
203
    }
204
}
205
 
206
/**
207
 * Updates the forums a user is tracking when the user is edited.
208
 *
209
 * @param stdClass $user The original user object.
210
 * @param stdClass $usernew The updated user object.
211
 */
212
function useredit_update_trackforums($user, $usernew) {
213
    global $CFG;
214
    if (!isset($usernew->trackforums)) {
215
        // Locked field.
216
        return;
217
    }
218
    if ((!isset($user->trackforums) || ($usernew->trackforums != $user->trackforums)) and !$usernew->trackforums) {
219
        require_once($CFG->dirroot.'/mod/forum/lib.php');
220
        forum_tp_delete_read_records($usernew->id);
221
    }
222
}
223
 
224
/**
225
 * Updates a users interests.
226
 *
227
 * @param stdClass $user
228
 * @param array $interests
229
 */
230
function useredit_update_interests($user, $interests) {
231
    core_tag_tag::set_item_tags('core', 'user', $user->id,
232
            context_user::instance($user->id), $interests);
233
}
234
 
235
/**
236
 * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
237
 *
238
 * @param MoodleQuickForm $mform
239
 * @param array $editoroptions
240
 * @param array $filemanageroptions
241
 * @param stdClass $user
242
 */
243
function useredit_shared_definition(&$mform, $editoroptions, $filemanageroptions, $user) {
244
    global $CFG, $USER, $DB;
245
 
246
    if ($user->id > 0) {
247
        useredit_load_preferences($user, false);
248
    }
249
 
250
    $strrequired = get_string('required');
251
    $stringman = get_string_manager();
252
 
253
    // Add the necessary names.
254
    foreach (useredit_get_required_name_fields() as $fullname) {
255
        $purpose = user_edit_map_field_purpose($user->id, $fullname);
256
        $mform->addElement('text', $fullname,  get_string($fullname),  'maxlength="100" size="30"' . $purpose);
257
        if ($stringman->string_exists('missing'.$fullname, 'core')) {
258
            $strmissingfield = get_string('missing'.$fullname, 'core');
259
        } else {
260
            $strmissingfield = $strrequired;
261
        }
262
        $mform->addRule($fullname, $strmissingfield, 'required', null, 'client');
263
        $mform->setType($fullname, PARAM_NOTAGS);
264
    }
265
 
266
    $enabledusernamefields = useredit_get_enabled_name_fields();
267
    // Add the enabled additional name fields.
268
    foreach ($enabledusernamefields as $addname) {
269
        $purpose = user_edit_map_field_purpose($user->id, $addname);
270
        $mform->addElement('text', $addname,  get_string($addname), 'maxlength="100" size="30"' . $purpose);
271
        $mform->setType($addname, PARAM_NOTAGS);
272
    }
273
 
274
    // Do not show email field if change confirmation is pending.
275
    if ($user->id > 0 and !empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
276
        $notice = get_string('emailchangepending', 'auth', $user);
277
        $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
278
                . get_string('emailchangecancel', 'auth') . '</a>';
279
        $mform->addElement('static', 'emailpending', get_string('email'), $notice);
280
    } else {
281
        $purpose = user_edit_map_field_purpose($user->id, 'email');
282
        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"' . $purpose);
283
        $mform->addRule('email', $strrequired, 'required', null, 'client');
284
        $mform->setType('email', PARAM_RAW_TRIMMED);
285
    }
286
 
287
    $choices = array();
288
    $choices['0'] = get_string('emaildisplayno');
289
    $choices['1'] = get_string('emaildisplayyes');
290
    $choices['2'] = get_string('emaildisplaycourse');
291
    $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
292
    $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
293
    $mform->addHelpButton('maildisplay', 'emaildisplay');
294
 
295
    if (get_config('tool_moodlenet', 'enablemoodlenet')) {
296
        $mform->addElement('text', 'moodlenetprofile', get_string('moodlenetprofile', 'user'), 'maxlength="255" size="30"');
297
        $mform->setType('moodlenetprofile', PARAM_NOTAGS);
298
        $mform->addHelpButton('moodlenetprofile', 'moodlenetprofile', 'user');
299
    }
300
 
301
    $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
302
    $mform->setType('city', PARAM_TEXT);
303
    if (!empty($CFG->defaultcity)) {
304
        $mform->setDefault('city', $CFG->defaultcity);
305
    }
306
 
307
    $purpose = user_edit_map_field_purpose($user->id, 'country');
308
    $choices = get_string_manager()->get_list_of_countries();
309
    $choices = array('' => get_string('selectacountry') . '...') + $choices;
310
    $mform->addElement('select', 'country', get_string('selectacountry'), $choices, $purpose);
311
    if (!empty($CFG->country)) {
312
        $mform->setDefault('country', core_user::get_property_default('country'));
313
    }
314
 
315
    if (isset($CFG->forcetimezone) and $CFG->forcetimezone != 99) {
316
        $choices = core_date::get_list_of_timezones($CFG->forcetimezone);
317
        $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
318
        $mform->addElement('hidden', 'timezone');
319
        $mform->setType('timezone', core_user::get_property_type('timezone'));
320
    } else {
321
        $choices = core_date::get_list_of_timezones($user->timezone, true);
322
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
323
    }
324
 
325
    if ($user->id < 0) {
326
        $purpose = user_edit_map_field_purpose($user->id, 'lang');
327
        $translations = get_string_manager()->get_list_of_translations();
328
        $mform->addElement('select', 'lang', get_string('preferredlanguage'), $translations, $purpose);
329
        $lang = empty($user->lang) ? $CFG->lang : $user->lang;
330
        $mform->setDefault('lang', $lang);
331
    }
332
 
333
    if (!empty($CFG->allowuserthemes)) {
334
        $choices = array();
335
        $choices[''] = get_string('default');
336
        $themes = get_list_of_themes();
337
        foreach ($themes as $key => $theme) {
338
            if (empty($theme->hidefromselector)) {
339
                $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
340
            }
341
        }
342
        $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
343
    }
344
 
345
    $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
346
    $mform->setType('description_editor', PARAM_RAW);
347
    $mform->addHelpButton('description_editor', 'userdescription');
348
 
349
    if (empty($USER->newadminuser)) {
350
        $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
351
        $mform->setExpanded('moodle_picture', true);
352
 
353
        if (!empty($CFG->enablegravatar)) {
354
            $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
355
        }
356
 
357
        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
358
 
359
        $mform->addElement('checkbox', 'deletepicture', get_string('deletepicture'));
360
        $mform->setDefault('deletepicture', 0);
361
 
362
        $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
363
        $mform->addHelpButton('imagefile', 'newpicture');
364
 
365
        $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
366
        $mform->setType('imagealt', PARAM_TEXT);
367
 
368
    }
369
 
370
    // Display user name fields that are not currenlty enabled here if there are any.
371
    $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
372
    if (count($disabledusernamefields) > 0) {
373
        $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
374
        foreach ($disabledusernamefields as $allname) {
375
            $purpose = user_edit_map_field_purpose($user->id, $allname);
376
            $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"' . $purpose);
377
            $mform->setType($allname, PARAM_NOTAGS);
378
        }
379
    }
380
 
381
    if (core_tag_tag::is_enabled('core', 'user') and empty($USER->newadminuser)) {
382
        $mform->addElement('header', 'moodle_interests', get_string('interests'));
383
        $mform->addElement('tags', 'interests', get_string('interestslist'),
384
            array('itemtype' => 'user', 'component' => 'core'));
385
        $mform->addHelpButton('interests', 'interestslist');
386
    }
387
 
388
    // Moodle optional fields.
389
    $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
390
 
391
    $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
392
    $mform->setType('idnumber', core_user::get_property_type('idnumber'));
393
 
394
    $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
395
    $mform->setType('institution', core_user::get_property_type('institution'));
396
 
397
    $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
398
    $mform->setType('department', core_user::get_property_type('department'));
399
 
400
    $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
401
    $mform->setType('phone1', core_user::get_property_type('phone1'));
402
    $mform->setForceLtr('phone1');
403
 
404
    $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
405
    $mform->setType('phone2', core_user::get_property_type('phone2'));
406
    $mform->setForceLtr('phone2');
407
 
408
    $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
409
    $mform->setType('address', core_user::get_property_type('address'));
410
}
411
 
412
/**
413
 * Return required user name fields for forms.
414
 *
415
 * @return array required user name fields in order according to settings.
416
 */
417
function useredit_get_required_name_fields() {
418
    global $CFG;
419
 
420
    // Get the name display format.
421
    $nameformat = $CFG->fullnamedisplay;
422
 
423
    // Names that are required fields on user forms.
424
    $necessarynames = array('firstname', 'lastname');
425
    $languageformat = get_string('fullnamedisplay');
426
 
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';
433
        }
434
        if (!preg_match($pattern, $nameformat)) {
435
            // If the nameformat doesn't contain the necessary name fields then use the languageformat.
436
            $nameformat = $languageformat;
437
        }
438
    }
439
 
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;
443
}
444
 
445
/**
446
 * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
447
 *
448
 * @return array Enabled user name fields.
449
 */
450
function useredit_get_enabled_name_fields() {
451
    global $CFG;
452
 
453
    // Get all of the other name fields which are not ranked as necessary.
454
    $additionalusernamefields = array_diff(\core_user\fields::get_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;
460
        }
461
    }
462
 
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;
466
}
467
 
468
/**
469
 * Gets user name fields not enabled from the setting fullnamedisplay.
470
 *
471
 * @param array $enabledadditionalusernames Current enabled additional user name fields.
472
 * @return array Disabled user name fields.
473
 */
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();
478
    }
479
 
480
    // These are the additional fields that are not currently enabled.
481
    $nonusednamefields = array_diff(\core_user\fields::get_name_fields(),
482
            array_merge(array('firstname', 'lastname'), $enabledadditionalusernames));
483
 
484
    // It may not be significant anywhere, but for compatibility, this used to return an array
485
    // with keys and values the same.
486
    $result = [];
487
    foreach ($nonusednamefields as $field) {
488
        $result[$field] = $field;
489
    }
490
    return $result;
491
}