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