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