[BUGFIX] Add check for valid directory name for TCA select fileFolder
[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 * @throws \RuntimeException
380 */
381 protected function addItemsFromFolder(array $result, $fieldName, array $items)
382 {
383 if (empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
384 || !is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
385 ) {
386 return $items;
387 }
388
389 $fileFolderRaw = $result['processedTca']['columns'][$fieldName]['config']['fileFolder'];
390 $fileFolder = GeneralUtility::getFileAbsFileName($fileFolderRaw);
391 if ($fileFolder === '') {
392 throw new \RuntimeException(
393 'Invalid folder given for item processing: ' . $fileFolderRaw . ' for table ' . $result['tableName'] . ', field ' . $fieldName,
394 1479399227
395 );
396 }
397 $fileFolder = rtrim($fileFolder, '/') . '/';
398
399 if (@is_dir($fileFolder)) {
400 $fileExtensionList = '';
401 if (!empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
402 && is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
403 ) {
404 $fileExtensionList = $result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'];
405 }
406 $recursionLevels = isset($fieldValue['config']['fileFolder_recursions'])
407 ? MathUtility::forceIntegerInRange($fieldValue['config']['fileFolder_recursions'], 0, 99)
408 : 99;
409 $fileArray = GeneralUtility::getAllFilesAndFoldersInPath([], $fileFolder, $fileExtensionList, 0, $recursionLevels);
410 $fileArray = GeneralUtility::removePrefixPathFromList($fileArray, $fileFolder);
411 foreach ($fileArray as $fileReference) {
412 $fileInformation = pathinfo($fileReference);
413 $icon = GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], strtolower($fileInformation['extension']))
414 ? '../' . PathUtility::stripPathSitePrefix($fileFolder) . $fileReference
415 : '';
416 $items[] = [
417 $fileReference,
418 $fileReference,
419 $icon
420 ];
421 }
422 }
423
424 return $items;
425 }
426
427 /**
428 * TCA config "foreign_table" evaluation. Add them to $items
429 *
430 * Used by TcaSelectItems and TcaSelectTreeItems data providers
431 *
432 * @param array $result Result array
433 * @param string $fieldName Current handle field name
434 * @param array $items Incoming items
435 * @return array Modified item array
436 * @throws \UnexpectedValueException
437 */
438 protected function addItemsFromForeignTable(array $result, $fieldName, array $items)
439 {
440 // Guard
441 if (empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
442 || !is_string($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
443 ) {
444 return $items;
445 }
446
447 $languageService = $this->getLanguageService();
448 $database = $this->getDatabaseConnection();
449
450 $foreignTable = $result['processedTca']['columns'][$fieldName]['config']['foreign_table'];
451
452 if (!is_array($GLOBALS['TCA'][$foreignTable])) {
453 throw new \UnexpectedValueException(
454 'Field ' . $fieldName . ' of table ' . $result['tableName'] . ' reference to foreign table '
455 . $foreignTable . ', but this table is not defined in TCA',
456 1439569743
457 );
458 }
459
460 $foreignTableQueryArray = $this->buildForeignTableQuery($result, $fieldName);
461 $queryResource = $database->exec_SELECT_queryArray($foreignTableQueryArray);
462
463 // Early return on error with flash message
464 $databaseError = $database->sql_error();
465 if (!empty($databaseError)) {
466 $msg = $databaseError . '. ';
467 $msg .= $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch');
468 $msgTitle = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch_title');
469 /** @var $flashMessage FlashMessage */
470 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, $msgTitle, FlashMessage::ERROR, true);
471 /** @var $flashMessageService FlashMessageService */
472 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
473 /** @var $defaultFlashMessageQueue FlashMessageQueue */
474 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
475 $defaultFlashMessageQueue->enqueue($flashMessage);
476 $database->sql_free_result($queryResource);
477 return $items;
478 }
479
480 $labelPrefix = '';
481 if (!empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'])) {
482 $labelPrefix = $result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'];
483 $labelPrefix = $languageService->sL($labelPrefix);
484 }
485
486 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
487
488 while ($foreignRow = $database->sql_fetch_assoc($queryResource)) {
489 BackendUtility::workspaceOL($foreignTable, $foreignRow);
490 if (is_array($foreignRow)) {
491 // If the foreign table sets selicon_field, this field can contain an image
492 // that represents this specific row.
493 $iconFieldName = '';
494 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field'])) {
495 $iconFieldName = $GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field'];
496 }
497 $iconPath = '';
498 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field_path'])) {
499 $iconPath = $GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field_path'];
500 }
501 if ($iconFieldName && $iconPath && $foreignRow[$iconFieldName]) {
502 // Prepare the row icon if available
503 $iParts = GeneralUtility::trimExplode(',', $foreignRow[$iconFieldName], true);
504 $icon = '../' . $iconPath . '/' . trim($iParts[0]);
505 } else {
506 // Else, determine icon based on record type, or a generic fallback
507 $icon = $iconFactory->mapRecordTypeToIconIdentifier($foreignTable, $foreignRow);
508 }
509 // Add the item
510 $items[] = [
511 $labelPrefix . BackendUtility::getRecordTitle($foreignTable, $foreignRow),
512 $foreignRow['uid'],
513 $icon
514 ];
515 }
516 }
517
518 $database->sql_free_result($queryResource);
519
520 return $items;
521 }
522
523 /**
524 * Remove items using "keepItems" pageTsConfig
525 *
526 * Used by TcaSelectItems and TcaSelectTreeItems data providers
527 *
528 * @param array $result Result array
529 * @param string $fieldName Current handle field name
530 * @param array $items Incoming items
531 * @return array Modified item array
532 */
533 protected function removeItemsByKeepItemsPageTsConfig(array $result, $fieldName, array $items)
534 {
535 $table = $result['tableName'];
536 if (!isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
537 || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
538 ) {
539 return $items;
540 }
541
542 // If keepItems is set but is an empty list all current items get removed
543 if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
544 && $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'] !== '0') {
545 return [];
546 }
547
548 return ArrayUtility::keepItemsInArray(
549 $items,
550 $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'],
551 function ($value) {
552 return $value[1];
553 }
554 );
555 }
556
557 /**
558 * Remove items using "removeItems" pageTsConfig
559 *
560 * Used by TcaSelectItems and TcaSelectTreeItems data providers
561 *
562 * @param array $result Result array
563 * @param string $fieldName Current handle field name
564 * @param array $items Incoming items
565 * @return array Modified item array
566 */
567 protected function removeItemsByRemoveItemsPageTsConfig(array $result, $fieldName, array $items)
568 {
569 $table = $result['tableName'];
570 if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
571 || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
572 ) {
573 return $items;
574 }
575
576 $removeItems = GeneralUtility::trimExplode(
577 ',',
578 $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'],
579 true
580 );
581 foreach ($items as $key => $itemValues) {
582 if (in_array($itemValues[1], $removeItems)) {
583 unset($items[$key]);
584 }
585 }
586
587 return $items;
588 }
589
590 /**
591 * Remove items user restriction on language field
592 *
593 * Used by TcaSelectItems and TcaSelectTreeItems data providers
594 *
595 * @param array $result Result array
596 * @param string $fieldName Current handle field name
597 * @param array $items Incoming items
598 * @return array Modified item array
599 */
600 protected function removeItemsByUserLanguageFieldRestriction(array $result, $fieldName, array $items)
601 {
602 // Guard clause returns if not a language field is handled
603 if (empty($result['processedTca']['ctrl']['languageField'])
604 || $result['processedTca']['ctrl']['languageField'] !== $fieldName
605 ) {
606 return $items;
607 }
608
609 $backendUser = $this->getBackendUser();
610 foreach ($items as $key => $itemValues) {
611 if (!$backendUser->checkLanguageAccess($itemValues[1])) {
612 unset($items[$key]);
613 }
614 }
615
616 return $items;
617 }
618
619 /**
620 * Remove items by user restriction on authMode items
621 *
622 * Used by TcaSelectItems and TcaSelectTreeItems data providers
623 *
624 * @param array $result Result array
625 * @param string $fieldName Current handle field name
626 * @param array $items Incoming items
627 * @return array Modified item array
628 */
629 protected function removeItemsByUserAuthMode(array $result, $fieldName, array $items)
630 {
631 // Guard clause returns early if no authMode field is configured
632 if (!isset($result['processedTca']['columns'][$fieldName]['config']['authMode'])
633 || !is_string($result['processedTca']['columns'][$fieldName]['config']['authMode'])
634 ) {
635 return $items;
636 }
637
638 $backendUser = $this->getBackendUser();
639 $authMode = $result['processedTca']['columns'][$fieldName]['config']['authMode'];
640 foreach ($items as $key => $itemValues) {
641 // @todo: checkAuthMode() uses $GLOBAL access for "individual" authMode - get rid of this
642 if (!$backendUser->checkAuthMode($result['tableName'], $fieldName, $itemValues[1], $authMode)) {
643 unset($items[$key]);
644 }
645 }
646
647 return $items;
648 }
649
650 /**
651 * Remove items if doktype is handled for non admin users
652 *
653 * Used by TcaSelectItems and TcaSelectTreeItems data providers
654 *
655 * @param array $result Result array
656 * @param string $fieldName Current handle field name
657 * @param array $items Incoming items
658 * @return array Modified item array
659 */
660 protected function removeItemsByDoktypeUserRestriction(array $result, $fieldName, array $items)
661 {
662 $table = $result['tableName'];
663 $backendUser = $this->getBackendUser();
664 // Guard clause returns if not correct table and field or if user is admin
665 if ($table !== 'pages' && $table !== 'pages_language_overlay'
666 || $fieldName !== 'doktype' || $backendUser->isAdmin()
667 ) {
668 return $items;
669 }
670
671 $allowedPageTypes = $backendUser->groupData['pagetypes_select'];
672 foreach ($items as $key => $itemValues) {
673 if (!GeneralUtility::inList($allowedPageTypes, $itemValues[1])) {
674 unset($items[$key]);
675 }
676 }
677
678 return $items;
679 }
680
681 /**
682 * Returns an array with the exclude fields as defined in TCA and FlexForms
683 * Used for listing the exclude fields in be_groups forms.
684 *
685 * @return array Array of arrays with excludeFields (fieldName, table:fieldName) from TCA
686 * and FlexForms (fieldName, table:extKey;sheetName;fieldName)
687 */
688 protected function getExcludeFields()
689 {
690 $languageService = $this->getLanguageService();
691 $finalExcludeArray = [];
692
693 // Fetch translations for table names
694 $tableToTranslation = [];
695 // All TCA keys
696 foreach ($GLOBALS['TCA'] as $table => $conf) {
697 $tableToTranslation[$table] = $languageService->sL($conf['ctrl']['title']);
698 }
699 // Sort by translations
700 asort($tableToTranslation);
701 foreach ($tableToTranslation as $table => $translatedTable) {
702 $excludeArrayTable = [];
703
704 // All field names configured and not restricted to admins
705 if (is_array($GLOBALS['TCA'][$table]['columns'])
706 && empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly'])
707 && (empty($GLOBALS['TCA'][$table]['ctrl']['rootLevel']) || !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']))
708 ) {
709 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $_) {
710 if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
711 // Get human readable names of fields
712 $translatedField = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
713 // Add entry, key 'labels' needed for sorting
714 $excludeArrayTable[] = [
715 'labels' => $translatedTable . ':' . $translatedField,
716 'sectionHeader' => $translatedTable,
717 'table' => $table,
718 'tableField' => $field,
719 'fieldName' => $field,
720 'fullField' => $field,
721 'fieldLabel' => $translatedField,
722 'origin' => 'tca',
723 ];
724 }
725 }
726 }
727 // All FlexForm fields
728 $flexFormArray = $this->getRegisteredFlexForms($table);
729 foreach ($flexFormArray as $tableField => $flexForms) {
730 // Prefix for field label, e.g. "Plugin Options:"
731 $labelPrefix = '';
732 if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
733 $labelPrefix = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
734 }
735 // Get all sheets and title
736 foreach ($flexForms as $extIdent => $extConf) {
737 $extTitle = $languageService->sl(trim($extConf['title']));
738 // Get all fields in sheet
739 foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
740 if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
741 continue;
742 }
743 foreach ($sheet['ROOT']['el'] as $pluginFieldName => $field) {
744 // Use only fields that have exclude flag set
745 if (empty($field['TCEforms']['exclude'])) {
746 continue;
747 }
748 $fieldLabel = !empty($field['TCEforms']['label'])
749 ? $languageService->sL($field['TCEforms']['label'])
750 : $pluginFieldName;
751 $excludeArrayTable[] = [
752 'labels' => trim($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent, ': ') . ':' . $fieldLabel,
753 'sectionHeader' => trim(($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent), ':'),
754 'table' => $table,
755 'tableField' => $tableField,
756 'extIdent' => $extIdent,
757 'fieldName' => $pluginFieldName,
758 'fullField' => $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $pluginFieldName,
759 'fieldLabel' => $fieldLabel,
760 'origin' => 'flexForm',
761 ];
762 }
763 }
764 }
765 }
766 // Sort fields by the translated value
767 if (!empty($excludeArrayTable)) {
768 usort($excludeArrayTable, function (array $array1, array $array2) {
769 $array1 = reset($array1);
770 $array2 = reset($array2);
771 if (is_string($array1) && is_string($array2)) {
772 return strcasecmp($array1, $array2);
773 }
774 return 0;
775 });
776 $finalExcludeArray = array_merge($finalExcludeArray, $excludeArrayTable);
777 }
778 }
779
780 return $finalExcludeArray;
781 }
782
783 /**
784 * Returns all registered FlexForm definitions with title and fields
785 *
786 * @param string $table Table to handle
787 * @return array Data structures with speaking extension title
788 */
789 protected function getRegisteredFlexForms($table)
790 {
791 if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
792 return [];
793 }
794 $flexForms = [];
795 foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
796 if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
797 $flexForms[$tableField] = [];
798 // Get pointer fields
799 $pointerFields = !empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType,default';
800 $pointerFields = GeneralUtility::trimExplode(',', $pointerFields);
801 // Get FlexForms
802 foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStructure) {
803 // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
804 $identFields = GeneralUtility::trimExplode(',', $flexFormKey);
805 $extIdent = $identFields[0];
806 if (!empty($identFields[1]) && $identFields[1] !== 'list' && $identFields[1] !== '*') {
807 $extIdent = $identFields[1];
808 }
809 // Load external file references
810 if (!is_array($dataStructure)) {
811 $file = GeneralUtility::getFileAbsFileName(str_ireplace('FILE:', '', $dataStructure));
812 if ($file && @is_file($file)) {
813 $dataStructure = GeneralUtility::getUrl($file);
814 }
815 $dataStructure = GeneralUtility::xml2array($dataStructure);
816 if (!is_array($dataStructure)) {
817 continue;
818 }
819 }
820 // Get flexform content
821 $dataStructure = GeneralUtility::resolveAllSheetsInDS($dataStructure);
822 if (empty($dataStructure['sheets']) || !is_array($dataStructure['sheets'])) {
823 continue;
824 }
825 // Use DS pointer to get extension title from TCA
826 // @todo: I don't understand this code ... does it make sense at all?
827 $title = $extIdent;
828 $keyFields = GeneralUtility::trimExplode(',', $flexFormKey);
829 foreach ($pointerFields as $pointerKey => $pointerName) {
830 if (empty($keyFields[$pointerKey])
831 || $keyFields[$pointerKey] === '*'
832 || $keyFields[$pointerKey] === 'list'
833 || $keyFields[$pointerKey] === 'default'
834 ) {
835 continue;
836 }
837 if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
838 $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
839 if (!is_array($items)) {
840 continue;
841 }
842 foreach ($items as $itemConf) {
843 if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
844 $title = $itemConf[0];
845 break 2;
846 }
847 }
848 }
849 }
850 $flexForms[$tableField][$extIdent] = [
851 'title' => $title,
852 'ds' => $dataStructure
853 ];
854 }
855 }
856 }
857 return $flexForms;
858 }
859
860 /**
861 * Returns an array with explicit Allow/Deny fields.
862 * Used for listing these field/value pairs in be_groups forms
863 *
864 * @return array Array with information from all of $GLOBALS['TCA']
865 */
866 protected function getExplicitAuthFieldValues()
867 {
868 $languageService = static::getLanguageService();
869 $adLabel = [
870 'ALLOW' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.allow'),
871 'DENY' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.deny')
872 ];
873 $allowDenyOptions = [];
874 foreach ($GLOBALS['TCA'] as $table => $_) {
875 // All field names configured:
876 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
877 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $__) {
878 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
879 if ($fieldConfig['type'] === 'select' && $fieldConfig['authMode']) {
880 // Check for items
881 if (is_array($fieldConfig['items'])) {
882 // Get Human Readable names of fields and table:
883 $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] =
884 $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']) . ': '
885 . $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
886 foreach ($fieldConfig['items'] as $iVal) {
887 // Values '' is not controlled by this setting.
888 if ((string)$iVal[1] !== '') {
889 // Find iMode
890 $iMode = '';
891 switch ((string)$fieldConfig['authMode']) {
892 case 'explicitAllow':
893 $iMode = 'ALLOW';
894 break;
895 case 'explicitDeny':
896 $iMode = 'DENY';
897 break;
898 case 'individual':
899 if ($iVal[4] === 'EXPL_ALLOW') {
900 $iMode = 'ALLOW';
901 } elseif ($iVal[4] === 'EXPL_DENY') {
902 $iMode = 'DENY';
903 }
904 break;
905 }
906 // Set iMode
907 if ($iMode) {
908 $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = [
909 $iMode,
910 $languageService->sL($iVal[0]),
911 $adLabel[$iMode]
912 ];
913 }
914 }
915 }
916 }
917 }
918 }
919 }
920 }
921 return $allowDenyOptions;
922 }
923
924 /**
925 * Build query to fetch foreign records. Helper method of
926 * addItemsFromForeignTable(), do not call otherwise.
927 *
928 * @param array $result Result array
929 * @param string $localFieldName Current handle field name
930 * @return array Query array ready to be executed via Database->exec_SELECT_queryArray()
931 */
932 protected function buildForeignTableQuery(array $result, $localFieldName)
933 {
934 $backendUser = $this->getBackendUser();
935
936 $foreignTableName = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table'];
937 $foreignTableClauseArray = $this->processForeignTableClause($result, $foreignTableName, $localFieldName);
938
939 $queryArray = [];
940 $queryArray['SELECT'] = BackendUtility::getCommonSelectFields($foreignTableName, $foreignTableName . '.');
941
942 // rootLevel = -1 means that elements can be on the rootlevel OR on any page (pid!=-1)
943 // rootLevel = 0 means that elements are not allowed on root level
944 // rootLevel = 1 means that elements are only on the root level (pid=0)
945 $rootLevel = 0;
946 if (isset($GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'])) {
947 $rootLevel = $GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'];
948 }
949 $deleteClause = BackendUtility::deleteClause($foreignTableName);
950 if ($rootLevel == 1 || $rootLevel == -1) {
951 $pidWhere = $foreignTableName . '.pid' . (($rootLevel == -1) ? '<>-1' : '=0');
952 $queryArray['FROM'] = $foreignTableName;
953 $queryArray['WHERE'] = $pidWhere . $deleteClause . $foreignTableClauseArray['WHERE'];
954 } else {
955 $pageClause = $backendUser->getPagePermsClause(1);
956 if ($foreignTableName === 'pages') {
957 $queryArray['FROM'] = 'pages';
958 $queryArray['WHERE'] = '1=1' . $deleteClause . ' AND' . $pageClause . $foreignTableClauseArray['WHERE'];
959 } else {
960 $queryArray['FROM'] = $foreignTableName . ', pages';
961 $queryArray['WHERE'] = 'pages.uid=' . $foreignTableName . '.pid AND pages.deleted=0'
962 . $deleteClause . ' AND' . $pageClause . $foreignTableClauseArray['WHERE'];
963 }
964 }
965
966 $queryArray['GROUPBY'] = $foreignTableClauseArray['GROUPBY'];
967 $queryArray['ORDERBY'] = $foreignTableClauseArray['ORDERBY'];
968 $queryArray['LIMIT'] = $foreignTableClauseArray['LIMIT'];
969
970 return $queryArray;
971 }
972
973 /**
974 * Replace markers in a where clause from TCA foreign_table_where
975 *
976 * ###REC_FIELD_[field name]###
977 * ###THIS_UID### - is current element uid (zero if new).
978 * ###CURRENT_PID### - is the current page id (pid of the record).
979 * ###SITEROOT###
980 * ###PAGE_TSCONFIG_ID### - a value you can set from Page TSconfig dynamically.
981 * ###PAGE_TSCONFIG_IDLIST### - a value you can set from Page TSconfig dynamically.
982 * ###PAGE_TSCONFIG_STR### - a value you can set from Page TSconfig dynamically.
983 *
984 * @param array $result Result array
985 * @param string $foreignTableName Name of foreign table
986 * @param string $localFieldName Current handle field name
987 * @return array Query parts with keys WHERE, ORDERBY, GROUPBY, LIMIT
988 */
989 protected function processForeignTableClause(array $result, $foreignTableName, $localFieldName)
990 {
991 $database = $this->getDatabaseConnection();
992 $localTable = $result['tableName'];
993 $effectivePid = $result['effectivePid'];
994
995 $foreignTableClause = '';
996 if (!empty($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
997 && is_string($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
998 ) {
999 $foreignTableClause = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'];
1000 // Replace possible markers in query
1001 if (strstr($foreignTableClause, '###REC_FIELD_')) {
1002 // " AND table.field='###REC_FIELD_field1###' AND ..." -> array(" AND table.field='", "field1###' AND ...")
1003 $whereClauseParts = explode('###REC_FIELD_', $foreignTableClause);
1004 foreach ($whereClauseParts as $key => $value) {
1005 if ($key !== 0) {
1006 // "field1###' AND ..." -> array("field1", "' AND ...")
1007 $whereClauseSubParts = explode('###', $value, 2);
1008 // @todo: Throw exception if there is no value? What happens for NEW records?
1009 $databaseRowKey = empty($result['flexParentDatabaseRow']) ? 'databaseRow' : 'flexParentDatabaseRow';
1010 $rowFieldValue = isset($result[$databaseRowKey][$whereClauseSubParts[0]]) ? $result[$databaseRowKey][$whereClauseSubParts[0]] : '';
1011 if (is_array($rowFieldValue)) {
1012 // If a select or group field is used here, it may have been processed already and
1013 // is now an array. Use first selected value in this case.
1014 $rowFieldValue = $rowFieldValue[0];
1015 }
1016 if (substr($whereClauseParts[0], -1) === '\'' && $whereClauseSubParts[1][0] === '\'') {
1017 $whereClauseParts[$key] = $database->quoteStr($rowFieldValue, $foreignTableName) . $whereClauseSubParts[1];
1018 } else {
1019 $whereClauseParts[$key] = $database->fullQuoteStr($rowFieldValue, $foreignTableName) . $whereClauseSubParts[1];
1020 }
1021 }
1022 }
1023 $foreignTableClause = implode('', $whereClauseParts);
1024 }
1025 // Use pid from parent page clause if in flex flom context
1026 if (strpos($foreignTableClause, '###CURRENT_PID###') !== false
1027 && !empty($result['flexParentDatabaseRow']['pid'])
1028 ) {
1029 $effectivePid = $result['flexParentDatabaseRow']['pid'];
1030 }
1031
1032 $siteRootUid = 0;
1033 foreach ($result['rootline'] as $rootlinePage) {
1034 if (!empty($rootlinePage['is_siteroot'])) {
1035 $siteRootUid = (int)$rootlinePage['uid'];
1036 break;
1037 }
1038 }
1039
1040 $pageTsConfigId = 0;
1041 if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_ID']) {
1042 $pageTsConfigId = (int)$result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_ID'];
1043 }
1044 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID']) {
1045 $pageTsConfigId = (int)$result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID'];
1046 }
1047
1048 $pageTsConfigIdList = 0;
1049 if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_IDLIST']) {
1050 $pageTsConfigIdList = $result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_IDLIST'];
1051 }
1052 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST']) {
1053 $pageTsConfigIdList = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST'];
1054 }
1055 $pageTsConfigIdListArray = GeneralUtility::trimExplode(',', $pageTsConfigIdList, true);
1056 $pageTsConfigIdList = [];
1057 foreach ($pageTsConfigIdListArray as $pageTsConfigIdListElement) {
1058 if (MathUtility::canBeInterpretedAsInteger($pageTsConfigIdListElement)) {
1059 $pageTsConfigIdList[] = (int)$pageTsConfigIdListElement;
1060 }
1061 }
1062 $pageTsConfigIdList = implode(',', $pageTsConfigIdList);
1063
1064 $pageTsConfigString = '';
1065 if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_STR']) {
1066 $pageTsConfigString = $result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_STR'];
1067 }
1068 if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR']) {
1069 $pageTsConfigString = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR'];
1070 $pageTsConfigString = $database->quoteStr($pageTsConfigString, $foreignTableName);
1071 }
1072
1073 $foreignTableClause = str_replace(
1074 [
1075 '###CURRENT_PID###',
1076 '###THIS_UID###',
1077 '###SITEROOT###',
1078 '###PAGE_TSCONFIG_ID###',
1079 '###PAGE_TSCONFIG_IDLIST###',
1080 '###PAGE_TSCONFIG_STR###'
1081 ],
1082 [
1083 (int)$effectivePid,
1084 (int)$result['databaseRow']['uid'],
1085 $siteRootUid,
1086 $pageTsConfigId,
1087 $pageTsConfigIdList,
1088 $pageTsConfigString
1089 ],
1090 $foreignTableClause
1091 );
1092 }
1093
1094 // Split the clause into an array with keys WHERE, GROUPBY, ORDERBY, LIMIT
1095 // Prepend a space to make sure "[[:space:]]+" will find a space there for the first element.
1096 $foreignTableClause = ' ' . $foreignTableClause;
1097 $foreignTableClauseArray = [
1098 'WHERE' => '',
1099 'GROUPBY' => '',
1100 'ORDERBY' => '',
1101 'LIMIT' => '',
1102 ];
1103 // Find LIMIT
1104 $reg = [];
1105 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1106 $foreignTableClauseArray['LIMIT'] = trim($reg[2]);
1107 $foreignTableClause = $reg[1];
1108 }
1109 // Find ORDER BY
1110 $reg = [];
1111 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1112 $foreignTableClauseArray['ORDERBY'] = trim($reg[2]);
1113 $foreignTableClause = $reg[1];
1114 }
1115 // Find GROUP BY
1116 $reg = [];
1117 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1118 $foreignTableClauseArray['GROUPBY'] = trim($reg[2]);
1119 $foreignTableClause = $reg[1];
1120 }
1121 // Rest is assumed to be "WHERE" clause
1122 $foreignTableClauseArray['WHERE'] = $foreignTableClause;
1123
1124 return $foreignTableClauseArray;
1125 }
1126
1127 /**
1128 * Convert the current database values into an array
1129 *
1130 * @param array $row database row
1131 * @param string $fieldName fieldname to process
1132 * @return array
1133 */
1134 protected function processDatabaseFieldValue(array $row, $fieldName)
1135 {
1136 $currentDatabaseValues = array_key_exists($fieldName, $row)
1137 ? $row[$fieldName]
1138 : '';
1139 return GeneralUtility::trimExplode(',', $currentDatabaseValues, true);
1140 }
1141
1142 /**
1143 * Validate and sanitize database row values of the select field with the given name.
1144 * Creates an array out of databaseRow[selectField] values.
1145 *
1146 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1147 *
1148 * @param array $result The current result array.
1149 * @param string $fieldName Name of the current select field.
1150 * @param array $staticValues Array with statically defined items, item value is used as array key.
1151 * @return array
1152 */
1153 protected function processSelectFieldValue(array $result, $fieldName, array $staticValues)
1154 {
1155 $fieldConfig = $result['processedTca']['columns'][$fieldName];
1156
1157 $currentDatabaseValueArray = array_key_exists($fieldName, $result['databaseRow']) ? $result['databaseRow'][$fieldName] : [];
1158 $newDatabaseValueArray = [];
1159
1160 // Add all values that were defined by static methods and do not come from the relation
1161 // e.g. TCA, TSconfig, itemProcFunc etc.
1162 foreach ($currentDatabaseValueArray as $value) {
1163 if (isset($staticValues[$value])) {
1164 $newDatabaseValueArray[] = $value;
1165 }
1166 }
1167
1168 if (isset($fieldConfig['config']['foreign_table']) && !empty($fieldConfig['config']['foreign_table'])) {
1169 /** @var RelationHandler $relationHandler */
1170 $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1171 $relationHandler->registerNonTableValues = !empty($fieldConfig['config']['allowNonIdValues']);
1172 if (!empty($fieldConfig['config']['MM']) && $result['command'] !== 'new') {
1173 // MM relation
1174 $relationHandler->start(
1175 implode(',', $currentDatabaseValueArray),
1176 $fieldConfig['config']['foreign_table'],
1177 $fieldConfig['config']['MM'],
1178 $result['databaseRow']['uid'],
1179 $result['tableName'],
1180 $fieldConfig['config']
1181 );
1182 } else {
1183 // Non MM relation
1184 // If not dealing with MM relations, use default live uid, not versioned uid for record relations
1185 $relationHandler->start(
1186 implode(',', $currentDatabaseValueArray),
1187 $fieldConfig['config']['foreign_table'],
1188 '',
1189 $this->getLiveUid($result),
1190 $result['tableName'],
1191 $fieldConfig['config']
1192 );
1193 }
1194 $newDatabaseValueArray = array_merge($newDatabaseValueArray, $relationHandler->getValueArray());
1195 }
1196
1197 if ($fieldConfig['config']['multiple']) {
1198 return $newDatabaseValueArray;
1199 }
1200 return array_unique($newDatabaseValueArray);
1201 }
1202
1203 /**
1204 * Translate the item labels
1205 *
1206 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1207 *
1208 * @param array $result Result array
1209 * @param array $itemArray Items
1210 * @param string $table
1211 * @param string $fieldName
1212 * @return array
1213 */
1214 public function translateLabels(array $result, array $itemArray, $table, $fieldName)
1215 {
1216 $languageService = $this->getLanguageService();
1217
1218 foreach ($itemArray as $key => $item) {
1219 if (!isset($dynamicItems[$key])) {
1220 $staticValues[$item[1]] = $item;
1221 }
1222 if (isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
1223 && !empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
1224 ) {
1225 $label = $languageService->sL($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]]);
1226 } else {
1227 $label = $languageService->sL(trim($item[0]));
1228 }
1229 $value = strlen((string)$item[1]) > 0 ? $item[1] : '';
1230 $icon = $item[2] ?: null;
1231 $helpText = $item[3] ?: null;
1232 $itemArray[$key] = [
1233 $label,
1234 $value,
1235 $icon,
1236 $helpText
1237 ];
1238 }
1239
1240 return $itemArray;
1241 }
1242
1243 /**
1244 * Sanitize incoming item array
1245 *
1246 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1247 *
1248 * @param mixed $itemArray
1249 * @param string $tableName
1250 * @param string $fieldName
1251 * @throws \UnexpectedValueException
1252 * @return array
1253 */
1254 public function sanitizeItemArray($itemArray, $tableName, $fieldName)
1255 {
1256 if (!is_array($itemArray)) {
1257 $itemArray = [];
1258 }
1259 foreach ($itemArray as $item) {
1260 if (!is_array($item)) {
1261 throw new \UnexpectedValueException(
1262 'An item in field ' . $fieldName . ' of table ' . $tableName . ' is not an array as expected',
1263 1439288036
1264 );
1265 }
1266 }
1267
1268 return $itemArray;
1269 }
1270
1271 /**
1272 * Make sure maxitems is always filled with a valid integer value.
1273 *
1274 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1275 *
1276 * @param mixed $maxItems
1277 * @return int
1278 */
1279 public function sanitizeMaxItems($maxItems)
1280 {
1281 if (!empty($maxItems)
1282 && (int)$maxItems > 1
1283 ) {
1284 $maxItems = (int)$maxItems;
1285 } else {
1286 $maxItems = 1;
1287 }
1288
1289 return $maxItems;
1290 }
1291
1292 /**
1293 * Gets the record uid of the live default record. If already
1294 * pointing to the live record, the submitted record uid is returned.
1295 *
1296 * @param array $result Result array
1297 * @return int
1298 * @throws \UnexpectedValueException
1299 */
1300 protected function getLiveUid(array $result)
1301 {
1302 $table = $result['tableName'];
1303 $row = $result['databaseRow'];
1304 $uid = $row['uid'];
1305 if (!empty($result['processedTca']['ctrl']['versioningWS'])
1306 && $result['pid'] === -1
1307 ) {
1308 if (empty($row['t3ver_oid'])) {
1309 throw new \UnexpectedValueException(
1310 'No t3ver_oid found for record ' . $row['uid'] . ' on table ' . $table,
1311 1440066481
1312 );
1313 }
1314 $uid = $row['t3ver_oid'];
1315 }
1316 return $uid;
1317 }
1318
1319 /**
1320 * Determine the static values in the item array
1321 *
1322 * Used by TcaSelectItems and TcaSelectTreeItems data providers
1323 *
1324 * @param array $itemArray All item records for the select field
1325 * @param array $dynamicItemArray Item records from dynamic sources
1326 * @return array
1327 */
1328 public function getStaticValues($itemArray, $dynamicItemArray)
1329 {
1330 $staticValues = [];
1331 foreach ($itemArray as $key => $item) {
1332 if (!isset($dynamicItemArray[$key])) {
1333 $staticValues[$item[1]] = $item;
1334 }
1335 }
1336 return $staticValues;
1337 }
1338
1339 /**
1340 * @return LanguageService
1341 */
1342 protected function getLanguageService()
1343 {
1344 return $GLOBALS['LANG'];
1345 }
1346
1347 /**
1348 * @return DatabaseConnection
1349 */
1350 protected function getDatabaseConnection()
1351 {
1352 return $GLOBALS['TYPO3_DB'];
1353 }
1354
1355 /**
1356 * @return BackendUserAuthentication
1357 */
1358 protected function getBackendUser()
1359 {
1360 return $GLOBALS['BE_USER'];
1361 }
1362 }