[TASK] Always use Icon API for Module Icons
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / FormDataProvider / AbstractItemProvider.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\FormDataProvider;
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\Module\ModuleLoader;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20 use TYPO3\CMS\Core\Database\DatabaseConnection;
21 use TYPO3\CMS\Core\Database\RelationHandler;
22 use TYPO3\CMS\Core\Imaging\IconFactory;
23 use TYPO3\CMS\Core\Messaging\FlashMessage;
24 use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
25 use TYPO3\CMS\Core\Messaging\FlashMessageService;
26 use TYPO3\CMS\Core\Utility\ArrayUtility;
27 use TYPO3\CMS\Core\Utility\GeneralUtility;
28 use TYPO3\CMS\Core\Utility\MathUtility;
29 use TYPO3\CMS\Core\Utility\PathUtility;
30 use TYPO3\CMS\Lang\LanguageService;
31
32 /**
33 * Contains methods used by Data providers that handle elements
34 * with single items like select, radio and some more.
35 */
36 abstract class AbstractItemProvider
37 {
38 /**
39 * Resolve "itemProcFunc" of elements.
40 *
41 * @param array $result Main result array
42 * @param string $fieldName Field name to handle item list for
43 * @param array $items Existing items array
44 * @return array New list of item elements
45 */
46 protected function resolveItemProcessorFunction(array $result, $fieldName, array $items)
47 {
48 $table = $result['tableName'];
49 $config = $result['processedTca']['columns'][$fieldName]['config'];
50
51 $pageTsProcessorParameters = null;
52 if (!empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['itemsProcFunc.'])) {
53 $pageTsProcessorParameters = $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['itemsProcFunc.'];
54 }
55 $processorParameters = [
56 // Function manipulates $items directly and return nothing
57 'items' => &$items,
58 'config' => $config,
59 'TSconfig' => $pageTsProcessorParameters,
60 'table' => $table,
61 'row' => $result['databaseRow'],
62 'field' => $fieldName,
63 ];
64 if (!empty($result['flexParentDatabaseRow'])) {
65 $processorParameters['flexParentDatabaseRow'] = $result['flexParentDatabaseRow'];
66 }
67
68 try {
69 GeneralUtility::callUserFunction($config['itemsProcFunc'], $processorParameters, $this);
70 } catch (\Exception $exception) {
71 // The itemsProcFunc method may throw an exception, create a flash message if so
72 $languageService = $this->getLanguageService();
73 $fieldLabel = $fieldName;
74 if (!empty($result['processedTca']['columns'][$fieldName]['label'])) {
75 $fieldLabel = $languageService->sL($result['processedTca']['columns'][$fieldName]['label']);
76 }
77 $message = sprintf(
78 $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.items_proc_func_error'),
79 $fieldLabel,
80 $exception->getMessage()
81 );
82 /** @var FlashMessage $flashMessage */
83 $flashMessage = GeneralUtility::makeInstance(
84 FlashMessage::class,
85 $message,
86 '',
87 FlashMessage::ERROR,
88 true
89 );
90 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
91 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
92 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
93 $defaultFlashMessageQueue->enqueue($flashMessage);
94 }
95
96 return $items;
97 }
98
99 /**
100 * PageTsConfig addItems:
101 *
102 * TCEFORMS.aTable.aField[.types][.aType].addItems.aValue = aLabel,
103 * with type specific options merged by pageTsConfig already
104 *
105 * Used by TcaSelectItems and TcaSelectTreeItems data providers
106 *
107 * @param array $result result array
108 * @param string $fieldName Current handle field name
109 * @param array $items Incoming items
110 * @return array Modified item array
111 */
112 protected function addItemsFromPageTsConfig(array $result, $fieldName, array $items)
113 {
114 $table = $result['tableName'];
115 if (!empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
116 && is_array($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
117 ) {
118 $addItemsArray = $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'];
119 foreach ($addItemsArray as $value => $label) {
120 // If the value ends with a dot, it is a subelement like "34.icon = mylabel.png", skip it
121 if (substr($value, -1) === '.') {
122 continue;
123 }
124 // Check if value "34 = mylabel" also has a "34.icon = myImage.png"
125 $icon = null;
126 if (isset($addItemsArray[$value . '.'])
127 && is_array($addItemsArray[$value . '.'])
128 && !empty($addItemsArray[$value . '.']['icon'])
129 ) {
130 $icon = $addItemsArray[$value . '.']['icon'];
131 }
132 $items[] = array($label, $value, $icon);
133 }
134 }
135 return $items;
136 }
137
138 /**
139 * TCA config "special" evaluation. Add them to $items
140 *
141 * Used by TcaSelectItems and TcaSelectTreeItems data providers
142 *
143 * @param array $result Result array
144 * @param string $fieldName Current handle field name
145 * @param array $items Incoming items
146 * @return array Modified item array
147 * @throws \UnexpectedValueException
148 */
149 protected function addItemsFromSpecial(array $result, $fieldName, array $items)
150 {
151 // Guard
152 if (empty($result['processedTca']['columns'][$fieldName]['config']['special'])
153 || !is_string($result['processedTca']['columns'][$fieldName]['config']['special'])
154 ) {
155 return $items;
156 }
157
158 $languageService = $this->getLanguageService();
159 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
160
161 $special = $result['processedTca']['columns'][$fieldName]['config']['special'];
162 switch (true) {
163 case ($special === 'tables'):
164 foreach ($GLOBALS['TCA'] as $currentTable => $_) {
165 if (!empty($GLOBALS['TCA'][$currentTable]['ctrl']['adminOnly'])) {
166 // Hide "admin only" tables
167 continue;
168 }
169 $label = !empty($GLOBALS['TCA'][$currentTable]['ctrl']['title']) ? $GLOBALS['TCA'][$currentTable]['ctrl']['title'] : '';
170 $icon = $iconFactory->mapRecordTypeToIconIdentifier($currentTable, []);
171 $helpText = [];
172 $languageService->loadSingleTableDescription($currentTable);
173 // @todo: check if this actually works, currently help texts are missing
174 $helpTextArray = $GLOBALS['TCA_DESCR'][$currentTable]['columns'][''];
175 if (!empty($helpTextArray['description'])) {
176 $helpText['description'] = $helpTextArray['description'];
177 }
178 $items[] = [$label, $currentTable, $icon, $helpText];
179 }
180 break;
181 case ($special === 'pagetypes'):
182 if (isset($GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'])
183 && is_array($GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'])
184 ) {
185 $specialItems = $GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'];
186 foreach ($specialItems as $specialItem) {
187 if (!is_array($specialItem) || $specialItem[1] === '--div--') {
188 // Skip non arrays and divider items
189 continue;
190 }
191 $label = $specialItem[0];
192 $value = $specialItem[1];
193 $icon = $iconFactory->mapRecordTypeToIconIdentifier('pages', ['doktype' => $specialItem[1]]);
194 $items[] = [$label, $value, $icon];
195 }
196 }
197 break;
198 case ($special === 'exclude'):
199 $excludeArrays = $this->getExcludeFields();
200 foreach ($excludeArrays as $excludeArray) {
201 // If the field comes from a FlexForm, the syntax is more complex
202 if ($excludeArray['origin'] === 'flexForm') {
203 // The field comes from a plugins FlexForm
204 // Add header if not yet set for plugin section
205 if (!isset($items[$excludeArray['sectionHeader']])) {
206 // there is no icon handling for plugins - we take the icon from the table
207 $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], array());
208 $items[$excludeArray['sectionHeader']] = [
209 $excludeArray['sectionHeader'],
210 '--div--',
211 $icon
212 ];
213 }
214 } else {
215 // Add header if not yet set for table
216 if (!isset($items[$excludeArray['table']])) {
217 $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], array());
218 $items[$excludeArray['table']] = [
219 $GLOBALS['TCA'][$excludeArray['table']]['ctrl']['title'],
220 '--div--',
221 $icon
222 ];
223 }
224 }
225 // Add help text
226 $helpText = [];
227 $languageService->loadSingleTableDescription($excludeArray['table']);
228 $helpTextArray = $GLOBALS['TCA_DESCR'][$excludeArray['table']]['columns'][$excludeArray['table']];
229 if (!empty($helpTextArray['description'])) {
230 $helpText['description'] = $helpTextArray['description'];
231 }
232 // Item configuration:
233 $items[] = array(
234 rtrim($excludeArray['origin'] === 'flexForm' ? $excludeArray['fieldLabel'] : $languageService->sL($GLOBALS['TCA'][$excludeArray['table']]['columns'][$excludeArray['fieldName']]['label']), ':') . ' (' . $excludeArray['fieldName'] . ')',
235 $excludeArray['table'] . ':' . $excludeArray['fullField'] ,
236 'empty-empty',
237 $helpText
238 );
239 }
240 break;
241 case ($special === 'explicitValues'):
242 $theTypes = $this->getExplicitAuthFieldValues();
243 $icons = [
244 'ALLOW' => 'status-status-permission-granted',
245 'DENY' => 'status-status-permission-denied'
246 ];
247 // Traverse types:
248 foreach ($theTypes as $tableFieldKey => $theTypeArrays) {
249 if (is_array($theTypeArrays['items'])) {
250 // Add header:
251 $items[] = [
252 $theTypeArrays['tableFieldLabel'],
253 '--div--',
254 ];
255 // Traverse options for this field:
256 foreach ($theTypeArrays['items'] as $itemValue => $itemContent) {
257 // Add item to be selected:
258 $items[] = [
259 '[' . $itemContent[2] . '] ' . $itemContent[1],
260 $tableFieldKey . ':' . preg_replace('/[:|,]/', '', $itemValue) . ':' . $itemContent[0],
261 $icons[$itemContent[0]]
262 ];
263 }
264 }
265 }
266 break;
267 case ($special === 'languages'):
268 foreach ($result['systemLanguageRows'] as $language) {
269 if ($language['uid'] !== -1) {
270 $items[] = [
271 0 => $language['title'] . ' [' . $language['uid'] . ']',
272 1 => $language['uid'],
273 2 => $language['flagIconIdentifier']
274 ];
275 }
276 }
277 break;
278 case ($special === 'custom'):
279 $customOptions = $GLOBALS['TYPO3_CONF_VARS']['BE']['customPermOptions'];
280 if (is_array($customOptions)) {
281 foreach ($customOptions as $coKey => $coValue) {
282 if (is_array($coValue['items'])) {
283 // Add header:
284 $items[] = [
285 $languageService->sL($coValue['header']),
286 '--div--'
287 ];
288 // Traverse items:
289 foreach ($coValue['items'] as $itemKey => $itemCfg) {
290 $icon = 'empty-empty';
291 $helpText = [];
292 if (!empty($itemCfg[2])) {
293 $helpText['description'] = $languageService->sL($itemCfg[2]);
294 }
295 $items[] = [
296 $languageService->sL($itemCfg[0]),
297 $coKey . ':' . preg_replace('/[:|,]/', '', $itemKey),
298 $icon,
299 $helpText
300 ];
301 }
302 }
303 }
304 }
305 break;
306 case ($special === 'modListGroup' || $special === 'modListUser'):
307 $loadModules = GeneralUtility::makeInstance(ModuleLoader::class);
308 $loadModules->load($GLOBALS['TBE_MODULES']);
309 $modList = $special === 'modListUser' ? $loadModules->modListUser : $loadModules->modListGroup;
310 if (is_array($modList)) {
311 foreach ($modList as $theMod) {
312 // Icon:
313 if (strpos($theMod, '_') !== false) {
314 list($mainModule, $subModule) = explode('_', $theMod, 2);
315 $icon = $loadModules->modules[$mainModule]['sub'][$subModule]['iconIdentifier'];
316 } else {
317 $icon = $loadModules->modules[$theMod]['iconIdentifier'];
318 }
319 if ($icon) {
320 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
321 $icon = $iconFactory->getIcon($icon)->render();
322 }
323 // Add help text
324 $helpText = [
325 'title' => $languageService->moduleLabels['labels'][$theMod . '_tablabel'],
326 'description' => $languageService->moduleLabels['labels'][$theMod . '_tabdescr']
327 ];
328
329 $label = '';
330 // Add label for main module:
331 $pp = explode('_', $theMod);
332 if (count($pp) > 1) {
333 $label .= $languageService->moduleLabels['tabs'][$pp[0] . '_tab'] . '>';
334 }
335 // Add modules own label now:
336 $label .= $languageService->moduleLabels['tabs'][$theMod . '_tab'];
337
338 // Item configuration:
339 $items[] = [$label, $theMod, $icon, $helpText];
340 }
341 }
342 break;
343 default:
344 throw new \UnexpectedValueException(
345 'Unknown special value ' . $special . ' for field ' . $fieldName . ' of table ' . $result['tableName'],
346 1439298496
347 );
348 }
349 return $items;
350 }
351
352 /**
353 * TCA config "fileFolder" evaluation. Add them to $items
354 *
355 * Used by TcaSelectItems and TcaSelectTreeItems data providers
356 *
357 * @param array $result Result array
358 * @param string $fieldName Current handle field name
359 * @param array $items Incoming items
360 * @return array Modified item array
361 */
362 protected function addItemsFromFolder(array $result, $fieldName, array $items)
363 {
364 if (empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
365 || !is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
366 ) {
367 return $items;
368 }
369
370 $fileFolder = $result['processedTca']['columns'][$fieldName]['config']['fileFolder'];
371 $fileFolder = GeneralUtility::getFileAbsFileName($fileFolder);
372 $fileFolder = rtrim($fileFolder, '/') . '/';
373
374 if (@is_dir($fileFolder)) {
375 $fileExtensionList = '';
376 if (!empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
377 && is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
378 ) {
379 $fileExtensionList = $result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'];
380 }
381 $recursionLevels = isset($fieldValue['config']['fileFolder_recursions'])
382 ? MathUtility::forceIntegerInRange($fieldValue['config']['fileFolder_recursions'], 0, 99)
383 : 99;
384 $fileArray = GeneralUtility::getAllFilesAndFoldersInPath([], $fileFolder, $fileExtensionList, 0, $recursionLevels);
385 $fileArray = GeneralUtility::removePrefixPathFromList($fileArray, $fileFolder);
386 foreach ($fileArray as $fileReference) {
387 $fileInformation = pathinfo($fileReference);
388 $icon = GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], strtolower($fileInformation['extension']))
389 ? '../' . PathUtility::stripPathSitePrefix($fileFolder) . $fileReference
390 : '';
391 $items[] = [
392 $fileReference,
393 $fileReference,
394 $icon
395 ];
396 }
397 }
398
399 return $items;
400 }
401
402 /**
403 * TCA config "foreign_table" evaluation. Add them to $items
404 *
405 * Used by TcaSelectItems and TcaSelectTreeItems data providers
406 *
407 * @param array $result Result array
408 * @param string $fieldName Current handle field name
409 * @param array $items Incoming items
410 * @return array Modified item array
411 */
412 protected function addItemsFromForeignTable(array $result, $fieldName, array $items)
413 {
414 // Guard
415 if (empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
416 || !is_string($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
417 ) {
418 return $items;
419 }
420
421 $languageService = $this->getLanguageService();
422 $database = $this->getDatabaseConnection();
423
424 $foreignTable = $result['processedTca']['columns'][$fieldName]['config']['foreign_table'];
425 $foreignTableQueryArray = $this->buildForeignTableQuery($result, $fieldName);
426 $queryResource = $database->exec_SELECT_queryArray($foreignTableQueryArray);
427
428 // Early return on error with flash message
429 $databaseError = $database->sql_error();
430 if (!empty($databaseError)) {
431 $msg = htmlspecialchars($databaseError) . '<br />' . LF;
432 $msg .= $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch');
433 $msgTitle = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch_title');
434 /** @var $flashMessage FlashMessage */
435 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, $msgTitle, FlashMessage::ERROR, true);
436 /** @var $flashMessageService FlashMessageService */
437 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
438 /** @var $defaultFlashMessageQueue FlashMessageQueue */
439 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
440 $defaultFlashMessageQueue->enqueue($flashMessage);
441 $database->sql_free_result($queryResource);
442 return $items;
443 }
444
445 $labelPrefix = '';
446 if (!empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'])) {
447 $labelPrefix = $result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'];
448 $labelPrefix = $languageService->sL($labelPrefix);
449 }
450 $iconFieldName = '';
451 if (!empty($result['processedTca']['ctrl']['selicon_field'])) {
452 $iconFieldName = $result['processedTca']['ctrl']['selicon_field'];
453 }
454 $iconPath = '';
455 if (!empty($result['processedTca']['ctrl']['selicon_field_path'])) {
456 $iconPath = $result['processedTca']['ctrl']['selicon_field_path'];
457 }
458
459 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
460
461 while ($foreignRow = $database->sql_fetch_assoc($queryResource)) {
462 BackendUtility::workspaceOL($foreignTable, $foreignRow);
463 if (is_array($foreignRow)) {
464 // Prepare the icon if available:
465 if ($iconFieldName && $iconPath && $foreignRow[$iconFieldName]) {
466 $iParts = GeneralUtility::trimExplode(',', $foreignRow[$iconFieldName], true);
467 $icon = '../' . $iconPath . '/' . trim($iParts[0]);
468 } else {
469 $icon = $iconFactory->mapRecordTypeToIconIdentifier($foreignTable, $foreignRow);
470 }
471 // Add the item
472 $items[] = [
473 $labelPrefix . htmlspecialchars(BackendUtility::getRecordTitle($foreignTable, $foreignRow)),
474 $foreignRow['uid'],
475 $icon
476 ];
477 }
478 }
479
480 $database->sql_free_result($queryResource);
481
482 return $items;
483 }
484
485 /**
486 * Remove items using "keepItems" pageTsConfig
487 *
488 * Used by TcaSelectItems and TcaSelectTreeItems data providers
489 *
490 * @param array $result Result array
491 * @param string $fieldName Current handle field name
492 * @param array $items Incoming items
493 * @return array Modified item array
494 */
495 protected function removeItemsByKeepItemsPageTsConfig(array $result, $fieldName, array $items)
496 {
497 $table = $result['tableName'];
498 if (!isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
499 || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
500 ) {
501 return $items;
502 }
503
504 // If keepItems is set but is an empty list all current items get removed
505 if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
506 && $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'] !== '0') {
507 return [];
508 }
509
510 return ArrayUtility::keepItemsInArray(
511 $items,
512 $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'],
513 function ($value) {
514 return $value[1];
515 }
516 );
517 }
518
519 /**
520 * Remove items using "removeItems" pageTsConfig
521 *
522 * Used by TcaSelectItems and TcaSelectTreeItems data providers
523 *
524 * @param array $result Result array
525 * @param string $fieldName Current handle field name
526 * @param array $items Incoming items
527 * @return array Modified item array
528 */
529 protected function removeItemsByRemoveItemsPageTsConfig(array $result, $fieldName, array $items)
530 {
531 $table = $result['tableName'];
532 if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
533 || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
534 ) {
535 return $items;
536 }
537
538 $removeItems = GeneralUtility::trimExplode(
539 ',',
540 $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'],
541 true
542 );
543 foreach ($items as $key => $itemValues) {
544 if (in_array($itemValues[1], $removeItems)) {
545 unset($items[$key]);
546 }
547 }
548
549 return $items;
550 }
551
552 /**
553 * Remove items user restriction on language field
554 *
555 * Used by TcaSelectItems and TcaSelectTreeItems data providers
556 *
557 * @param array $result Result array
558 * @param string $fieldName Current handle field name
559 * @param array $items Incoming items
560 * @return array Modified item array
561 */
562 protected function removeItemsByUserLanguageFieldRestriction(array $result, $fieldName, array $items)
563 {
564 // Guard clause returns if not a language field is handled
565 if (empty($result['processedTca']['ctrl']['languageField'])
566 || $result['processedTca']['ctrl']['languageField'] !== $fieldName
567 ) {
568 return $items;
569 }
570
571 $backendUser = $this->getBackendUser();
572 foreach ($items as $key => $itemValues) {
573 if (!$backendUser->checkLanguageAccess($itemValues[1])) {
574 unset($items[$key]);
575 }
576 }
577
578 return $items;
579 }
580
581 /**
582 * Remove items by user restriction on authMode items
583 *
584 * Used by TcaSelectItems and TcaSelectTreeItems data providers
585 *
586 * @param array $result Result array
587 * @param string $fieldName Current handle field name
588 * @param array $items Incoming items
589 * @return array Modified item array
590 */
591 protected function removeItemsByUserAuthMode(array $result, $fieldName, array $items)
592 {
593 // Guard clause returns early if no authMode field is configured
594 if (!isset($result['processedTca']['columns'][$fieldName]['config']['authMode'])
595 || !is_string($result['processedTca']['columns'][$fieldName]['config']['authMode'])
596 ) {
597 return $items;
598 }
599
600 $backendUser = $this->getBackendUser();
601 $authMode = $result['processedTca']['columns'][$fieldName]['config']['authMode'];
602 foreach ($items as $key => $itemValues) {
603 // @todo: checkAuthMode() uses $GLOBAL access for "individual" authMode - get rid of this
604 if (!$backendUser->checkAuthMode($result['tableName'], $fieldName, $itemValues[1], $authMode)) {
605 unset($items[$key]);
606 }
607 }
608
609 return $items;
610 }
611
612 /**
613 * Remove items if doktype is handled for non admin users
614 *
615 * Used by TcaSelectItems and TcaSelectTreeItems data providers
616 *
617 * @param array $result Result array
618 * @param string $fieldName Current handle field name
619 * @param array $items Incoming items
620 * @return array Modified item array
621 */
622 protected function removeItemsByDoktypeUserRestriction(array $result, $fieldName, array $items)
623 {
624 $table = $result['tableName'];
625 $backendUser = $this->getBackendUser();
626 // Guard clause returns if not correct table and field or if user is admin
627 if ($table !== 'pages' && $table !== 'pages_language_overlay'
628 || $fieldName !== 'doktype' || $backendUser->isAdmin()
629 ) {
630 return $items;
631 }
632
633 $allowedPageTypes = $backendUser->groupData['pagetypes_select'];
634 foreach ($items as $key => $itemValues) {
635 if (!GeneralUtility::inList($allowedPageTypes, $itemValues[1])) {
636 unset($items[$key]);
637 }
638 }
639
640 return $items;
641 }
642
643 /**
644 * Returns an array with the exclude fields as defined in TCA and FlexForms
645 * Used for listing the exclude fields in be_groups forms.
646 *
647 * @return array Array of arrays with excludeFields (fieldName, table:fieldName) from TCA
648 * and FlexForms (fieldName, table:extKey;sheetName;fieldName)
649 */
650 protected function getExcludeFields()
651 {
652 $languageService = $this->getLanguageService();
653 $finalExcludeArray = [];
654
655 // Fetch translations for table names
656 $tableToTranslation = [];
657 // All TCA keys
658 foreach ($GLOBALS['TCA'] as $table => $conf) {
659 $tableToTranslation[$table] = $languageService->sL($conf['ctrl']['title']);
660 }
661 // Sort by translations
662 asort($tableToTranslation);
663 foreach ($tableToTranslation as $table => $translatedTable) {
664 $excludeArrayTable = [];
665
666 // All field names configured and not restricted to admins
667 if (is_array($GLOBALS['TCA'][$table]['columns'])
668 && empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly'])
669 && (empty($GLOBALS['TCA'][$table]['ctrl']['rootLevel']) || !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']))
670 ) {
671 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $_) {
672 if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
673 // Get human readable names of fields
674 $translatedField = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
675 // Add entry, key 'labels' needed for sorting
676 $excludeArrayTable[] = [
677 'labels' => $translatedTable . ':' . $translatedField,
678 'sectionHeader' => $translatedTable,
679 'table' => $table,
680 'tableField' => $field,
681 'fieldName' => $field,
682 'fullField' => $field,
683 'fieldLabel' => $translatedField,
684 'origin' => 'tca',
685 ];
686 }
687 }
688 }
689 // All FlexForm fields
690 $flexFormArray = $this->getRegisteredFlexForms($table);
691 foreach ($flexFormArray as $tableField => $flexForms) {
692 // Prefix for field label, e.g. "Plugin Options:"
693 $labelPrefix = '';
694 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
695 $labelPrefix = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
696 }
697 // Get all sheets and title
698 foreach ($flexForms as $extIdent => $extConf) {
699 $extTitle = $languageService->sl(trim($extConf['title']));
700 // Get all fields in sheet
701 foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
702 if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
703 continue;
704 }
705 foreach ($sheet['ROOT']['el'] as $pluginFieldName => $field) {
706 // Use only fields that have exclude flag set
707 if (empty($field['TCEforms']['exclude'])) {
708 continue;
709 }
710 $fieldLabel = !empty($field['TCEforms']['label'])
711 ? $languageService->sL($field['TCEforms']['label'])
712 : $pluginFieldName;
713 $excludeArrayTable[] = [
714 'labels' => trim($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent, ': ') . ':' . $fieldLabel,
715 'sectionHeader' => trim(($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent), ':'),
716 'table' => $table,
717 'tableField' => $tableField,
718 'extIdent' => $extIdent,
719 'fieldName' => $pluginFieldName,
720 'fullField' => $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $pluginFieldName,
721 'fieldLabel' => $fieldLabel,
722 'origin' => 'flexForm',
723 ];
724 }
725 }
726 }
727 }
728 // Sort fields by the translated value
729 if (!empty($excludeArrayTable)) {
730 usort($excludeArrayTable, function (array $array1, array $array2) {
731 $array1 = reset($array1);
732 $array2 = reset($array2);
733 if (is_string($array1) && is_string($array2)) {
734 return strcasecmp($array1, $array2);
735 }
736 return 0;
737 });
738 $finalExcludeArray = array_merge($finalExcludeArray, $excludeArrayTable);
739 }
740 }
741
742 return $finalExcludeArray;
743 }
744
745 /**
746 * Returns all registered FlexForm definitions with title and fields
747 *
748 * @param string $table Table to handle
749 * @return array Data structures with speaking extension title
750 */
751 protected function getRegisteredFlexForms($table)
752 {
753 if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
754 return [];
755 }
756 $flexForms = [];
757 foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
758 if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
759 $flexForms[$tableField] = [];
760 // Get pointer fields
761 $pointerFields = !empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType,default';
762 $pointerFields = GeneralUtility::trimExplode(',', $pointerFields);
763 // Get FlexForms
764 foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStructure) {
765 // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
766 $identFields = GeneralUtility::trimExplode(',', $flexFormKey);
767 $extIdent = $identFields[0];
768 if (!empty($identFields[1]) && $identFields[1] !== 'list' && $identFields[1] !== '*') {
769 $extIdent = $identFields[1];
770 }
771 // Load external file references
772 if (!is_array($dataStructure)) {
773 $file = GeneralUtility::getFileAbsFileName(str_ireplace('FILE:', '', $dataStructure));
774 if ($file && @is_file($file)) {
775 $dataStructure = GeneralUtility::getUrl($file);
776 }
777 $dataStructure = GeneralUtility::xml2array($dataStructure);
778 if (!is_array($dataStructure)) {
779 continue;
780 }
781 }
782 // Get flexform content
783 $dataStructure = GeneralUtility::resolveAllSheetsInDS($dataStructure);
784 if (empty($dataStructure['sheets']) || !is_array($dataStructure['sheets'])) {
785 continue;
786 }
787 // Use DS pointer to get extension title from TCA
788 // @todo: I don't understand this code ... does it make sense at all?
789 $title = $extIdent;
790 $keyFields = GeneralUtility::trimExplode(',', $flexFormKey);
791 foreach ($pointerFields as $pointerKey => $pointerName) {
792 if (empty($keyFields[$pointerKey])
793 || $keyFields[$pointerKey] === '*'
794 || $keyFields[$pointerKey] === 'list'
795 || $keyFields[$pointerKey] === 'default'
796 ) {
797 continue;
798 }
799 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
800 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
801 if (!is_array($items)) {
802 continue;
803 }
804 foreach ($items as $itemConf) {
805 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
806 $title = $itemConf[0];
807 break 2;
808 }
809 }
810 }
811 }
812 $flexForms[$tableField][$extIdent] = [
813 'title' => $title,
814 'ds' => $dataStructure
815 ];
816 }
817 }
818 }
819 return $flexForms;
820 }
821
822 /**
823 * Returns an array with explicit Allow/Deny fields.
824 * Used for listing these field/value pairs in be_groups forms
825 *
826 * @return array Array with information from all of $GLOBALS['TCA']
827 */
828 protected function getExplicitAuthFieldValues()
829 {
830 $languageService = static::getLanguageService();
831 $adLabel = [
832 'ALLOW' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.allow'),
833 'DENY' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.deny')
834 ];
835 $allowDenyOptions = [];
836 foreach ($GLOBALS['TCA'] as $table => $_) {
837 // All field names configured:
838 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
839 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $__) {
840 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
841 if ($fieldConfig['type'] === 'select' && $fieldConfig['authMode']) {
842 // Check for items
843 if (is_array($fieldConfig['items'])) {
844 // Get Human Readable names of fields and table:
845 $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] =
846 $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']) . ': '
847 . $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
848 foreach ($fieldConfig['items'] as $iVal) {
849 // Values '' is not controlled by this setting.
850 if ((string)$iVal[1] !== '') {
851 // Find iMode
852 $iMode = '';
853 switch ((string)$fieldConfig['authMode']) {
854 case 'explicitAllow':
855 $iMode = 'ALLOW';
856 break;
857 case 'explicitDeny':
858 $iMode = 'DENY';
859 break;
860 case 'individual':
861 if ($iVal[4] === 'EXPL_ALLOW') {
862 $iMode = 'ALLOW';
863 } elseif ($iVal[4] === 'EXPL_DENY') {
864 $iMode = 'DENY';
865 }
866 break;
867 }
868 // Set iMode
869 if ($iMode) {
870 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = [
871 $iMode,
872 $languageService->sL($iVal[0]),
873 $adLabel[$iMode]
874 ];
875 }
876 }
877 }
878 }
879 }
880 }
881 }
882 }
883 return $allowDenyOptions;
884 }
885
886 /**
887 * Build query to fetch foreign records
888 *
889 * @param array $result Result array
890 * @param string $localFieldName Current handle field name
891 * @return array Query array ready to be executed via Database->exec_SELECT_queryArray()
892 * @throws \UnexpectedValueException
893 */
894 protected function buildForeignTableQuery(array $result, $localFieldName)
895 {
896 $backendUser = $this->getBackendUser();
897
898 $foreignTableName = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table'];
899
900 if (!is_array($GLOBALS['TCA'][$foreignTableName])) {
901 throw new \UnexpectedValueException(
902 'Field ' . $localFieldName . ' of table ' . $result['tableName'] . ' reference to foreign table '
903 . $foreignTableName . ', but this table is not defined in TCA',
904 1439569743
905 );
906 }
907
908 $foreignTableClauseArray = $this->processForeignTableClause($result, $foreignTableName, $localFieldName);
909
910 $queryArray = [];
911 $queryArray['SELECT'] = BackendUtility::getCommonSelectFields($foreignTableName, $foreignTableName . '.');
912
913 // rootLevel = -1 means that elements can be on the rootlevel OR on any page (pid!=-1)
914 // rootLevel = 0 means that elements are not allowed on root level
915 // rootLevel = 1 means that elements are only on the root level (pid=0)
916 $rootLevel = 0;
917 if (isset($GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'])) {
918 $rootLevel = $GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'];
919 }
920 $deleteClause = BackendUtility::deleteClause($foreignTableName);
921 if ($rootLevel == 1 || $rootLevel == -1) {
922 $pidWhere = $foreignTableName . '.pid' . (($rootLevel == -1) ? '<>-1' : '=0');
923 $queryArray['FROM'] = $foreignTableName;
924 $queryArray['WHERE'] = $pidWhere . $deleteClause . $foreignTableClauseArray['WHERE'];
925 } else {
926 $pageClause = $backendUser->getPagePermsClause(1);
927 if ($foreignTableName === 'pages') {
928 $queryArray['FROM'] = 'pages';
929 $queryArray['WHERE'] = '1=1' . $deleteClause . ' AND' . $pageClause . $foreignTableClauseArray['WHERE'];
930 } else {
931 $queryArray['FROM'] = $foreignTableName . ', pages';
932 $queryArray['WHERE'] = 'pages.uid=' . $foreignTableName . '.pid AND pages.deleted=0'
933 . $deleteClause . ' AND' . $pageClause . $foreignTableClauseArray['WHERE'];
934 }
935 }
936
937 $queryArray['GROUPBY'] = $foreignTableClauseArray['GROUPBY'];
938 $queryArray['ORDERBY'] = $foreignTableClauseArray['ORDERBY'];
939 $queryArray['LIMIT'] = $foreignTableClauseArray['LIMIT'];
940
941 return $queryArray;
942 }
943
944 /**
945 * Replace markers in a where clause from TCA foreign_table_where
946 *
947 * ###REC_FIELD_[field name]###
948 * ###THIS_UID### - is current element uid (zero if new).
949 * ###CURRENT_PID### - is the current page id (pid of the record).
950 * ###SITEROOT###
951 * ###PAGE_TSCONFIG_ID### - a value you can set from Page TSconfig dynamically.
952 * ###PAGE_TSCONFIG_IDLIST### - a value you can set from Page TSconfig dynamically.
953 * ###PAGE_TSCONFIG_STR### - a value you can set from Page TSconfig dynamically.
954 *
955 * @param array $result Result array
956 * @param string $foreignTableName Name of foreign table
957 * @param string $localFieldName Current handle field name
958 * @return array Query parts with keys WHERE, ORDERBY, GROUPBY, LIMIT
959 */
960 protected function processForeignTableClause(array $result, $foreignTableName, $localFieldName)
961 {
962 $database = $this->getDatabaseConnection();
963 $localTable = $result['tableName'];
964
965 $foreignTableClause = '';
966 if (!empty($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
967 && is_string($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
968 ) {
969 $foreignTableClause = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'];
970 // Replace possible markers in query
971 if (strstr($foreignTableClause, '###REC_FIELD_')) {
972 // " AND table.field='###REC_FIELD_field1###' AND ..." -> array(" AND table.field='", "field1###' AND ...")
973 $whereClauseParts = explode('###REC_FIELD_', $foreignTableClause);
974 foreach ($whereClauseParts as $key => $value) {
975 if ($key !== 0) {
976 // "field1###' AND ..." -> array("field1", "' AND ...")
977 $whereClauseSubParts = explode('###', $value, 2);
978 // @todo: Throw exception if there is no value? What happens for NEW records?
979 $databaseRowKey = empty($result['flexParentDatabaseRow']) ? 'databaseRow' : 'flexParentDatabaseRow';
980 $rowFieldValue = isset($result[$databaseRowKey][$whereClauseSubParts[0]]) ? $result[$databaseRowKey][$whereClauseSubParts[0]] : '';
981 if (is_array($rowFieldValue)) {
982 // If a select or group field is used here, it may have been processed already and
983 // is now an array. Use first selected value in this case.
984 $rowFieldValue = $rowFieldValue[0];
985 }
986 if (substr($whereClauseParts[0], -1) === '\'' && $whereClauseSubParts[1][0] === '\'') {
987 $whereClauseParts[$key] = $database->quoteStr($rowFieldValue, $foreignTableName) . $whereClauseSubParts[1];
988 } else {
989 $whereClauseParts[$key] = $database->fullQuoteStr($rowFieldValue, $foreignTableName) . $whereClauseSubParts[1];
990 }
991 }
992 }
993 $foreignTableClause = implode('', $whereClauseParts);
994 }
995
996 $siteRootUid = 0;
997 foreach ($result['rootline'] as $rootlinePage) {
998 if (!empty($rootlinePage['is_siteroot'])) {
999 $siteRootUid = (int)$rootlinePage['uid'];
1000 break;
1001 }
1002 }
1003 $pageTsConfigId = 0;
1004 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID']) {
1005 $pageTsConfigId = (int)$result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID'];
1006 }
1007 $pageTsConfigIdList = 0;
1008 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST']) {
1009 $pageTsConfigIdList = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST'];
1010 $pageTsConfigIdListArray = GeneralUtility::trimExplode(',', $pageTsConfigIdList, true);
1011 $pageTsConfigIdList = [];
1012 foreach ($pageTsConfigIdListArray as $pageTsConfigIdListElement) {
1013 if (MathUtility::canBeInterpretedAsInteger($pageTsConfigIdListElement)) {
1014 $pageTsConfigIdList[] = (int)$pageTsConfigIdListElement;
1015 }
1016 }
1017 $pageTsConfigIdList = implode(',', $pageTsConfigIdList);
1018 }
1019 $pageTsConfigString = '';
1020 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR']) {
1021 $pageTsConfigString = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR'];
1022 $pageTsConfigString = $database->quoteStr($pageTsConfigString, $foreignTableName);
1023 }
1024
1025 $foreignTableClause = str_replace(
1026 [
1027 '###CURRENT_PID###',
1028 '###THIS_UID###',
1029 '###SITEROOT###',
1030 '###PAGE_TSCONFIG_ID###',
1031 '###PAGE_TSCONFIG_IDLIST###',
1032 '###PAGE_TSCONFIG_STR###'
1033 ],
1034 [
1035 (int)$result['effectivePid'],
1036 (int)$result['databaseRow']['uid'],
1037 $siteRootUid,
1038 $pageTsConfigId,
1039 $pageTsConfigIdList,
1040 $pageTsConfigString
1041 ],
1042 $foreignTableClause
1043 );
1044 }
1045
1046 // Split the clause into an array with keys WHERE, GROUPBY, ORDERBY, LIMIT
1047 // Prepend a space to make sure "[[:space:]]+" will find a space there for the first element.
1048 $foreignTableClause = ' ' . $foreignTableClause;
1049 $foreignTableClauseArray = [
1050 'WHERE' => '',
1051 'GROUPBY' => '',
1052 'ORDERBY' => '',
1053 'LIMIT' => '',
1054 ];
1055 // Find LIMIT
1056 $reg = [];
1057 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1058 $foreignTableClauseArray['LIMIT'] = trim($reg[2]);
1059 $foreignTableClause = $reg[1];
1060 }
1061 // Find ORDER BY
1062 $reg = [];
1063 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1064 $foreignTableClauseArray['ORDERBY'] = trim($reg[2]);
1065 $foreignTableClause = $reg[1];
1066 }
1067 // Find GROUP BY
1068 $reg = [];
1069 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1070 $foreignTableClauseArray['GROUPBY'] = trim($reg[2]);
1071 $foreignTableClause = $reg[1];
1072 }
1073 // Rest is assumed to be "WHERE" clause
1074 $foreignTableClauseArray['WHERE'] = $foreignTableClause;
1075
1076 return $foreignTableClauseArray;
1077 }
1078
1079 /**
1080 * Convert the current database values into an array
1081 *
1082 * @param array $row database row
1083 * @param string $fieldName fieldname to process
1084 * @return array
1085 */
1086 protected function processDatabaseFieldValue(array $row, $fieldName)
1087 {
1088 $currentDatabaseValues = array_key_exists($fieldName, $row)
1089 ? $row[$fieldName]
1090 : '';
1091 return GeneralUtility::trimExplode(',', $currentDatabaseValues, true);
1092 }
1093
1094 /**
1095 * Validate and sanitize database row values of the select field with the given name.
1096 * Creates an array out of databaseRow[selectField] values.
1097 *
1098 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1099 *
1100 * @param array $result The current result array.
1101 * @param string $fieldName Name of the current select field.
1102 * @param array $staticValues Array with statically defined items, item value is used as array key.
1103 * @return array
1104 */
1105 protected function processSelectFieldValue(array $result, $fieldName, array $staticValues)
1106 {
1107 $fieldConfig = $result['processedTca']['columns'][$fieldName];
1108
1109 $currentDatabaseValueArray = array_key_exists($fieldName, $result['databaseRow']) ? $result['databaseRow'][$fieldName] : [];
1110 $newDatabaseValueArray = [];
1111
1112 // Add all values that were defined by static methods and do not come from the relation
1113 // e.g. TCA, TSconfig, itemProcFunc etc.
1114 foreach ($currentDatabaseValueArray as $value) {
1115 if (isset($staticValues[$value])) {
1116 $newDatabaseValueArray[] = $value;
1117 }
1118 }
1119
1120 if (isset($fieldConfig['config']['foreign_table']) && !empty($fieldConfig['config']['foreign_table'])) {
1121 /** @var RelationHandler $relationHandler */
1122 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1123 $relationHandler->registerNonTableValues = !empty($fieldConfig['config']['allowNonIdValues']);
1124 if (!empty($fieldConfig['config']['MM']) && $result['command'] !== 'new') {
1125 // MM relation
1126 $relationHandler->start(
1127 implode(',', $currentDatabaseValueArray),
1128 $fieldConfig['config']['foreign_table'],
1129 $fieldConfig['config']['MM'],
1130 $result['databaseRow']['uid'],
1131 $result['tableName'],
1132 $fieldConfig['config']
1133 );
1134 } else {
1135 // Non MM relation
1136 // If not dealing with MM relations, use default live uid, not versioned uid for record relations
1137 $relationHandler->start(
1138 implode(',', $currentDatabaseValueArray),
1139 $fieldConfig['config']['foreign_table'],
1140 '',
1141 $this->getLiveUid($result),
1142 $result['tableName'],
1143 $fieldConfig['config']
1144 );
1145 }
1146 $newDatabaseValueArray = array_merge($newDatabaseValueArray, $relationHandler->getValueArray());
1147 }
1148
1149 return array_unique($newDatabaseValueArray);
1150 }
1151
1152 /**
1153 * Translate the item labels
1154 *
1155 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1156 *
1157 * @param array $result Result array
1158 * @param array $itemArray Items
1159 * @param string $table
1160 * @param string $fieldName
1161 * @return array
1162 */
1163 public function translateLabels(array $result, array $itemArray, $table, $fieldName)
1164 {
1165 $languageService = $this->getLanguageService();
1166
1167 foreach ($itemArray as $key => $item) {
1168 if (!isset($dynamicItems[$key])) {
1169 $staticValues[$item[1]] = $item;
1170 }
1171 if (isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
1172 && !empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
1173 ) {
1174 $label = $languageService->sL($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]]);
1175 } else {
1176 $label = $languageService->sL(trim($item[0]));
1177 }
1178 $value = strlen((string)$item[1]) > 0 ? $item[1] : '';
1179 $icon = $item[2] ?: null;
1180 $helpText = $item[3] ?: null;
1181 $itemArray[$key] = [
1182 $label,
1183 $value,
1184 $icon,
1185 $helpText
1186 ];
1187 }
1188
1189 return $itemArray;
1190 }
1191
1192 /**
1193 * Sanitize incoming item array
1194 *
1195 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1196 *
1197 * @param mixed $itemArray
1198 * @param string $tableName
1199 * @param string $fieldName
1200 * @throws \UnexpectedValueException
1201 * @return array
1202 */
1203 public function sanitizeItemArray($itemArray, $tableName, $fieldName)
1204 {
1205 if (!is_array($itemArray)) {
1206 $itemArray = [];
1207 }
1208 foreach ($itemArray as $item) {
1209 if (!is_array($item)) {
1210 throw new \UnexpectedValueException(
1211 'An item in field ' . $fieldName . ' of table ' . $tableName . ' is not an array as expected',
1212 1439288036
1213 );
1214 }
1215 }
1216
1217 return $itemArray;
1218 }
1219
1220 /**
1221 * Make sure maxitems is always filled with a valid integer value.
1222 *
1223 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1224 *
1225 * @param mixed $maxItems
1226 * @return int
1227 */
1228 public function sanitizeMaxItems($maxItems)
1229 {
1230 if (!empty($maxItems)
1231 && (int)$maxItems > 1
1232 ) {
1233 $maxItems = (int)$maxItems;
1234 } else {
1235 $maxItems = 1;
1236 }
1237
1238 return $maxItems;
1239 }
1240
1241 /**
1242 * Gets the record uid of the live default record. If already
1243 * pointing to the live record, the submitted record uid is returned.
1244 *
1245 * @param array $result Result array
1246 * @return int
1247 * @throws \UnexpectedValueException
1248 */
1249 protected function getLiveUid(array $result)
1250 {
1251 $table = $result['tableName'];
1252 $row = $result['databaseRow'];
1253 $uid = $row['uid'];
1254 if (!empty($result['processedTca']['ctrl']['versioningWS'])
1255 && $result['pid'] === -1
1256 ) {
1257 if (empty($row['t3ver_oid'])) {
1258 throw new \UnexpectedValueException(
1259 'No t3ver_oid found for record ' . $row['uid'] . ' on table ' . $table,
1260 1440066481
1261 );
1262 }
1263 $uid = $row['t3ver_oid'];
1264 }
1265 return $uid;
1266 }
1267
1268 /**
1269 * Determine the static values in the item array
1270 *
1271 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1272 *
1273 * @param array $itemArray All item records for the select field
1274 * @param array $dynamicItemArray Item records from dynamic sources
1275 * @return array
1276 */
1277 public function getStaticValues($itemArray, $dynamicItemArray)
1278 {
1279 $staticValues = [];
1280 foreach ($itemArray as $key => $item) {
1281 if (!isset($dynamicItemArray[$key])) {
1282 $staticValues[$item[1]] = $item;
1283 }
1284 }
1285 return $staticValues;
1286 }
1287
1288 /**
1289 * @return LanguageService
1290 */
1291 protected function getLanguageService()
1292 {
1293 return $GLOBALS['LANG'];
1294 }
1295
1296 /**
1297 * @return DatabaseConnection
1298 */
1299 protected function getDatabaseConnection()
1300 {
1301 return $GLOBALS['TYPO3_DB'];
1302 }
1303
1304 /**
1305 * @return BackendUserAuthentication
1306 */
1307 protected function getBackendUser()
1308 {
1309 return $GLOBALS['BE_USER'];
1310 }
1311 }