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