‪TYPO3CMS  10.4
FlexFormTools.php
Go to the documentation of this file.
1 <?php
2 
3 declare(strict_types=1);
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 
19 
33 
38 {
44  public ‪$reNumberIndexesOfSectionData = false;
45 
52  public ‪$flexArray2Xml_options = [
53  'parentTagMap' => [
54  'data' => 'sheet',
55  'sheet' => 'language',
56  'language' => 'field',
57  'el' => 'field',
58  'field' => 'value',
59  'field:el' => 'el',
60  'el:_IS_NUM' => 'section',
61  'section' => 'itemType'
62  ],
63  'disableTypeAttrib' => 2
64  ];
65 
71  public ‪$callBackObj;
72 
78  public ‪$cleanFlexFormXML = [];
79 
118  public function ‪getDataStructureIdentifier(array $fieldTca, string $tableName, string $fieldName, array $row): string
119  {
120  $dataStructureIdentifier = null;
121  // Hook to inject an own logic to point to a data structure elsewhere.
122  // A hook has to implement method getDataStructureIdentifierPreProcess() to be called here.
123  // All hooks are called in a row, each MUST return an array, and the FIRST one that
124  // returns a non-empty array is used as final identifier.
125  // It is important to restrict hooks as much as possible to give other hooks a chance to kick in.
126  // The returned identifier is later given to parseFlexFormDataStructureByIdentifier() and a hook in there MUST
127  // be used to handle this identifier again.
128  // Warning: If adding source record details like the uid or pid here, this may turn out to be fragile.
129  // Be sure to test scenarios like workspaces and data handler copy/move well, additionally, this may
130  // break in between different core versions.
131  // It is probably a good idea to return at least something like [ 'type' => 'myExtension', ... ], see
132  // the core internal 'tca' and 'record' return values below
133  if (!empty(‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
134  && is_array(‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])) {
135  $hookClasses = ‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
136  foreach ($hookClasses as $hookClass) {
137  $hookInstance = GeneralUtility::makeInstance($hookClass);
138  if (method_exists($hookClass, 'getDataStructureIdentifierPreProcess')) {
139  $dataStructureIdentifier = $hookInstance->getDataStructureIdentifierPreProcess(
140  $fieldTca,
141  $tableName,
142  $fieldName,
143  $row
144  );
145  if (!is_array($dataStructureIdentifier)) {
146  throw new \RuntimeException(
147  'Hook class ' . $hookClass . ' method getDataStructureIdentifierPreProcess must return an array',
148  1478096535
149  );
150  }
151  if (!empty($dataStructureIdentifier)) {
152  // Early break at first hook that returned something!
153  break;
154  }
155  }
156  }
157  }
158 
159  // If hooks didn't return something, kick in core logic
160  if (empty($dataStructureIdentifier)) {
161  $tcaDataStructureArray = $fieldTca['config']['ds'] ?? null;
162  $tcaDataStructurePointerField = $fieldTca['config']['ds_pointerField'] ?? null;
163  if (!is_array($tcaDataStructureArray) && $tcaDataStructurePointerField) {
164  // "ds" is not an array, but "ds_pointerField" is set -> data structure is found in different table
165  $dataStructureIdentifier = $this->‪getDataStructureIdentifierFromRecord(
166  $fieldTca,
167  $tableName,
168  $fieldName,
169  $row
170  );
171  } elseif (is_array($tcaDataStructureArray)) {
172  $dataStructureIdentifier = $this->‪getDataStructureIdentifierFromTcaArray(
173  $fieldTca,
174  $tableName,
175  $fieldName,
176  $row
177  );
178  } else {
179  throw new \RuntimeException(
180  'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
181  . ' The field is configured as type="flex" and no "ds_pointerField" is defined and "ds" is not an array.'
182  . ' Either configure a default data structure in [\'ds\'][\'default\'] or add a "ds_pointerField" lookup mechanism'
183  . ' that specifies the data structure',
184  1463826960
185  );
186  }
187  }
188 
189  // Second hook to manipulate identifier again. This can be used to add additional data to
190  // identifiers. Be careful here, especially if stuff from the source record like uid or pid
191  // is added! This may easily lead to issues with data handler details like copy or move records,
192  // localization and version overlays. Test this very well!
193  // Multiple hooks may add information to the same identifier here - take care to namespace array keys.
194  // Information added here can be later used in parseDataStructureByIdentifier post process hook again.
195  if (!empty(‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])
196  && is_array(‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'])) {
197  $hookClasses = ‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'];
198  foreach ($hookClasses as $hookClass) {
199  $hookInstance = GeneralUtility::makeInstance($hookClass);
200  if (method_exists($hookClass, 'getDataStructureIdentifierPostProcess')) {
201  $dataStructureIdentifier = $hookInstance->getDataStructureIdentifierPostProcess(
202  $fieldTca,
203  $tableName,
204  $fieldName,
205  $row,
206  $dataStructureIdentifier
207  );
208  if (!is_array($dataStructureIdentifier) || empty($dataStructureIdentifier)) {
209  throw new \RuntimeException(
210  'Hook class ' . $hookClass . ' method getDataStructureIdentifierPostProcess must return a non empty array',
211  1478350835
212  );
213  }
214  }
215  }
216  }
217 
218  return json_encode($dataStructureIdentifier);
219  }
220 
270  protected function ‪getDataStructureIdentifierFromRecord(array $fieldTca, string $tableName, string $fieldName, array $row): array
271  {
272  $pointerFieldName = $finalPointerFieldName = $fieldTca['config']['ds_pointerField'];
273  if (!array_key_exists($pointerFieldName, $row)) {
274  // Pointer field does not exist in row at all -> throw
275  throw new ‪InvalidTcaException(
276  'No data structure for field "' . $fieldName . '" in table "' . $tableName . '" found, no "ds" array'
277  . ' configured and given row does not have a field with ds_pointerField name "' . $pointerFieldName . '".',
278  1464115059
279  );
280  }
281  $pointerValue = $row[$pointerFieldName];
282  // If set, this is typically set to "pid"
283  $parentFieldName = $fieldTca['config']['ds_pointerField_searchParent'] ?? null;
284  $pointerSubFieldName = $fieldTca['config']['ds_pointerField_searchParent_subField'] ?? null;
285  if (!$pointerValue && $parentFieldName) {
286  // Fetch rootline until a valid pointer value is found
287  $handledUids = [];
288  while (!$pointerValue) {
289  $handledUids[$row['uid']] = 1;
290  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
291  $queryBuilder->getRestrictions()
292  ->removeAll()
293  ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
294  $queryBuilder->select('uid', $parentFieldName, $pointerFieldName);
295  if (!empty($pointerSubFieldName)) {
296  $queryBuilder->addSelect($pointerSubFieldName);
297  }
298  $queryStatement = $queryBuilder->from($tableName)
299  ->where(
300  $queryBuilder->expr()->eq(
301  'uid',
302  $queryBuilder->createNamedParameter($row[$parentFieldName], \PDO::PARAM_INT)
303  )
304  )
305  ->execute();
306  $rowCount = $queryBuilder
307  ->count('uid')
308  ->execute()
309  ->fetchColumn(0);
310  if ($rowCount !== 1) {
312  'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
313  . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
314  . ' with uid "' . $row[$parentFieldName] . '" was done. This row however does not exist or was deleted.',
315  1463833794
316  );
317  }
318  $row = $queryStatement->fetch();
319  if (isset($handledUids[$row[$parentFieldName]])) {
320  // Row has been fetched before already -> loop detected!
322  'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
323  . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
324  . ' with uid "' . $row[$parentFieldName] . '" was done. A loop of records was detected, the tree is broken.',
325  1464110956
326  );
327  }
328  ‪BackendUtility::workspaceOL($tableName, $row);
329  ‪BackendUtility::fixVersioningPid($tableName, $row, true);
330  // New pointer value: This is the "subField" value if given, else the field value
331  // ds_pointerField_searchParent_subField is the "template on next level" structure from templavoila
332  if ($pointerSubFieldName && $row[$pointerSubFieldName]) {
333  $finalPointerFieldName = $pointerSubFieldName;
334  $pointerValue = $row[$pointerSubFieldName];
335  } else {
336  $pointerValue = $row[$pointerFieldName];
337  }
338  if (!$pointerValue && ((int)$row[$parentFieldName] === 0 || $row[$parentFieldName] === null)) {
339  // If on root level and still no valid pointer found -> exception
341  'The data structure for field "' . $fieldName . '" in table "' . $tableName . '" has to be looked up'
342  . ' in field "' . $pointerFieldName . '". That field had no valid value, so a lookup in parent record'
343  . ' with uid "' . $row[$parentFieldName] . '" was done. Root node with uid "' . $row['uid'] . '"'
344  . ' was fetched and still no valid pointer field value was found.',
345  1464112555
346  );
347  }
348  }
349  }
350  if (!$pointerValue) {
351  // Still no valid pointer value -> exception, This still can be a data integrity issue, so throw a catchable exception
353  'No data structure for field "' . $fieldName . '" in table "' . $tableName . '" found, no "ds" array'
354  . ' configured and data structure could be found by resolving parents. This is probably a TCA misconfiguration.',
355  1464114011
356  );
357  }
358  // Ok, finally we have the field value. This is now either a data structure directly, or a pointer to a file,
359  // or the value can be interpreted as integer (is a uid) and "ds_tableField" is set, so this is the table, uid and field
360  // where the final data structure can be found.
361  if (‪MathUtility::canBeInterpretedAsInteger($pointerValue)) {
362  if (!isset($fieldTca['config']['ds_tableField'])) {
363  throw new ‪InvalidTcaException(
364  'Invalid data structure pointer for field "' . $fieldName . '" in table "' . $tableName . '", the value'
365  . 'resolved to "' . $pointerValue . '" . which is an integer, so "ds_tableField" must be configured',
366  1464115639
367  );
368  }
369  if (substr_count($fieldTca['config']['ds_tableField'], ':') !== 1) {
370  // ds_tableField must be of the form "table:field"
371  throw new ‪InvalidTcaException(
372  'Invalid TCA configuration for field "' . $fieldName . '" in table "' . $tableName . '", the setting'
373  . '"ds_tableField" must be of the form "tableName:fieldName"',
374  1464116002
375  );
376  }
377  [$foreignTableName, $foreignFieldName] = ‪GeneralUtility::trimExplode(':', $fieldTca['config']['ds_tableField']);
378  $dataStructureIdentifier = [
379  'type' => 'record',
380  'tableName' => $foreignTableName,
381  'uid' => (int)$pointerValue,
382  'fieldName' => $foreignFieldName,
383  ];
384  } else {
385  $dataStructureIdentifier = [
386  'type' => 'record',
387  'tableName' => $tableName,
388  'uid' => (int)$row['uid'],
389  'fieldName' => $finalPointerFieldName,
390  ];
391  }
392  return $dataStructureIdentifier;
393  }
394 
436  protected function ‪getDataStructureIdentifierFromTcaArray(array $fieldTca, string $tableName, string $fieldName, array $row): array
437  {
438  $dataStructureIdentifier = [
439  'type' => 'tca',
440  'tableName' => $tableName,
441  'fieldName' => $fieldName,
442  'dataStructureKey' => null,
443  ];
444  $tcaDataStructurePointerField = $fieldTca['config']['ds_pointerField'] ?? null;
445  if ($tcaDataStructurePointerField === null) {
446  // No ds_pointerField set -> use 'default' as ds array key if exists.
447  if (isset($fieldTca['config']['ds']['default'])) {
448  $dataStructureIdentifier['dataStructureKey'] = 'default';
449  } else {
450  // A tca is configured as flex without ds_pointerField. A 'default' key must exist, otherwise
451  // this is a configuration error.
452  // May happen with an unloaded extension -> catchable
453  throw new ‪InvalidTcaException(
454  'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
455  . ' The field is configured as type="flex" and no "ds_pointerField" is defined. Either configure'
456  . ' a default data structure in [\'ds\'][\'default\'] or add a "ds_pointerField" lookup mechanism'
457  . ' that specifies the data structure',
458  1463652560
459  );
460  }
461  } else {
462  // ds_pointerField is set, it can be a comma separated list of two fields, explode it.
463  $pointerFieldArray = ‪GeneralUtility::trimExplode(',', $tcaDataStructurePointerField, true);
464  // Obvious configuration error, either one or two fields must be declared
465  $pointerFieldsCount = count($pointerFieldArray);
466  if ($pointerFieldsCount !== 1 && $pointerFieldsCount !== 2) {
467  // If it's there, it must be correct -> not catchable
468  throw new \RuntimeException(
469  'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
470  . ' ds_pointerField must be either a single field name, or a comma separated list of two fields,'
471  . ' the invalid configuration string provided was: "' . $tcaDataStructurePointerField . '"',
472  1463577497
473  );
474  }
475  // Verify first field exists in row array. If not, this is a hard error: Any extension that sets a
476  // ds_pointerField to some field name should take care that field does exist, too. They are a pair,
477  // so there shouldn't be a situation where the field does not exist. Throw an exception if that is violated.
478  if (!isset($row[$pointerFieldArray[0]])) {
479  // If it's declared, it must exist -> not catchable
480  throw new \RuntimeException(
481  'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
482  . ' ds_pointerField "' . $pointerFieldArray[0] . '" points to a field name that does not exist.',
483  1463578899
484  );
485  }
486  // Similar situation for the second field: If it is set, the field must exist.
487  if (isset($pointerFieldArray[1]) && !isset($row[$pointerFieldArray[1]])) {
488  // If it's declared, it must exist -> not catchable
489  throw new \RuntimeException(
490  'TCA misconfiguration in table "' . $tableName . '" field "' . $fieldName . '" config section:'
491  . ' Second part "' . $pointerFieldArray[1] . '" of ds_pointerField with full value "'
492  . $tcaDataStructurePointerField . '" points to a field name that does not exist.',
493  1463578900
494  );
495  }
496  if ($pointerFieldsCount === 1) {
497  if (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]]])) {
498  // Field value points directly to an existing key in tca ds
499  $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]];
500  } elseif (isset($fieldTca['config']['ds']['default'])) {
501  // Field value does not exit in tca ds, fall back to default key if exists
502  $dataStructureIdentifier['dataStructureKey'] = 'default';
503  } else {
504  // The value of the ds_pointerField field points to a key in the ds array that does
505  // not exist, and there is no fallback either. This can happen if an extension brings
506  // new flex form definitions and that extension is unloaded later. "Old" records of the
507  // extension could then still point to the no longer existing key in ds. We throw a
508  // specific exception here to give controllers an opportunity to catch this case.
510  'Field value of field "' . $pointerFieldArray[0] . '" of database record with uid "'
511  . $row['uid'] . '" from table "' . $tableName . '" points to a "ds" key ' . $row[$pointerFieldArray[0]]
512  . ' but this key does not exist and there is no "default" fallback.',
513  1463653197
514  );
515  }
516  } else {
517  // Two comma separated field names
518  if (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]] . ',' . $row[$pointerFieldArray[1]]])) {
519  // firstValue,secondValue
520  $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]] . ',' . $row[$pointerFieldArray[1]];
521  } elseif (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]] . ',*'])) {
522  // firstValue,*
523  $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]] . ',*';
524  } elseif (isset($fieldTca['config']['ds']['*,' . $row[$pointerFieldArray[1]]])) {
525  // *,secondValue
526  $dataStructureIdentifier['dataStructureKey'] = '*,' . $row[$pointerFieldArray[1]];
527  } elseif (isset($fieldTca['config']['ds'][$row[$pointerFieldArray[0]]])) {
528  // firstValue
529  $dataStructureIdentifier['dataStructureKey'] = $row[$pointerFieldArray[0]];
530  } elseif (isset($fieldTca['config']['ds']['default'])) {
531  // Fall back to default
532  $dataStructureIdentifier['dataStructureKey'] = 'default';
533  } else {
534  // No ds_pointerField value could be determined and 'default' does not exist as
535  // fallback. This is the same case as the above scenario, throw a
536  // InvalidCombinedPointerFieldException here, too.
538  'Field combination of fields "' . $pointerFieldArray[0] . '" and "' . $pointerFieldArray[1] . '" of database'
539  . 'record with uid "' . $row['uid'] . '" from table "' . $tableName . '" with values "' . $row[$pointerFieldArray[0]] . '"'
540  . ' and "' . $row[$pointerFieldArray[1]] . '" could not be resolved to any registered data structure and '
541  . ' no "default" fallback exists.',
542  1463678524
543  );
544  }
545  }
546  }
547  return $dataStructureIdentifier;
548  }
549 
579  public function ‪parseDataStructureByIdentifier(string $identifier): array
580  {
581  // Throw an exception for an empty string. This might be a valid use case for new
582  // records in some situations, so this is catchable to give callers a chance to deal with that.
583  if (empty($identifier)) {
585  'Empty string given to parseFlexFormDataStructureByIdentifier(). This exception might '
586  . ' be caught to handle some new record situations properly',
587  1478100828
588  );
589  }
590 
591  $identifier = json_decode($identifier, true);
592 
593  if (!is_array($identifier) || empty($identifier)) {
594  // If there is some identifier and it can't be decoded, programming error -> not catchable
595  throw new \RuntimeException(
596  'Identifier could not be decoded to an array.',
597  1478345642
598  );
599  }
600 
601  $dataStructure = '';
602 
603  // Hook to fetch data structure by given identifier.
604  // Method parseFlexFormDataStructureByIdentifier() must be implemented and returns either an
605  // empty string "not my business", or a string with the resolved data structure string, or FILE: reference,
606  // or a fully parsed data structure as array.
607  // Result of the FIRST hook that gives a non-empty string is used, namespace your identifiers in
608  // a way that there is little chance they overlap (eg. prefix with extension name).
609  // If implemented, this hook should be paired with a hook in getDataStructureIdentifier() above.
610  foreach (‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'] ?? [] as $hookClass) {
611  $hookInstance = GeneralUtility::makeInstance($hookClass);
612  if (method_exists($hookClass, 'parseDataStructureByIdentifierPreProcess')) {
613  $dataStructure = $hookInstance->parseDataStructureByIdentifierPreProcess($identifier);
614  if (!is_string($dataStructure) && !is_array($dataStructure)) {
615  // Programming error -> not catchable
616  throw new \RuntimeException(
617  'Hook class ' . $hookClass . ' method parseDataStructureByIdentifierPreProcess must either'
618  . ' return an empty string or a data structure string or a parsed data structure array.',
619  1478168512
620  );
621  }
622  if (!empty($dataStructure)) {
623  // Early break if a hook resolved to something!
624  break;
625  }
626  }
627  }
628 
629  // If hooks didn't resolve, try own methods
630  if (empty($dataStructure)) {
631  if ($identifier['type'] === 'record') {
632  // Handle "record" type, see getDataStructureIdentifierFromRecord()
633  if (empty($identifier['tableName']) || empty($identifier['uid']) || empty($identifier['fieldName'])) {
634  throw new \RuntimeException(
635  'Incomplete "record" based identifier: ' . json_encode($identifier),
636  1478113873
637  );
638  }
639  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($identifier['tableName']);
640  $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
641  $dataStructure = $queryBuilder
642  ->select($identifier['fieldName'])
643  ->from($identifier['tableName'])
644  ->where(
645  $queryBuilder->expr()->eq(
646  'uid',
647  $queryBuilder->createNamedParameter($identifier['uid'], \PDO::PARAM_INT)
648  )
649  )
650  ->execute()
651  ->fetchColumn(0);
652  } elseif ($identifier['type'] === 'tca') {
653  // Handle "tca" type, see getDataStructureIdentifierFromTcaArray
654  if (empty($identifier['tableName']) || empty($identifier['fieldName']) || empty($identifier['dataStructureKey'])) {
655  throw new \RuntimeException(
656  'Incomplete "tca" based identifier: ' . json_encode($identifier),
657  1478113471
658  );
659  }
660  $table = $identifier['tableName'];
661  $field = $identifier['fieldName'];
662  $dataStructureKey = $identifier['dataStructureKey'];
663  if (!isset(‪$GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey])
664  || !is_string(‪$GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey])
665  ) {
666  // This may happen for elements pointing to an unloaded extension -> catchable
668  'Specified identifier ' . json_encode($identifier) . ' does not resolve to a valid'
669  . ' TCA array value',
670  1478105491
671  );
672  }
673  $dataStructure = ‪$GLOBALS['TCA'][$table]['columns'][$field]['config']['ds'][$dataStructureKey];
674  } else {
676  'Identifier ' . json_encode($identifier) . ' could not be resolved',
677  1478104554
678  );
679  }
680  }
681 
682  // Hooks may have parse the data structure already to an array. If that is not the case, parse it now.
683  if (is_string($dataStructure)) {
684  // Resolve FILE: prefix pointing to a DS in a file
685  if (strpos(trim($dataStructure), 'FILE:') === 0) {
686  $file = GeneralUtility::getFileAbsFileName(substr(trim($dataStructure), 5));
687  if (empty($file) || !@is_file($file)) {
688  throw new \RuntimeException(
689  'Data structure file ' . $file . ' could not be resolved to an existing file',
690  1478105826
691  );
692  }
693  $dataStructure = (string)file_get_contents($file);
694  }
695 
696  // Parse main structure
697  $dataStructure = ‪GeneralUtility::xml2array($dataStructure);
698  }
699 
700  // Throw if it still is not an array, probably because GeneralUtility::xml2array() failed.
701  // This also may happen if artificial identifiers were constructed which don't resolve. The
702  // flex form "exclude" access rights systems does that -> catchable
703  if (!is_array($dataStructure)) {
705  'Parse error: Data structure could not be resolved to a valid structure.',
706  1478106090
707  );
708  }
709 
710  // Create default sheet if there is none, yet.
711  if (isset($dataStructure['ROOT']) && isset($dataStructure['sheets'])) {
712  throw new \RuntimeException(
713  'Parsed data structure has both ROOT and sheets on top level. Thats invalid.',
714  1440676540
715  );
716  }
717  if (isset($dataStructure['ROOT']) && is_array($dataStructure['ROOT'])) {
718  $dataStructure['sheets']['sDEF']['ROOT'] = $dataStructure['ROOT'];
719  unset($dataStructure['ROOT']);
720  }
721 
722  // Resolve FILE:EXT and EXT: for single sheets
723  if (isset($dataStructure['sheets']) && is_array($dataStructure['sheets'])) {
724  foreach ($dataStructure['sheets'] as $sheetName => $sheetStructure) {
725  if (!is_array($sheetStructure)) {
726  if (strpos(trim($sheetStructure), 'FILE:') === 0) {
727  $file = GeneralUtility::getFileAbsFileName(substr(trim($sheetStructure), 5));
728  } else {
729  $file = GeneralUtility::getFileAbsFileName(trim($sheetStructure));
730  }
731  if ($file && @is_file($file)) {
732  $sheetStructure = ‪GeneralUtility::xml2array((string)file_get_contents($file));
733  }
734  }
735  $dataStructure['sheets'][$sheetName] = $sheetStructure;
736  }
737  }
738 
739  // Hook to manipulate data structure further. This can be used to add or remove fields
740  // from given structure. Multiple hooks can be registered, all are called. They
741  // receive the parsed structure and the identifier array.
742  foreach (‪$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['flexParsing'] ?? [] as $hookClass) {
743  $hookInstance = GeneralUtility::makeInstance($hookClass);
744  if (method_exists($hookClass, 'parseDataStructureByIdentifierPostProcess')) {
745  $dataStructure = $hookInstance->parseDataStructureByIdentifierPostProcess($dataStructure, $identifier);
746  if (!is_array($dataStructure)) {
747  // Programming error -> not catchable
748  throw new \RuntimeException(
749  'Hook class ' . $hookClass . ' method parseDataStructureByIdentifierPreProcess must return and array.',
750  1478350806
751  );
752  }
753  }
754  }
755 
756  return $dataStructure;
757  }
758 
769  public function ‪traverseFlexFormXMLData($table, $field, $row, ‪$callBackObj, $callBackMethod_value)
770  {
771  $PA = [];
772  if (!is_array(‪$GLOBALS['TCA'][$table]) || !is_array(‪$GLOBALS['TCA'][$table]['columns'][$field])) {
773  return 'TCA table/field was not defined.';
774  }
775  $this->callBackObj = ‪$callBackObj;
776 
777  // Get data structure. The methods may throw various exceptions, with some of them being
778  // ok in certain scenarios, for instance on new record rows. Those are ok to "eat" here
779  // and substitute with a dummy DS.
780  $dataStructureArray = ['sheets' => ['sDEF' => []]];
781  try {
782  $dataStructureIdentifier = $this->‪getDataStructureIdentifier(‪$GLOBALS['TCA'][$table]['columns'][$field], $table, $field, $row);
783  $dataStructureArray = $this->‪parseDataStructureByIdentifier($dataStructureIdentifier);
785  }
786 
787  // Get flexform XML data
788  $editData = ‪GeneralUtility::xml2array($row[$field]);
789  if (!is_array($editData)) {
790  return 'Parsing error: ' . $editData;
791  }
792  // Check if $dataStructureArray['sheets'] is indeed an array before loop or it will crash with runtime error
793  if (!is_array($dataStructureArray['sheets'])) {
794  return 'Data Structure ERROR: sheets is defined but not an array for table ' . $table . (isset($row['uid']) ? ' and uid ' . $row['uid'] : '');
795  }
796  // Traverse languages:
797  foreach ($dataStructureArray['sheets'] as $sheetKey => $sheetData) {
798  // Render sheet:
799  if (is_array($sheetData['ROOT']) && is_array($sheetData['ROOT']['el'])) {
800  $PA['vKeys'] = ['DEF'];
801  $PA['lKey'] = 'lDEF';
802  $PA['callBackMethod_value'] = $callBackMethod_value;
803  $PA['table'] = $table;
804  $PA['field'] = $field;
805  $PA['uid'] = $row['uid'];
806  // Render flexform:
807  $this->‪traverseFlexFormXMLData_recurse($sheetData['ROOT']['el'], $editData['data'][$sheetKey]['lDEF'], $PA, 'data/' . $sheetKey . '/lDEF');
808  } else {
809  return 'Data Structure ERROR: No ROOT element found for sheet "' . $sheetKey . '".';
810  }
811  }
812  return true;
813  }
814 
823  public function ‪traverseFlexFormXMLData_recurse($dataStruct, $editData, &$PA, $path = ''): void
824  {
825  if (is_array($dataStruct)) {
826  foreach ($dataStruct as $key => $value) {
827  if (isset($value['type']) && $value['type'] === 'array') {
828  // Array (Section) traversal
829  if ($value['section']) {
830  if (isset($editData[$key]['el']) && is_array($editData[$key]['el'])) {
831  if ($this->reNumberIndexesOfSectionData) {
832  $temp = [];
833  $c3 = 0;
834  foreach ($editData[$key]['el'] as $v3) {
835  $temp[++$c3] = $v3;
836  }
837  $editData[$key]['el'] = $temp;
838  }
839  foreach ($editData[$key]['el'] as $k3 => $v3) {
840  if (is_array($v3)) {
841  $cc = $k3;
842  $theType = key($v3);
843  $theDat = $v3[$theType];
844  $newSectionEl = $value['el'][$theType];
845  if (is_array($newSectionEl)) {
846  $this->‪traverseFlexFormXMLData_recurse([$theType => $newSectionEl], [$theType => $theDat], $PA, $path . '/' . $key . '/el/' . $cc);
847  }
848  }
849  }
850  }
851  } else {
852  // Array traversal
853  if (isset($editData[$key]['el'])) {
854  $this->‪traverseFlexFormXMLData_recurse($value['el'], $editData[$key]['el'], $PA, $path . '/' . $key . '/el');
855  }
856  }
857  } elseif (isset($value['TCEforms']['config']) && is_array($value['TCEforms']['config'])) {
858  // Processing a field value:
859  foreach ($PA['vKeys'] as $vKey) {
860  $vKey = 'v' . $vKey;
861  // Call back
862  if (!empty($PA['callBackMethod_value']) && isset($editData[$key][$vKey])) {
863  $this->‪executeCallBackMethod($PA['callBackMethod_value'], [
864  $value,
865  $editData[$key][$vKey],
866  $PA,
867  $path . '/' . $key . '/' . $vKey,
868  $this
869  ]);
870  }
871  }
872  }
873  }
874  }
875  }
876 
884  protected function ‪executeCallBackMethod($methodName, array $parameterArray)
885  {
886  return call_user_func_array([$this->callBackObj, $methodName], $parameterArray);
887  }
888 
889  /***********************************
890  *
891  * Processing functions
892  *
893  ***********************************/
903  public function ‪cleanFlexFormXML($table, $field, $row)
904  {
905  // New structure:
906  $this->‪cleanFlexFormXML = [];
907  // Create and call iterator object:
908  $flexObj = GeneralUtility::makeInstance(\‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
909  $flexObj->reNumberIndexesOfSectionData = true;
910  $flexObj->traverseFlexFormXMLData($table, $field, $row, $this, 'cleanFlexFormXML_callBackFunction');
911  return $this->‪flexArray2Xml($this->‪cleanFlexFormXML, true);
912  }
913 
924  public function ‪cleanFlexFormXML_callBackFunction($dsArr, $data, $PA, $path, $pObj)
925  {
926  // Just setting value in our own result array, basically replicating the structure:
927  $pObj->setArrayValueByPath($path, $this->‪cleanFlexFormXML, $data);
928  }
929 
930  /***********************************
931  *
932  * Multi purpose functions
933  *
934  ***********************************/
942  public function &‪getArrayValueByPath($pathArray, &$array)
943  {
944  if (!is_array($pathArray)) {
945  $pathArray = explode('/', $pathArray);
946  }
947  if (is_array($array) && !empty($pathArray)) {
948  $key = array_shift($pathArray);
949  if (isset($array[$key])) {
950  if (empty($pathArray)) {
951  return $array[$key];
952  }
953  return $this->‪getArrayValueByPath($pathArray, $array[$key]);
954  }
955  return null;
956  }
957  }
958 
967  public function ‪setArrayValueByPath($pathArray, &$array, $value)
968  {
969  if (isset($value)) {
970  if (!is_array($pathArray)) {
971  $pathArray = explode('/', $pathArray);
972  }
973  if (is_array($array) && !empty($pathArray)) {
974  $key = array_shift($pathArray);
975  if (empty($pathArray)) {
976  $array[$key] = $value;
977  return true;
978  }
979  if (!isset($array[$key])) {
980  $array[$key] = [];
981  }
982  return $this->‪setArrayValueByPath($pathArray, $array[$key], $value);
983  }
984  }
985  }
986 
994  public function ‪flexArray2Xml($array, $addPrologue = false)
995  {
996  if (‪$GLOBALS['TYPO3_CONF_VARS']['BE']['flexformForceCDATA']) {
997  $this->flexArray2Xml_options['useCDATA'] = 1;
998  }
999  ‪$output = GeneralUtility::array2xml($array, '', 0, 'T3FlexForms', 4, $this->flexArray2Xml_options);
1000  if ($addPrologue) {
1001  ‪$output = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>' . LF . ‪$output;
1002  }
1003  return ‪$output;
1004  }
1005 }
‪TYPO3\CMS\Core\Utility\GeneralUtility\xml2array
‪static mixed xml2array($string, $NSprefix='', $reportDocTag=false)
Definition: GeneralUtility.php:1531
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException
Definition: InvalidParentRowException.php:23
‪TYPO3\CMS\Core\Configuration\FlexForm
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\traverseFlexFormXMLData
‪bool string traverseFlexFormXMLData($table, $field, $row, $callBackObj, $callBackMethod_value)
Definition: FlexFormTools.php:765
‪TYPO3\CMS\Core\Utility\MathUtility\canBeInterpretedAsInteger
‪static bool canBeInterpretedAsInteger($var)
Definition: MathUtility.php:74
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\$cleanFlexFormXML
‪array $cleanFlexFormXML
Definition: FlexFormTools.php:74
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\setArrayValueByPath
‪mixed setArrayValueByPath($pathArray, &$array, $value)
Definition: FlexFormTools.php:963
‪TYPO3
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidCombinedPointerFieldException
Definition: InvalidCombinedPointerFieldException.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidSinglePointerFieldException
Definition: InvalidSinglePointerFieldException.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\getDataStructureIdentifierFromRecord
‪array getDataStructureIdentifierFromRecord(array $fieldTca, string $tableName, string $fieldName, array $row)
Definition: FlexFormTools.php:266
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\flexArray2Xml
‪string flexArray2Xml($array, $addPrologue=false)
Definition: FlexFormTools.php:990
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\$flexArray2Xml_options
‪array $flexArray2Xml_options
Definition: FlexFormTools.php:50
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\executeCallBackMethod
‪mixed executeCallBackMethod($methodName, array $parameterArray)
Definition: FlexFormTools.php:880
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException
Definition: InvalidParentRowRootException.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\cleanFlexFormXML_callBackFunction
‪cleanFlexFormXML_callBackFunction($dsArr, $data, $PA, $path, $pObj)
Definition: FlexFormTools.php:920
‪TYPO3\CMS\Backend\Utility\BackendUtility\fixVersioningPid
‪static fixVersioningPid($table, &$rr, $ignoreWorkspaceMatch=false)
Definition: BackendUtility.php:3511
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException
Definition: InvalidIdentifierException.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
Definition: FlexFormTools.php:38
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\cleanFlexFormXML
‪string cleanFlexFormXML($table, $field, $row)
Definition: FlexFormTools.php:899
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\getDataStructureIdentifierFromTcaArray
‪array getDataStructureIdentifierFromTcaArray(array $fieldTca, string $tableName, string $fieldName, array $row)
Definition: FlexFormTools.php:432
‪TYPO3\CMS\Backend\Utility\BackendUtility
Definition: BackendUtility.php:75
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidTcaException
Definition: InvalidTcaException.php:24
‪TYPO3\CMS\Core\Utility\GeneralUtility\trimExplode
‪static string[] trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
Definition: GeneralUtility.php:1059
‪$output
‪$output
Definition: annotationChecker.php:119
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException
Definition: InvalidPointerFieldValueException.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\getDataStructureIdentifier
‪string getDataStructureIdentifier(array $fieldTca, string $tableName, string $fieldName, array $row)
Definition: FlexFormTools.php:114
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\$reNumberIndexesOfSectionData
‪bool $reNumberIndexesOfSectionData
Definition: FlexFormTools.php:43
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:5
‪TYPO3\CMS\Backend\Utility\BackendUtility\workspaceOL
‪static workspaceOL($table, &$row, $wsid=-99, $unsetMovePointers=false)
Definition: BackendUtility.php:3586
‪TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
Definition: DeletedRestriction.php:28
‪TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException
Definition: InvalidParentRowLoopException.php:22
‪TYPO3\CMS\Core\Utility\MathUtility
Definition: MathUtility.php:22
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\$callBackObj
‪object $callBackObj
Definition: FlexFormTools.php:68
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\parseDataStructureByIdentifier
‪array parseDataStructureByIdentifier(string $identifier)
Definition: FlexFormTools.php:575
‪TYPO3\CMS\Core\Database\ConnectionPool
Definition: ConnectionPool.php:46
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:46
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\traverseFlexFormXMLData_recurse
‪traverseFlexFormXMLData_recurse($dataStruct, $editData, &$PA, $path='')
Definition: FlexFormTools.php:819
‪TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools\getArrayValueByPath
‪mixed & getArrayValueByPath($pathArray, &$array)
Definition: FlexFormTools.php:938