Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

main/auth/profile.php (1 issue)

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\UserBundle\Entity\User;
6
use ChamiloSession as Session;
7
8
/**
9
 * This file displays the user's profile,
10
 * optionally it allows users to modify their profile as well.
11
 *
12
 * See inc/conf/profile.conf.php to modify settings
13
 */
14
$cidReset = true;
15
require_once __DIR__.'/../inc/global.inc.php';
16
api_block_inactive_user();
17
18
$this_section = SECTION_MYPROFILE;
19
$allowSocialTool = api_get_setting('allow_social_tool') === 'true';
20
if ($allowSocialTool) {
21
    $this_section = SECTION_SOCIAL;
22
}
23
24
$logInfo = [
25
    'tool' => 'profile',
26
    'action' => $this_section,
27
];
28
Event::registerLog($logInfo);
29
30
$_SESSION['this_section'] = $this_section;
31
32
if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) {
33
    api_not_allowed(true);
34
}
35
36
$htmlHeadXtra[] = api_get_password_checker_js('#username', '#password1');
37
$htmlHeadXtra[] = api_get_css_asset('cropper/dist/cropper.min.css');
38
$htmlHeadXtra[] = api_get_asset('cropper/dist/cropper.min.js');
39
$htmlHeadXtra[] = '<script>
40
$(function() {
41
    $("#id_generate_api_key").on("click", function (e) {
42
        e.preventDefault();
43
44
        $.ajax({
45
            contentType: "application/x-www-form-urlencoded",
46
            type: "POST",
47
            url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=generate_api_key",
48
            data: "num_key_id="+"",
49
            success: function(datos) {
50
                $("#div_api_key").html(datos);
51
            }
52
        });
53
    });
54
55
});
56
57
function confirmation(name) {
58
    if (confirm("'.get_lang('AreYouSureToDeleteJS', '').' " + name + " ?")) {
59
            document.forms["profile"].submit();
60
    } else {
61
        return false;
62
    }
63
}
64
function show_image(image,width,height) {
65
    width = parseInt(width) + 20;
66
    height = parseInt(height) + 20;
67
    window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
68
}
69
</script>';
70
71
$jquery_ready_content = '';
72
if (api_get_setting('allow_message_tool') === 'true') {
73
    $jquery_ready_content = <<<EOF
74
    $(".message-content .message-delete").click(function(){
75
        $(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
76
        $(".message-view").animate({ opacity: "show" }, "slow");
77
    });
78
EOF;
79
}
80
81
$tool_name = is_profile_editable() ? get_lang('ModifProfile') : get_lang('ViewProfile');
82
$table_user = Database::get_main_table(TABLE_MAIN_USER);
83
84
/*
85
 * Get initial values for all fields.
86
 */
87
$user_data = $originalUserInfo = api_get_user_info(
88
    api_get_user_id(),
89
    false,
90
    false,
91
    false,
92
    false,
93
    true,
94
    true
95
);
96
$array_list_key = UserManager::get_api_keys(api_get_user_id());
97
$id_temp_key = UserManager::get_api_key_id(api_get_user_id(), 'dokeos');
98
$value_array = [];
99
if (isset($array_list_key[$id_temp_key])) {
100
    $value_array = $array_list_key[$id_temp_key];
101
}
102
$user_data['api_key_generate'] = $value_array;
103
104
if ($user_data !== false) {
105
    if (api_get_setting('login_is_email') === 'true') {
106
        $user_data['username'] = $user_data['email'];
107
    }
108
    if (is_null($user_data['language'])) {
109
        $user_data['language'] = api_get_setting('platformLanguage');
110
    }
111
}
112
113
$form = new FormValidator('profile');
114
115
if (api_is_western_name_order()) {
116
    // FIRST NAME and LAST NAME
117
    $form->addElement('text', 'firstname', get_lang('FirstName'), ['size' => 40]);
118
    $form->addElement('text', 'lastname', get_lang('LastName'), ['size' => 40]);
119
} else {
120
    // LAST NAME and FIRST NAME
121
    $form->addElement('text', 'lastname', get_lang('LastName'), ['size' => 40]);
122
    $form->addElement('text', 'firstname', get_lang('FirstName'), ['size' => 40]);
123
}
124
if (api_get_setting('profile', 'name') !== 'true') {
125
    $form->freeze(['lastname', 'firstname']);
126
}
127
$form->applyFilter(['lastname', 'firstname'], 'stripslashes');
128
$form->applyFilter(['lastname', 'firstname'], 'trim');
129
$form->applyFilter(['lastname', 'firstname'], 'html_filter');
130
$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
131
$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
132
133
//    USERNAME
134
$form->addElement(
135
    'text',
136
    'username',
137
    get_lang('UserName'),
138
    [
139
        'id' => 'username',
140
        'maxlength' => USERNAME_MAX_LENGTH,
141
        'size' => USERNAME_MAX_LENGTH,
142
    ]
143
);
144
145
if (api_get_setting('profile', 'login') !== 'true' || api_get_setting('login_is_email') === 'true') {
146
    $form->freeze('username');
147
}
148
$form->applyFilter('username', 'stripslashes');
149
$form->applyFilter('username', 'trim');
150
$form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
151
$form->addRule('username', get_lang('UsernameWrong'), 'username');
152
$form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
153
154
//    OFFICIAL CODE
155
if (defined('CONFVAL_ASK_FOR_OFFICIAL_CODE') && CONFVAL_ASK_FOR_OFFICIAL_CODE === true) {
0 ignored issues
show
The constant CONFVAL_ASK_FOR_OFFICIAL_CODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
156
    $form->addElement('text', 'official_code', get_lang('OfficialCode'), ['size' => 40]);
157
    if (api_get_setting('profile', 'officialcode') !== 'true') {
158
        $form->freeze('official_code');
159
    }
160
    $form->applyFilter('official_code', 'stripslashes');
161
    $form->applyFilter('official_code', 'trim');
162
    $form->applyFilter('official_code', 'html_filter');
163
    if (api_get_setting('registration', 'officialcode') === 'true' &&
164
        api_get_setting('profile', 'officialcode') === 'true'
165
    ) {
166
        $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
167
    }
168
}
169
170
// EMAIL
171
$form->addElement('email', 'email', get_lang('Email'), ['size' => 40]);
172
if (api_get_setting('profile', 'email') !== 'true') {
173
    $form->freeze('email');
174
}
175
176
if (api_get_setting('registration', 'email') === 'true' && api_get_setting('profile', 'email') === 'true') {
177
    $form->applyFilter('email', 'stripslashes');
178
    $form->applyFilter('email', 'trim');
179
    $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
180
    $form->addRule('email', get_lang('EmailWrong'), 'email');
181
}
182
183
// OPENID URL
184
if (is_profile_editable() && api_get_setting('openid_authentication') === 'true') {
185
    $form->addElement('text', 'openid', get_lang('OpenIDURL'), ['size' => 40]);
186
    if (api_get_setting('profile', 'openid') !== 'true') {
187
        $form->freeze('openid');
188
    }
189
    $form->applyFilter('openid', 'trim');
190
}
191
192
//    PHONE
193
$form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
194
if (api_get_setting('profile', 'phone') !== 'true') {
195
    $form->freeze('phone');
196
}
197
$form->applyFilter('phone', 'stripslashes');
198
$form->applyFilter('phone', 'trim');
199
$form->applyFilter('phone', 'html_filter');
200
201
//  PICTURE
202
if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
203
    $form->addFile(
204
        'picture',
205
        [
206
            $user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage'),
207
            get_lang('OnlyImagesAllowed'),
208
        ],
209
        [
210
            'id' => 'picture',
211
            'class' => 'picture-form',
212
            'crop_image' => true,
213
            'crop_ratio' => '1 / 1',
214
            'accept' => 'image/*',
215
        ]
216
    );
217
218
    $form->addProgress();
219
    if (!empty($user_data['picture_uri'])) {
220
        $form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
221
    }
222
    $allowed_picture_types = api_get_supported_image_extensions(false);
223
    $form->addRule(
224
        'picture',
225
        get_lang('OnlyImagesAllowed').' ('.implode(', ', $allowed_picture_types).')',
226
        'filetype',
227
        $allowed_picture_types
228
    );
229
}
230
231
//    LANGUAGE
232
$form->addSelectLanguage('language', get_lang('Language'));
233
if (api_get_setting('profile', 'language') !== 'true') {
234
    $form->freeze('language');
235
}
236
237
// THEME
238
if (is_profile_editable() && api_get_setting('user_selected_theme') === 'true') {
239
    $form->addElement('SelectTheme', 'theme', get_lang('Theme'));
240
    if (api_get_setting('profile', 'theme') !== 'true') {
241
        $form->freeze('theme');
242
    }
243
    $form->applyFilter('theme', 'trim');
244
}
245
246
//    EXTENDED PROFILE  this make the page very slow!
247
if (api_get_setting('extended_profile') === 'true') {
248
    $width_extended_profile = 500;
249
    //    MY PERSONAL OPEN AREA
250
    $form->addHtmlEditor(
251
        'openarea',
252
        [get_lang('MyPersonalOpenArea'), get_lang('MyPersonalOpenAreaHelp')],
253
        false,
254
        false,
255
        [
256
            'ToolbarSet' => 'Profile',
257
            'Width' => $width_extended_profile,
258
            'Height' => '350',
259
        ]
260
    );
261
    //    MY COMPETENCES
262
    $form->addHtmlEditor(
263
        'competences',
264
        [get_lang('MyCompetences'), get_lang('MyCompetencesHelp')],
265
        false,
266
        false,
267
        [
268
            'ToolbarSet' => 'Profile',
269
            'Width' => $width_extended_profile,
270
            'Height' => '130',
271
        ]
272
    );
273
    //    MY DIPLOMAS
274
    $form->addHtmlEditor(
275
        'diplomas',
276
        [get_lang('MyDiplomas'), get_lang('MyDiplomasHelp')],
277
        false,
278
        false,
279
        [
280
            'ToolbarSet' => 'Profile',
281
            'Width' => $width_extended_profile,
282
            'Height' => '130',
283
        ]
284
    );
285
    // WHAT I AM ABLE TO TEACH
286
    $form->addHtmlEditor(
287
        'teach',
288
        [get_lang('MyTeach'), get_lang('MyTeachingCapabilitiesHelp')],
289
        false,
290
        false,
291
        [
292
            'ToolbarSet' => 'Profile',
293
            'Width' => $width_extended_profile,
294
            'Height' => '130',
295
        ]
296
    );
297
298
    //    MY PRODUCTIONS
299
    $form->addElement('file', 'production', [get_lang('MyProductions'), get_lang('MyProductionsHelp')]);
300
    if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
301
        $form->addElement('static', 'productions_list', null, $production_list);
302
    }
303
    // openarea is untrimmed for maximum openness
304
    $form->applyFilter(['competences', 'diplomas', 'teach', 'openarea'], 'stripslashes');
305
    $form->applyFilter(['competences', 'diplomas', 'teach'], 'trim');
306
}
307
308
$showPassword = is_platform_authentication();
309
$links = api_get_configuration_value('auth_password_links');
310
$extraLink = '';
311
if (!empty($links) &&
312
    isset($links['profiles']) &&
313
    isset($links['profiles'][$user_data['status']]) &&
314
    isset($links['profiles'][$user_data['status']][$user_data['auth_source']])
315
) {
316
    $extraUserConditions = $links['profiles'][$user_data['status']][$user_data['auth_source']];
317
    if (isset($extraUserConditions['show_password_field'])) {
318
        $showPassword = $extraUserConditions['show_password_field'];
319
    }
320
321
    if (isset($extraUserConditions['extra_link'])) {
322
        $extraLink = $extraUserConditions['extra_link'];
323
    }
324
}
325
326
//    PASSWORD, if auth_source is platform
327
if ($showPassword &&
328
    is_profile_editable() &&
329
    api_get_setting('profile', 'password') === 'true'
330
) {
331
    $form->addElement('password', 'password0', [get_lang('Pass'), get_lang('TypeCurrentPassword')], ['size' => 40]);
332
    $form->addElement(
333
        'password',
334
        'password1',
335
        [get_lang('NewPass'), get_lang('EnterYourNewPassword')],
336
        ['id' => 'password1', 'size' => 40]
337
    );
338
    $form->addElement(
339
        'password',
340
        'password2',
341
        [get_lang('Confirmation'), get_lang('RepeatYourNewPassword')],
342
        ['size' => 40]
343
    );
344
    //    user must enter identical password twice so we can prevent some user errors
345
    $form->addRule(['password1', 'password2'], get_lang('PassTwo'), 'compare');
346
    $form->addPasswordRule('password1');
347
}
348
349
$form->addHtml($extraLink);
350
351
$extraField = new ExtraField('user');
352
$return = $extraField->addElements($form, api_get_user_id(), ['pause_formation', 'start_pause_date', 'end_pause_date']);
353
$jquery_ready_content = $return['jquery_ready_content'];
354
355
// the $jquery_ready_content variable collects all functions that
356
// will be load in the $(document).ready javascript function
357
$htmlHeadXtra[] = '<script>
358
$(function() {
359
    '.$jquery_ready_content.'
360
});
361
</script>';
362
363
if (api_get_setting('profile', 'apikeys') == 'true') {
364
    $form->addElement('html', '<div id="div_api_key">');
365
    $form->addElement(
366
        'text',
367
        'api_key_generate',
368
        get_lang('MyApiKey'),
369
        ['size' => 40, 'id' => 'id_api_key_generate']
370
    );
371
    $form->addElement('html', '</div>');
372
    $form->addButton(
373
        'generate_api_key',
374
        get_lang('GenerateApiKey'),
375
        'cogs',
376
        'default',
377
        'default',
378
        null,
379
        ['id' => 'id_generate_api_key']
380
    );
381
}
382
//    SUBMIT
383
if (is_profile_editable()) {
384
    $form->addButtonUpdate(get_lang('SaveSettings'), 'apply_change');
385
} else {
386
    $form->freeze();
387
}
388
389
// Student cannot modified their user conditions
390
$extraConditions = api_get_configuration_value('show_conditions_to_user');
391
if ($extraConditions && isset($extraConditions['conditions'])) {
392
    $extraConditions = $extraConditions['conditions'];
393
    foreach ($extraConditions as $condition) {
394
        $element = $form->getElement('extra_'.$condition['variable']);
395
        if ($element) {
396
            $element->freeze();
397
        }
398
    }
399
}
400
401
$form->setDefaults($user_data);
402
403
$filtered_extension = false;
404
405
if ($form->validate()) {
406
    $hook = HookUpdateUser::create();
407
408
    if ($hook) {
409
        $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
410
    }
411
412
    $wrong_current_password = false;
413
    $user_data = $form->getSubmitValues(1);
414
    /** @var User $user */
415
    $user = UserManager::getRepository()->find(api_get_user_id());
416
417
    // set password if a new one was provided
418
    $validPassword = false;
419
    $passwordWasChecked = false;
420
421
    if ($user &&
422
        (!empty($user_data['password0']) &&
423
        !empty($user_data['password1'])) ||
424
        (!empty($user_data['password0']) &&
425
        api_get_setting('profile', 'email') == 'true')
426
    ) {
427
        $passwordWasChecked = true;
428
        $validPassword = UserManager::isPasswordValid(
429
            $user->getPassword(),
430
            $user_data['password0'],
431
            $user->getSalt()
432
        );
433
434
        if ($validPassword) {
435
            $password = $user_data['password1'];
436
        } else {
437
            Display::addFlash(
438
                Display:: return_message(
439
                    get_lang('CurrentPasswordEmptyOrIncorrect'),
440
                    'warning',
441
                    false
442
                )
443
            );
444
        }
445
    }
446
447
    $allow_users_to_change_email_with_no_password = true;
448
    if (is_platform_authentication() &&
449
        api_get_setting('allow_users_to_change_email_with_no_password') == 'false'
450
    ) {
451
        $allow_users_to_change_email_with_no_password = false;
452
    }
453
454
    // If user sending the email to be changed (input available and not frozen )
455
    if (api_get_setting('profile', 'email') == 'true') {
456
        if ($allow_users_to_change_email_with_no_password) {
457
            if (!check_user_email($user_data['email'])) {
458
                $changeemail = $user_data['email'];
459
            }
460
        } else {
461
            // Normal behaviour
462
            if (!check_user_email($user_data['email']) && $validPassword) {
463
                $changeemail = $user_data['email'];
464
            }
465
466
            if (!check_user_email($user_data['email']) && empty($user_data['password0'])) {
467
                Display::addFlash(
468
                    Display:: return_message(
469
                        get_lang('ToChangeYourEmailMustTypeYourPassword'),
470
                        'error',
471
                        false
472
                    )
473
                );
474
            }
475
        }
476
    }
477
478
    // Upload picture if a new one is provided
479
    if ($_FILES['picture']['size']) {
480
        $new_picture = UserManager::update_user_picture(
481
            api_get_user_id(),
482
            $_FILES['picture']['name'],
483
            $_FILES['picture']['tmp_name'],
484
            $user_data['picture_crop_result']
485
        );
486
487
        if ($new_picture) {
488
            $user_data['picture_uri'] = $new_picture;
489
490
            Display::addFlash(
491
                Display:: return_message(
492
                    get_lang('PictureUploaded'),
493
                    'normal',
494
                    false
495
                )
496
            );
497
        }
498
    } elseif (!empty($user_data['remove_picture'])) {
499
        // remove existing picture if asked
500
        UserManager::deleteUserPicture(api_get_user_id());
501
        $user_data['picture_uri'] = '';
502
    }
503
504
    // Remove production.
505
    if (isset($user_data['remove_production']) &&
506
        is_array($user_data['remove_production'])
507
    ) {
508
        foreach (array_keys($user_data['remove_production']) as $production) {
509
            UserManager::remove_user_production(api_get_user_id(), urldecode($production));
510
        }
511
        if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
512
            $form->insertElementBefore(
513
                $form->createElement('static', null, null, $production_list),
514
                'productions_list'
515
            );
516
        }
517
        $form->removeElement('productions_list');
518
        Display::addFlash(
519
            Display:: return_message(get_lang('FileDeleted'), 'normal', false)
520
        );
521
    }
522
523
    // upload production if a new one is provided
524
    if (isset($_FILES['production']) && $_FILES['production']['size']) {
525
        $res = upload_user_production(api_get_user_id());
526
        if (!$res) {
527
            //it's a bit excessive to assume the extension is the reason why
528
            // upload_user_production() returned false, but it's true in most cases
529
            $filtered_extension = true;
530
        } else {
531
            Display::addFlash(
532
                Display:: return_message(
533
                    get_lang('ProductionUploaded'),
534
                    'normal',
535
                    false
536
                )
537
            );
538
        }
539
    }
540
541
    // remove values that shouldn't go in the database
542
    unset(
543
        $user_data['password0'],
544
        $user_data['password1'],
545
        $user_data['password2'],
546
        $user_data['MAX_FILE_SIZE'],
547
        $user_data['remove_picture'],
548
        $user_data['apply_change'],
549
        $user_data['email']
550
    );
551
552
    // Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
553
    // we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
554
    $my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
555
    if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
556
        //ensure there is at least a http:// scheme in the URI provided
557
        $user_data['openid'] = 'http://'.$my_user_openid;
558
    }
559
    $extras = [];
560
561
    //Checking the user language
562
    $languages = api_get_languages();
563
    if (!in_array($user_data['language'], $languages['folder'])) {
564
        $user_data['language'] = api_get_setting('platformLanguage');
565
    }
566
    $_SESSION['_user']['language'] = $user_data['language'];
567
568
    //Only update values that are request by the "profile" setting
569
    $profile_list = api_get_setting('profile');
570
    //Adding missing variables
571
572
    $available_values_to_modify = [];
573
    foreach ($profile_list as $key => $status) {
574
        if ($status == 'true') {
575
            switch ($key) {
576
                case 'login':
577
                    $available_values_to_modify[] = 'username';
578
                    break;
579
                case 'name':
580
                    $available_values_to_modify[] = 'firstname';
581
                    $available_values_to_modify[] = 'lastname';
582
                    break;
583
                case 'picture':
584
                    $available_values_to_modify[] = 'picture_uri';
585
                    break;
586
                default:
587
                    $available_values_to_modify[] = $key;
588
                    break;
589
            }
590
        }
591
    }
592
593
    //Fixing missing variables
594
    $available_values_to_modify = array_merge(
595
        $available_values_to_modify,
596
        ['competences', 'diplomas', 'openarea', 'teach', 'openid', 'address']
597
    );
598
599
    // build SQL query
600
    $sql = "UPDATE $table_user SET";
601
    unset($user_data['api_key_generate']);
602
603
    foreach ($user_data as $key => $value) {
604
        if (substr($key, 0, 6) === 'extra_') { //an extra field
605
            continue;
606
        } elseif (strpos($key, 'remove_extra_') !== false) {
607
        } else {
608
            if (in_array($key, $available_values_to_modify)) {
609
                $sql .= " $key = '".Database::escape_string($value)."',";
610
            }
611
        }
612
    }
613
614
    $changePassword = false;
615
    // Change email
616
    if ($allow_users_to_change_email_with_no_password) {
617
        if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
618
            $sql .= " email = '".Database::escape_string($changeemail)."' ";
619
        }
620
        if (isset($password) && in_array('password', $available_values_to_modify)) {
621
            $changePassword = true;
622
        }
623
    } else {
624
        if (isset($changeemail) && !isset($password) && in_array('email', $available_values_to_modify)) {
625
            $sql .= " email = '".Database::escape_string($changeemail)."'";
626
        } else {
627
            if (isset($password) && in_array('password', $available_values_to_modify)) {
628
                if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
629
                    $sql .= " email = '".Database::escape_string($changeemail)."' ";
630
                }
631
                $changePassword = true;
632
            }
633
        }
634
    }
635
636
    $sql = rtrim($sql, ',');
637
    if ($changePassword && !empty($password)) {
638
        UserManager::updatePassword(api_get_user_id(), $password);
639
    }
640
641
    if (api_get_setting('profile', 'officialcode') === 'true' &&
642
        isset($user_data['official_code'])
643
    ) {
644
        $sql .= ", official_code = '".Database::escape_string($user_data['official_code'])."'";
645
    }
646
647
    $sql .= " WHERE id  = '".api_get_user_id()."'";
648
    Database::query($sql);
649
650
    if ($passwordWasChecked == false) {
651
        Display::addFlash(
652
            Display:: return_message(get_lang('ProfileReg'), 'normal', false)
653
        );
654
    } else {
655
        if ($validPassword) {
656
            Display::addFlash(
657
                Display:: return_message(get_lang('ProfileReg'), 'normal', false)
658
            );
659
        }
660
    }
661
662
    $extraField = new ExtraFieldValue('user');
663
    $extraField->saveFieldValues($user_data);
664
665
    $userInfo = api_get_user_info(
666
        api_get_user_id(),
667
        false,
668
        false,
669
        false,
670
        false,
671
        true,
672
        true
673
    );
674
    Session::write('_user', $userInfo);
675
676
    $notification = api_get_configuration_value('user_notification_settings');
677
    if (!empty($notification)) {
678
        foreach ($notification as $label => $notificationSettings) {
679
            $sendMessage = false;
680
            if (isset($notificationSettings['if_field_changes'])) {
681
                foreach ($notificationSettings['if_field_changes'] as $field) {
682
                    if ($originalUserInfo[$field] != $userInfo[$field]) {
683
                        $sendMessage = true;
684
                        break;
685
                    }
686
                }
687
            }
688
689
            if ($sendMessage) {
690
                $subject = $notificationSettings['subject'];
691
                $content = $notificationSettings['content'];
692
                $userInfo['extra_fields'] = UserManager::get_extra_user_data(api_get_user_id());
693
                $template = new Template();
694
                $template->assign('old', $originalUserInfo);
695
                $template->assign('new', $userInfo);
696
                $content = $template->fetch($template->get_template($content));
697
698
                $emails = explode(',', $notificationSettings['email']);
699
                foreach ($emails as $email) {
700
                    api_mail_html(
701
                        '',
702
                        $email,
703
                        $subject,
704
                        $content,
705
                        $userInfo['complete_name'],
706
                        $notificationSettings['sender_email'],
707
                        [
708
                            'reply_to' => [
709
                                'mail' => $userInfo['mail'],
710
                                'name' => $userInfo['complete_name'],
711
                            ],
712
                        ]
713
                    );
714
                }
715
            }
716
        }
717
    }
718
719
    if ($hook) {
720
        Database::getManager()->clear(User::class); // Avoid cache issue (user entity is used before)
721
        $user = api_get_user_entity(api_get_user_id()); // Get updated user info for hook event
722
        $hook->setEventData(['user' => $user]);
723
        $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
724
    }
725
726
    Session::erase('system_timezone');
727
728
    $url = api_get_self();
729
    header("Location: $url");
730
    exit;
731
}
732
733
$actions = '';
734
if ($allowSocialTool) {
735
    if (api_get_setting('extended_profile') === 'true') {
736
        if (api_get_setting('allow_message_tool') === 'true') {
737
            $actions .= '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.
738
                Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
739
            $actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
740
                Display::return_icon('inbox.png', get_lang('Messages')).'</a>';
741
        }
742
        $show = isset($_GET['show']) ? '&show='.(int) $_GET['show'] : '';
743
744
        if (isset($_GET['type']) && $_GET['type'] === 'extended') {
745
            $actions .= '<a href="profile.php?type=reduced'.$show.'">'.
746
                Display::return_icon('edit.png', get_lang('EditNormalProfile'), '', 16).'</a>';
747
        } else {
748
            $actions .= '<a href="profile.php?type=extended'.$show.'">'.
749
                Display::return_icon('edit.png', get_lang('EditExtendProfile'), '', 16).'</a>';
750
        }
751
    }
752
}
753
754
$show_delete_account_button = api_get_setting('platform_unsubscribe_allowed') === 'true' ? true : false;
755
756
$tpl = new Template(get_lang('ModifyProfile'));
757
758
if ($actions) {
759
    $tpl->assign(
760
        'actions',
761
        Display::toolbarAction('toolbar', [$actions])
762
    );
763
}
764
765
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
766
$tabs = SocialManager::getHomeProfileTabs('profile');
767
768
if ($allowSocialTool) {
769
    SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'home');
770
    $menu = SocialManager::show_social_menu(
771
        'home',
772
        null,
773
        api_get_user_id(),
774
        false,
775
        $show_delete_account_button
776
    );
777
    $tpl->assign('social_menu_block', $menu);
778
    $tpl->assign('social_right_content', $tabs.$form->returnForm());
779
    $social_layout = $tpl->get_template('social/edit_profile.tpl');
780
781
    $tpl->display($social_layout);
782
} else {
783
    $bigImage = UserManager::getUserPicture(api_get_user_id(), USER_IMAGE_SIZE_BIG);
784
    $normalImage = UserManager::getUserPicture(api_get_user_id(), USER_IMAGE_SIZE_ORIGINAL);
785
786
    $imageToShow = '<div id="image-message-container">';
787
    $imageToShow .= '<a class="expand-image pull-right" href="'.$bigImage.'" /><img src="'.$normalImage.'"></a>';
788
    $imageToShow .= '</div>';
789
790
    $content = $imageToShow.$form->returnForm().$tabs;
791
792
    $tpl->assign('content', $content);
793
    $tpl->display_one_col_template();
794
}
795
796
// Helper functions defined below this point
797
798
/**
799
 * Is user auth_source is platform ?
800
 *
801
 * @return bool Whether auth_source is 'platform' or not
802
 */
803
function is_platform_authentication()
804
{
805
    $tabUserInfo = api_get_user_info();
806
807
    return $tabUserInfo['auth_source'] == PLATFORM_AUTH_SOURCE;
808
}
809
810
/**
811
 * Can a user edit his/her profile?
812
 *
813
 * @return bool Whether the profile can be edited by the user or not
814
 */
815
function is_profile_editable()
816
{
817
    if (isset($GLOBALS['profileIsEditable'])) {
818
        return (bool) $GLOBALS['profileIsEditable'];
819
    }
820
821
    return true;
822
}
823
824
/**
825
 * Upload a submitted user production.
826
 *
827
 * @param int $userId User id
828
 *
829
 * @return mixed The filename of the new production or FALSE if the upload has failed
830
 */
831
function upload_user_production($userId)
832
{
833
    $productionRepository = UserManager::getUserPathById($userId, 'system');
834
835
    if (!file_exists($productionRepository)) {
836
        @mkdir($productionRepository, api_get_permissions_for_new_directories(), true);
837
    }
838
    $filename = api_replace_dangerous_char($_FILES['production']['name']);
839
    $filename = disable_dangerous_file($filename);
840
841
    if (filter_extension($filename)) {
842
        if (@move_uploaded_file($_FILES['production']['tmp_name'], $productionRepository.$filename)) {
843
            return $filename;
844
        }
845
    }
846
847
    return false; // this should be returned if anything went wrong with the upload
848
}
849
850
/**
851
 * Check current user's current password.
852
 *
853
 * @param string $email E-mail
854
 *
855
 * @return bool Whether this e-mail is already in use or not
856
 */
857
function check_user_email($email)
858
{
859
    $userId = api_get_user_id();
860
    if ($userId != strval(intval($userId)) || empty($email)) {
861
        return false;
862
    }
863
    $tableUser = Database::get_main_table(TABLE_MAIN_USER);
864
    $email = Database::escape_string($email);
865
    $sql = "SELECT * FROM $tableUser WHERE user_id = $userId AND email = '$email'";
866
    $result = Database::query($sql);
867
868
    return Database::num_rows($result) != 0;
869
}
870