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