Issues (2034)

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