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