SetupModuleController.php 47.3 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
15

16
17
namespace TYPO3\CMS\Setup\Controller;

18
use Psr\EventDispatcher\EventDispatcherInterface;
19
20
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
21
use TYPO3\CMS\Backend\Backend\Avatar\DefaultAvatarProvider;
22
use TYPO3\CMS\Backend\Module\ModuleLoader;
23
use TYPO3\CMS\Backend\Routing\UriBuilder;
24
use TYPO3\CMS\Backend\Template\ModuleTemplate;
25
use TYPO3\CMS\Backend\Utility\BackendUtility;
26
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
27
use TYPO3\CMS\Core\Core\Environment;
28
29
use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
30
use TYPO3\CMS\Core\Database\ConnectionPool;
31
32
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
33
use TYPO3\CMS\Core\Http\HtmlResponse;
34
use TYPO3\CMS\Core\Imaging\Icon;
35
use TYPO3\CMS\Core\Imaging\IconFactory;
36
use TYPO3\CMS\Core\Localization\LanguageService;
37
use TYPO3\CMS\Core\Localization\Locales;
38
use TYPO3\CMS\Core\Messaging\FlashMessage;
39
use TYPO3\CMS\Core\Messaging\FlashMessageService;
40
use TYPO3\CMS\Core\Page\PageRenderer;
41
42
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
use TYPO3\CMS\Core\Resource\ResourceFactory;
43
44
45
use TYPO3\CMS\Core\SysLog\Action\Setting as SystemLogSettingAction;
use TYPO3\CMS\Core\SysLog\Error as SystemLogErrorClassification;
use TYPO3\CMS\Core\SysLog\Type as SystemLogType;
46
use TYPO3\CMS\Core\Utility\GeneralUtility;
47
use TYPO3\CMS\Setup\Event\AddJavaScriptModulesEvent;
48

49
50
/**
 * Script class for the Setup module
51
52
 *
 * @internal This is a specific Backend Controller implementation and is not considered part of the Public TYPO3 API.
53
 */
54
class SetupModuleController
55
{
56

57
58
59
    /**
     * Flag if password has not been updated
     */
60
    const PASSWORD_NOT_UPDATED = 0;
61
62
63
64

    /**
     * Flag if password has been updated
     */
65
    const PASSWORD_UPDATED = 1;
66
67
68
69

    /**
     * Flag if both new passwords do not match
     */
70
    const PASSWORD_NOT_THE_SAME = 2;
71
72
73
74
75

    /**
     * Flag if the current password given was not identical to the real
     * current password
     */
76
77
78
79
80
    const PASSWORD_OLD_WRONG = 3;

    /**
     * @var string
     */
81
    protected $content;
82
83
84
85

    /**
     * @var array
     */
86
    protected $overrideConf;
87
88
89
90

    /**
     * @var bool
     */
91
    protected $languageUpdate;
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

    /**
     * @var bool
     */
    protected $pagetreeNeedsRefresh = false;

    /**
     * @var array
     */
    protected $tsFieldConf;

    /**
     * @var bool
     */
    protected $saveData = false;

    /**
     * @var int
     */
    protected $passwordIsUpdated = self::PASSWORD_NOT_UPDATED;

    /**
     * @var bool
     */
    protected $passwordIsSubmitted = false;

    /**
     * @var bool
     */
    protected $setupIsUpdated = false;

    /**
     * @var bool
     */
    protected $settingsAreResetToDefault = false;

    /**
     * Form protection instance
     *
     * @var \TYPO3\CMS\Core\FormProtection\BackendFormProtection
     */
    protected $formProtection;

    /**
     * The name of the module
     *
     * @var string
     */
    protected $moduleName = 'user_setup';

142
143
144
145
146
147
148
    /**
     * ModuleTemplate object
     *
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

149
150
151
152
153
    /**
     * @var EventDispatcherInterface
     */
    protected $eventDispatcher;

154
155
    /**
     * Instantiate the form protection before a simulated user is initialized.
156
157
     *
     * @param EventDispatcherInterface $eventDispatcher
158
     */
159
    public function __construct(EventDispatcherInterface $eventDispatcher)
160
    {
161
        $this->eventDispatcher = $eventDispatcher;
162
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
163
        $this->formProtection = FormProtectionFactory::get();
164
165
166
        $pageRenderer = $this->moduleTemplate->getPageRenderer();
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/FormEngine');
167
168
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Setup/SetupModule');
        $this->processAdditionalJavaScriptModules($pageRenderer);
169
170
        $pageRenderer->addInlineSetting('FormEngine', 'formName', 'editform');
        $pageRenderer->addInlineLanguageLabelArray([
171
172
            'FormEngine.remainingCharacters' => $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.remainingCharacters'),
        ]);
173
174
    }

175
176
177
178
179
180
181
182
183
184
    protected function processAdditionalJavaScriptModules(PageRenderer $pageRenderer): void
    {
        $event = new AddJavaScriptModulesEvent();
        /** @var AddJavaScriptModulesEvent $event */
        $event = $this->eventDispatcher->dispatch($event);
        foreach ($event->getModules() as $moduleName) {
            $pageRenderer->loadRequireJsModule($moduleName);
        }
    }

185
186
187
188
189
190
    /**
     * Initializes the module for display of the settings form.
     */
    protected function initialize()
    {
        $this->getLanguageService()->includeLLFile('EXT:setup/Resources/Private/Language/locallang.xlf');
191
        $this->moduleTemplate->setTitle($this->getLanguageService()->getLL('UserSettings'));
192
193
194
195
196
197
198
199
200
        // Getting the 'override' values as set might be set in User TSconfig
        $this->overrideConf = $this->getBackendUser()->getTSConfig()['setup.']['override.'] ?? null;
        // Getting the disabled fields might be set in User TSconfig (eg setup.fields.password.disabled=1)
        $this->tsFieldConf = $this->getBackendUser()->getTSConfig()['setup.']['fields.'] ?? null;
        // id password is disabled, disable repeat of password too (password2)
        if ($this->tsFieldConf['password.']['disabled'] ?? false) {
            $this->tsFieldConf['password2.']['disabled'] = 1;
            $this->tsFieldConf['passwordCurrent.']['disabled'] = 1;
        }
201
202
203
204
    }

    /**
     * If settings are submitted to _POST[DATA], store them
205
     * NOTICE: This method is called before the \TYPO3\CMS\Backend\Template\ModuleTemplate
206
     * is included. See bottom of document.
207
208
     *
     * @param array $postData parsed body of the request
209
     */
210
    protected function storeIncomingData(array $postData)
211
212
    {
        // First check if something is submitted in the data-array from POST vars
213
        $d = $postData['data'] ?? null;
214
        $columns = $GLOBALS['TYPO3_USER_SETTINGS']['columns'];
215
216
        $backendUser = $this->getBackendUser();
        $beUserId = $backendUser->user['uid'];
217
        $storeRec = [];
218
        $fieldList = $this->getFieldsFromShowItem();
219
        if (is_array($d) && $this->formProtection->validateToken((string)($postData['formToken'] ?? ''), 'BE user setup', 'edit')) {
220
            // UC hashed before applying changes
221
            $save_before = md5(serialize($backendUser->uc));
222
223
            // PUT SETTINGS into the ->uc array:
            // Reload left frame when switching BE language
224
            if (isset($d['lang']) && $d['lang'] !== $backendUser->uc['lang']) {
225
226
227
                $this->languageUpdate = true;
            }
            // Reload pagetree if the title length is changed
228
            if (isset($d['titleLen']) && $d['titleLen'] !== $backendUser->uc['titleLen']) {
229
230
231
232
                $this->pagetreeNeedsRefresh = true;
            }
            if ($d['setValuesToDefault']) {
                // If every value should be default
233
                $backendUser->resetUC();
234
235
236
237
                $this->settingsAreResetToDefault = true;
            } elseif ($d['save']) {
                // Save all submitted values if they are no array (arrays are with table=be_users) and exists in $GLOBALS['TYPO3_USER_SETTINGS'][columns]
                foreach ($columns as $field => $config) {
238
                    if (!in_array($field, $fieldList, true)) {
239
240
241
                        continue;
                    }
                    if ($config['table']) {
242
                        if ($config['table'] === 'be_users' && !in_array($field, ['password', 'password2', 'passwordCurrent', 'email', 'realName', 'admin', 'avatar'], true)) {
243
                            if (!isset($config['access']) || $this->checkAccess($config) && $backendUser->user[$field] !== $d['be_users'][$field]) {
244
245
246
247
248
249
                                if ($config['type'] === 'check') {
                                    $fieldValue = isset($d['be_users'][$field]) ? 1 : 0;
                                } else {
                                    $fieldValue = $d['be_users'][$field];
                                }
                                $storeRec['be_users'][$beUserId][$field] = $fieldValue;
250
                                $backendUser->user[$field] = $fieldValue;
251
252
253
254
                            }
                        }
                    }
                    if ($config['type'] === 'check') {
255
                        $backendUser->uc[$field] = isset($d[$field]) ? 1 : 0;
256
                    } else {
257
                        $backendUser->uc[$field] = htmlspecialchars($d[$field]);
258
259
260
261
262
263
                    }
                }
                // Personal data for the users be_user-record (email, name, password...)
                // If email and name is changed, set it in the users record:
                $be_user_data = $d['be_users'];
                // Possibility to modify the transmitted values. Useful to do transformations, like RSA password decryption
264
265
266
                foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['modifyUserDataBeforeSave'] ?? [] as $function) {
                    $params = ['be_user_data' => &$be_user_data];
                    GeneralUtility::callUserFunction($function, $params, $this);
267
268
269
270
                }
                $this->passwordIsSubmitted = (string)$be_user_data['password'] !== '';
                $passwordIsConfirmed = $this->passwordIsSubmitted && $be_user_data['password'] === $be_user_data['password2'];
                // Update the real name:
271
272
                if ($be_user_data['realName'] !== $backendUser->user['realName']) {
                    $backendUser->user['realName'] = ($storeRec['be_users'][$beUserId]['realName'] = substr($be_user_data['realName'], 0, 80));
273
274
                }
                // Update the email address:
275
276
                if ($be_user_data['email'] !== $backendUser->user['email']) {
                    $backendUser->user['email'] = ($storeRec['be_users'][$beUserId]['email'] = substr($be_user_data['email'], 0, 80));
277
278
279
                }
                // Update the password:
                if ($passwordIsConfirmed) {
280
                    if ($backendUser->isAdmin()) {
281
282
                        $passwordOk = true;
                    } else {
283
                        $currentPasswordHashed = $backendUser->user['password'];
Christian Kuhn's avatar
Christian Kuhn committed
284
                        $passwordOk = false;
285
                        $saltFactory = GeneralUtility::makeInstance(PasswordHashFactory::class);
Christian Kuhn's avatar
Christian Kuhn committed
286
                        try {
287
                            $hashInstance = $saltFactory->get($currentPasswordHashed, 'BE');
Christian Kuhn's avatar
Christian Kuhn committed
288
                            $passwordOk = $hashInstance->checkPassword($be_user_data['passwordCurrent'], $currentPasswordHashed);
289
                        } catch (InvalidPasswordHashException $e) {
Christian Kuhn's avatar
Christian Kuhn committed
290
291
292
                            // Could not find hash class responsible for existing password. This is a
                            // misconfiguration and user can not change its password.
                        }
293
294
                    }
                    if ($passwordOk) {
295
296
297
298
299
300
301
302
303
304
305
306
307
308
                        $this->passwordIsUpdated = self::PASSWORD_UPDATED;
                        $storeRec['be_users'][$beUserId]['password'] = $be_user_data['password'];
                    } else {
                        $this->passwordIsUpdated = self::PASSWORD_OLD_WRONG;
                    }
                } else {
                    $this->passwordIsUpdated = self::PASSWORD_NOT_THE_SAME;
                }

                $this->setAvatarFileUid($beUserId, $be_user_data['avatar'], $storeRec);

                $this->saveData = true;
            }
            // Inserts the overriding values.
309
310
            $backendUser->overrideUC();
            $save_after = md5(serialize($backendUser->uc));
311
312
            // If something in the uc-array of the user has changed, we save the array...
            if ($save_before != $save_after) {
313
                $backendUser->writeUC($backendUser->uc);
314
                $backendUser->writelog(SystemLogType::SETTING, SystemLogSettingAction::CHANGE, SystemLogErrorClassification::MESSAGE, 1, 'Personal settings changed', []);
315
316
317
318
                $this->setupIsUpdated = true;
            }
            // Persist data if something has changed:
            if (!empty($storeRec) && $this->saveData) {
319
320
321
322
323
                // Set user to admin to circumvent DataHandler restrictions.
                // Not using isAdmin() to fetch the original value, just in case it has been boolean casted.
                $savedUserAdminState = $backendUser->user['admin'];
                $backendUser->user['admin'] = true;
                // Make dedicated instance of TCE for storing the changes.
324
                $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
325
                $dataHandler->start($storeRec, [], $backendUser);
326
327
328
                // This is to make sure that the users record can be updated even if in another workspace. This is tolerated.
                $dataHandler->bypassWorkspaceRestrictions = true;
                $dataHandler->process_datamap();
329
330
                // reset the user record admin flag to previous value, just in case it gets used any further.
                $backendUser->user['admin'] = $savedUserAdminState;
331
332
333
                if ($this->passwordIsUpdated === self::PASSWORD_NOT_UPDATED || count($storeRec['be_users'][$beUserId]) > 1) {
                    $this->setupIsUpdated = true;
                }
334
                BackendUtility::setUpdateSignal('updateTopbar');
335
336
337
338
339
340
341
342
343
344
345
346
            }
        }
    }

    /**
     * Generate necessary JavaScript
     *
     * @return string
     */
    protected function getJavaScript()
    {
        $javaScript = '';
347
348
349
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['setupScriptHook'] ?? [] as $function) {
            $params = [];
            $javaScript .= GeneralUtility::callUserFunction($function, $params, $this);
350
351
352
353
354
        }
        return $javaScript;
    }

    /**
355
356
357
358
     * Injects the request object, checks if data should be saved, and prepares a HTML page
     *
     * @param ServerRequestInterface $request the current request
     * @return ResponseInterface the response with the content
359
     */
360
    public function mainAction(ServerRequestInterface $request): ResponseInterface
361
    {
362
363
364
365
366
367
368
        $this->initialize();
        if ($request->getMethod() === 'POST') {
            $postData = $request->getParsedBody();
            if (is_array($postData) && !empty($postData)) {
                $this->storeIncomingData($postData);
            }
        }
369
        if ($this->languageUpdate) {
370
371
            $this->content .= $this->buildInstructionDataTag('TYPO3.ModuleMenu.App.refreshMenu');
            $this->content .= $this->buildInstructionDataTag('TYPO3.Backend.Topbar.refresh');
372
373
374
375
        }
        if ($this->pagetreeNeedsRefresh) {
            BackendUtility::setUpdateSignal('updatePageTree');
        }
376
377
378

        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $this->content .= '<form action="' . (string)$uriBuilder->buildUriFromRoute('user_setup') . '" method="post" id="SetupModuleController" name="usersetup" enctype="multipart/form-data">';
379
        $this->content .= '<div id="user-setup-wrapper">';
380
        $this->content .= $this->moduleTemplate->header($this->getLanguageService()->getLL('UserSettings'));
381
        $this->addFlashMessages();
382

383
384
        $formToken = $this->formProtection->generateToken('BE user setup', 'edit');

385
386
        // Render the menu items
        $menuItems = $this->renderUserSetup();
387
        $this->content .= $this->moduleTemplate->getDynamicTabMenu($menuItems, 'user-setup', 1, false, false);
388
        $this->content .= '<div>';
389
        $this->content .= '<input type="hidden" name="formToken" value="' . htmlspecialchars($formToken) . '" />
390
            <input type="hidden" value="1" name="data[save]" />
391
            <input type="hidden" name="data[setValuesToDefault]" value="0" id="setValuesToDefault" />';
392
        $this->content .= '</div>';
393
394
395
        // End of wrapper div
        $this->content .= '</div>';
        // Setting up the buttons and markers for docheader
396
        $this->getButtons($request->getQueryParams()['route']);
397
398
        // Build the <body> for the module
        // Renders the module page
399
        $this->moduleTemplate->setContent($this->content);
400
        $this->content .= '</form>';
401
        return new HtmlResponse($this->moduleTemplate->renderContent());
402
403
    }

404
405
406
407
408
409
410
411
    protected function buildInstructionDataTag(string $dispatchAction): string
    {
        return sprintf(
            '<typo3-immediate-action action="%s"></typo3-immediate-action>' . "\n",
            htmlspecialchars($dispatchAction)
        );
    }

412
413
414
    /**
     * Create the panel of buttons for submitting the form or otherwise perform operations.
     */
415
    protected function getButtons(string $route)
416
    {
417
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
418
419
420
421
        $cshButton = $buttonBar->makeHelpButton()
            ->setModuleName('_MOD_user_setup')
            ->setFieldName('');
        $buttonBar->addButton($cshButton);
422
423
424

        $saveButton = $buttonBar->makeInputButton()
            ->setName('data[save]')
425
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
426
            ->setValue('1')
427
            ->setForm('SetupModuleController')
428
            ->setShowLabelText(true)
429
            ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL));
430
431

        $buttonBar->addButton($saveButton);
432
        $shortcutButton = $buttonBar->makeShortcutButton()
433
            ->setRouteIdentifier($this->moduleName)
434
            ->setDisplayName($this->getLanguageService()->sL('LLL:EXT:setup/Resources/Private/Language/locallang_mod.xlf:mlang_labels_tablabel'));
435
        $buttonBar->addButton($shortcutButton);
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    }

    /******************************
     *
     * Render module
     *
     ******************************/

    /**
     * renders the data for all tabs in the user setup and returns
     * everything that is needed with tabs and dyntab menu
     *
     * @return array Ready to use for the dyntabmenu itemarray
     */
    protected function renderUserSetup()
    {
452
        $backendUser = $this->getBackendUser();
453
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
454
        $html = '';
455
        $result = [];
456
        $firstTabLabel = '';
457
        $code = [];
458
459
460
        $fieldArray = $this->getFieldsFromShowItem();
        $tabLabel = '';
        foreach ($fieldArray as $fieldName) {
461
462
463
464
465
            $config = $GLOBALS['TYPO3_USER_SETTINGS']['columns'][$fieldName];
            if (isset($config['access']) && !$this->checkAccess($config)) {
                continue;
            }

466
            if (strpos($fieldName, '--div--;') === 0) {
467
468
469
470
471
                if ($firstTabLabel === '') {
                    // First tab
                    $tabLabel = $this->getLabel(substr($fieldName, 8), '', false);
                    $firstTabLabel = $tabLabel;
                } else {
472
                    $result[] = [
473
474
                        'label' => $tabLabel,
                        'content' => count($code) ? implode(LF, $code) : ''
475
                    ];
476
                    $tabLabel = $this->getLabel(substr($fieldName, 8), '', false);
477
                    $code = [];
478
479
480
481
                }
                continue;
            }
            $label = $this->getLabel($config['label'], $fieldName);
482
            $label = $this->getCSH($config['csh'] ?: $fieldName, $label, $fieldName);
483
484
            $type = $config['type'];
            $class = $config['class'];
485
            if ($type !== 'check' && $type !== 'select') {
486
487
                $class .= ' form-control';
            }
488
489
490
            if ($type === 'select') {
                $class .= ' form-select';
            }
491
            $more = '';
492
            if ($class) {
493
                $more .= ' class="' . htmlspecialchars($class) . '"';
494
            }
495
            $style = $config['style'];
496
            if ($style) {
497
                $more .= ' style="' . htmlspecialchars($style) . '"';
498
499
500
501
            }
            if (isset($this->overrideConf[$fieldName])) {
                $more .= ' disabled="disabled"';
            }
502
            $value = $config['table'] === 'be_users' ? $backendUser->user[$fieldName] : $backendUser->uc[$fieldName];
503
504
505
506
507
508
509
510
511
512
            if (!$value && isset($config['default'])) {
                $value = $config['default'];
            }
            $dataAdd = '';
            if ($config['table'] === 'be_users') {
                $dataAdd = '[be_users]';
            }

            switch ($type) {
                case 'text':
513
                case 'number':
514
515
516
                case 'email':
                case 'password':
                    $noAutocomplete = '';
517
518
519
520
521
522

                    $maxLength = $config['max'] ?? 0;
                    if ((int)$maxLength > 0) {
                        $more .= ' maxlength="' . (int)$maxLength . '"';
                    }

523
524
                    if ($type === 'password') {
                        $value = '';
525
                        $noAutocomplete = 'autocomplete="new-password" ';
526
527
                        $more .= ' data-rsa-encryption=""';
                    }
528
                    $html = '<input aria-labelledby="label_' . htmlspecialchars($fieldName) . '" id="field_' . htmlspecialchars($fieldName) . '"
529
530
                        type="' . htmlspecialchars($type) . '"
                        name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']" ' .
531
532
533
534
535
536
                        $noAutocomplete .
                        'value="' . htmlspecialchars($value) . '" ' .
                        $more .
                        ' />';
                    break;
                case 'check':
537
                    $html = $label . '<div class="checkbox"><label><input id="field_' . htmlspecialchars($fieldName) . '"
538
                        type="checkbox"
539
                        aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
540
                        name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
541
542
543
544
545
546
547
                        ($value ? ' checked="checked"' : '') .
                        $more .
                        ' /></label></div>';
                    $label = '';
                    break;
                case 'select':
                    if ($config['itemsProcFunc']) {
548
                        $html = GeneralUtility::callUserFunction($config['itemsProcFunc'], $config, $this);
549
                    } else {
550
                        $html = '<select id="field_' . htmlspecialchars($fieldName) . '"
551
                            aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
552
                            name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
553
554
                            $more . '>' . LF;
                        foreach ($config['items'] as $key => $optionLabel) {
555
                            $html .= '<option value="' . htmlspecialchars($key) . '"' . ($value == $key ? ' selected="selected"' : '') . '>' . $this->getLabel($optionLabel, '', false) . '</option>' . LF;
556
557
558
559
560
                        }
                        $html .= '</select>';
                    }
                    break;
                case 'user':
561
                    $html = GeneralUtility::callUserFunction($config['userFunc'], $config, $this);
562
563
                    break;
                case 'button':
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                    if (!empty($config['clickData'])) {
                        $clickData = $config['clickData'];
                        $buttonAttributes = [
                            'type' => 'button',
                            'class' => 'btn btn-default',
                            'aria-labelledby' => 'label_' . htmlspecialchars($fieldName),
                            'value' => $this->getLabel($config['buttonlabel'], '', false),
                        ];
                        if (isset($clickData['eventName'])) {
                            $buttonAttributes['data-event'] = 'click';
                            $buttonAttributes['data-event-name'] = htmlspecialchars($clickData['eventName']);
                            $buttonAttributes['data-event-payload'] = htmlspecialchars($fieldName);
                        }
                        $html = '<br><input '
                            . GeneralUtility::implodeAttributes($buttonAttributes, false) . ' />';
                    } elseif (!empty($config['onClick'])) {
                        /**
                         * @deprecated Will be removed in TYPO3 v12.0
                         */
583
584
585
586
587
588
589
590
                        $onClick = $config['onClick'];
                        if ($config['onClickLabels']) {
                            foreach ($config['onClickLabels'] as $key => $labelclick) {
                                $config['onClickLabels'][$key] = $this->getLabel($labelclick, '', false);
                            }
                            $onClick = vsprintf($onClick, $config['onClickLabels']);
                        }
                        $html = '<br><input class="btn btn-default" type="button"
591
                            aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
592
593
                            value="' . $this->getLabel($config['buttonlabel'], '', false) . '"
                            onclick="' . $onClick . '" />';
594
                    }
595
596
                    if (!empty($config['confirm'])) {
                        $confirmData = $config['confirmData'];
597
598
599
600
601
602
                        // cave: values must be processed by `htmlspecialchars()`
                        $buttonAttributes = [
                            'type' => 'button',
                            'class' => 'btn btn-default t3js-modal-trigger',
                            'data-severity' => 'warning',
                            'data-title' => $this->getLabel($config['label'], '', false),
603
                            'data-bs-content' => $this->getLabel($confirmData['message'], '', false),
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
                            'value' => htmlspecialchars($this->getLabel($config['buttonlabel'], '', false)),
                        ];
                        if (isset($confirmData['eventName'])) {
                            $buttonAttributes['data-event'] = 'confirm';
                            $buttonAttributes['data-event-name'] = htmlspecialchars($confirmData['eventName']);
                            $buttonAttributes['data-event-payload'] = htmlspecialchars($fieldName);
                        }
                        if (isset($confirmData['jsCodeAfterOk'])) {
                            /**
                             * @deprecated Will be removed in TYPO3 v12.0
                             */
                            $buttonAttributes['data-href'] = 'javascript:' . htmlspecialchars($confirmData['jsCodeAfterOk']);
                        }
                        $html = '<br><input '
                            . GeneralUtility::implodeAttributes($buttonAttributes, false) . ' />';
619
                    }
620
621
622
623
                    break;
                case 'avatar':
                    // Get current avatar image
                    $html = '<br>';
624
                    $avatarFileUid = $this->getAvatarFileUid($backendUser->user['uid']);
625
626
627

                    if ($avatarFileUid) {
                        $defaultAvatarProvider = GeneralUtility::makeInstance(DefaultAvatarProvider::class);
628
                        $avatarImage = $defaultAvatarProvider->getImage($backendUser->user, 32);
629
630
                        if ($avatarImage) {
                            $icon = '<span class="avatar"><span class="avatar-image">' .
631
                                '<img alt="" src="' . htmlspecialchars($avatarImage->getUrl(true)) . '"' .
632
                                ' width="' . (int)$avatarImage->getWidth() . '" ' .
633
634
635
636
637
638
639
                                'height="' . (int)$avatarImage->getHeight() . '" />' .
                                '</span></span>';
                            $html .= '<span class="pull-left" style="padding-right: 10px" id="image_' . htmlspecialchars($fieldName) . '">' . $icon . ' </span>';
                        }
                    }
                    $html .= '<input id="field_' . htmlspecialchars($fieldName) . '" type="hidden" ' .
                            'name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' . $more .
640
                            ' value="' . (int)$avatarFileUid . '" data-setup-avatar-field="' . htmlspecialchars($fieldName) . '" />';
641
642

                    $html .= '<div class="btn-group">';
643
                    $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
644
                    if ($avatarFileUid) {
645
                        $html .=
646
                            '<button type="button" id="clear_button_' . htmlspecialchars($fieldName) . '" aria-label="' . htmlspecialchars($this->getLanguageService()->getLL('avatar.clear')) . '" '
647
                                . ' class="btn btn-default">'
648
                                . $iconFactory->getIcon('actions-delete', Icon::SIZE_SMALL)
649
                            . '</button>';
650
                    }
651
                    $html .=
652
                        '<button type="button" id="add_button_' . htmlspecialchars($fieldName) . '" class="btn btn-default btn-add-avatar"'
653
                            . ' aria-label="' . htmlspecialchars($this->getLanguageService()->getLL('avatar.openFileBrowser')) . '"'
654
655
                            . ' data-setup-avatar-url="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute('wizard_element_browser', ['mode' => 'file', 'bparams' => '||||__IDENTIFIER__'])) . '"'
                            . '>' . $iconFactory->getIcon('actions-insert-record', Icon::SIZE_SMALL)
656
                            . '</button></div>';
657
658
659
660
661
                    break;
                default:
                    $html = '';
            }

662
            $code[] = '<div class="form-section"><div class="row"><div class="form-group t3js-formengine-field-item col-md-12">' .
663
664
                $label .
                $html .
665
                '</div></div></div>';
666
667
        }

668
        $result[] = [
669
670
            'label' => $tabLabel,
            'content' => count($code) ? implode(LF, $code) : ''
671
        ];
672
673
674
675
        return $result;
    }

    /**
676
677
     * Return a select with available languages.
     * This method is called from the setup module fake TCA userFunc.
678
679
680
     *
     * @return string Complete select as HTML string or warning box if something went wrong.
     */
681
    public function renderLanguageSelect()
682
    {
683
684
        $backendUser = $this->getBackendUser();
        $language = $this->getLanguageService();
685
        $languageOptions = [];
686
        // Compile the languages dropdown
687
688
        $langDefault = htmlspecialchars($language->getLL('lang_default'));
        $languageOptions[$langDefault] = '<option value=""' . ($backendUser->uc['lang'] === '' ? ' selected="selected"' : '') . '>' . $langDefault . '</option>';
689
        if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lang']['availableLanguages'])) {
690
691
692
            // get all labels in default language as well
            $defaultLanguageLabelService = LanguageService::create('default');
            $defaultLanguageLabelService->includeLLFile('EXT:setup/Resources/Private/Language/locallang.xlf');
693
694
695
696
697
698
            // Traverse the number of languages
            $locales = GeneralUtility::makeInstance(Locales::class);
            $languages = $locales->getLanguages();

            foreach ($languages as $locale => $name) {
                if ($locale !== 'default') {
699
                    $defaultName = $defaultLanguageLabelService->getLL('lang_') ?: $name;
700
701
702
703
704
                    $localizedName = htmlspecialchars($language->getLL('lang_' . $locale));
                    if ($localizedName === '') {
                        $localizedName = htmlspecialchars($name);
                    }
                    $localLabel = '  -  [' . htmlspecialchars($defaultName) . ']';
705
                    $available = in_array($locale, $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lang']['availableLanguages'], true) || is_dir(Environment::getLabelsPath() . '/' . $locale);
706
707
708
                    if ($available) {
                        $languageOptions[$defaultName] = '<option value="' . $locale . '"' . ($backendUser->uc['lang'] === $locale ? ' selected="selected"' : '') . '>' . $localizedName . $localLabel . '</option>';
                    }
709
710
711
712
713
                }
            }
        }
        ksort($languageOptions);
        $languageCode = '
714
            <select aria-labelledby="label_lang" id="field_lang" name="data[lang]" class="form-select">' . implode('', $languageOptions) . '
715
            </select>';
716
        if ($backendUser->uc['lang'] && !@is_dir(Environment::getLabelsPath() . '/' . $backendUser->uc['lang'])) {
717
            $languageUnavailableWarning = htmlspecialchars(sprintf($language->getLL('languageUnavailable'), $language->getLL('lang_' . $backendUser->uc['lang']))) . '&nbsp;&nbsp;<br />&nbsp;&nbsp;' . htmlspecialchars($language->getLL('languageUnavailable.' . ($backendUser->isAdmin() ? 'admin' : 'user')));
718
            $languageCode = '<br /><span class="label label-danger">' . $languageUnavailableWarning . '</span><br /><br />' . $languageCode;
719
720
721
722
723
        }
        return $languageCode;
    }

    /**
724
725
     * Returns a select with all modules for startup.
     * This method is called from the setup module fake TCA userFunc.
726
727
728
     *
     * @return string Complete select as HTML string
     */
729
    public function renderStartModuleSelect()
730
    {
731
        // Load available backend modules
732
733
734
        $loadModules = GeneralUtility::makeInstance(ModuleLoader::class);
        $loadModules->observeWorkspaces = true;
        $loadModules->load($GLOBALS['TBE_MODULES']);
735
        $startModuleSelect = '<option value="">' . htmlspecialchars($this->getLanguageService()->getLL('startModule.firstInMenu')) . '</option>';
736
        foreach ($loadModules->modules as $mainMod => $modData) {
737
738
739
            $hasSubmodules = !empty($modData['sub']) && is_array($modData['sub']);
            $isStandalone = $modData['standalone'] ?? false;
            if ($hasSubmodules || $isStandalone) {
740
                $modules = '';
741
742
743
744
745
746
747
748
749
                if (($hasSubmodules)) {
                    foreach ($modData['sub'] as $subData) {
                        $modName = $subData['name'];
                        $modules .= '<option value="' . htmlspecialchars($modName) . '"';
                        $modules .= $this->getBackendUser()->uc['startModule'] === $modName ? ' selected="selected"' : '';
                        $modules .= '>' . htmlspecialchars($this->getLanguageService()->sL($loadModules->getLabelsForModule($modName)['title'])) . '</option>';
                    }
                } elseif ($isStandalone) {
                    $modName = $modData['name'];
750
                    $modules .= '<option value="' . htmlspecialchars($modName) . '"';
751
752
                    $modules .= $this->getBackendUser()->uc['startModule'] === $modName ? ' selected="selected"' : '';
                    $modules .= '>' . htmlspecialchars($this->getLanguageService()->sL($loadModules->getLabelsForModule($modName)['title'])) . '</option>';
753
                }
754
                $groupLabel = htmlspecialchars($this->getLanguageService()->sL($loadModules->getLabelsForModule($mainMod)['title']));
755
756
757
                $startModuleSelect .= '<optgroup label="' . htmlspecialchars($groupLabel) . '">' . $modules . '</optgroup>';
            }
        }
758
        return '<select id="field_startModule" aria-labelledby="label_startModule" name="data[startModule]" class="form-select">' . $startModuleSelect . '</select>';
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
    }

    /**
     * Returns access check (currently only "admin" is supported)
     *
     * @param array $config Configuration of the field, access mode is defined in key 'access'
     * @return bool Whether it is allowed to modify the given field
     */
    protected function checkAccess(array $config)
    {
        $access = $config['access'];
        if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['setup']['accessLevelCheck'][$access])) {
            if (class_exists($access)) {
                $accessObject = GeneralUtility::makeInstance($access);
                if (method_exists($accessObject, 'accessLevelCheck')) {
                    // Initialize vars. If method fails, $set will be set to FALSE
                    return $accessObject->accessLevelCheck($config);
                }
            }
778
        } elseif ($access === 'admin') {
779
            return $this->getBackendUser()->isAdmin();
780
781
782
783
784
785
786
787
788
789
790
791
792
        }

        return false;
    }

    /**
     * Returns the label $str from getLL() and grays out the value if the $str/$key is found in $this->overrideConf array
     *
     * @param string $str Locallang key
     * @param string $key Alternative override-config key
     * @param bool $addLabelTag Defines whether the string should be wrapped in a <label> tag.
     * @return string HTML output.
     */
793
    protected function getLabel($str, $key = '', $addLabelTag = true)
794
    {
795
        if (strpos($str, 'LLL:') === 0) {
796
            $out = htmlspecialchars($this->getLanguageService()->sL($str));
797
798
799
800
801
802
803
        } else {
            $out = htmlspecialchars($str);
        }
        if (isset($this->overrideConf[$key ?: $str])) {
            $out = '<span style="color:#999999">' . $out . '</span>';
        }
        if ($addLabelTag) {
804
            $out = '<label>' . $out . '</label>';
805
806
807
808
809
810
811
812
813
        }
        return $out;
    }

    /**
     * Returns the CSH Icon for given string
     *
     * @param string $str Locallang key
     * @param string $label The label to be used, that should be wrapped in help
814
     * @param string $fieldName field name
815
816
     * @return string HTML output.
     */
817
    protected function getCSH($str, $label, $fieldName)
818
819
820
821
822
823
824
825
    {
        $context = '_MOD_user_setup';
        $field = $str;
        $strParts = explode(':', $str);
        if (count($strParts) > 1) {
            // Setting comes from another extension
            $context = $strParts[0];
            $field = $strParts[1];
826
        } elseif ($str !== 'language' && $str !== 'reset') {
827
828
            $field = 'option_' . $str;
        }
829
        return '<span id="label_' . htmlspecialchars($fieldName) . '">' . BackendUtility::wrapInHelp($context, $field, $label) . '</span>';
830
831
832
833
    }

    /**
     * Returns array with fields defined in $GLOBALS['TYPO3_USER_SETTINGS']['showitem']
834
     * Remove fields which are disabled by user TSconfig
835
     *
836
     * @return string[] Array with field names visible in form
837
838
839
     */
    protected function getFieldsFromShowItem()
    {
840
        $allowedFields = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_USER_SETTINGS']['showitem'], true);
841
        if ($this->getBackendUser()->isAdmin()) {
842
            // Do not ask for current password if admin (unknown for other users and no security gain)
843
844
845
846
847
            $key = array_search('passwordCurrent', $allowedFields);
            if ($key !== false) {
                unset($allowedFields[$key]);
            }
        }
848
849
850

        $backendUser = $this->getBackendUser();
        $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
851
        if ($backendUser->getOriginalUserIdWhenInSwitchUserMode() && in_array((int)$backendUser->user['uid'], $systemMaintainers, true)) {
852
853
854
855
856
857
858
859
860
861
862
863
            // DataHandler denies changing password of system maintainer users in switch user mode.
            // Do not show the password fields is this case.
            $key = array_search('password', $allowedFields);
            if ($key !== false) {
                unset($allowedFields[$key]);
            }
            $key = array_search('password2', $allowedFields);
            if ($key !== false) {
                unset($allowedFields[$key]);
            }
        }

864
865
866
        if (!is_array($this->tsFieldConf)) {
            return $allowedFields;
        }
867
868
869
870
871
872
873
874
875
876
        foreach ($this->tsFieldConf as $fieldName => $userTsFieldConfig) {
            if (!empty($userTsFieldConfig['disabled'])) {
                $fieldName = rtrim($fieldName, '.');
                $key = array_search($fieldName, $allowedFields);
                if ($key !== false) {
                    unset($allowedFields[$key]);
                }
            }
        }
        return $allowedFields;
877
878
879
880
881
882
883
884
885
886
    }

    /**
     * Get Avatar fileUid
     *
     * @param int $beUserId
     * @return int
     */
    protected function getAvatarFileUid($beUserId)
    {
887
888
889
890
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
        $file = $queryBuilder
            ->select('uid_local')
            ->from('sys_file_reference')
891
            ->where(
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
                $queryBuilder->expr()->eq(
                    'tablenames',
                    $queryBuilder->createNamedParameter('be_users', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'fieldname',
                    $queryBuilder->createNamedParameter('avatar', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'table_local',
                    $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'uid_foreign',
                    $queryBuilder->createNamedParameter($beUserId, \PDO::PARAM_INT)
                )
908
            )
909
910
911
            ->execute()
            ->fetchColumn();
        return (int)$file;
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    }

    /**
     * Set avatar fileUid for backend user
     *
     * @param int $beUserId
     * @param int $fileUid
     * @param array $storeRec
     */
    protected function setAvatarFileUid($beUserId, $fileUid, array &$storeRec)
    {

        // Update is only needed when new fileUid is set
        if ((int)$fileUid === $this->getAvatarFileUid($beUserId)) {
            return;
        }

929
930
931
932
933
        // If user is not allowed to modify avatar $fileUid is empty - so don't overwrite existing avatar
        if (empty($fileUid)) {
            return;
        }

934
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
935
        $queryBuilder->getRestrictions()->removeAll();
936
937
        $queryBuilder
            ->delete('sys_file_reference')
938
            ->where(
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
                $queryBuilder->expr()->eq(
                    'tablenames',
                    $queryBuilder->createNamedParameter('be_users', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'fieldname',
                    $queryBuilder->createNamedParameter('avatar', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'table_local',
                    $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
                ),
                $queryBuilder->expr()->eq(
                    'uid_foreign',
                    $queryBuilder->createNamedParameter($beUserId, \PDO::PARAM_INT)
                )
955
            )
956
            ->execute();
957

958
959
960
961
962
        // If Avatar is marked for delete => set it to empty string so it will be updated properly
        if ($fileUid === 'delete') {
            $fileUid = '';
        }

963
964
965
966
967
        // Create new reference
        if ($fileUid) {

            // Get file object
            try {
968
                $file = GeneralUtility::makeInstance(ResourceFactory::class)->getFileObject($fileUid);
969
970
971
972
973
            } catch (FileDoesNotExistException $e) {
                $file = false;
            }

            // Check if user is allowed to use the image (only when not in simulation mode)
974
            if ($file && !$file->getStorage()->checkFileActionPermission('read', $file)) {
975
976
977
978
                $file = false;
            }

            // Check if extension is allowed
979
            if ($file && $file->isImage()) {
980
981

                // Create new file reference
982
                $storeRec['sys_file_reference']['NEW1234'] = [
983
984
                    'uid_local' => (int)$fileUid,
                    'uid_foreign' => (int)$beUserId,
985
986
987
988
                    'tablenames' => 'be_users',
                    'fieldname' => 'avatar',
                    'pid' => 0,
                    'table_local' => 'sys_file',
989
                ];
990
991
992
993
994
995
996
997
                $storeRec['be_users'][(int)$beUserId]['avatar'] = 'NEW1234';
            }
        }
    }

    /**
     * Returns the current BE user.
     *
998
     * @return BackendUserAuthentication