[BUGFIX] Do not override global BE_USER for user settings simulation
[Packages/TYPO3.CMS.git] / typo3 / sysext / setup / Classes / Controller / SetupModuleController.php
1 <?php
2 namespace TYPO3\CMS\Setup\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Backend\Avatar\DefaultAvatarProvider;
20 use TYPO3\CMS\Backend\Module\AbstractModule;
21 use TYPO3\CMS\Backend\Module\ModuleLoader;
22 use TYPO3\CMS\Backend\Utility\BackendUtility;
23 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
24 use TYPO3\CMS\Core\Database\ConnectionPool;
25 use TYPO3\CMS\Core\DataHandling\DataHandler;
26 use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
27 use TYPO3\CMS\Core\Imaging\Icon;
28 use TYPO3\CMS\Core\Imaging\IconFactory;
29 use TYPO3\CMS\Core\Messaging\FlashMessage;
30 use TYPO3\CMS\Core\Messaging\FlashMessageService;
31 use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
32 use TYPO3\CMS\Core\Resource\ResourceFactory;
33 use TYPO3\CMS\Core\Utility\GeneralUtility;
34
35 /**
36 * Script class for the Setup module
37 */
38 class SetupModuleController extends AbstractModule
39 {
40 /**
41 * Flag if password has not been updated
42 */
43 const PASSWORD_NOT_UPDATED = 0;
44
45 /**
46 * Flag if password has been updated
47 */
48 const PASSWORD_UPDATED = 1;
49
50 /**
51 * Flag if both new passwords do not match
52 */
53 const PASSWORD_NOT_THE_SAME = 2;
54
55 /**
56 * Flag if the current password given was not identical to the real
57 * current password
58 */
59 const PASSWORD_OLD_WRONG = 3;
60
61 /**
62 * @var array
63 */
64 public $MOD_MENU = [];
65
66 /**
67 * @var array
68 */
69 public $MOD_SETTINGS = [];
70
71 /**
72 * @var string
73 */
74 public $content;
75
76 /**
77 * @var array
78 */
79 public $overrideConf;
80
81 /**
82 * backend user object, set during simulate-user operation
83 *
84 * @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
85 */
86 public $OLD_BE_USER;
87
88 /**
89 * @var bool
90 */
91 public $languageUpdate;
92
93 /**
94 * @var bool
95 */
96 protected $pagetreeNeedsRefresh = false;
97
98 /**
99 * @var bool
100 */
101 protected $isAdmin;
102
103 /**
104 * @var array
105 */
106 protected $tsFieldConf;
107
108 /**
109 * @var bool
110 */
111 protected $saveData = false;
112
113 /**
114 * @var int
115 */
116 protected $passwordIsUpdated = self::PASSWORD_NOT_UPDATED;
117
118 /**
119 * @var bool
120 */
121 protected $passwordIsSubmitted = false;
122
123 /**
124 * @var bool
125 */
126 protected $setupIsUpdated = false;
127
128 /**
129 * @var bool
130 */
131 protected $settingsAreResetToDefault = false;
132
133 /**
134 * Form protection instance
135 *
136 * @var \TYPO3\CMS\Core\FormProtection\BackendFormProtection
137 */
138 protected $formProtection;
139
140 /**
141 * @var string
142 */
143 protected $simulateSelector = '';
144
145 /**
146 * @var int
147 */
148 protected $simUser;
149
150 /**
151 * The name of the module
152 *
153 * @var string
154 */
155 protected $moduleName = 'user_setup';
156
157 /**
158 * @var ModuleLoader
159 */
160 protected $loadModules;
161
162 /**
163 * @var BackendUserAuthentication
164 */
165 protected $beUser;
166
167 /**
168 * Instantiate the form protection before a simulated user is initialized.
169 */
170 public function __construct()
171 {
172 parent::__construct();
173 $this->formProtection = FormProtectionFactory::get();
174 $pageRenderer = $this->moduleTemplate->getPageRenderer();
175 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
176 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/FormEngine');
177 $pageRenderer->addInlineSetting('FormEngine', 'formName', 'editform');
178 $pageRenderer->addInlineLanguageLabelArray([
179 'FormEngine.remainingCharacters' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.remainingCharacters',
180 ], true);
181 }
182
183 /**
184 * Getter for the form protection instance.
185 *
186 * @return \TYPO3\CMS\Core\FormProtection\BackendFormProtection
187 */
188 public function getFormProtection()
189 {
190 return $this->formProtection;
191 }
192
193 /**
194 * If settings are submitted to _POST[DATA], store them
195 * NOTICE: This method is called before the \TYPO3\CMS\Backend\Template\ModuleTemplate
196 * is included. See bottom of document.
197 */
198 public function storeIncomingData()
199 {
200 // First check if something is submitted in the data-array from POST vars
201 $d = GeneralUtility::_POST('data');
202 $columns = $GLOBALS['TYPO3_USER_SETTINGS']['columns'];
203 $beUserId = $this->beUser->user['uid'];
204 $storeRec = [];
205 $fieldList = $this->getFieldsFromShowItem();
206 if (is_array($d) && $this->formProtection->validateToken((string)GeneralUtility::_POST('formToken'), 'BE user setup', 'edit')) {
207 // UC hashed before applying changes
208 $save_before = md5(serialize($this->beUser->uc));
209 // PUT SETTINGS into the ->uc array:
210 // Reload left frame when switching BE language
211 if (isset($d['lang']) && $d['lang'] != $this->beUser->uc['lang']) {
212 $this->languageUpdate = true;
213 }
214 // Reload pagetree if the title length is changed
215 if (isset($d['titleLen']) && $d['titleLen'] !== $this->beUser->uc['titleLen']) {
216 $this->pagetreeNeedsRefresh = true;
217 }
218 if ($d['setValuesToDefault']) {
219 // If every value should be default
220 $this->beUser->resetUC();
221 $this->settingsAreResetToDefault = true;
222 } elseif ($d['save']) {
223 // Save all submitted values if they are no array (arrays are with table=be_users) and exists in $GLOBALS['TYPO3_USER_SETTINGS'][columns]
224 foreach ($columns as $field => $config) {
225 if (!in_array($field, $fieldList)) {
226 continue;
227 }
228 if ($config['table']) {
229 if ($config['table'] === 'be_users' && !in_array($field, ['password', 'password2', 'passwordCurrent', 'email', 'realName', 'admin', 'avatar'])) {
230 if (!isset($config['access']) || $this->checkAccess($config) && $this->beUser->user[$field] !== $d['be_users'][$field]) {
231 if ($config['type'] === 'check') {
232 $fieldValue = isset($d['be_users'][$field]) ? 1 : 0;
233 } else {
234 $fieldValue = $d['be_users'][$field];
235 }
236 $storeRec['be_users'][$beUserId][$field] = $fieldValue;
237 $this->beUser->user[$field] = $fieldValue;
238 }
239 }
240 }
241 if ($config['type'] === 'check') {
242 $this->beUser->uc[$field] = isset($d[$field]) ? 1 : 0;
243 } else {
244 $this->beUser->uc[$field] = htmlspecialchars($d[$field]);
245 }
246 }
247 // Personal data for the users be_user-record (email, name, password...)
248 // If email and name is changed, set it in the users record:
249 $be_user_data = $d['be_users'];
250 // Possibility to modify the transmitted values. Useful to do transformations, like RSA password decryption
251 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['modifyUserDataBeforeSave'])) {
252 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['modifyUserDataBeforeSave'] as $function) {
253 $params = ['be_user_data' => &$be_user_data];
254 GeneralUtility::callUserFunction($function, $params, $this);
255 }
256 }
257 $this->passwordIsSubmitted = (string)$be_user_data['password'] !== '';
258 $passwordIsConfirmed = $this->passwordIsSubmitted && $be_user_data['password'] === $be_user_data['password2'];
259 // Update the real name:
260 if ($be_user_data['realName'] !== $this->beUser->user['realName']) {
261 $this->beUser->user['realName'] = ($storeRec['be_users'][$beUserId]['realName'] = substr($be_user_data['realName'], 0, 80));
262 }
263 // Update the email address:
264 if ($be_user_data['email'] !== $this->beUser->user['email']) {
265 $this->beUser->user['email'] = ($storeRec['be_users'][$beUserId]['email'] = substr($be_user_data['email'], 0, 80));
266 }
267 // Update the password:
268 if ($passwordIsConfirmed) {
269 $currentPasswordHashed = $GLOBALS['BE_USER']->user['password'];
270 $saltFactory = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance($currentPasswordHashed);
271 if ($saltFactory->checkPassword($be_user_data['passwordCurrent'], $currentPasswordHashed)) {
272 $this->passwordIsUpdated = self::PASSWORD_UPDATED;
273 $storeRec['be_users'][$beUserId]['password'] = $be_user_data['password'];
274 } else {
275 $this->passwordIsUpdated = self::PASSWORD_OLD_WRONG;
276 }
277 } else {
278 $this->passwordIsUpdated = self::PASSWORD_NOT_THE_SAME;
279 }
280
281 $this->setAvatarFileUid($beUserId, $be_user_data['avatar'], $storeRec);
282
283 $this->saveData = true;
284 }
285 // Inserts the overriding values.
286 $this->beUser->overrideUC();
287 $save_after = md5(serialize($this->beUser->uc));
288 // If something in the uc-array of the user has changed, we save the array...
289 if ($save_before != $save_after) {
290 $this->beUser->writeUC($this->beUser->uc);
291 $this->beUser->writelog(254, 1, 0, 1, 'Personal settings changed', []);
292 $this->setupIsUpdated = true;
293 }
294 // Persist data if something has changed:
295 if (!empty($storeRec) && $this->saveData) {
296 // Make instance of TCE for storing the changes.
297 /** @var DataHandler $dataHandler */
298 $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
299 // This is so the user can actually update his user record.
300 $isAdmin = $this->beUser->user['admin'];
301 $this->beUser->user['admin'] = 1;
302 $dataHandler->start($storeRec, [], $this->beUser);
303 // This is to make sure that the users record can be updated even if in another workspace. This is tolerated.
304 $dataHandler->bypassWorkspaceRestrictions = true;
305 $dataHandler->process_datamap();
306 unset($tce);
307 if ($this->passwordIsUpdated === self::PASSWORD_NOT_UPDATED || count($storeRec['be_users'][$beUserId]) > 1) {
308 $this->setupIsUpdated = true;
309 }
310 // Restore admin status after processing
311 $this->beUser->user['admin'] = $isAdmin;
312
313 BackendUtility::setUpdateSignal('updateTopbar');
314 }
315 }
316 }
317
318 /******************************
319 *
320 * Rendering module
321 *
322 ******************************/
323 /**
324 * Initializes the module for display of the settings form.
325 */
326 public function init()
327 {
328 $this->getLanguageService()->includeLLFile('EXT:setup/Resources/Private/Language/locallang.xlf');
329
330 // Returns the script user - that is the REAL logged in user! ($GLOBALS[BE_USER] might be another user due to simulation!)
331 $scriptUser = $this->getRealScriptUserObj();
332
333 $this->isAdmin = $scriptUser->isAdmin();
334 // Getting the 'override' values as set might be set in User TSconfig
335 $this->overrideConf = $this->beUser->getTSConfigProp('setup.override');
336 // Getting the disabled fields might be set in User TSconfig (eg setup.fields.password.disabled=1)
337 $this->tsFieldConf = $this->beUser->getTSConfigProp('setup.fields');
338 // id password is disabled, disable repeat of password too (password2)
339 if (isset($this->tsFieldConf['password.']) && $this->tsFieldConf['password.']['disabled']) {
340 $this->tsFieldConf['password2.']['disabled'] = 1;
341 $this->tsFieldConf['passwordCurrent.']['disabled'] = 1;
342 }
343 }
344
345 /**
346 * Generate necessary JavaScript
347 *
348 * @return string
349 */
350 protected function getJavaScript()
351 {
352 $javaScript = '';
353 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['setupScriptHook'])) {
354 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['setupScriptHook'] as $function) {
355 $params = [];
356 $javaScript .= GeneralUtility::callUserFunction($function, $params, $this);
357 }
358 }
359 return $javaScript;
360 }
361
362 /**
363 * Generate the main settings form:
364 */
365 public function main()
366 {
367 $this->content .= '<form action="' . BackendUtility::getModuleUrl('user_setup') . '" method="post" id="SetupModuleController" name="usersetup" enctype="multipart/form-data">';
368 if ($this->languageUpdate) {
369 $this->moduleTemplate->addJavaScriptCode('languageUpdate', '
370 if (top && top.TYPO3.ModuleMenu.App) {
371 top.TYPO3.ModuleMenu.App.refreshMenu();
372 }
373 ');
374 }
375 if ($this->pagetreeNeedsRefresh) {
376 BackendUtility::setUpdateSignal('updatePageTree');
377 }
378 // Start page:
379 $this->moduleTemplate->getPageRenderer()->addJsFile('EXT:backend/Resources/Public/JavaScript/md5.js');
380 // Use a wrapper div
381 $this->content .= '<div id="user-setup-wrapper">';
382 // Load available backend modules
383 $this->loadModules = GeneralUtility::makeInstance(ModuleLoader::class);
384 $this->loadModules->observeWorkspaces = true;
385 $this->loadModules->load($GLOBALS['TBE_MODULES']);
386 $this->content .= $this->moduleTemplate->header($this->getLanguageService()->getLL('UserSettings'));
387 $this->addFlashMessages();
388
389 // Render user switch
390 $this->content .= $this->renderSimulateUserSelectAndLabel();
391
392 // Render the menu items
393 $menuItems = $this->renderUserSetup();
394 $this->content .= $this->moduleTemplate->getDynamicTabMenu($menuItems, 'user-setup', 1, false, false);
395 $formToken = $this->formProtection->generateToken('BE user setup', 'edit');
396 $this->content .= '<div>';
397 $this->content .= '<input type="hidden" name="simUser" value="' . (int)$this->simUser . '" />
398 <input type="hidden" name="formToken" value="' . htmlspecialchars($formToken) . '" />
399 <input type="hidden" value="1" name="data[save]" />
400 <input type="hidden" name="data[setValuesToDefault]" value="0" id="setValuesToDefault" />';
401 $this->content .= '</div>';
402 // End of wrapper div
403 $this->content .= '</div>';
404 // Setting up the buttons and markers for docheader
405 $this->getButtons();
406 // Build the <body> for the module
407 // Renders the module page
408 $this->moduleTemplate->setContent($this->content);
409 $this->content .= '</form>';
410 }
411
412 /**
413 * Injects the request object for the current request or subrequest
414 * Simply calls main() and init() and writes the content to the response
415 *
416 * @param ServerRequestInterface $request the current request
417 * @param ResponseInterface $response
418 * @return ResponseInterface the response with the content
419 */
420 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
421 {
422 $GLOBALS['SOBE'] = $this;
423 $this->simulateUser();
424 $this->init();
425 $this->storeIncomingData();
426 $this->main();
427
428 $response->getBody()->write($this->moduleTemplate->renderContent());
429 return $response;
430 }
431
432 /**
433 * Create the panel of buttons for submitting the form or otherwise perform operations.
434 */
435 protected function getButtons()
436 {
437 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
438 $cshButton = $buttonBar->makeHelpButton()
439 ->setModuleName('_MOD_user_setup')
440 ->setFieldName('');
441 $buttonBar->addButton($cshButton);
442
443 $saveButton = $buttonBar->makeInputButton()
444 ->setName('data[save]')
445 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
446 ->setValue('1')
447 ->setForm('SetupModuleController')
448 ->setShowLabelText(true)
449 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL));
450
451 $buttonBar->addButton($saveButton);
452 $shortcutButton = $buttonBar->makeShortcutButton()
453 ->setModuleName($this->moduleName);
454 $buttonBar->addButton($shortcutButton);
455 }
456
457 /******************************
458 *
459 * Render module
460 *
461 ******************************/
462
463 /**
464 * renders the data for all tabs in the user setup and returns
465 * everything that is needed with tabs and dyntab menu
466 *
467 * @return array Ready to use for the dyntabmenu itemarray
468 */
469 protected function renderUserSetup()
470 {
471 $html = '';
472 $result = [];
473 $firstTabLabel = '';
474 $code = [];
475 $fieldArray = $this->getFieldsFromShowItem();
476 $tabLabel = '';
477 foreach ($fieldArray as $fieldName) {
478 $config = $GLOBALS['TYPO3_USER_SETTINGS']['columns'][$fieldName];
479 if (isset($config['access']) && !$this->checkAccess($config)) {
480 continue;
481 }
482
483 if (substr($fieldName, 0, 8) === '--div--;') {
484 if ($firstTabLabel === '') {
485 // First tab
486 $tabLabel = $this->getLabel(substr($fieldName, 8), '', false);
487 $firstTabLabel = $tabLabel;
488 } else {
489 $result[] = [
490 'label' => $tabLabel,
491 'content' => count($code) ? implode(LF, $code) : ''
492 ];
493 $tabLabel = $this->getLabel(substr($fieldName, 8), '', false);
494 $code = [];
495 }
496 continue;
497 }
498 $label = $this->getLabel($config['label'], $fieldName);
499 $label = $this->getCSH($config['csh'] ?: $fieldName, $label);
500 $type = $config['type'];
501 $class = $config['class'];
502 if ($type !== 'check') {
503 $class .= ' form-control';
504 }
505 $more = '';
506 if ($class) {
507 $more .= ' class="' . htmlspecialchars($class) . '"';
508 }
509 $style = $config['style'];
510 if ($style) {
511 $more .= ' style="' . htmlspecialchars($style) . '"';
512 }
513 if (isset($this->overrideConf[$fieldName])) {
514 $more .= ' disabled="disabled"';
515 }
516 $value = $config['table'] === 'be_users' ? $this->beUser->user[$fieldName] : $this->beUser->uc[$fieldName];
517 if (!$value && isset($config['default'])) {
518 $value = $config['default'];
519 }
520 $dataAdd = '';
521 if ($config['table'] === 'be_users') {
522 $dataAdd = '[be_users]';
523 }
524
525 switch ($type) {
526 case 'text':
527 case 'email':
528 case 'password':
529 $noAutocomplete = '';
530
531 $maxLength = $config['max'] ?? 0;
532 if ((int)$maxLength > 0) {
533 $more .= ' maxlength="' . (int)$maxLength . '"';
534 }
535
536 if ($type === 'password') {
537 $value = '';
538 $noAutocomplete = 'autocomplete="off" ';
539 $more .= ' data-rsa-encryption=""';
540 }
541 $html = '<input id="field_' . htmlspecialchars($fieldName) . '"
542 type="' . htmlspecialchars($type) . '"
543 name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']" ' .
544 $noAutocomplete .
545 'value="' . htmlspecialchars($value) . '" ' .
546 $more .
547 ' />';
548 break;
549 case 'check':
550 $html = $label . '<div class="checkbox"><label><input id="field_' . htmlspecialchars($fieldName) . '"
551 type="checkbox"
552 name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
553 ($value ? ' checked="checked"' : '') .
554 $more .
555 ' /></label></div>';
556 $label = '';
557 break;
558 case 'select':
559 if ($config['itemsProcFunc']) {
560 $html = GeneralUtility::callUserFunction($config['itemsProcFunc'], $config, $this);
561 } else {
562 $html = '<select id="field_' . htmlspecialchars($fieldName) . '"
563 name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' .
564 $more . '>' . LF;
565 foreach ($config['items'] as $key => $optionLabel) {
566 $html .= '<option value="' . htmlspecialchars($key) . '"' . ($value == $key ? ' selected="selected"' : '') . '>' . $this->getLabel($optionLabel, '', false) . '</option>' . LF;
567 }
568 $html .= '</select>';
569 }
570 break;
571 case 'user':
572 $html = GeneralUtility::callUserFunction($config['userFunc'], $config, $this);
573 break;
574 case 'button':
575 if ($config['onClick']) {
576 $onClick = $config['onClick'];
577 if ($config['onClickLabels']) {
578 foreach ($config['onClickLabels'] as $key => $labelclick) {
579 $config['onClickLabels'][$key] = $this->getLabel($labelclick, '', false);
580 }
581 $onClick = vsprintf($onClick, $config['onClickLabels']);
582 }
583 $html = '<br><input class="btn btn-default" type="button"
584 value="' . $this->getLabel($config['buttonlabel'], '', false) . '"
585 onclick="' . $onClick . '" />';
586 }
587 if (!empty($config['confirm'])) {
588 $confirmData = $config['confirmData'];
589 $html = '<br><input class="btn btn-default t3js-modal-trigger" type="button"'
590 . ' value="' . $this->getLabel($config['buttonlabel'], '', false) . '"'
591 . ' data-href="javascript:' . htmlspecialchars($confirmData['jsCodeAfterOk']) . '"'
592 . ' data-severity="warning"'
593 . ' data-title="' . $this->getLabel($config['label'], '', false) . '"'
594 . ' data-content="' . $this->getLabel($confirmData['message'], '', false) . '" />';
595 }
596 break;
597 case 'avatar':
598 // Get current avatar image
599 $html = '<br>';
600 $avatarFileUid = $this->getAvatarFileUid($this->beUser->user['uid']);
601
602 if ($avatarFileUid) {
603 $defaultAvatarProvider = GeneralUtility::makeInstance(DefaultAvatarProvider::class);
604 $avatarImage = $defaultAvatarProvider->getImage($this->beUser->user, 32);
605 if ($avatarImage) {
606 $icon = '<span class="avatar"><span class="avatar-image">' .
607 '<img src="' . htmlspecialchars($avatarImage->getUrl(true)) . '"' .
608 ' width="' . (int)$avatarImage->getWidth() . '" ' .
609 'height="' . (int)$avatarImage->getHeight() . '" />' .
610 '</span></span>';
611 $html .= '<span class="pull-left" style="padding-right: 10px" id="image_' . htmlspecialchars($fieldName) . '">' . $icon . ' </span>';
612 }
613 }
614 $html .= '<input id="field_' . htmlspecialchars($fieldName) . '" type="hidden" ' .
615 'name="data' . $dataAdd . '[' . htmlspecialchars($fieldName) . ']"' . $more .
616 ' value="' . (int)$avatarFileUid . '" />';
617
618 $html .= '<div class="btn-group">';
619 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
620 if ($avatarFileUid) {
621 $html .=
622 '<a id="clear_button_' . htmlspecialchars($fieldName) . '" '
623 . 'onclick="clearExistingImage(); return false;" class="btn btn-default">'
624 . $iconFactory->getIcon('actions-delete', Icon::SIZE_SMALL)
625 . '</a>';
626 }
627 $html .=
628 '<a id="add_button_' . htmlspecialchars($fieldName) . '" class="btn btn-default btn-add-avatar"'
629 . ' onclick="openFileBrowser();return false;">'
630 . $iconFactory->getIcon('actions-insert-record', Icon::SIZE_SMALL)
631 . '</a></div>';
632
633 $this->addAvatarButtonJs($fieldName);
634 break;
635 default:
636 $html = '';
637 }
638
639 $code[] = '<div class="form-section"><div class="row"><div class="form-group t3js-formengine-field-item col-md-12">' .
640 $label .
641 $html .
642 '</div></div></div>';
643 }
644
645 $result[] = [
646 'label' => $tabLabel,
647 'content' => count($code) ? implode(LF, $code) : ''
648 ];
649 return $result;
650 }
651
652 /******************************
653 *
654 * Helper functions
655 *
656 ******************************/
657 /**
658 * Returns the backend user object, either the global OR the $this->OLD_BE_USER which is set during simulate-user operation.
659 * Anyway: The REAL user is returned - the one logged in.
660 *
661 * @return BackendUserAuthentication The REAL user is returned - the one logged in.
662 */
663 protected function getRealScriptUserObj()
664 {
665 return is_object($this->OLD_BE_USER) ? $this->OLD_BE_USER : $this->beUser;
666 }
667
668 /**
669 * Return a select with available languages
670 *
671 * @param array $params unused
672 * @param SetupModuleController $controller
673 * @return string Complete select as HTML string or warning box if something went wrong.
674 */
675 public function renderLanguageSelect(array $params, $controller)
676 {
677 $languageOptions = [];
678 // Compile the languages dropdown
679 $langDefault = htmlspecialchars($this->getLanguageService()->getLL('lang_default'));
680 $languageOptions[$langDefault] = '<option value=""' . ($controller->beUser->uc['lang'] === '' ? ' selected="selected"' : '') . '>' . $langDefault . '</option>';
681 // Traverse the number of languages
682 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
683 $locales = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Localization\Locales::class);
684 $languages = $locales->getLanguages();
685 foreach ($languages as $locale => $name) {
686 if ($locale !== 'default') {
687 $defaultName = isset($GLOBALS['LOCAL_LANG']['default']['lang_' . $locale]) ? $GLOBALS['LOCAL_LANG']['default']['lang_' . $locale][0]['source'] : $name;
688 $localizedName = htmlspecialchars($this->getLanguageService()->getLL('lang_' . $locale));
689 if ($localizedName === '') {
690 $localizedName = htmlspecialchars($name);
691 }
692 $localLabel = ' - [' . htmlspecialchars($defaultName) . ']';
693 $available = is_dir(PATH_typo3conf . 'l10n/' . $locale);
694 if ($available) {
695 $languageOptions[$defaultName] = '<option value="' . $locale . '"' . ($controller->beUser->uc['lang'] === $locale ? ' selected="selected"' : '') . '>' . $localizedName . $localLabel . '</option>';
696 }
697 }
698 }
699 ksort($languageOptions);
700 $languageCode = '
701 <select id="field_lang" name="data[lang]" class="form-control">' . implode('', $languageOptions) . '
702 </select>';
703 if ($controller->beUser->uc['lang'] && !@is_dir((PATH_typo3conf . 'l10n/' . $controller->beUser->uc['lang']))) {
704 // TODO: The text constants have to be moved into language files
705 $languageUnavailableWarning = 'The selected language "' . htmlspecialchars($this->getLanguageService()->getLL('lang_' . $controller->beUser->uc['lang'])) . '" is not available before the language files are installed.&nbsp;&nbsp;<br />&nbsp;&nbsp;' . ($controller->beUser->isAdmin() ? 'You can use the Language module to easily download new language files.' : 'Please ask your system administrator to do this.');
706 $languageCode = '<br /><span class="label label-danger">' . $languageUnavailableWarning . '</span><br /><br />' . $languageCode;
707 }
708 return $languageCode;
709 }
710
711 /**
712 * Returns a select with all modules for startup
713 *
714 * @param array $params
715 * @param SetupModuleController $pObj
716 *
717 * @return string Complete select as HTML string
718 */
719 public function renderStartModuleSelect($params, $pObj)
720 {
721 // Load available backend modules
722 $this->loadModules = GeneralUtility::makeInstance(ModuleLoader::class);
723 $this->loadModules->observeWorkspaces = true;
724 $this->loadModules->load($GLOBALS['TBE_MODULES']);
725 $startModuleSelect = '<option value="">' . htmlspecialchars($this->getLanguageService()->getLL('startModule.firstInMenu')) . '</option>';
726 foreach ($pObj->loadModules->modules as $mainMod => $modData) {
727 if (!empty($modData['sub']) && is_array($modData['sub'])) {
728 $modules = '';
729 foreach ($modData['sub'] as $subData) {
730 $modName = $subData['name'];
731 $modules .= '<option value="' . htmlspecialchars($modName) . '"';
732 $modules .= $pObj->beUser->uc['startModule'] === $modName ? ' selected="selected"' : '';
733 $modules .= '>' . htmlspecialchars($this->getLanguageService()->sL($this->loadModules->getLabelsForModule($modName)['title'])) . '</option>';
734 }
735 $groupLabel = htmlspecialchars($this->getLanguageService()->sL($this->loadModules->getLabelsForModule($mainMod)['title']));
736 $startModuleSelect .= '<optgroup label="' . htmlspecialchars($groupLabel) . '">' . $modules . '</optgroup>';
737 }
738 }
739 return '<select id="field_startModule" name="data[startModule]" class="form-control">' . $startModuleSelect . '</select>';
740 }
741
742 /**
743 * Will make the simulate-user selector if the logged in user is administrator.
744 * It will also set the GLOBAL(!) BE_USER to the simulated user selected if any (and set $this->OLD_BE_USER to logged in user)
745 */
746 public function simulateUser()
747 {
748 // If admin, allow simulation of another user
749 $this->simUser = 0;
750 $this->simulateSelector = '';
751 unset($this->OLD_BE_USER);
752 $currentBeUser = $this->getBackendUser();
753 if ($currentBeUser->isAdmin()) {
754 $this->simUser = (int)GeneralUtility::_GP('simUser');
755 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('be_users');
756 $users = $queryBuilder
757 ->select('*')
758 ->from('be_users')
759 ->where(
760 $queryBuilder->expr()->neq(
761 'uid',
762 $queryBuilder->createNamedParameter($currentBeUser->user['uid'], \PDO::PARAM_INT)
763 ),
764 $queryBuilder->expr()->notLike(
765 'username',
766 $queryBuilder->createNamedParameter(
767 $queryBuilder->escapeLikeWildcards('_cli_') . '%',
768 \PDO::PARAM_STR
769 )
770 )
771 )
772 ->orderBy('username')
773 ->execute()
774 ->fetchAll();
775 $opt = [];
776 foreach ($users as $rr) {
777 $label = $rr['username'] . ($rr['realName'] ? ' (' . $rr['realName'] . ')' : '');
778 $opt[] = '<option value="' . (int)$rr['uid'] . '"' . ($this->simUser === (int)$rr['uid'] ? ' selected="selected"' : '') . '>' . htmlspecialchars($label) . '</option>';
779 }
780 if (!empty($opt)) {
781 $this->simulateSelector = '<select id="field_simulate" class="form-control" name="simulateUser" onchange="window.location.href=' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('user_setup') . '&simUser=') . '+this.options[this.selectedIndex].value;"><option></option>' . implode('', $opt) . '</select>';
782 }
783 }
784 // This can only be set if the previous code was executed.
785 if ($this->simUser > 0) {
786 // Save old user...
787 $this->OLD_BE_USER = $currentBeUser;
788 // Unset current
789 // New backend user object
790 $currentBeUser = GeneralUtility::makeInstance(BackendUserAuthentication::class);
791 $currentBeUser->setBeUserByUid($this->simUser);
792 $currentBeUser->fetchGroupData();
793 $currentBeUser->backendSetUC();
794 }
795 $this->beUser = $currentBeUser;
796 }
797
798 /**
799 * Render simulate user select and label
800 *
801 * @return string
802 */
803 protected function renderSimulateUserSelectAndLabel()
804 {
805 if ($this->simulateSelector === '') {
806 return '';
807 }
808
809 return '<div class="form-inline"><div class="form-group"><p>'
810 . '<label for="field_simulate" style="margin-right: 20px;">'
811 . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:setup/Resources/Private/Language/locallang.xlf:simulate'))
812 . '</label>'
813 . $this->simulateSelector
814 . '</p></div></div>';
815 }
816
817 /**
818 * Returns access check (currently only "admin" is supported)
819 *
820 * @param array $config Configuration of the field, access mode is defined in key 'access'
821 * @return bool Whether it is allowed to modify the given field
822 */
823 protected function checkAccess(array $config)
824 {
825 $access = $config['access'];
826
827 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['setup']['accessLevelCheck'][$access])) {
828 if (class_exists($access)) {
829 $accessObject = GeneralUtility::makeInstance($access);
830 if (method_exists($accessObject, 'accessLevelCheck')) {
831 // Initialize vars. If method fails, $set will be set to FALSE
832 return $accessObject->accessLevelCheck($config);
833 }
834 }
835 } elseif ($access === 'admin') {
836 return $this->isAdmin;
837 }
838
839 return false;
840 }
841
842 /**
843 * Returns the label $str from getLL() and grays out the value if the $str/$key is found in $this->overrideConf array
844 *
845 * @param string $str Locallang key
846 * @param string $key Alternative override-config key
847 * @param bool $addLabelTag Defines whether the string should be wrapped in a <label> tag.
848 * @return string HTML output.
849 */
850 protected function getLabel($str, $key = '', $addLabelTag = true)
851 {
852 if (substr($str, 0, 4) === 'LLL:') {
853 $out = htmlspecialchars($this->getLanguageService()->sL($str));
854 } else {
855 $out = htmlspecialchars($str);
856 }
857 if (isset($this->overrideConf[$key ?: $str])) {
858 $out = '<span style="color:#999999">' . $out . '</span>';
859 }
860 if ($addLabelTag) {
861 $out = '<label>' . $out . '</label>';
862 }
863 return $out;
864 }
865
866 /**
867 * Returns the CSH Icon for given string
868 *
869 * @param string $str Locallang key
870 * @param string $label The label to be used, that should be wrapped in help
871 * @return string HTML output.
872 */
873 protected function getCSH($str, $label)
874 {
875 $context = '_MOD_user_setup';
876 $field = $str;
877 $strParts = explode(':', $str);
878 if (count($strParts) > 1) {
879 // Setting comes from another extension
880 $context = $strParts[0];
881 $field = $strParts[1];
882 } elseif ($str !== 'language' && $str !== 'simuser' && $str !== 'reset') {
883 $field = 'option_' . $str;
884 }
885 return BackendUtility::wrapInHelp($context, $field, $label);
886 }
887
888 /**
889 * Returns array with fields defined in $GLOBALS['TYPO3_USER_SETTINGS']['showitem']
890 * Remove fields which are disabled by user TSconfig
891 *
892 * @return string[] Array with field names visible in form
893 */
894 protected function getFieldsFromShowItem()
895 {
896 $allowedFields = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_USER_SETTINGS']['showitem'], true);
897 if (!is_array($this->tsFieldConf)) {
898 return $allowedFields;
899 }
900 foreach ($this->tsFieldConf as $fieldName => $userTsFieldConfig) {
901 if (!empty($userTsFieldConfig['disabled'])) {
902 $fieldName = rtrim($fieldName, '.');
903 $key = array_search($fieldName, $allowedFields);
904 if ($key !== false) {
905 unset($allowedFields[$key]);
906 }
907 }
908 }
909 return $allowedFields;
910 }
911
912 /**
913 * Get Avatar fileUid
914 *
915 * @param int $beUserId
916 * @return int
917 */
918 protected function getAvatarFileUid($beUserId)
919 {
920 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
921 $file = $queryBuilder
922 ->select('uid_local')
923 ->from('sys_file_reference')
924 ->where(
925 $queryBuilder->expr()->eq(
926 'tablenames',
927 $queryBuilder->createNamedParameter('be_users', \PDO::PARAM_STR)
928 ),
929 $queryBuilder->expr()->eq(
930 'fieldname',
931 $queryBuilder->createNamedParameter('avatar', \PDO::PARAM_STR)
932 ),
933 $queryBuilder->expr()->eq(
934 'table_local',
935 $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
936 ),
937 $queryBuilder->expr()->eq(
938 'uid_foreign',
939 $queryBuilder->createNamedParameter($beUserId, \PDO::PARAM_INT)
940 )
941 )
942 ->execute()
943 ->fetchColumn();
944 return (int)$file;
945 }
946
947 /**
948 * Set avatar fileUid for backend user
949 *
950 * @param int $beUserId
951 * @param int $fileUid
952 * @param array $storeRec
953 */
954 protected function setAvatarFileUid($beUserId, $fileUid, array &$storeRec)
955 {
956
957 // Update is only needed when new fileUid is set
958 if ((int)$fileUid === $this->getAvatarFileUid($beUserId)) {
959 return;
960 }
961
962 // If user is not allowed to modify avatar $fileUid is empty - so don't overwrite existing avatar
963 if (empty($fileUid)) {
964 return;
965 }
966
967 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
968 $queryBuilder->getRestrictions()->removeAll();
969 $queryBuilder
970 ->delete('sys_file_reference')
971 ->where(
972 $queryBuilder->expr()->eq(
973 'tablenames',
974 $queryBuilder->createNamedParameter('be_users', \PDO::PARAM_STR)
975 ),
976 $queryBuilder->expr()->eq(
977 'fieldname',
978 $queryBuilder->createNamedParameter('avatar', \PDO::PARAM_STR)
979 ),
980 $queryBuilder->expr()->eq(
981 'table_local',
982 $queryBuilder->createNamedParameter('sys_file', \PDO::PARAM_STR)
983 ),
984 $queryBuilder->expr()->eq(
985 'uid_foreign',
986 $queryBuilder->createNamedParameter($beUserId, \PDO::PARAM_INT)
987 )
988 )
989 ->execute();
990
991 // If Avatar is marked for delete => set it to empty string so it will be updated properly
992 if ($fileUid === 'delete') {
993 $fileUid = '';
994 }
995
996 // Create new reference
997 if ($fileUid) {
998
999 // Get file object
1000 try {
1001 $file = ResourceFactory::getInstance()->getFileObject($fileUid);
1002 } catch (FileDoesNotExistException $e) {
1003 $file = false;
1004 }
1005
1006 // Check if user is allowed to use the image (only when not in simulation mode)
1007 if ($file && $this->simUser === 0 && !$file->getStorage()->checkFileActionPermission('read', $file)) {
1008 $file = false;
1009 }
1010
1011 // Check if extension is allowed
1012 if ($file && GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $file->getExtension())) {
1013
1014 // Create new file reference
1015 $storeRec['sys_file_reference']['NEW1234'] = [
1016 'uid_local' => (int)$fileUid,
1017 'uid_foreign' => (int)$beUserId,
1018 'tablenames' => 'be_users',
1019 'fieldname' => 'avatar',
1020 'pid' => 0,
1021 'table_local' => 'sys_file',
1022 ];
1023 $storeRec['be_users'][(int)$beUserId]['avatar'] = 'NEW1234';
1024 }
1025 }
1026 }
1027
1028 /**
1029 * Add JavaScript to for browse files button
1030 *
1031 * @param string $fieldName
1032 */
1033 protected function addAvatarButtonJs($fieldName)
1034 {
1035 $this->moduleTemplate->addJavaScriptCode('avatar-button', '
1036 var browserWin="";
1037
1038 function openFileBrowser() {
1039 var url = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('wizard_element_browser', ['mode' => 'file', 'bparams' => '||||dummy|setFileUid'])) . ';
1040 browserWin = window.open(url,"Typo3WinBrowser","height=650,width=800,status=0,menubar=0,resizable=1,scrollbars=1");
1041 browserWin.focus();
1042 }
1043
1044 function clearExistingImage() {
1045 $(' . GeneralUtility::quoteJSvalue('#image_' . htmlspecialchars($fieldName)) . ').hide();
1046 $(' . GeneralUtility::quoteJSvalue('#clear_button_' . htmlspecialchars($fieldName)) . ').hide();
1047 $(' . GeneralUtility::quoteJSvalue('#field_' . htmlspecialchars($fieldName)) . ').val(\'delete\');
1048 }
1049
1050 function setFileUid(field, value, fileUid) {
1051 clearExistingImage();
1052 $(' . GeneralUtility::quoteJSvalue('#field_' . htmlspecialchars($fieldName)) . ').val(fileUid);
1053 $(' . GeneralUtility::quoteJSvalue('#add_button_' . htmlspecialchars($fieldName)) . ').removeClass(\'btn-default\').addClass(\'btn-info\');
1054
1055 browserWin.close();
1056 }
1057 ');
1058 }
1059
1060 /**
1061 * Returns the current BE user.
1062 *
1063 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1064 */
1065 protected function getBackendUser()
1066 {
1067 return $GLOBALS['BE_USER'];
1068 }
1069
1070 /**
1071 * Returns LanguageService
1072 *
1073 * @return \TYPO3\CMS\Lang\LanguageService
1074 */
1075 protected function getLanguageService()
1076 {
1077 return $GLOBALS['LANG'];
1078 }
1079
1080 /**
1081 * Add FlashMessages for various actions
1082 */
1083 protected function addFlashMessages()
1084 {
1085 $flashMessages = [];
1086
1087 // Show if setup was saved
1088 if ($this->setupIsUpdated && !$this->settingsAreResetToDefault) {
1089 $flashMessages[] = $this->getFlashMessage('setupWasUpdated', 'UserSettings');
1090 }
1091
1092 // Show if temporary data was cleared
1093 if ($this->settingsAreResetToDefault) {
1094 $flashMessages[] = $this->getFlashMessage('settingsAreReset', 'resetConfiguration');
1095 }
1096
1097 // Notice
1098 if ($this->setupIsUpdated || $this->settingsAreResetToDefault) {
1099 $flashMessages[] = $this->getFlashMessage('activateChanges', '', FlashMessage::INFO);
1100 }
1101
1102 // If password is updated, output whether it failed or was OK.
1103 if ($this->passwordIsSubmitted) {
1104 $flashMessage = null;
1105 switch ($this->passwordIsUpdated) {
1106 case self::PASSWORD_OLD_WRONG:
1107 $flashMessages[] = $this->getFlashMessage('oldPassword_failed', 'newPassword', FlashMessage::ERROR);
1108 break;
1109 case self::PASSWORD_NOT_THE_SAME:
1110 $flashMessages[] = $this->getFlashMessage('newPassword_failed', 'newPassword', FlashMessage::ERROR);
1111 break;
1112 case self::PASSWORD_UPDATED:
1113 $flashMessages[] = $this->getFlashMessage('newPassword_ok', 'newPassword');
1114 break;
1115 }
1116 }
1117 if (!empty($flashMessages)) {
1118 $this->enqueueFlashMessages($flashMessages);
1119 }
1120 }
1121
1122 /**
1123 * @param array $flashMessages
1124 * @throws \TYPO3\CMS\Core\Exception
1125 */
1126 protected function enqueueFlashMessages(array $flashMessages)
1127 {
1128 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
1129 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1130 foreach ($flashMessages as $flashMessage) {
1131 $defaultFlashMessageQueue->enqueue($flashMessage);
1132 }
1133 }
1134
1135 /**
1136 * @param string $message
1137 * @param string $title
1138 * @param int $severity
1139 * @return FlashMessage
1140 */
1141 protected function getFlashMessage($message, $title, $severity = FlashMessage::OK)
1142 {
1143 $title = !empty($title) ? $this->getLanguageService()->getLL($title) : ' ';
1144 return GeneralUtility::makeInstance(
1145 FlashMessage::class,
1146 $this->getLanguageService()->getLL($message),
1147 $title,
1148 $severity
1149 );
1150 }
1151 }