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