SetupModuleController.php 47.4 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
436
437
            ->setArguments([
                'route' => $route,
            ]);
438
        $buttonBar->addButton($shortcutButton);
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
    }

    /******************************
     *
     * 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()
    {
455
        $backendUser = $this->getBackendUser();
456
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
457
        $html = '';
458
        $result = [];
459
        $firstTabLabel = '';
460
        $code = [];
461
462
463
        $fieldArray = $this->getFieldsFromShowItem();
        $tabLabel = '';
        foreach ($fieldArray as $fieldName) {
464
465
466
467
468
            $config = $GLOBALS['TYPO3_USER_SETTINGS']['columns'][$fieldName];
            if (isset($config['access']) && !$this->checkAccess($config)) {
                continue;
            }

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

            switch ($type) {
                case 'text':
516
                case 'number':
517
518
519
                case 'email':
                case 'password':
                    $noAutocomplete = '';
520
521
522
523
524
525

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

526
527
                    if ($type === 'password') {
                        $value = '';
528
                        $noAutocomplete = 'autocomplete="new-password" ';
529
530
                        $more .= ' data-rsa-encryption=""';
                    }
531
                    $html = '<input aria-labelledby="label_' . htmlspecialchars($fieldName) . '" id="field_' . htmlspecialchars($fieldName) . '"
532
533
                        type="' . htmlspecialchars($type) . '"
                        name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']" ' .
534
535
536
537
538
539
                        $noAutocomplete .
                        'value="' . htmlspecialchars($value) . '" ' .
                        $more .
                        ' />';
                    break;
                case 'check':
540
                    $html = $label . '<div class="checkbox"><label><input id="field_' . htmlspecialchars($fieldName) . '"
541
                        type="checkbox"
542
                        aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
543
                        name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
544
545
546
547
548
549
550
                        ($value ? ' checked="checked"' : '') .
                        $more .
                        ' /></label></div>';
                    $label = '';
                    break;
                case 'select':
                    if ($config['itemsProcFunc']) {
551
                        $html = GeneralUtility::callUserFunction($config['itemsProcFunc'], $config, $this);
552
                    } else {
553
                        $html = '<select id="field_' . htmlspecialchars($fieldName) . '"
554
                            aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
555
                            name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
556
557
                            $more . '>' . LF;
                        foreach ($config['items'] as $key => $optionLabel) {
558
                            $html .= '<option value="' . htmlspecialchars($key) . '"' . ($value == $key ? ' selected="selected"' : '') . '>' . $this->getLabel($optionLabel, '', false) . '</option>' . LF;
559
560
561
562
563
                        }
                        $html .= '</select>';
                    }
                    break;
                case 'user':
564
                    $html = GeneralUtility::callUserFunction($config['userFunc'], $config, $this);
565
566
                    break;
                case 'button':
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
                    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
                         */
586
587
588
589
590
591
592
593
                        $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"
594
                            aria-labelledby="label_' . htmlspecialchars($fieldName) . '"
595
596
                            value="' . $this->getLabel($config['buttonlabel'], '', false) . '"
                            onclick="' . $onClick . '" />';
597
                    }
598
599
                    if (!empty($config['confirm'])) {
                        $confirmData = $config['confirmData'];
600
601
602
603
604
605
                        // 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),
606
                            'data-bs-content' => $this->getLabel($confirmData['message'], '', false),
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
                            '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) . ' />';
622
                    }
623
624
625
626
                    break;
                case 'avatar':
                    // Get current avatar image
                    $html = '<br>';
627
                    $avatarFileUid = $this->getAvatarFileUid($backendUser->user['uid']);
628
629
630

                    if ($avatarFileUid) {
                        $defaultAvatarProvider = GeneralUtility::makeInstance(DefaultAvatarProvider::class);
631
                        $avatarImage = $defaultAvatarProvider->getImage($backendUser->user, 32);
632
633
                        if ($avatarImage) {
                            $icon = '<span class="avatar"><span class="avatar-image">' .
634
                                '<img alt="" src="' . htmlspecialchars($avatarImage->getUrl(true)) . '"' .
635
                                ' width="' . (int)$avatarImage->getWidth() . '" ' .
636
637
638
639
640
641
642
                                '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 .
643
                            ' value="' . (int)$avatarFileUid . '" data-setup-avatar-field="' . htmlspecialchars($fieldName) . '" />';
644
645

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

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

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

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

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

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

    /**
     * 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);
                }
            }
781
        } elseif ($access === 'admin') {
782
            return $this->getBackendUser()->isAdmin();
783
784
785
786
787
788
789
790
791
792
793
794
795
        }

        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.
     */
796
    protected function getLabel($str, $key = '', $addLabelTag = true)
797
    {
798
        if (strpos($str, 'LLL:') === 0) {
799
            $out = htmlspecialchars($this->getLanguageService()->sL($str));
800
801
802
803
804
805
806
        } else {
            $out = htmlspecialchars($str);
        }
        if (isset($this->overrideConf[$key ?: $str])) {
            $out = '<span style="color:#999999">' . $out . '</span>';
        }
        if ($addLabelTag) {
807
            $out = '<label>' . $out . '</label>';
808
809
810
811
812
813
814
815
816
        }
        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
817
     * @param string $fieldName field name
818
819
     * @return string HTML output.
     */
820
    protected function getCSH($str, $label, $fieldName)
821
822
823
824
825
826
827
828
    {
        $context = '_MOD_user_setup';
        $field = $str;
        $strParts = explode(':', $str);
        if (count($strParts) > 1) {
            // Setting comes from another extension
            $context = $strParts[0];
            $field = $strParts[1];
829
        } elseif ($str !== 'language' && $str !== 'reset') {
830
831
            $field = 'option_' . $str;
        }
832
        return '<span id="label_' . htmlspecialchars($fieldName) . '">' . BackendUtility::wrapInHelp($context, $field, $label) . '</span>';
833
834
835
836
    }

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

        $backendUser = $this->getBackendUser();
        $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ?? []);
854
        if ($backendUser->getOriginalUserIdWhenInSwitchUserMode() && in_array((int)$backendUser->user['uid'], $systemMaintainers, true)) {
855
856
857
858
859
860
861
862
863
864
865
866
            // 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]);
            }
        }

867
868
869
        if (!is_array($this->tsFieldConf)) {
            return $allowedFields;
        }
870
871
872
873
874
875
876
877
878
879
        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;
880
881
882
883
884
885
886
887
888
889
    }

    /**
     * Get Avatar fileUid
     *
     * @param int $beUserId
     * @return int
     */
    protected function getAvatarFileUid($beUserId)
    {
890
891
892
893
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
        $file = $queryBuilder
            ->select('uid_local')
            ->from('sys_file_reference')
894
            ->where(
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
                $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)
                )
911
            )
912
913
914
            ->execute()
            ->fetchColumn();
        return (int)$file;
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
    }

    /**
     * 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;
        }

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

937
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
938
        $queryBuilder->getRestrictions()->removeAll();
939
940
        $queryBuilder
            ->delete('sys_file_reference')
941
            ->where(
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
                $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)
                )
958
            )
959
            ->execute();
960

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

966
967
968
969
970
        // Create new reference
        if ($fileUid) {

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

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

            // Check if extension is allowed
982
            if ($file && $file->isImage()) {
983
984

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

    /**
     * Returns the current BE user.
     *
1001
     * @return BackendUserAuthentication
1002
1003
1004
1005
1006
1007
1008
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }

    /**
1009
     * @return LanguageService
1010
1011
1012
1013
1014
1015
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064