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