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