649986f2b5fc7df690875731a93b3864da6437ae
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Configuration / FlexForm / FlexFormTools.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\Core\Configuration\FlexForm;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidCombinedPointerFieldException;
20 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
21 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException;
22 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException;
23 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException;
24 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException;
25 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidSinglePointerFieldException;
26 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidTcaException;
27 use TYPO3\CMS\Core\Database\ConnectionPool;
28 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Core\Utility\MathUtility;
31
32 /**
33 * Contains functions for manipulating flex form data
34 */
35 class FlexFormTools
36 {
37 /**
38 * If set, section indexes are re-numbered before processing
39 *
40 * @var bool
41 */
42 public $reNumberIndexesOfSectionData = false;
43
44 /**
45 * Options for array2xml() for flexform.
46 * This will map the weird keys from the internal array to tags that could potentially be checked with a DTD/schema
47 *
48 * @var array
49 */
50 public $flexArray2Xml_options = [
51 'parentTagMap' => [
52 'data' => 'sheet',
53 'sheet' => 'language',
54 'language' => 'field',
55 'el' => 'field',
56 'field' => 'value',
57 'field:el' => 'el',
58 'el:_IS_NUM' => 'section',
59 'section' => 'itemType'
60 ],
61 'disableTypeAttrib' => 2
62 ];
63
64 /**
65 * Reference to object called
66 *
67 * @var object
68 */
69 public $callBackObj = null;
70
71 /**
72 * Used for accumulation of clean XML
73 *
74 * @var array
75 */
76 public $cleanFlexFormXML = [];
77
78 /**
79 * The method locates a specific data structure from given TCA and row combination
80 * and returns an identifier string that can be handed around, and can be resolved
81 * to a single data structure later without giving $row and $tca data again.
82 *
83 * Note: The returned syntax is meant to only specify the target location of the data structure.
84 * It SHOULD NOT be abused and enriched with data from the record that is dealt with. For
85 * instance, it is now allowed to add source record specific date like the uid or the pid!
86 * If that is done, it is up to the hook consumer to take care of possible side effects, eg. if
87 * the data handler copies or moves records around and those references change.
88 *
89 * This method gets: Source data that influences the target location of a data structure
90 * This method returns: Target specification of the data structure
91 *
92 * This method is "paired" with method getFlexFormDataStructureByIdentifier() that
93 * will resolve the returned syntax again and returns the data structure itself.
94 *
95 * Both methods can be extended via hooks to return and accept additional
96 * identifier strings if needed, and to transmit further information within the identifier strings.
97 *
98 * Note that the TCA for data structure definitions MUST NOT be overridden by
99 * 'columnsOverrides' or by parent TCA in an inline relation! This would create a huge mess.
100 *
101 * Note: This method and the resolving methods belowe are well unit tested and document all
102 * nasty details this way.
103 *
104 * @param array $fieldTca Full TCA of the field in question that has type=flex set
105 * @param string $tableName The table name of the TCA field
106 * @param string $fieldName The field name
107 * @param array $row The data row
108 * @return string Identifier string
109 * @throws \RuntimeException If TCA is misconfigured
110 */
111 public function getDataStructureIdentifier(array $fieldTca, string $tableName, string $fieldName, array $row): string
112 {
113 $dataStructureIdentifier = null;
114 // Hook to inject an own logic to point to a data structure elsewhere.
115 // A hook has to implement method getDataStructureIdentifierPreProcess() to be called here.
116 // All hooks are called in a row, each MUST return an array, and the FIRST one that
117 // returns a non-empty array is used as final identifier.
118 // It is important to restrict hooks as much as possible to give other hooks a chance to kick in.
119 // The returned identifier is later given to parseFlexFormDataStructureByIdentifier() and a hook in there MUST
120 // be used to handle this identifier again.
121 // Warning: If adding source record details like the uid or pid here, this may turn out to be fragile.
122 // Be sure to test scenarios like workspaces and data handler copy/move well, additionally, this may
123 // break in between different core versions.
124 // It is probably a good idea to return at least something like [ 'type' => 'myExtension', ... ], see
125 // the core internal 'tca' and 'record' return values below
126 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
127 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])) {
128 $hookClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
129 foreach ($hookClasses as $hookClass) {
130 $hookInstance = GeneralUtility::makeInstance($hookClass);
131 if (method_exists($hookClass, 'getDataStructureIdentifierPreProcess')) {
132 $dataStructureIdentifier = $hookInstance->getDataStructureIdentifierPreProcess(
133 $fieldTca,
134 $tableName,
135 $fieldName,
136 $row
137 );
138 if (!is_array($dataStructureIdentifier)) {
139 throw new \RuntimeException(
140 'Hook class ' . $hookClass . ' method getDataStructureIdentifierPreProcess must return an array',
141 1478096535
142 );
143 }
144 if (!empty($dataStructureIdentifier)) {
145 // Early break at first hook that returned something!
146 break;
147 }
148 }
149 }
150 }
151
152 // If hooks didn't return something, kick in core logic
153 if (empty($dataStructureIdentifier)) {
154 $tcaDataStructureArray = $fieldTca['config']['ds'] ?? null;
155 $tcaDataStructurePointerField = $fieldTca['config']['ds_pointerField'] ?? null;
156 if (!is_array($tcaDataStructureArray) && $tcaDataStructurePointerField) {
157 // "ds" is not an array, but "ds_pointerField" is set -> data structure is found in different table
158 $dataStructureIdentifier = $this->getDataStructureIdentifierFromRecord(
159 $fieldTca,
160 $tableName,
161 $fieldName,
162 $row
163 );
164 } elseif (is_array($tcaDataStructureArray)) {
165 $dataStructureIdentifier = $this->getDataStructureIdentifierFromTcaArray(
166 $fieldTca,
167 $tableName,
168 $fieldName,
169 $row
170 );
171 } else {
172 throw new \RuntimeException(
173 'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
174 . ' The field is configured as type="flex" and no "ds_pointerField" is defined and "ds" is not an array.'
175 . ' Either configure a default data structure in [\'ds\'][\'default\'] or add a "ds_pointerField" lookup mechanism'
176 . ' that specifies the data structure',
177 1463826960
178 );
179 }
180 }
181
182 // Second hook to manipulate identifier again. This can be used to add additional data to
183 // identifiers. Be careful here, especially if stuff from the source record like uid or pid
184 // is added! This may easily lead to issues with data handler details like copy or move records,
185 // localization and version overlays. Test this very well!
186 // Multiple hooks may add information to the same identifier here - take care to namespace array keys.
187 // Information added here can be later used in parseDataStructureByIdentifier post process hook again.
188 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
189 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])) {
190 $hookClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
191 foreach ($hookClasses as $hookClass) {
192 $hookInstance = GeneralUtility::makeInstance($hookClass);
193 if (method_exists($hookClass, 'getDataStructureIdentifierPostProcess')) {
194 $dataStructureIdentifier = $hookInstance->getDataStructureIdentifierPostProcess(
195 $fieldTca,
196 $tableName,
197 $fieldName,
198 $row,
199 $dataStructureIdentifier
200 );
201 if (!is_array($dataStructureIdentifier) || empty($dataStructureIdentifier)) {
202 throw new \RuntimeException(
203 'Hook class ' . $hookClass . ' method getDataStructureIdentifierPostProcess must return a non empty array',
204 1478350835
205 );
206 }
207 }
208 }
209 }
210
211 return json_encode($dataStructureIdentifier);
212 }
213
214 /**
215 * The data structure is located in a record. This method resolves the record and
216 * returns an array to identify that record.
217 *
218 * The example setup below looks in current row for a tx_templavoila_ds value. If not found,
219 * it will search the rootline (the table is a tree, typically pages) until a value in
220 * tx_templavoila_next_ds or tx_templavoila_ds is found. That value should then be an
221 * integer, that points to a record in tx_templavoila_datastructure, and then the data
222 * structure is found in field dataprot:
223 *
224 * fieldTca = [
225 * 'config' => [
226 * 'type' => 'flex',
227 * 'ds_pointerField' => 'tx_templavoila_ds',
228 * 'ds_pointerField_searchParent' => 'pid',
229 * 'ds_pointerField_searchParent_subField' => 'tx_templavoila_next_ds',
230 * 'ds_tableField' => 'tx_templavoila_datastructure:dataprot',
231 * ]
232 * ]
233 *
234 * More simple scenario without tree traversal and having a valid data structure directly
235 * located in field theFlexDataStructureField.
236 *
237 * fieldTca = [
238 * 'config' => [
239 * 'type' => 'flex',
240 * 'ds_pointerField' => 'theFlexDataStructureField',
241 * ]
242 * ]
243 *
244 * Example return array:
245 * [
246 * 'type' => 'record',
247 * 'tableName' => 'tx_templavoila_datastructure',
248 * 'uid' => 42,
249 * 'fieldName' => 'dataprot',
250 * ];
251 *
252 * @param array $fieldTca Full TCA of the field in question that has type=flex set
253 * @param string $tableName The table name of the TCA field
254 * @param string $fieldName The field name
255 * @param array $row The data row
256 * @return array Identifier as array, see example above
257 * @throws InvalidParentRowException
258 * @throws InvalidParentRowLoopException
259 * @throws InvalidParentRowRootException
260 * @throws InvalidPointerFieldValueException
261 * @throws InvalidTcaException
262 */
263 protected function getDataStructureIdentifierFromRecord(array $fieldTca, string $tableName, string $fieldName, array $row): array
264 {
265 $pointerFieldName = $finalPointerFieldName = $fieldTca['config']['ds_pointerField'];
266 if (!array_key_exists($pointerFieldName, $row)) {
267 // Pointer field does not exist in row at all -> throw
268 throw new InvalidTcaException(
269 'No data structure for field "' . $fieldName . '" in table "' . $tableName . '" found, no "ds" array'
270 . ' configured and given row does not have a field with ds_pointerField name "' . $pointerFieldName . '".',
271 1464115059
272 );
273 }
274 $pointerValue = $row[$pointerFieldName];
275 // If set, this is typically set to "pid"
276 $parentFieldName = $fieldTca['config']['ds_pointerField_searchParent'] ?? null;
277 $pointerSubFieldName = $fieldTca['config']['ds_pointerField_searchParent_subField'] ?? null;
278 if (!$pointerValue && $parentFieldName) {
279 // Fetch rootline until a valid pointer value is found
280 $handledUids = [];
281 while (!$pointerValue) {
282 $handledUids[$row['uid']] = 1;
283 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
284 $queryBuilder->getRestrictions()
285 ->removeAll()
286 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
287 $queryBuilder->select('uid', $parentFieldName, $pointerFieldName);
288 if (!empty($pointerSubFieldName)) {
289 $queryBuilder->addSelect($pointerSubFieldName);
290 }
291 $queryStatement = $queryBuilder->from($tableName)
292 ->where(
293 $queryBuilder->expr()->eq(
294 'uid',
295 $queryBuilder->createNamedParameter($row[$parentFieldName], \PDO::PARAM_INT)
296 )
297 )
298 ->execute();
299 if ($queryStatement->rowCount() !== 1) {
300 throw new InvalidParentRowException(
301 'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
302 . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
303 . ' with uid "' . $row[$parentFieldName] . '" was done. This row however does not exist or was deleted.',
304 1463833794
305 );
306 }
307 $row = $queryStatement->fetch();
308 if (isset($handledUids[$row[$parentFieldName]])) {
309 // Row has been fetched before already -> loop detected!
310 throw new InvalidParentRowLoopException(
311 'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
312 . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
313 . ' with uid "' . $row[$parentFieldName] . '" was done. A loop of records was detected, the tree is broken.',
314 1464110956
315 );
316 }
317 BackendUtility::workspaceOL($tableName, $row);
318 BackendUtility::fixVersioningPid($tableName, $row, true);
319 // New pointer value: This is the "subField" value if given, else the field value
320 // ds_pointerField_searchParent_subField is the "template on next level" structure from templavoila
321 if ($pointerSubFieldName && $row[$pointerSubFieldName]) {
322 $finalPointerFieldName = $pointerSubFieldName;
323 $pointerValue = $row[$pointerSubFieldName];
324 } else {
325 $pointerValue = $row[$pointerFieldName];
326 }
327 if (!$pointerValue && ((int)$row[$parentFieldName] === 0 || $row[$parentFieldName] === null)) {
328 // If on root level and still no valid pointer found -> exception
329 throw new InvalidParentRowRootException(
330 'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
331 . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
332 . ' with uid "' . $row[$parentFieldName] . '" was done. Root node with uid "' . $row['uid'] . '"'
333 . ' was fetched and still no valid pointer field value was found.',
334 1464112555
335 );
336 }
337 }
338 }
339 if (!$pointerValue) {
340 // Still no valid pointer value -> exception, This still can be a data integrity issue, so throw a catchable exception
341 throw new InvalidPointerFieldValueException(
342 'No data structure for field "' . $fieldName . '" in table "' . $tableName . '" found, no "ds" array'
343 . ' configured and data structure could be found by resolving parents. This is probably a TCA misconfiguration.',
344 1464114011
345 );
346 }
347 // Ok, finally we have the field value. This is now either a data structure directly, or a pointer to a file,
348 // or the value can be interpreted as integer (is an uid) and "ds_tableField" is set, so this is the table, uid and field
349 // where the final data structure can be found.
350 if (MathUtility::canBeInterpretedAsInteger($pointerValue)) {
351 if (!isset($fieldTca['config']['ds_tableField'])) {
352 throw new InvalidTcaException(
353 'Invalid data structure pointer for field "' . $fieldName . '" in table "' . $tableName . '", the value'
354 . 'resolved to "' . $pointerValue . '" . which is an integer, so "ds_tableField" must be configured',
355 1464115639
356 );
357 }
358 if (substr_count($fieldTca['config']['ds_tableField'], ':') !== 1) {
359 // ds_tableField must be of the form "table:field"
360 throw new InvalidTcaException(
361 'Invalid TCA configuration for field "' . $fieldName . '" in table "' . $tableName . '", the setting'
362 . '"ds_tableField" must be of the form "tableName:fieldName"',
363 1464116002
364 );
365 }
366 list($foreignTableName, $foreignFieldName) = GeneralUtility::trimExplode(':', $fieldTca['config']['ds_tableField']);
367 $dataStructureIdentifier = [
368 'type' => 'record',
369 'tableName' => $foreignTableName,
370 'uid' => (int)$pointerValue,
371 'fieldName' => $foreignFieldName,
372 ];
373 } else {
374 $dataStructureIdentifier = [
375 'type' => 'record',
376 'tableName' => $tableName,
377 'uid' => (int)$row['uid'],
378 'fieldName' => $finalPointerFieldName,
379 ];
380 }
381 return $dataStructureIdentifier;
382 }
383
384 /**
385 * Find matching data structure in TCA ds array.
386 *
387 * Data structure is defined in 'ds' config array.
388 * Also, there can be a ds_pointerField
389 *
390 * fieldTca = [
391 * 'config' => [
392 * 'type' => 'flex',
393 * 'ds' => [
394 * 'aName' => '<T3DataStructure>...' OR 'FILE:...'
395 * ],
396 * 'ds_pointerField' => 'optionalSetting,upToTwoCommaSeparatedFieldNames',
397 * ]
398 * ]
399 *
400 * This method returns an array of the form:
401 * [
402 * 'type' => 'Tca:',
403 * 'tableName' => $tableName,
404 * 'fieldName' => $fieldName,
405 * 'dataStructureKey' => $key,
406 * ];
407 *
408 * Example:
409 * [
410 * 'type' => 'Tca:',
411 * 'tableName' => 'tt_content',
412 * 'fieldName' => 'pi_flexform',
413 * 'dataStructureKey' => 'powermail_pi1,list',
414 * ];
415 *
416 * @param array $fieldTca Full TCA of the field in question that has type=flex set
417 * @param string $tableName The table name of the TCA field
418 * @param string $fieldName The field name
419 * @param array $row The data row
420 * @return array Identifier as array, see example above
421 * @throws InvalidCombinedPointerFieldException
422 * @throws InvalidSinglePointerFieldException
423 * @throws InvalidTcaException
424 */
425 protected function getDataStructureIdentifierFromTcaArray(array $fieldTca, string $tableName, string $fieldName, array $row): array
426 {
427 $dataStructureIdentifier = [
428 'type' => 'tca',
429 'tableName' => $tableName,
430 'fieldName' => $fieldName,
431 'dataStructureKey' => null,
432 ];
433 $tcaDataStructurePointerField = $fieldTca['config']['ds_pointerField'] ?? null;
434 if ($tcaDataStructurePointerField === null) {
435 // No ds_pointerField set -> use 'default' as ds array key if exists.
436 if (isset($fieldTca['config']['ds']['default'])) {
437 $dataStructureIdentifier['dataStructureKey'] = 'default';
438 } else {
439 // A tca is configured as flex without ds_pointerField. A 'default' key must exist, otherwise
440 // this is a configuration error.
441 // May happen with an unloaded extension -> catchable
442 throw new InvalidTcaException(
443 'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
444 . ' The field is configured as type="flex" and no "ds_pointerField" is defined. Either configure'
445 . ' a default data structure in [\'ds\'][\'default\'] or add a "ds_pointerField" lookup mechanism'
446 . ' that specifies the data structure',
447 1463652560
448 );
449 }
450 } else {
451 // ds_pointerField is set, it can be a comma separated list of two fields, explode it.
452 $pointerFieldArray = GeneralUtility::trimExplode(',', $tcaDataStructurePointerField, true);
453 // Obvious configuration error, either one or two fields must be declared
454 $pointerFieldsCount = count($pointerFieldArray);
455 if ($pointerFieldsCount !== 1 && $pointerFieldsCount !== 2) {
456 // If it's there, it must be correct -> not catchable
457 throw new \RuntimeException(
458 'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
459 . ' ds_pointerField must be either a single field name, or a comma separated list of two fields,'
460 . ' the invalid configuration string provided was: "' . $tcaDataStructurePointerField . '"',
461 1463577497
462 );
463 }
464 // Verify first field exists in row array. If not, this is a hard error: Any extension that sets a
465 // ds_pointerField to some field name should take care that field does exist, too. They are a pair,
466 // so there shouldn't be a situation where the field does not exist. Throw an exception if that is violated.
467 if (!isset($row[$pointerFieldArray[0]])) {
468 // If it's declared, it must exist -> not catchable
469 throw new \RuntimeException(
470 'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
471 . ' ds_pointerField "' . $pointerFieldArray[0] . '" points to a field name that does not exist.',
472 1463578899
473 );
474 }
475 // Similar situation for the second field: If it is set, the field must exist.
476 if (isset($pointerFieldArray[1]) && !isset($row[$pointerFieldArray[1]])) {
477 // If it's declared, it must exist -> not catchable
478 throw new \RuntimeException(
479 'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
480 . ' Second part "' . $pointerFieldArray[1] . '" of ds_pointerField with full value "'
481 . $tcaDataStructurePointerField . '" points to a field name that does not exist.',
482 1463578900
483 );
484 }
485 if ($pointerFieldsCount === 1) {
486 if (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]]])) {
487 // Field value points directly to an existing key in tca ds
488 $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]];
489 } elseif (isset($fieldTca['config']['ds']['default'])) {
490 // Field value does not exit in tca ds, fall back to default key if exists
491 $dataStructureIdentifier['dataStructureKey'] = 'default';
492 } else {
493 // The value of the ds_pointerField field points to a key in the ds array that does
494 // not exists, and there is no fallback either. This can happen if an extension brings
495 // new flex form definitions and that extension is unloaded later. "Old" records of the
496 // extension could then still point to the no longer existing key in ds. We throw a
497 // specific exception here to give controllers an opportunity to catch this case.
498 throw new InvalidSinglePointerFieldException(
499 'Field value of field "' . $pointerFieldArray[0] . '" of database record with uid "'
500 . $row['uid'] . '" from table "' . $tableName . '" points to a "ds" key ' . $row[$pointerFieldArray[0]]
501 . ' but this key does not exist and there is no "default" fallback.',
502 1463653197
503 );
504 }
505 } else {
506 // Two comma separated field names
507 if (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]] . ',' . $row[$pointerFieldArray[1]]])) {
508 // firstValue,secondValue
509 $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]] . ',' . $row[$pointerFieldArray[1]];
510 } elseif (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[1]] . ',*'])) {
511 // secondValue,* ?!
512 // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - just remove this elseif together with two unit tests
513 // This case is a wrong implementation - it matches "secondFieldValue,*", but it
514 // should match "*,secondFieldValue" only. Since this bug has been in the code for ages, it
515 // still works in v8 but is deprecated now.
516 // Try to log a meaningful deprecation message though, so devs can adapt
517 GeneralUtility::deprecationLog(
518 'TCA field "' . $fieldName . '" of table "' . $tableName . '" has a registered data structure'
519 . ' with name "' . $row[$pointerFieldArray[1]] . ',*". The ds_pointerField is set to "'
520 . $tcaDataStructurePointerField . '", with the matching value "' . $row[$pointerFieldArray[1]] . '"'
521 . ' for field "' . $pointerFieldArray[1] . '". This should be the other way round, so the name'
522 . ' should be: "*,' . $row[$pointerFieldArray[1]] . '" in the ds TCA array. Please change that'
523 . ' until TYPO3 v9, this matching code will be removed then.'
524 );
525 $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[1]] . ',*';
526 } elseif (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]] . ',*'])) {
527 // firstValue,*
528 $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]] . ',*';
529 } elseif (isset($fieldTca['config']['ds']['*,' . $row[$pointerFieldArray[1]]])) {
530 // *,secondValue
531 $dataStructureIdentifier['dataStructureKey'] = '*,' . $row[$pointerFieldArray[1]];
532 } elseif (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]]])) {
533 // firstValue
534 $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]];
535 } elseif (isset($fieldTca['config']['ds']['default'])) {
536 // Fall back to default
537 $dataStructureIdentifier['dataStructureKey'] = 'default';
538 } else {
539 // No ds_pointerField value could be determined and 'default' does not exist as
540 // fallback. This is the same case as the above scenario, throw a
541 // InvalidCombinedPointerFieldException here, too.
542 throw new InvalidCombinedPointerFieldException(
543 'Field combination of fields "' . $pointerFieldArray[0] . '" and "' . $pointerFieldArray[1] . '" of database'
544 . 'record with uid "' . $row['uid'] . '" from table "' . $tableName . '" with values "' . $row[$pointerFieldArray[0]] . '"'
545 . ' and "' . $row[$pointerFieldArray[1]] . '" could not be resolved to any registered data structure and '
546 . ' no "default" fallback exists.',
547 1463678524
548 );
549 }
550 }
551 }
552 return $dataStructureIdentifier;
553 }
554
555 /**
556 * Parse a data structure identified by $identifier to the final data structure array.
557 * This method is called after getDataStructureIdentifier(), finds the data structure
558 * and returns it.
559 *
560 * Hooks allow to manipulate the find logic and to post process the data structure array.
561 *
562 * Note that the TCA for data structure definitions MUST NOT be overridden by
563 * 'columnsOverrides' or by parent TCA in an inline relation! This would create a huge mess.
564 *
565 * After the data structure definition is found, the method resolves:
566 * * FILE:EXT: prefix of the data structure itself - the ds is in a file
567 * * FILE:EXT: prefix for sheets - if single sheets are in files
568 * * EXT: prefix for sheets - if single sheets are in files (slightly different b/w compat syntax)
569 * * Create an sDEF sheet if the data structure has non, yet.
570 *
571 * After that method is run, the data structure is fully resolved to an array,
572 * and same base normalization is done: If the ds did not contain a sheet,
573 * it will have one afterwards as "sDEF"
574 *
575 * This method gets: Target specification of the data structure.
576 * This method returns: The normalized data structure parsed to an array.
577 *
578 * Read the unit tests for nasty details.
579 *
580 * @param string $identifier String to find the data structure location
581 * @return array Parsed and normalized data structure
582 * @throws InvalidIdentifierException
583 */
584 public function parseDataStructureByIdentifier(string $identifier): array
585 {
586 // Throw an exception for an empty string. This might be a valid use case for new
587 // records in some situations, so this is catchable to give callers a chance to deal with that.
588 if (empty($identifier)) {
589 throw new InvalidIdentifierException(
590 'Empty string given to parseFlexFormDataStructureByIdentifier(). This exception might '
591 . ' be caught to handle some new record situations properly',
592 1478100828
593 );
594 }
595
596 $identifier = json_decode($identifier, true);
597
598 if (!is_array($identifier) || empty($identifier)) {
599 // If there is some identifier and it can't be decoded, programming error -> not catchable
600 throw new \RuntimeException(
601 'Identifier could not be decoded to an array.',
602 1478345642
603 );
604 }
605
606 $dataStructure = '';
607
608 // Hook to fetch data structure by given identifier.
609 // Method parseFlexFormDataStructureByIdentifier() must be implemented and returns either an
610 // empty string "not my business", or a string with the resolved data structure string, or FILE: reference,
611 // or a fully parsed data structure as aray.
612 // Result of the FIRST hook that gives an non-empty string is used, namespace your identifiers in
613 // a way that there is little chance they overlap (eg. prefix with extension name).
614 // If implemented, this hook should be paired with a hook in getDataStructureIdentifier() above.
615 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
616 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
617 ) {
618 $hookClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
619 foreach ($hookClasses as $hookClass) {
620 $hookInstance = GeneralUtility::makeInstance($hookClass);
621 if (method_exists($hookClass, 'parseDataStructureByIdentifierPreProcess')) {
622 $dataStructure = $hookInstance->parseDataStructureByIdentifierPreProcess($identifier);
623 if (!is_string($dataStructure) && !is_array($dataStructure)) {
624 // Programming error -> not catchable
625 throw new \RuntimeException(
626 'Hook class ' . $hookClass . ' method parseDataStructureByIdentifierPreProcess must either'
627 . ' return an empty string or a data structure string or a parsed data structure array.',
628 1478168512
629 );
630 }
631 if (!empty($dataStructure)) {
632 // Early break if a hook resolved to something!
633 break;
634 }
635 }
636 }
637 }
638
639 // If hooks didn't resolve, try own methods
640 if (empty($dataStructure)) {
641 if ($identifier['type'] === 'record') {
642 // Handle "record" type, see getDataStructureIdentifierFromRecord()
643 if (empty($identifier['tableName']) || empty($identifier['uid']) || empty($identifier['fieldName'])) {
644 throw new \RuntimeException(
645 'Incomplete "record" based identifier: ' . json_encode($identifier),
646 1478113873
647 );
648 }
649 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($identifier['tableName']);
650 $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
651 $dataStructure = $queryBuilder
652 ->select($identifier['fieldName'])
653 ->from($identifier['tableName'])
654 ->where(
655 $queryBuilder->expr()->eq(
656 'uid',
657 $queryBuilder->createNamedParameter($identifier['uid'], \PDO::PARAM_INT)
658 )
659 )
660 ->execute()
661 ->fetchColumn(0);
662 } elseif ($identifier['type'] === 'tca') {
663 // Handle "tca" type, see getDataStructureIdentifierFromTcaArray
664 if (empty($identifier['tableName']) || empty($identifier['fieldName']) || empty($identifier['dataStructureKey'])) {
665 throw new \RuntimeException(
666 'Incomplete "tca" based identifier: ' . json_encode($identifier),
667 1478113471
668 );
669 }
670 $table = $identifier['tableName'];
671 $field = $identifier['fieldName'];
672 $dataStructureKey = $identifier['dataStructureKey'];
673 if (!isset($GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey])
674 || !is_string($GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey])
675 ) {
676 // This may happen for elements pointing to an unloaded extension -> catchable
677 throw new InvalidIdentifierException(
678 'Specified identifier ' . json_encode($identifier) . ' does not resolve to a valid'
679 . ' TCA array value',
680 1478105491
681 );
682 }
683 $dataStructure = $GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey];
684 } else {
685 throw new InvalidIdentifierException(
686 'Identifier ' . json_encode($identifier) . ' could not be resolved',
687 1478104554
688 );
689 }
690 }
691
692 // Hooks may have parse the data structure already to an array. If that is not the case, parse it now.
693 if (is_string($dataStructure)) {
694 // Resolve FILE: prefix pointing to a DS in a file
695 if (strpos(trim($dataStructure), 'FILE:') === 0) {
696 $file = GeneralUtility::getFileAbsFileName(substr(trim($dataStructure), 5));
697 if (empty($file) || !@is_file($file)) {
698 throw new \RuntimeException(
699 'Data structure file ' . $file . ' could not be resolved to an existing file',
700 1478105826
701 );
702 }
703 $dataStructure = file_get_contents($file);
704 }
705
706 // Parse main structure
707 $dataStructure = GeneralUtility::xml2array($dataStructure);
708 }
709
710 // Throw if it still is not an array, probably because GeneralUtility::xml2array() failed.
711 // This also may happen if artificial identifiers were constructed which don't resolve. The
712 // flex form "exclude" access rights systems does that -> catchable
713 if (!is_array($dataStructure)) {
714 throw new InvalidIdentifierException(
715 'Parse error: Data structure could not be resolved to a valid structure.',
716 1478106090
717 );
718 }
719
720 // Create default sheet if there is none, yet.
721 if (isset($dataStructure['ROOT']) && isset($dataStructure['sheets'])) {
722 throw new \RuntimeException(
723 'Parsed data structure has both ROOT and sheets on top level. Thats invalid.',
724 1440676540
725 );
726 }
727 if (isset($dataStructure['ROOT']) && is_array($dataStructure['ROOT'])) {
728 $dataStructure['sheets']['sDEF']['ROOT'] = $dataStructure['ROOT'];
729 unset($dataStructure['ROOT']);
730 }
731
732 // Resolve FILE:EXT and EXT: for single sheets
733 if (isset($dataStructure['sheets']) && is_array($dataStructure['sheets'])) {
734 foreach ($dataStructure['sheets'] as $sheetName => $sheetStructure) {
735 if (!is_array($sheetStructure)) {
736 if (strpos(trim($sheetStructure), 'FILE:') === 0) {
737 $file = GeneralUtility::getFileAbsFileName(substr(trim($sheetStructure), 5));
738 } else {
739 $file = GeneralUtility::getFileAbsFileName(trim($sheetStructure));
740 }
741 if ($file && @is_file($file)) {
742 $sheetStructure = GeneralUtility::xml2array(file_get_contents($file));
743 }
744 }
745 $dataStructure['sheets'][$sheetName] = $sheetStructure;
746 }
747 }
748
749 // Hook to manipulate data structure further. This can be used to add or remove fields
750 // from given structure. Multiple hooks can be registered, all are called. They
751 // receive the parsed structure and the identifier array.
752 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
753 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
754 ) {
755 $hookClasses = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
756 foreach ($hookClasses as $hookClass) {
757 $hookInstance = GeneralUtility::makeInstance($hookClass);
758 if (method_exists($hookClass, 'parseDataStructureByIdentifierPostProcess')) {
759 $dataStructure = $hookInstance->parseDataStructureByIdentifierPostProcess($dataStructure, $identifier);
760 if (!is_array($dataStructure)) {
761 // Programming error -> not catchable
762 throw new \RuntimeException(
763 'Hook class ' . $hookClass . ' method parseDataStructureByIdentifierPreProcess must return and array.',
764 1478350806
765 );
766 }
767 }
768 }
769 }
770
771 return $dataStructure;
772 }
773
774 /**
775 * Handler for Flex Forms
776 *
777 * @param string $table The table name of the record
778 * @param string $field The field name of the flexform field to work on
779 * @param array $row The record data array
780 * @param object $callBackObj Object in which the call back function is located
781 * @param string $callBackMethod_value Method name of call back function in object for values
782 * @return bool|string true on success, string if error happened (error string returned)
783 */
784 public function traverseFlexFormXMLData($table, $field, $row, $callBackObj, $callBackMethod_value)
785 {
786 if (!is_array($GLOBALS['TCA'][$table]) || !is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
787 return 'TCA table/field was not defined.';
788 }
789 $this->callBackObj = $callBackObj;
790 // Get Data Structure:
791 $dataStructureIdentifier = $this->getDataStructureIdentifier($GLOBALS['TCA'][$table]['columns'][$field], $table, $field, $row);
792 $dataStructureArray = $this->parseDataStructureByIdentifier($dataStructureIdentifier);
793 // Get flexform XML data
794 $editData = GeneralUtility::xml2array($row[$field]);
795 if (!is_array($editData)) {
796 return 'Parsing error: ' . $editData;
797 }
798 // Check if $dataStructureArray['sheets'] is indeed an array before loop or it will crash with runtime error
799 if (!is_array($dataStructureArray['sheets'])) {
800 return 'Data Structure ERROR: sheets is defined but not an array for table ' . $table . (isset($row['uid']) ? ' and uid ' . $row['uid'] : '');
801 }
802 // Traverse languages:
803 foreach ($dataStructureArray['sheets'] as $sheetKey => $sheetData) {
804 // Render sheet:
805 if (is_array($sheetData['ROOT']) && is_array($sheetData['ROOT']['el'])) {
806 $PA['vKeys'] = ['DEF'];
807 $PA['lKey'] = 'lDEF';
808 $PA['callBackMethod_value'] = $callBackMethod_value;
809 $PA['table'] = $table;
810 $PA['field'] = $field;
811 $PA['uid'] = $row['uid'];
812 // Render flexform:
813 $this->traverseFlexFormXMLData_recurse($sheetData['ROOT']['el'], $editData['data'][$sheetKey]['lDEF'], $PA, 'data/' . $sheetKey . '/lDEF');
814 } else {
815 return 'Data Structure ERROR: No ROOT element found for sheet "' . $sheetKey . '".';
816 }
817 }
818 return true;
819 }
820
821 /**
822 * Recursively traversing flexform data according to data structure and element data
823 *
824 * @param array $dataStruct (Part of) data structure array that applies to the sub section of the flexform data we are processing
825 * @param array $editData (Part of) edit data array, reflecting current part of data structure
826 * @param array $PA Additional parameters passed.
827 * @param string $path Telling the "path" to the element in the flexform XML
828 * @return array
829 */
830 public function traverseFlexFormXMLData_recurse($dataStruct, $editData, &$PA, $path = '')
831 {
832 if (is_array($dataStruct)) {
833 foreach ($dataStruct as $key => $value) {
834 // The value of each entry must be an array.
835 if (is_array($value)) {
836 if ($value['type'] === 'array') {
837 // Array (Section) traversal
838 if ($value['section']) {
839 $cc = 0;
840 if (is_array($editData[$key]['el'])) {
841 if ($this->reNumberIndexesOfSectionData) {
842 $temp = [];
843 $c3 = 0;
844 foreach ($editData[$key]['el'] as $v3) {
845 $temp[++$c3] = $v3;
846 }
847 $editData[$key]['el'] = $temp;
848 }
849 foreach ($editData[$key]['el'] as $k3 => $v3) {
850 if (is_array($v3)) {
851 $cc = $k3;
852 $theType = key($v3);
853 $theDat = $v3[$theType];
854 $newSectionEl = $value['el'][$theType];
855 if (is_array($newSectionEl)) {
856 $this->traverseFlexFormXMLData_recurse([$theType => $newSectionEl], [$theType => $theDat], $PA, $path . '/' . $key . '/el/' . $cc);
857 }
858 }
859 }
860 }
861 } else {
862 // Array traversal
863 if (is_array($editData) && is_array($editData[$key])) {
864 $this->traverseFlexFormXMLData_recurse($value['el'], $editData[$key]['el'], $PA, $path . '/' . $key . '/el');
865 }
866 }
867 } elseif (is_array($value['TCEforms']['config'])) {
868 // Processing a field value:
869 foreach ($PA['vKeys'] as $vKey) {
870 $vKey = 'v' . $vKey;
871 // Call back
872 if ($PA['callBackMethod_value'] && is_array($editData) && is_array($editData[$key])) {
873 $this->executeCallBackMethod($PA['callBackMethod_value'], [$value, $editData[$key][$vKey], $PA, $path . '/' . $key . '/' . $vKey, $this]);
874 }
875 }
876 }
877 }
878 }
879 }
880 }
881
882 /**
883 * Execute method on callback object
884 *
885 * @param string $methodName Method name to call
886 * @param array $parameterArray Parameters
887 * @return mixed Result of callback object
888 */
889 protected function executeCallBackMethod($methodName, array $parameterArray)
890 {
891 return call_user_func_array([$this->callBackObj, $methodName], $parameterArray);
892 }
893
894 /***********************************
895 *
896 * Processing functions
897 *
898 ***********************************/
899 /**
900 * Cleaning up FlexForm XML to hold only the values it may according to its Data Structure. Also the order of tags will follow that of the data structure.
901 * BE CAREFUL: DO not clean records in workspaces unless IN the workspace! The Data Structure might resolve falsely on a workspace record when cleaned from Live workspace.
902 *
903 * @param string $table Table name
904 * @param string $field Field name of the flex form field in which the XML is found that should be cleaned.
905 * @param array $row The record
906 * @return string Clean XML from FlexForm field
907 */
908 public function cleanFlexFormXML($table, $field, $row)
909 {
910 // New structure:
911 $this->cleanFlexFormXML = [];
912 // Create and call iterator object:
913 $flexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
914 $flexObj->reNumberIndexesOfSectionData = true;
915 $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'cleanFlexFormXML_callBackFunction');
916 return $this->flexArray2Xml($this->cleanFlexFormXML, true);
917 }
918
919 /**
920 * Call back function for \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools class
921 * Basically just setting the value in a new array (thus cleaning because only values that are valid are visited!)
922 *
923 * @param array $dsArr Data structure for the current value
924 * @param mixed $data Current value
925 * @param array $PA Additional configuration used in calling function
926 * @param string $path Path of value in DS structure
927 * @param FlexFormTools $pObj caller
928 */
929 public function cleanFlexFormXML_callBackFunction($dsArr, $data, $PA, $path, $pObj)
930 {
931 // Just setting value in our own result array, basically replicating the structure:
932 $pObj->setArrayValueByPath($path, $this->cleanFlexFormXML, $data);
933 }
934
935 /***********************************
936 *
937 * Multi purpose functions
938 *
939 ***********************************/
940 /**
941 * Get a value from a multi-dimensional array by giving a path "../../.." pointing to the element
942 *
943 * @param string $pathArray The path pointing to the value field, eg. test/2/title to access $array['test'][2]['title']
944 * @param array $array Array to get value from. Passed by reference so the value returned can be used to change the value in the array!
945 * @return mixed Value returned
946 */
947 public function &getArrayValueByPath($pathArray, &$array)
948 {
949 if (!is_array($pathArray)) {
950 $pathArray = explode('/', $pathArray);
951 }
952 if (is_array($array) && !empty($pathArray)) {
953 $key = array_shift($pathArray);
954 if (isset($array[$key])) {
955 if (empty($pathArray)) {
956 return $array[$key];
957 }
958 return $this->getArrayValueByPath($pathArray, $array[$key]);
959 }
960 return null;
961 }
962 }
963
964 /**
965 * Set a value in a multi-dimensional array by giving a path "../../.." pointing to the element
966 *
967 * @param string $pathArray The path pointing to the value field, eg. test/2/title to access $array['test'][2]['title']
968 * @param array $array Array to set value in. Passed by reference so the value returned can be used to change the value in the array!
969 * @param mixed $value Value to set
970 * @return mixed Value returned
971 */
972 public function setArrayValueByPath($pathArray, &$array, $value)
973 {
974 if (isset($value)) {
975 if (!is_array($pathArray)) {
976 $pathArray = explode('/', $pathArray);
977 }
978 if (is_array($array) && !empty($pathArray)) {
979 $key = array_shift($pathArray);
980 if (empty($pathArray)) {
981 $array[$key] = $value;
982 return true;
983 }
984 if (!isset($array[$key])) {
985 $array[$key] = [];
986 }
987 return $this->setArrayValueByPath($pathArray, $array[$key], $value);
988 }
989 }
990 }
991
992 /**
993 * Convert FlexForm data array to XML
994 *
995 * @param array $array Array to output in <T3FlexForms> XML
996 * @param bool $addPrologue If set, the XML prologue is returned as well.
997 * @return string XML content.
998 */
999 public function flexArray2Xml($array, $addPrologue = false)
1000 {
1001 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['flexformForceCDATA']) {
1002 $this->flexArray2Xml_options['useCDATA'] = 1;
1003 }
1004 $output = GeneralUtility::array2xml($array, '', 0, 'T3FlexForms', 4, $this->flexArray2Xml_options);
1005 if ($addPrologue) {
1006 $output = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>' . LF . $output;
1007 }
1008 return $output;
1009 }
1010 }