[TASK] Remove non-CGL-compliant switch clause in EXT:setup
[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 TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
19 use TYPO3\CMS\Core\Database\DatabaseConnection;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Core\Messaging\FlashMessage;
22
23 /**
24 * Script class for the Setup module
25 *
26 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
27 */
28 class SetupModuleController {
29
30 const PASSWORD_NOT_UPDATED = 0;
31 const PASSWORD_UPDATED = 1;
32 const PASSWORD_NOT_THE_SAME = 2;
33 const PASSWORD_OLD_WRONG = 3;
34
35 /**
36 * @var array
37 */
38 public $MOD_MENU = array();
39
40 /**
41 * @var array
42 */
43 public $MOD_SETTINGS = array();
44
45 /**
46 * @var \TYPO3\CMS\Backend\Template\DocumentTemplate
47 */
48 public $doc;
49
50 /**
51 * @var string
52 */
53 public $content;
54
55 /**
56 * @var array
57 */
58 public $overrideConf;
59
60 /**
61 * backend user object, set during simulate-user operation
62 *
63 * @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
64 */
65 public $OLD_BE_USER;
66
67 /**
68 * @var bool
69 */
70 public $languageUpdate;
71
72 /**
73 * @var bool
74 */
75 protected $pagetreeNeedsRefresh = FALSE;
76
77 /**
78 * @var bool
79 */
80 protected $isAdmin;
81
82 /**
83 * @var array
84 */
85 protected $tsFieldConf;
86
87 /**
88 * @var bool
89 */
90 protected $saveData = FALSE;
91
92 /**
93 * @var int
94 */
95 protected $passwordIsUpdated = self::PASSWORD_NOT_UPDATED;
96
97 /**
98 * @var bool
99 */
100 protected $passwordIsSubmitted = FALSE;
101
102 /**
103 * @var bool
104 */
105 protected $setupIsUpdated = FALSE;
106
107 /**
108 * @var bool
109 */
110 protected $tempDataIsCleared = FALSE;
111
112 /**
113 * @var bool
114 */
115 protected $settingsAreResetToDefault = FALSE;
116
117 /**
118 * Form protection instance
119 *
120 * @var \TYPO3\CMS\Core\FormProtection\BackendFormProtection
121 */
122 protected $formProtection;
123
124 /**
125 * @var string
126 */
127 protected $simulateSelector = '';
128
129 /**
130 * @var string
131 */
132 protected $simUser = '';
133
134 /**
135 * The name of the module
136 *
137 * @var string
138 */
139 protected $moduleName = 'user_setup';
140
141 /**
142 * Instantiate the form protection before a simulated user is initialized.
143 */
144 public function __construct() {
145 $this->formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get();
146 }
147
148 /**
149 * Getter for the form protection instance.
150 *
151 * @return \TYPO3\CMS\Core\FormProtection\BackendFormProtection
152 */
153 public function getFormProtection() {
154 return $this->formProtection;
155 }
156
157 /**
158 * If settings are submitted to _POST[DATA], store them
159 * NOTICE: This method is called before the \TYPO3\CMS\Backend\Template\DocumentTemplate
160 * is included. See bottom of document.
161 *
162 * @see \TYPO3\CMS\Backend\Template\DocumentTemplate
163 */
164 public function storeIncomingData() {
165 // First check if something is submitted in the data-array from POST vars
166 $d = GeneralUtility::_POST('data');
167 $columns = $GLOBALS['TYPO3_USER_SETTINGS']['columns'];
168 $beUser = $this->getBackendUser();
169 $beUserId = $beUser->user['uid'];
170 $storeRec = array();
171 $fieldList = $this->getFieldsFromShowItem();
172 if (is_array($d) && $this->formProtection->validateToken((string)GeneralUtility::_POST('formToken'), 'BE user setup', 'edit')) {
173 // UC hashed before applying changes
174 $save_before = md5(serialize($beUser->uc));
175 // PUT SETTINGS into the ->uc array:
176 // Reload left frame when switching BE language
177 if (isset($d['lang']) && $d['lang'] != $beUser->uc['lang']) {
178 $this->languageUpdate = TRUE;
179 }
180 // Reload pagetree if the title length is changed
181 if (isset($d['titleLen']) && $d['titleLen'] !== $beUser->uc['titleLen']) {
182 $this->pagetreeNeedsRefresh = TRUE;
183 }
184 if ($d['setValuesToDefault']) {
185 // If every value should be default
186 $beUser->resetUC();
187 $this->settingsAreResetToDefault = TRUE;
188 } elseif ($d['clearSessionVars']) {
189 foreach ($beUser->uc as $key => $value) {
190 if (!isset($columns[$key])) {
191 unset($beUser->uc[$key]);
192 }
193 }
194 $this->tempDataIsCleared = TRUE;
195 } elseif ($d['save']) {
196 // Save all submitted values if they are no array (arrays are with table=be_users) and exists in $GLOBALS['TYPO3_USER_SETTINGS'][columns]
197 foreach ($columns as $field => $config) {
198 if (!in_array($field, $fieldList)) {
199 continue;
200 }
201 if ($config['table']) {
202 if ($config['table'] === 'be_users' && !in_array($field, array('password', 'password2', 'passwordCurrent', 'email', 'realName', 'admin'))) {
203 if (!isset($config['access']) || $this->checkAccess($config) && $beUser->user[$field] !== $d['be_users'][$field]) {
204 if ($config['type'] === 'check') {
205 $fieldValue = isset($d['be_users'][$field]) ? 1 : 0;
206 } else {
207 $fieldValue = $d['be_users'][$field];
208 }
209 $storeRec['be_users'][$beUserId][$field] = $fieldValue;
210 $beUser->user[$field] = $fieldValue;
211 }
212 }
213 }
214 if ($config['type'] === 'check') {
215 $beUser->uc[$field] = isset($d[$field]) ? 1 : 0;
216 } else {
217 $beUser->uc[$field] = htmlspecialchars($d[$field]);
218 }
219 }
220 // Personal data for the users be_user-record (email, name, password...)
221 // If email and name is changed, set it in the users record:
222 $be_user_data = $d['be_users'];
223 // Possibility to modify the transmitted values. Useful to do transformations, like RSA password decryption
224 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['modifyUserDataBeforeSave'])) {
225 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['modifyUserDataBeforeSave'] as $function) {
226 $params = array('be_user_data' => &$be_user_data);
227 GeneralUtility::callUserFunction($function, $params, $this);
228 }
229 }
230 $this->passwordIsSubmitted = (string)$be_user_data['password'] !== '';
231 $passwordIsConfirmed = $this->passwordIsSubmitted && $be_user_data['password'] === $be_user_data['password2'];
232 // Update the real name:
233 if ($be_user_data['realName'] !== $beUser->user['realName']) {
234 $beUser->user['realName'] = ($storeRec['be_users'][$beUserId]['realName'] = substr($be_user_data['realName'], 0, 80));
235 }
236 // Update the email address:
237 if ($be_user_data['email'] !== $beUser->user['email']) {
238 $beUser->user['email'] = ($storeRec['be_users'][$beUserId]['email'] = substr($be_user_data['email'], 0, 80));
239 }
240 // Update the password:
241 if ($passwordIsConfirmed) {
242 $currentPasswordHashed = $GLOBALS['BE_USER']->user['password'];
243 $saltFactory = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance($currentPasswordHashed);
244 if ($saltFactory->checkPassword($be_user_data['passwordCurrent'], $currentPasswordHashed)) {
245 $this->passwordIsUpdated = self::PASSWORD_UPDATED;
246 $storeRec['be_users'][$beUserId]['password'] = $be_user_data['password'];
247 } else {
248 $this->passwordIsUpdated = self::PASSWORD_OLD_WRONG;
249 }
250 } else {
251 $this->passwordIsUpdated = self::PASSWORD_NOT_THE_SAME;
252 }
253 $this->saveData = TRUE;
254 }
255 // Inserts the overriding values.
256 $beUser->overrideUC();
257 $save_after = md5(serialize($beUser->uc));
258 // If something in the uc-array of the user has changed, we save the array...
259 if ($save_before != $save_after) {
260 $beUser->writeUC($beUser->uc);
261 $beUser->writelog(254, 1, 0, 1, 'Personal settings changed', array());
262 $this->setupIsUpdated = TRUE;
263 }
264 // If the temporary data has been cleared, lets make a log note about it
265 if ($this->tempDataIsCleared) {
266 $beUser->writelog(254, 1, 0, 1, $this->getLanguageService()->getLL('tempDataClearedLog'), array());
267 }
268 // Persist data if something has changed:
269 if (count($storeRec) && $this->saveData) {
270 // Make instance of TCE for storing the changes.
271 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
272 $tce->stripslashes_values = 0;
273 // This is so the user can actually update his user record.
274 $isAdmin = $beUser->user['admin'];
275 $beUser->user['admin'] = 1;
276 $tce->start($storeRec, array(), $beUser);
277 // This is to make sure that the users record can be updated even if in another workspace. This is tolerated.
278 $tce->bypassWorkspaceRestrictions = TRUE;
279 $tce->process_datamap();
280 unset($tce);
281 if ($this->passwordIsUpdated === self::PASSWORD_NOT_UPDATED || count($storeRec['be_users'][$beUserId]) > 1) {
282 $this->setupIsUpdated = TRUE;
283 }
284 // Restore admin status after processing
285 $beUser->user['admin'] = $isAdmin;
286 }
287 }
288 }
289
290 /******************************
291 *
292 * Rendering module
293 *
294 ******************************/
295 /**
296 * Initializes the module for display of the settings form.
297 *
298 * @return void
299 */
300 public function init() {
301 $this->getLanguageService()->includeLLFile('EXT:setup/mod/locallang.xlf');
302
303 // Returns the script user - that is the REAL logged in user! ($GLOBALS[BE_USER] might be another user due to simulation!)
304 $scriptUser = $this->getRealScriptUserObj();
305
306 $this->isAdmin = $scriptUser->isAdmin();
307 // Getting the 'override' values as set might be set in User TSconfig
308 $this->overrideConf = $this->getBackendUser()->getTSConfigProp('setup.override');
309 // Getting the disabled fields might be set in User TSconfig (eg setup.fields.password.disabled=1)
310 $this->tsFieldConf = $this->getBackendUser()->getTSConfigProp('setup.fields');
311 // id password is disabled, disable repeat of password too (password2)
312 if (isset($this->tsFieldConf['password.']) && $this->tsFieldConf['password.']['disabled']) {
313 $this->tsFieldConf['password2.']['disabled'] = 1;
314 $this->tsFieldConf['passwordCurrent.']['disabled'] = 1;
315 }
316 // Create instance of object for output of data
317 $this->doc = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
318 $this->doc->backPath = $GLOBALS['BACK_PATH'];
319 $this->doc->setModuleTemplate('EXT:setup/Resources/Private/Templates/setup.html');
320 $this->doc->form = '<form action="' . BackendUtility::getModuleUrl('user_setup') . '" method="post" name="usersetup" enctype="application/x-www-form-urlencoded">';
321 $this->doc->addStyleSheet('module', 'sysext/setup/Resources/Public/Styles/styles.css');
322 $this->doc->JScode .= $this->getJavaScript();
323 }
324
325 /**
326 * Generate necessary JavaScript
327 *
328 * @return string
329 */
330 protected function getJavaScript() {
331 $javaScript = '';
332 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['setupScriptHook'])) {
333 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/setup/mod/index.php']['setupScriptHook'] as $function) {
334 $params = array();
335 $javaScript .= GeneralUtility::callUserFunction($function, $params, $this);
336 }
337 }
338 return $javaScript;
339 }
340
341 /**
342 * Generate the main settings form:
343 *
344 * @return void
345 */
346 public function main() {
347 if ($this->languageUpdate) {
348 $this->doc->JScodeArray['languageUpdate'] .= '
349 if (top.refreshMenu) {
350 top.refreshMenu();
351 } else {
352 top.TYPO3ModuleMenu.refreshMenu();
353 }
354 ';
355 }
356 if ($this->pagetreeNeedsRefresh) {
357 BackendUtility::setUpdateSignal('updatePageTree');
358 }
359 // Start page:
360 $this->doc->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/md5.js');
361 // Use a wrapper div
362 $this->content .= '<div id="user-setup-wrapper">';
363 // Load available backend modules
364 $this->loadModules = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Module\ModuleLoader::class);
365 $this->loadModules->observeWorkspaces = TRUE;
366 $this->loadModules->load($GLOBALS['TBE_MODULES']);
367 $this->content .= $this->doc->header($this->getLanguageService()->getLL('UserSettings'));
368 // Show if setup was saved
369 if ($this->setupIsUpdated && !$this->tempDataIsCleared && !$this->settingsAreResetToDefault) {
370 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('setupWasUpdated'), $this->getLanguageService()->getLL('UserSettings'));
371 $this->content .= $flashMessage->render();
372 }
373 // Show if temporary data was cleared
374 if ($this->tempDataIsCleared) {
375 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('tempDataClearedFlashMessage'), $this->getLanguageService()->getLL('tempDataCleared'));
376 $this->content .= $flashMessage->render();
377 }
378 // Show if temporary data was cleared
379 if ($this->settingsAreResetToDefault) {
380 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('settingsAreReset'), $this->getLanguageService()->getLL('resetConfiguration'));
381 $this->content .= $flashMessage->render();
382 }
383 // Notice
384 if ($this->setupIsUpdated || $this->settingsAreResetToDefault) {
385 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('activateChanges'), '', FlashMessage::INFO);
386 $this->content .= $flashMessage->render();
387 }
388 // If password is updated, output whether it failed or was OK.
389 if ($this->passwordIsSubmitted) {
390 $flashMessage = NULL;
391 switch ($this->passwordIsUpdated) {
392 case self::PASSWORD_OLD_WRONG:
393 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('oldPassword_failed'), $this->getLanguageService()->getLL('newPassword'), FlashMessage::ERROR);
394 break;
395 case self::PASSWORD_NOT_THE_SAME:
396 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('newPassword_failed'), $this->getLanguageService()->getLL('newPassword'), FlashMessage::ERROR);
397 break;
398 case self::PASSWORD_UPDATED:
399 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->getLL('newPassword_ok'), $this->getLanguageService()->getLL('newPassword'));
400 break;
401 }
402 if ($flashMessage) {
403 $this->content .= $flashMessage->render();
404 }
405 }
406
407 // Render user switch
408 $this->content .= $this->renderSimulateUserSelectAndLabel();
409
410 // Render the menu items
411 $menuItems = $this->renderUserSetup();
412 $this->content .= $this->doc->getDynamicTabMenu($menuItems, 'user-setup', 1, FALSE, FALSE);
413 $formToken = $this->formProtection->generateToken('BE user setup', 'edit');
414 $this->content .= $this->doc->section('', '<input type="hidden" name="simUser" value="' . $this->simUser . '" />
415 <input type="hidden" name="formToken" value="' . $formToken . '" />
416 <input type="hidden" value="1" name="data[save]" />
417 <input type="hidden" name="data[setValuesToDefault]" value="0" id="setValuesToDefault" />
418 <input type="hidden" name="data[clearSessionVars]" value="0" id="clearSessionVars" />');
419 // End of wrapper div
420 $this->content .= '</div>';
421 // Setting up the buttons and markers for docheader
422 $docHeaderButtons = $this->getButtons();
423 $markers['CSH'] = $docHeaderButtons['csh'];
424 $markers['CONTENT'] = $this->content;
425 // Build the <body> for the module
426 $this->content = $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
427 // Renders the module page
428 $this->content = $this->doc->render($this->getLanguageService()->getLL('UserSettings'), $this->content);
429 }
430
431 /**
432 * Prints the content / ends page
433 *
434 * @return void
435 */
436 public function printContent() {
437 echo $this->content;
438 }
439
440 /**
441 * Create the panel of buttons for submitting the form or otherwise perform operations.
442 *
443 * @return array All available buttons as an assoc. array
444 */
445 protected function getButtons() {
446 $buttons = array(
447 'csh' => '',
448 'save' => '',
449 'shortcut' => ''
450 );
451 $buttons['csh'] = BackendUtility::cshItem('_MOD_user_setup', '');
452 $buttons['save'] = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-document-save', array('html' => '<input type="image" name="data[save]" class="c-inputButton" src="clear.gif" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDoc', TRUE) . '" />'));
453 if ($this->getBackendUser()->mayMakeShortcut()) {
454 $buttons['shortcut'] = $this->doc->makeShortcutIcon('', '', $this->moduleName);
455 }
456 return $buttons;
457 }
458
459 /******************************
460 *
461 * Render module
462 *
463 ******************************/
464
465 /**
466 * renders the data for all tabs in the user setup and returns
467 * everything that is needed with tabs and dyntab menu
468 *
469 * @return array Ready to use for the dyntabmenu itemarray
470 */
471 protected function renderUserSetup() {
472 $result = array();
473 $firstTabLabel = '';
474 $code = array();
475 $i = 0;
476 $fieldArray = $this->getFieldsFromShowItem();
477 $tabLabel = '';
478 foreach ($fieldArray as $fieldName) {
479 $more = '';
480 if (substr($fieldName, 0, 8) === '--div--;') {
481 if ($firstTabLabel === '') {
482 // First tab
483 $tabLabel = $this->getLabel(substr($fieldName, 8), '', FALSE);
484 $firstTabLabel = $tabLabel;
485 } else {
486 $result[] = array(
487 'label' => $tabLabel,
488 'content' => count($code) ? implode(LF, $code) : ''
489 );
490 $tabLabel = $this->getLabel(substr($fieldName, 8), '', FALSE);
491 $i = 0;
492 $code = array();
493 }
494 continue;
495 }
496 $config = $GLOBALS['TYPO3_USER_SETTINGS']['columns'][$fieldName];
497
498 // Field my be disabled in setup.fields
499 if (isset($this->tsFieldConf[$fieldName . '.']['disabled']) && $this->tsFieldConf[$fieldName . '.']['disabled'] == 1) {
500 continue;
501 }
502 if (isset($config['access']) && !$this->checkAccess($config)) {
503 continue;
504 }
505 $label = $this->getLabel($config['label'], $fieldName);
506 $label = $this->getCSH($config['csh'] ?: $fieldName, $label);
507 $type = $config['type'];
508 $class = $config['class'];
509
510 if ($type !== 'check') {
511 $class .= ' form-control';
512 }
513
514 $style = $config['style'];
515 if ($class) {
516 $more .= ' class="' . $class . '"';
517 }
518 if ($style) {
519 $more .= ' style="' . $style . '"';
520 }
521 if (isset($this->overrideConf[$fieldName])) {
522 $more .= ' disabled="disabled"';
523 }
524 $value = $config['table'] === 'be_users' ? $this->getBackendUser()->user[$fieldName] : $this->getBackendUser()->uc[$fieldName];
525 if (!$value && isset($config['default'])) {
526 $value = $config['default'];
527 }
528 $dataAdd = '';
529 if ($config['table'] === 'be_users') {
530 $dataAdd = '[be_users]';
531 }
532
533 switch ($type) {
534 case 'text':
535 case 'email':
536 case 'password':
537 $noAutocomplete = '';
538 if ($type === 'password') {
539 $value = '';
540 $noAutocomplete = 'autocomplete="off" ';
541 }
542 $html = '<input id="field_' . $fieldName . '"
543 type="' . $type . '"
544 name="data' . $dataAdd . '[' . $fieldName . ']" ' .
545 $noAutocomplete .
546 'value="' . htmlspecialchars($value) . '" ' .
547 $more .
548 ' />';
549 break;
550 case 'check':
551 $html = $label . '<div class="checkbox"><label><input id="field_' . $fieldName . '"
552 type="checkbox"
553 name="data' . $dataAdd . '[' . $fieldName . ']"' .
554 ($value ? ' checked="checked"' : '') .
555 $more .
556 ' /></label></div>';
557 $label = '';
558 break;
559 case 'select':
560 if ($config['itemsProcFunc']) {
561 $html = GeneralUtility::callUserFunction($config['itemsProcFunc'], $config, $this, '');
562 } else {
563 $html = '<select id="field_' . $fieldName . '"
564 name="data' . $dataAdd . '[' . $fieldName . ']"' .
565 $more . '>' . LF;
566 foreach ($config['items'] as $key => $optionLabel) {
567 $html .= '<option value="' . $key . '"' . ($value == $key ? ' selected="selected"' : '') . '>' . $this->getLabel($optionLabel, '', FALSE) . '</option>' . LF;
568 }
569 $html .= '</select>';
570 }
571 break;
572 case 'user':
573 $html = GeneralUtility::callUserFunction($config['userFunc'], $config, $this, '');
574 break;
575 case 'button':
576 if ($config['onClick']) {
577 $onClick = $config['onClick'];
578 if ($config['onClickLabels']) {
579 foreach ($config['onClickLabels'] as $key => $labelclick) {
580 $config['onClickLabels'][$key] = $this->getLabel($labelclick, '', FALSE);
581 }
582 $onClick = vsprintf($onClick, $config['onClickLabels']);
583 }
584 $html = '<br><input class="btn btn-default" type="button"
585 value="' . $this->getLabel($config['buttonlabel'], '', FALSE) . '"
586 onclick="' . $onClick . '" />';
587 }
588 break;
589 default:
590 $html = '';
591 }
592
593 $code[] = '<div class="form-section"><div class="form-group">' .
594 $label .
595 $html .
596 '</div></div>';
597 }
598
599 $result[] = array(
600 'label' => $tabLabel,
601 'content' => count($code) ? implode(LF, $code) : ''
602 );
603 return $result;
604 }
605
606 /******************************
607 *
608 * Helper functions
609 *
610 ******************************/
611 /**
612 * Returns the backend user object, either the global OR the $this->OLD_BE_USER which is set during simulate-user operation.
613 * Anyway: The REAL user is returned - the one logged in.
614 *
615 * @return BackendUserAuthentication The REAL user is returned - the one logged in.
616 */
617 protected function getRealScriptUserObj() {
618 return is_object($this->OLD_BE_USER) ? $this->OLD_BE_USER : $this->getBackendUser();
619 }
620
621 /**
622 * Return a select with available languages
623 *
624 * @return string Complete select as HTML string or warning box if something went wrong.
625 */
626 public function renderLanguageSelect($params, $pObj) {
627 $languageOptions = array();
628 // Compile the languages dropdown
629 $langDefault = $this->getLanguageService()->getLL('lang_default', TRUE);
630 $languageOptions[$langDefault] = '<option value=""' . ($this->getBackendUser()->uc['lang'] === '' ? ' selected="selected"' : '') . '>' . $langDefault . '</option>';
631 // Traverse the number of languages
632 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
633 $locales = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Localization\Locales::class);
634 $languages = $locales->getLanguages();
635 foreach ($languages as $locale => $name) {
636 if ($locale !== 'default') {
637 $defaultName = isset($GLOBALS['LOCAL_LANG']['default']['lang_' . $locale]) ? $GLOBALS['LOCAL_LANG']['default']['lang_' . $locale][0]['source'] : $name;
638 $localizedName = $this->getLanguageService()->getLL('lang_' . $locale, TRUE);
639 if ($localizedName === '') {
640 $localizedName = htmlspecialchars($name);
641 }
642 $localLabel = ' - [' . htmlspecialchars($defaultName) . ']';
643 $available = is_dir(PATH_typo3conf . 'l10n/' . $locale) ? TRUE : FALSE;
644 if ($available) {
645 $languageOptions[$defaultName] = '<option value="' . $locale . '"' . ($this->getBackendUser()->uc['lang'] === $locale ? ' selected="selected"' : '') . '>' . $localizedName . $localLabel . '</option>';
646 }
647 }
648 }
649 ksort($languageOptions);
650 $languageCode = '
651 <select id="field_lang" name="data[lang]" class="form-control">' . implode('', $languageOptions) . '
652 </select>';
653 if ($this->getBackendUser()->uc['lang'] && !@is_dir((PATH_typo3conf . 'l10n/' . $this->getBackendUser()->uc['lang']))) {
654 $languageUnavailableWarning = 'The selected language "' . $this->getLanguageService()->getLL(('lang_' . $this->getBackendUser()->uc['lang']), TRUE) . '" is not available before the language files are installed.<br />' . ($this->getBackendUser()->isAdmin() ? 'You can use the Language module to easily download new language files.' : 'Please ask your system administrator to do this.');
655 $languageUnavailableMessage = GeneralUtility::makeInstance(FlashMessage::class, $languageUnavailableWarning, '', FlashMessage::WARNING);
656 $languageCode = $languageUnavailableMessage->render() . $languageCode;
657 }
658 return $languageCode;
659 }
660
661 /**
662 * Returns a select with all modules for startup
663 *
664 * @return string Complete select as HTML string
665 */
666 public function renderStartModuleSelect($params, $pObj) {
667 $startModuleSelect = '<option value="">' . $this->getLanguageService()->getLL('startModule.firstInMenu', TRUE) . '</option>';
668 foreach ($pObj->loadModules->modules as $mainMod => $modData) {
669 if (!empty($modData['sub']) && is_array($modData['sub'])) {
670 $modules = '';
671 foreach ($modData['sub'] as $subData) {
672 $modName = $subData['name'];
673 $modules .= '<option value="' . htmlspecialchars($modName) . '"';
674 $modules .= $this->getBackendUser()->uc['startModule'] === $modName ? ' selected="selected"' : '';
675 $modules .= '>' . $this->getLanguageService()->moduleLabels['tabs'][$modName . '_tab'] . '</option>';
676 }
677 $groupLabel = $this->getLanguageService()->moduleLabels['tabs'][$mainMod . '_tab'];
678 $startModuleSelect .= '<optgroup label="' . htmlspecialchars($groupLabel) . '">' . $modules . '</optgroup>';
679 }
680 }
681 return '<select id="field_startModule" name="data[startModule]" class="form-control">' . $startModuleSelect . '</select>';
682 }
683
684 /**
685 * Will make the simulate-user selector if the logged in user is administrator.
686 * 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)
687 *
688 * @return void
689 */
690 public function simulateUser() {
691 // If admin, allow simulation of another user
692 $this->simUser = 0;
693 $this->simulateSelector = '';
694 unset($this->OLD_BE_USER);
695 if ($this->getBackendUser()->isAdmin()) {
696 $this->simUser = (int)GeneralUtility::_GP('simUser');
697 // Make user-selector:
698 $db = $this->getDatabaseConnection();
699 $where = 'AND username NOT LIKE ' . $db->fullQuoteStr($db->escapeStrForLike('_cli_', 'be_users') . '%', 'be_users');
700 $where .= ' AND uid <> ' . (int)$this->getBackendUser()->user['uid'] . BackendUtility::BEenableFields('be_users');
701 $users = BackendUtility::getUserNames('username,usergroup,usergroup_cached_list,uid,realName', $where);
702 $opt = array();
703 foreach ($users as $rr) {
704 $label = htmlspecialchars(($rr['username'] . ($rr['realName'] ? ' (' . $rr['realName'] . ')' : '')));
705 $opt[] = '<option value="' . $rr['uid'] . '"' . ($this->simUser == $rr['uid'] ? ' selected="selected"' : '') . '>' . $label . '</option>';
706 }
707 if (!empty($opt)) {
708 $this->simulateSelector = '<select id="field_simulate" name="simulateUser" onchange="window.location.href=' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('user_setup') . '&simUser=') . '+this.options[this.selectedIndex].value;"><option></option>' . implode('', $opt) . '</select>';
709 }
710 }
711 // This can only be set if the previous code was executed.
712 if ($this->simUser > 0) {
713 // Save old user...
714 $this->OLD_BE_USER = $this->getBackendUser();
715 unset($GLOBALS['BE_USER']);
716 // Unset current
717 // New backend user object
718 $BE_USER = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class);
719 $BE_USER->setBeUserByUid($this->simUser);
720 $BE_USER->fetchGroupData();
721 $BE_USER->backendSetUC();
722 // Must do this, because unsetting $BE_USER before apparently unsets the reference to the global variable by this name!
723 $GLOBALS['BE_USER'] = $BE_USER;
724 }
725 }
726
727 /**
728 * Render simulate user select and label
729 *
730 * @return string
731 */
732 protected function renderSimulateUserSelectAndLabel() {
733 if ($this->simulateSelector === '') {
734 return '';
735 }
736
737 return '<p>' .
738 '<label for="field_simulate" style="margin-right: 20px;">' .
739 $this->getLanguageService()->sL('LLL:EXT:setup/mod/locallang.xlf:simulate') .
740 '</label>' .
741 $this->simulateSelector .
742 '</p>';
743 }
744
745 /**
746 * Returns access check (currently only "admin" is supported)
747 *
748 * @param array $config Configuration of the field, access mode is defined in key 'access'
749 * @return bool Whether it is allowed to modify the given field
750 */
751 protected function checkAccess(array $config) {
752 $access = $config['access'];
753
754 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['setup']['accessLevelCheck'][$access])) {
755 if (class_exists($access)) {
756 $accessObject = GeneralUtility::makeInstance($access);
757 if (method_exists($accessObject, 'accessLevelCheck')) {
758 // Initialize vars. If method fails, $set will be set to FALSE
759 return $accessObject->accessLevelCheck($config);
760 }
761 }
762 } elseif ($access == 'admin') {
763 return $this->isAdmin;
764 }
765
766 return FALSE;
767 }
768
769 /**
770 * Returns the label $str from getLL() and grays out the value if the $str/$key is found in $this->overrideConf array
771 *
772 * @param string $str Locallang key
773 * @param string $key Alternative override-config key
774 * @param bool $addLabelTag Defines whether the string should be wrapped in a <label> tag.
775 * @param string $altLabelTagId Alternative id for use in "for" attribute of <label> tag. By default the $str key is used prepended with "field_".
776 * @return string HTML output.
777 */
778 protected function getLabel($str, $key = '', $addLabelTag = TRUE, $altLabelTagId = '') {
779 if (substr($str, 0, 4) === 'LLL:') {
780 $out = $this->getLanguageService()->sL($str);
781 } else {
782 $out = htmlspecialchars($str);
783 }
784 if (isset($this->overrideConf[$key ?: $str])) {
785 $out = '<span style="color:#999999">' . $out . '</span>';
786 }
787 if ($addLabelTag) {
788 $out = '<label for="' . ($altLabelTagId ?: 'field_' . $key) . '">' . $out . '</label>';
789 }
790 return $out;
791 }
792
793 /**
794 * Returns the CSH Icon for given string
795 *
796 * @param string $str Locallang key
797 * @param string $label The label to be used, that should be wrapped in help
798 * @return string HTML output.
799 */
800 protected function getCSH($str, $label) {
801 $context = '_MOD_user_setup';
802 $field = $str;
803 $strParts = explode(':', $str);
804 if (count($strParts) > 1) {
805 // Setting comes from another extension
806 $context = $strParts[0];
807 $field = $strParts[1];
808 } elseif (!GeneralUtility::inList('language,simuser,reset', $str)) {
809 $field = 'option_' . $str;
810 }
811 return BackendUtility::wrapInHelp($context, $field, $label);
812 }
813
814 /**
815 * Returns array with fields defined in $GLOBALS['TYPO3_USER_SETTINGS']['showitem']
816 *
817 * @return array Array with fieldnames visible in form
818 */
819 protected function getFieldsFromShowItem() {
820 return GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_USER_SETTINGS']['showitem'], TRUE);
821 }
822
823 /**
824 * Returns the current BE user.
825 *
826 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
827 */
828 protected function getBackendUser() {
829 return $GLOBALS['BE_USER'];
830 }
831
832 /**
833 * Returns LanguageService
834 *
835 * @return \TYPO3\CMS\Lang\LanguageService
836 */
837 protected function getLanguageService() {
838 return $GLOBALS['LANG'];
839 }
840
841 /**
842 * @return DatabaseConnection
843 */
844 protected function getDatabaseConnection() {
845 return $GLOBALS['TYPO3_DB'];
846 }
847
848 }