2 namespace TYPO3\CMS\Core\DataHandling
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use Doctrine\DBAL\DBALException
;
18 use Doctrine\DBAL\Driver\Statement
;
19 use Doctrine\DBAL\Platforms\PostgreSqlPlatform
;
20 use Doctrine\DBAL\Platforms\SqlitePlatform
;
21 use Doctrine\DBAL\Platforms\SQLServerPlatform
;
22 use Doctrine\DBAL\Types\IntegerType
;
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\LoggerAwareTrait
;
25 use TYPO3\CMS\Backend\Utility\BackendUtility
;
26 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication
;
27 use TYPO3\CMS\Core\Cache\CacheManager
;
28 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
;
29 use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait
;
30 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException
;
31 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException
;
32 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException
;
33 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException
;
34 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException
;
35 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
;
36 use TYPO3\CMS\Core\Configuration\Richtext
;
37 use TYPO3\CMS\Core\Core\Environment
;
38 use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException
;
39 use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory
;
40 use TYPO3\CMS\Core\Database\Connection
;
41 use TYPO3\CMS\Core\Database\ConnectionPool
;
42 use TYPO3\CMS\Core\Database\Query\QueryHelper
;
43 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction
;
44 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
;
45 use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface
;
46 use TYPO3\CMS\Core\Database\ReferenceIndex
;
47 use TYPO3\CMS\Core\Database\RelationHandler
;
48 use TYPO3\CMS\Core\DataHandling\History\RecordHistoryStore
;
49 use TYPO3\CMS\Core\DataHandling\Localization\DataMapProcessor
;
50 use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory
;
51 use TYPO3\CMS\Core\Html\RteHtmlParser
;
52 use TYPO3\CMS\Core\Localization\LanguageService
;
53 use TYPO3\CMS\Core\Messaging\FlashMessage
;
54 use TYPO3\CMS\Core\Messaging\FlashMessageService
;
55 use TYPO3\CMS\Core\
Resource\ResourceFactory
;
56 use TYPO3\CMS\Core\Service\OpcodeCacheService
;
57 use TYPO3\CMS\Core\Type\Bitmask\Permission
;
58 use TYPO3\CMS\Core\Utility\ArrayUtility
;
59 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
60 use TYPO3\CMS\Core\Utility\File\BasicFileUtility
;
61 use TYPO3\CMS\Core\Utility\GeneralUtility
;
62 use TYPO3\CMS\Core\Utility\MathUtility
;
63 use TYPO3\CMS\Core\Utility\PathUtility
;
64 use TYPO3\CMS\Core\Utility\StringUtility
;
65 use TYPO3\CMS\Core\Versioning\VersionState
;
68 * The main data handler class which takes care of correctly updating and inserting records.
69 * This class was formerly known as TCEmain.
71 * This is the TYPO3 Core Engine class for manipulation of the database
72 * This class is used by eg. the tce_db BE route (SimpleDataHandlerController) which provides an the interface for POST forms to this class.
75 * - $GLOBALS['TCA'] must exist
76 * - $GLOBALS['LANG'] must exist
78 * Also see document 'TYPO3 Core API' for details.
80 class DataHandler
implements LoggerAwareInterface
83 use PublicPropertyDeprecationTrait
;
88 protected $deprecatedPublicProperties = [
89 'updateModeL10NdiffData' => 'Using updateModeL10NdiffData is deprecated and will not be possible anymore in TYPO3 v10.0.',
90 'updateModeL10NdiffDataClear' => 'Using updateModeL10NdiffDataClear is deprecated and will not be possible anymore in TYPO3 v10.0.',
93 // *********************
94 // Public variables you can configure before using the class:
95 // *********************
97 * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
98 * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
102 public $storeLogMessages = true;
105 * If TRUE, actions are logged to sys_log.
109 public $enableLogging = true;
112 * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
117 public $reverseOrder = false;
120 * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
121 * is similar, it's not saved then.
125 public $checkSimilar = true;
128 * This will read the record after having updated or inserted it. If anything is not properly submitted an error
129 * is written to the log. This feature consumes extra time by selecting records
133 public $checkStoredRecords = true;
136 * If set, values '' and 0 will equal each other when the stored records are checked.
140 public $checkStoredRecords_loose = true;
143 * If this is set, then a page is deleted by deleting the whole branch under it (user must have
144 * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
148 public $deleteTree = false;
151 * If set, then the 'hideAtCopy' flag for tables will be ignored.
155 public $neverHideAtCopy = false;
158 * If set, then the TCE class has been instantiated during an import action of a T3D
162 public $isImporting = false;
165 * If set, then transformations are NOT performed on the input.
169 public $dontProcessTransformations = false;
172 * Will distinguish between translations (with parent) and localizations (without parent) while still using the same methods to copy the records
173 * TRUE: translation of a record connected to the default language
174 * FALSE: localization of a record without connection to the default language
178 protected $useTransOrigPointerField = true;
181 * TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value.
182 * FALSE: Will not update anything.
183 * "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
187 protected $updateModeL10NdiffData = true;
190 * If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again!
191 * It's meant as the opposite of declaring the record translated.
195 protected $updateModeL10NdiffDataClear = false;
198 * If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()).
199 * YOU MUST KNOW what you do if you use this feature!
203 public $bypassWorkspaceRestrictions = false;
206 * If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away.
207 * YOU MUST KNOW what you are doing with this feature!
211 public $bypassFileHandling = false;
214 * If TRUE, access check, check for deleted etc. for records is bypassed.
215 * YOU MUST KNOW what you are doing if you use this feature!
219 public $bypassAccessCheckForRecords = false;
222 * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
223 * If '*' then all will (that the user has permission to of course)
227 public $copyWhichTables = '*';
230 * If 0 then branch is NOT copied.
231 * If 1 then pages on the 1st level is copied.
232 * If 2 then pages on the second level is copied ... and so on
236 public $copyTree = 0;
239 * [table][fields]=value: New records are created with default values and you can set this array on the
240 * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
241 * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
242 * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
246 public $defaultValues = [];
249 * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
250 * override the incoming data. You must set this externally. You must make sure the fields in this array are also
251 * found in the table, because it's not checked. All columns can be set by this array!
255 public $overrideValues = [];
258 * [filename]=alternative_filename: Use this array to force another name onto a file.
259 * Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field,
260 * then 'my_file.txt' will be used as the name instead.
264 public $alternativeFileName = [];
267 * Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
271 public $alternativeFilePath = [];
274 * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
275 * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
276 * Then an empty checkbox will disable the field.
280 public $data_disableFields = [];
283 * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
284 * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
285 * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
286 * The option is used for import of T3D files when synchronizing between two mirrored servers.
287 * As a security measure this feature is available only for Admin Users (for now)
291 public $suggestedInsertUids = [];
294 * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
295 * iteration functions inside DataHandler for traversing a FlexForm structure.
301 // *********************
302 // Internal variables (mapping arrays) which can be used (read-only) from outside
303 // *********************
305 * Contains mapping of auto-versionized records.
309 public $autoVersionIdMap = [];
312 * When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
316 public $substNEWwithIDs = [];
319 * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
323 public $substNEWwithIDs_table = [];
326 * Holds the tables and there the ids of newly created child records from IRRE
330 public $newRelatedIDs = [];
333 * This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
337 public $copyMappingArray_merged = [];
340 * Per-table array with UIDs that have been deleted.
344 protected $deletedRecords = [];
347 * A map between input file name and final destination for files being attached to records.
351 public $copiedFileMap = [];
354 * Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
358 public $RTEmagic_copyIndex = [];
361 * Errors are collected in this variable.
365 public $errorLog = [];
368 * Fields from the pages-table for which changes will trigger a pagetree refresh
372 public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid', 'extendToSubpages'];
375 * Indicates whether the pagetree needs a refresh because of important changes
379 public $pagetreeNeedsRefresh = false;
381 // *********************
382 // Internal Variables, do not touch.
383 // *********************
385 // Variables set in init() function:
388 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
390 * @var BackendUserAuthentication
395 * Will be set to uid of be_user executing this script
402 * Will be set to username of be_user executing this script
409 * Will be set if user is admin
416 * Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
420 public $defaultPermissions = [
421 'user' => 'show,edit,delete,new,editcontent',
422 'group' => 'show,edit,new,editcontent',
427 * The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
431 protected $excludedTablesAndFields = [];
434 * Data submitted from the form view, used to control behaviours,
435 * e.g. this is used to activate/deactivate fields and thus store NULL values
439 protected $control = [];
442 * Set with incoming data array
446 public $datamap = [];
449 * Set with incoming cmd array
456 * List of changed old record ids to new records ids
460 protected $mmHistoryRecords = [];
463 * List of changed old record ids to new records ids
467 protected $historyRecords = [];
488 * The interval between sorting numbers used with tables with a 'sorting' field defined.
490 * Min 1, should be power of 2
494 public $sortIntervals = 256;
496 // Internal caching arrays
498 * Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
502 protected $recUpdateAccessCache = [];
505 * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
509 protected $recInsertAccessCache = [];
512 * Caching array for check of whether records are in a webmount
516 protected $isRecordInWebMount_Cache = [];
519 * Caching array for page ids in webmounts
523 protected $isInWebMount_Cache = [];
526 * Used for caching page records in pageInfo()
530 protected $pageCache = [];
534 * For accumulation of MM relations that must be written after new records are created.
538 public $dbAnalysisStore = [];
541 * For accumulation of files which must be deleted after processing of all input content
545 public $removeFilesStore = [];
548 * Uploaded files, set by process_uploads()
552 public $uploadedFileArray = [];
555 * Used for tracking references that might need correction after operations
559 public $registerDBList = [];
562 * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
566 public $registerDBPids = [];
569 * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
570 * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
571 * Read from copyMappingArray_merged instead which is accumulating this information.
573 * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
574 * are only available after an action has been completed.
578 public $copyMappingArray = [];
581 * Array used for remapping uids and values at the end of process_datamap
585 public $remapStack = [];
588 * Array used for remapping uids and values at the end of process_datamap
589 * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
593 public $remapStackRecords = [];
596 * Array used for checking whether new children need to be remapped
600 protected $remapStackChildIds = [];
603 * Array used for executing addition actions after remapping happened (set processRemapStack())
607 protected $remapStackActions = [];
610 * Array used for executing post-processing on the reference index
614 protected $remapStackRefIndex = [];
617 * Array used for additional calls to $this->updateRefIndex
621 public $updateRefIndexStack = [];
624 * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
625 * This variable is set by \TYPO3\CMS\Impext\ImportExport
629 public $callFromImpExp = false;
633 * basicFileFunctions object
634 * For "singleton" file-manipulation object
636 * @var BasicFileUtility
641 * Set to "currentRecord" during checking of values.
645 public $checkValue_currentRecord = [];
648 * A signal flag used to tell file processing that auto versioning has happened and hence certain action should be applied.
652 public $autoVersioningUpdate = false;
655 * Disable delete clause
659 protected $disableDeleteClause = false;
664 protected $checkModifyAccessListHookObjects;
669 protected $version_remapMMForVersionSwap_reg;
672 * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
673 * This object instantiates itself on versioning and localization ...
675 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
677 protected $outerMostInstance;
680 * Internal cache for collecting records that should trigger cache clearing
684 protected static $recordsToClearCacheFor = [];
687 * Internal cache for pids of records which were deleted. It's not possible
688 * to retrieve the parent folder/page at a later stage
692 protected static $recordPidsForDeletedRecords = [];
695 * Runtime Cache to store and retrieve data computed for a single request
697 * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
699 protected $runtimeCache;
702 * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
706 protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
709 * Sets up the data handler cache and some additional options, the main logic is done in the start() method.
711 public function __construct()
713 $this->checkStoredRecords
= (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecords'];
714 $this->checkStoredRecords_loose
= (bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['checkStoredRecordsLoose'];
715 $this->runtimeCache
= $this->getRuntimeCache();
719 * @param array $control
721 public function setControl(array $control)
723 $this->control
= $control;
728 * For details, see 'TYPO3 Core API' document.
729 * This function does not start the processing of data, but merely initializes the object
731 * @param array $data Data to be modified or inserted in the database
732 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
733 * @param BackendUserAuthentication|null $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
735 public function start($data, $cmd, $altUserObject = null)
737 // Initializing BE_USER
738 $this->BE_USER
= is_object($altUserObject) ?
$altUserObject : $GLOBALS['BE_USER'];
739 $this->userid
= $this->BE_USER
->user
['uid'];
740 $this->username
= $this->BE_USER
->user
['username'];
741 $this->admin
= $this->BE_USER
->user
['admin'];
742 if ($this->BE_USER
->uc
['recursiveDelete']) {
743 $this->deleteTree
= 1;
745 // Initializing default permissions for pages
746 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
747 if (isset($defaultPermissions['user'])) {
748 $this->defaultPermissions
['user'] = $defaultPermissions['user'];
750 if (isset($defaultPermissions['group'])) {
751 $this->defaultPermissions
['group'] = $defaultPermissions['group'];
753 if (isset($defaultPermissions['everybody'])) {
754 $this->defaultPermissions
['everybody'] = $defaultPermissions['everybody'];
756 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
758 $this->excludedTablesAndFields
= array_flip($this->getExcludeListArray());
760 // Setting the data and cmd arrays
761 if (is_array($data)) {
763 $this->datamap
= $data;
765 if (is_array($cmd)) {
767 $this->cmdmap
= $cmd;
772 * Function that can mirror input values in datamap-array to other uid numbers.
773 * Example: $mirror[table][11] = '22,33' will look for content in $this->datamap[table][11] and copy it to $this->datamap[table][22] and $this->datamap[table][33]
775 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
777 public function setMirror($mirror)
779 if (!is_array($mirror)) {
783 foreach ($mirror as $table => $uid_array) {
784 if (!isset($this->datamap
[$table])) {
788 foreach ($uid_array as $id => $uidList) {
789 if (!isset($this->datamap
[$table][$id])) {
793 $theIdsInArray = GeneralUtility
::trimExplode(',', $uidList, true);
794 foreach ($theIdsInArray as $copyToUid) {
795 $this->datamap
[$table][$copyToUid] = $this->datamap
[$table][$id];
802 * Initializes default values coming from User TSconfig
804 * @param array $userTS User TSconfig array
806 public function setDefaultsFromUserTS($userTS)
808 if (!is_array($userTS)) {
812 foreach ($userTS as $k => $v) {
813 $k = mb_substr($k, 0, -1);
814 if (!$k ||
!is_array($v) ||
!isset($GLOBALS['TCA'][$k])) {
818 if (is_array($this->defaultValues
[$k])) {
819 $this->defaultValues
[$k] = array_merge($this->defaultValues
[$k], $v);
821 $this->defaultValues
[$k] = $v;
827 * Processing of uploaded files.
828 * It turns out that some versions of PHP arranges submitted data for files different if sent in an array. This function will unify this so the internal array $this->uploadedFileArray will always contain files arranged in the same structure.
830 * @param array $postFiles $_FILES array
832 public function process_uploads($postFiles)
834 if (!is_array($postFiles)) {
839 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
840 $this->newlog('All editing in this workspace has been frozen!', 1);
843 $subA = reset($postFiles);
844 if (is_array($subA)) {
845 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
846 // Initialize the uploadedFilesArray:
847 $this->uploadedFileArray
= [];
849 foreach ($subA as $key => $values) {
850 $this->process_uploads_traverseArray($this->uploadedFileArray
, $values, $key);
853 $this->uploadedFileArray
= $subA;
859 * Traverse the upload array if needed to rearrange values.
861 * @param array $outputArr $this->uploadedFileArray passed by reference
862 * @param array $inputArr Input array ($_FILES parts)
863 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
865 * @see process_uploads()
867 public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet)
869 if (is_array($inputArr)) {
870 foreach ($inputArr as $key => $value) {
871 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
874 $outputArr[$keyToSet] = $inputArr;
878 /*********************************************
882 *********************************************/
884 * Hook: processDatamap_afterDatabaseOperations
885 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
887 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
888 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
890 * @param array $hookObjectsArr (reference) Array with hook objects
891 * @param string $status (reference) Status of the current operation, 'new' or 'update
892 * @param string $table (reference) The table currently processing data for
893 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
894 * @param array $fieldArray (reference) The field array of a record
896 public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
898 // Process hook directly:
899 if (!isset($this->remapStackRecords
[$table][$id])) {
900 foreach ($hookObjectsArr as $hookObj) {
901 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
902 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
906 $this->remapStackRecords
[$table][$id]['processDatamap_afterDatabaseOperations'] = [
908 'fieldArray' => $fieldArray,
909 'hookObjectsArr' => $hookObjectsArr
915 * Gets the 'checkModifyAccessList' hook objects.
916 * The first call initializes the accordant objects.
918 * @return array The 'checkModifyAccessList' hook objects (if any)
919 * @throws \UnexpectedValueException
921 protected function getCheckModifyAccessListHookObjects()
923 if (!isset($this->checkModifyAccessListHookObjects
)) {
924 $this->checkModifyAccessListHookObjects
= [];
925 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] ??
[] as $className) {
926 $hookObject = GeneralUtility
::makeInstance($className);
927 if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface
) {
928 throw new \
UnexpectedValueException($className . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface
::class, 1251892472);
930 $this->checkModifyAccessListHookObjects
[] = $hookObject;
933 return $this->checkModifyAccessListHookObjects
;
936 /*********************************************
940 *********************************************/
942 * Processing the data-array
943 * Call this function to process the data-array set by start()
947 public function process_datamap()
949 $this->controlActiveElements();
951 // Keep versionized(!) relations here locally:
952 $registerDBList = [];
953 $this->registerElementsToBeDeleted();
954 $this->datamap
= $this->unsetElementsToBeDeleted($this->datamap
);
956 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
957 $this->newlog('All editing in this workspace has been frozen!', 1);
960 // First prepare user defined objects (if any) for hooks which extend this function:
961 $hookObjectsArr = [];
962 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] ??
[] as $className) {
963 $hookObject = GeneralUtility
::makeInstance($className);
964 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
965 $hookObject->processDatamap_beforeStart($this);
967 $hookObjectsArr[] = $hookObject;
969 // Pre-process data-map and synchronize localization states
970 $this->datamap
= GeneralUtility
::makeInstance(SlugEnricher
::class)->enrichDataMap($this->datamap
);
971 $this->datamap
= DataMapProcessor
::instance($this->datamap
, $this->BE_USER
)->process();
972 // Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
975 if (isset($this->datamap
['pages'])) {
976 $orderOfTables[] = 'pages';
978 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap
)));
979 // Process the tables...
980 foreach ($orderOfTables as $table) {
982 // - table is set in $GLOBALS['TCA'],
983 // - table is NOT readOnly
984 // - the table is set with content in the data-array (if not, there's nothing to process...)
985 // - permissions for tableaccess OK
986 $modifyAccessList = $this->checkModifyAccessList($table);
987 if (!$modifyAccessList) {
988 $this->log($table, 0, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
990 if (!isset($GLOBALS['TCA'][$table]) ||
$this->tableReadOnly($table) ||
!is_array($this->datamap
[$table]) ||
!$modifyAccessList) {
994 if ($this->reverseOrder
) {
995 $this->datamap
[$table] = array_reverse($this->datamap
[$table], 1);
997 // For each record from the table, do:
998 // $id is the record uid, may be a string if new records...
999 // $incomingFieldArray is the array of fields
1000 foreach ($this->datamap
[$table] as $id => $incomingFieldArray) {
1001 if (!is_array($incomingFieldArray)) {
1006 // Hook: processDatamap_preProcessFieldArray
1007 foreach ($hookObjectsArr as $hookObj) {
1008 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
1009 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
1012 // ******************************
1013 // Checking access to the record
1014 // ******************************
1015 $createNewVersion = false;
1016 $recordAccess = false;
1017 $old_pid_value = '';
1018 $this->autoVersioningUpdate
= false;
1019 // Is it a new record? (Then Id is a string)
1020 if (!MathUtility
::canBeInterpretedAsInteger($id)) {
1021 // Get a fieldArray with default values
1022 $fieldArray = $this->newFieldArray($table);
1023 // A pid must be set for new records.
1024 if (isset($incomingFieldArray['pid'])) {
1025 $pid_value = $incomingFieldArray['pid'];
1026 // Checking and finding numerical pid, it may be a string-reference to another value
1029 if (strpos($pid_value, 'NEW') !== false) {
1030 if ($pid_value[0] === '-') {
1032 $pid_value = substr($pid_value, 1);
1036 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
1037 if (isset($this->substNEWwithIDs
[$pid_value])) {
1038 if ($negFlag === 1) {
1039 $old_pid_value = $this->substNEWwithIDs
[$pid_value];
1041 $pid_value = (int)($negFlag * $this->substNEWwithIDs
[$pid_value]);
1043 $canProceed = false;
1046 $pid_value = (int)$pid_value;
1048 $fieldArray = $this->resolveSortingAndPidForNewRecord($table, $pid_value, $fieldArray);
1051 $theRealPid = $fieldArray['pid'];
1052 // Now, check if we may insert records on this pid.
1053 if ($theRealPid >= 0) {
1054 // Checks if records can be inserted on this $pid.
1055 // If this is a page translation, the check needs to be done for the l10n_parent record
1056 if ($table === 'pages' && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
1057 $recordAccess = $this->checkRecordInsertAccess($table, $incomingFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
1059 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
1061 if ($recordAccess) {
1062 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
1063 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $incomingFieldArray, true);
1064 if (!$recordAccess) {
1065 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1066 } elseif (!$this->bypassWorkspaceRestrictions
) {
1067 // Workspace related processing:
1068 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1069 if ($res = $this->BE_USER
->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
1071 $recordAccess = false;
1072 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
1075 // So, if no live records were allowed, we have to create a new version of this record:
1076 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1077 $createNewVersion = true;
1079 $recordAccess = false;
1080 $this->newlog('Record could not be created in this workspace in this branch', 1);
1086 $this->logger
->debug('Internal ERROR: pid should not be less than zero!');
1088 // Yes new record, change $record_status to 'insert'
1091 // Nope... $id is a number
1093 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
1094 if (!$recordAccess) {
1095 if ($this->enableLogging
) {
1096 $propArr = $this->getRecordProperties($table, $id);
1097 $this->log($table, $id, 2, 0, 1, 'Attempt to modify record \'%s\' (%s) without permission. Or non-existing page.', 2, [$propArr['header'], $table . ':' . $id], $propArr['event_pid']);
1101 // Next check of the record permissions (internals)
1102 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $id);
1103 if (!$recordAccess) {
1104 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1106 // Here we fetch the PID of the record that we point to...
1107 $tempdata = $this->recordInfo($table, $id, 'pid' . (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) ?
',t3ver_wsid,t3ver_stage' : ''));
1108 $theRealPid = $tempdata['pid'];
1109 // Use the new id of the versionized record we're trying to write to:
1110 // (This record is a child record of a parent and has already been versionized.)
1111 if (!empty($this->autoVersionIdMap
[$table][$id])) {
1112 // For the reason that creating a new version of this record, automatically
1113 // created related child records (e.g. "IRRE"), update the accordant field:
1114 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1115 // Use the new id of the copied/versionized record:
1116 $id = $this->autoVersionIdMap
[$table][$id];
1117 $recordAccess = true;
1118 $this->autoVersioningUpdate
= true;
1119 } elseif (!$this->bypassWorkspaceRestrictions
&& ($errorCode = $this->BE_USER
->workspaceCannotEditRecord($table, $tempdata))) {
1120 $recordAccess = false;
1121 // Versioning is required and it must be offline version!
1122 // Check if there already is a workspace version
1123 $WSversion = BackendUtility
::getWorkspaceVersionOfRecord($this->BE_USER
->workspace
, $table, $id, 'uid,t3ver_oid');
1125 $id = $WSversion['uid'];
1126 $recordAccess = true;
1127 } elseif ($this->BE_USER
->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1128 // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1129 $this->pagetreeNeedsRefresh
= true;
1131 /** @var DataHandler $tce */
1132 $tce = GeneralUtility
::makeInstance(__CLASS__
);
1133 $tce->enableLogging
= $this->enableLogging
;
1134 // Setting up command for creating a new version of the record:
1136 $cmd[$table][$id]['version'] = [
1138 // Default is to create a version of the individual records... element versioning that is.
1139 'label' => 'Auto-created for WS #' . $this->BE_USER
->workspace
1141 $tce->start([], $cmd, $this->BE_USER
);
1142 $tce->process_cmdmap();
1143 $this->errorLog
= array_merge($this->errorLog
, $tce->errorLog
);
1144 // If copying was successful, share the new uids (also of related children):
1145 if (!empty($tce->copyMappingArray
[$table][$id])) {
1146 foreach ($tce->copyMappingArray
as $origTable => $origIdArray) {
1147 foreach ($origIdArray as $origId => $newId) {
1148 $this->uploadedFileArray
[$origTable][$newId] = $this->uploadedFileArray
[$origTable][$origId];
1149 $this->autoVersionIdMap
[$origTable][$origId] = $newId;
1152 ArrayUtility
::mergeRecursiveWithOverrule($this->RTEmagic_copyIndex
, $tce->RTEmagic_copyIndex
);
1153 // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
1154 // Update registerDBList, that holds the copied relations to child records:
1155 $registerDBList = array_merge($registerDBList, $tce->registerDBList
);
1156 // For the reason that creating a new version of this record, automatically
1157 // created related child records (e.g. "IRRE"), update the accordant field:
1158 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1159 // Use the new id of the copied/versionized record:
1160 $id = $this->autoVersionIdMap
[$table][$id];
1161 $recordAccess = true;
1162 $this->autoVersioningUpdate
= true;
1164 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
1167 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version not allowed in workspace!', 1);
1171 // The default is 'update'
1174 // If access was granted above, proceed to create or update record:
1175 if (!$recordAccess) {
1179 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1180 list($tscPID) = BackendUtility
::getTSCpid($table, $id, $old_pid_value ?
$old_pid_value : $fieldArray['pid']);
1181 if ($status === 'new' && $table === 'pages') {
1182 $TSConfig = BackendUtility
::getPagesTSconfig($tscPID)['TCEMAIN.'] ??
[];
1183 if (isset($TSConfig['permissions.']) && is_array($TSConfig['permissions.'])) {
1184 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
1187 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1188 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1189 $newVersion_placeholderFieldArray = [];
1190 if ($createNewVersion) {
1191 // create a placeholder array with already processed field content
1192 $newVersion_placeholderFieldArray = $fieldArray;
1194 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
1195 // Forcing some values unto field array:
1196 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1197 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1198 if ($createNewVersion) {
1199 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1201 // Setting system fields
1202 if ($status === 'new') {
1203 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1204 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1205 if ($createNewVersion) {
1206 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1209 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1210 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1211 if ($createNewVersion) {
1212 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1215 } elseif ($this->checkSimilar
) {
1216 // Removing fields which are equal to the current value:
1217 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1219 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1220 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1221 if ($createNewVersion) {
1222 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1225 // Set stage to "Editing" to make sure we restart the workflow
1226 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1227 $fieldArray['t3ver_stage'] = 0;
1229 // Hook: processDatamap_postProcessFieldArray
1230 foreach ($hookObjectsArr as $hookObj) {
1231 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1232 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1235 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1236 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
1237 if (is_array($fieldArray)) {
1238 if ($status === 'new') {
1239 if ($table === 'pages') {
1240 // for new pages always a refresh is needed
1241 $this->pagetreeNeedsRefresh
= true;
1244 // This creates a new version of the record with online placeholder and offline version
1245 if ($createNewVersion) {
1246 // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1247 $this->pagetreeNeedsRefresh
= true;
1249 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
1250 // Setting placeholder state value for temporary record
1251 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER
);
1252 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1253 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1254 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $this->getPlaceholderTitleForTableLabel($table);
1255 // Saving placeholder as 'original'
1256 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, false, $incomingFieldArray['uid'] ??
0);
1257 // For the actual new offline version, set versioning values to point to placeholder:
1258 $fieldArray['pid'] = -1;
1259 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs
[$id];
1260 $fieldArray['t3ver_id'] = 1;
1261 // Setting placeholder state value for version (so it can know it is currently a new version...)
1262 $fieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER_VERSION
);
1263 $fieldArray['t3ver_label'] = 'First draft version';
1264 $fieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1265 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1266 $phShadowId = $this->insertDB($table, $id, $fieldArray, true, 0, true);
1268 // Processes fields of the placeholder record:
1269 $this->triggerRemapAction($table, $id, [$this, 'placeholderShadowing'], [$table, $phShadowId]);
1270 // Hold auto-versionized ids of placeholders:
1271 $this->autoVersionIdMap
[$table][$this->substNEWwithIDs
[$id]] = $phShadowId;
1274 $this->insertDB($table, $id, $fieldArray, false, $incomingFieldArray['uid']);
1277 if ($table === 'pages') {
1278 // only a certain number of fields needs to be checked for updates
1279 // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1280 $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages
, array_keys($fieldArray));
1281 if (!empty($fieldsToCheck)) {
1282 $this->pagetreeNeedsRefresh
= true;
1285 $this->updateDB($table, $id, $fieldArray);
1286 $this->placeholderShadowing($table, $id);
1289 // Hook: processDatamap_afterDatabaseOperations
1290 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1291 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1292 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1295 // Process the stack of relations to remap/correct
1296 $this->processRemapStack();
1297 $this->dbAnalysisStoreExec();
1298 $this->removeRegisteredFiles();
1299 // Hook: processDatamap_afterAllOperations
1300 // Note: When this hook gets called, all operations on the submitted data have been finished.
1301 foreach ($hookObjectsArr as $hookObj) {
1302 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1303 $hookObj->processDatamap_afterAllOperations($this);
1306 if ($this->isOuterMostInstance()) {
1307 $this->processClearCacheQueue();
1308 $this->resetElementsToBeDeleted();
1313 * @param string $table
1314 * @param string $value
1315 * @param string $dbType
1318 protected function normalizeTimeFormat(string $table, string $value, string $dbType): string
1320 $connection = GeneralUtility
::makeInstance(ConnectionPool
::class)->getConnectionForTable($table);
1321 $platform = $connection->getDatabasePlatform();
1322 if ($platform instanceof SQLServerPlatform
) {
1323 $defaultLength = QueryHelper
::getDateTimeFormats()[$dbType]['empty'];
1327 strlen($defaultLength)
1334 * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
1335 * depending on the record that should be added or where it should be added.
1337 * This method is called from process_datamap()
1339 * @param string $table the table name of the record to insert
1340 * @param int $pid the real PID (numeric) where the record should be
1341 * @param array $fieldArray field+value pairs to add
1342 * @return array the modified field array
1344 protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
1346 $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ??
'';
1347 // Points to a page on which to insert the element, possibly in the top of the page
1349 // Ensure that the "pid" is not a translated page ID, but the default page ID
1350 $pid = $this->getDefaultLanguagePageId($pid);
1351 // The numerical pid is inserted in the data array
1352 $fieldArray['pid'] = $pid;
1353 // If this table is sorted we better find the top sorting number
1355 $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1357 } elseif ($sortColumn) {
1358 // Points to another record before itself
1359 // If this table is sorted we better find the top sorting number
1360 // Because $pid is < 0, getSortNumber() returns an array
1361 $sortingInfo = $this->getSortNumber($table, 0, $pid);
1362 $fieldArray['pid'] = $sortingInfo['pid'];
1363 $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1365 // Here we fetch the PID of the record that we point to
1366 $record = $this->recordInfo($table, abs($pid), 'pid');
1367 // Ensure that the "pid" is not a translated page ID, but the default page ID
1368 $fieldArray['pid'] = $this->getDefaultLanguagePageId($record['pid']);
1374 * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record:
1376 * @param string $table Table name
1377 * @param int $id Record uid
1379 public function placeholderShadowing($table, $id)
1381 if ($liveRec = BackendUtility
::getLiveVersionOfRecord($table, $id, '*')) {
1382 if (VersionState
::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1383 $justStoredRecord = BackendUtility
::getRecord($table, $id);
1385 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1386 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1387 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1388 if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
1389 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
1391 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1392 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1393 $shadowCols .= ',' . implode(',', GeneralUtility
::makeInstance(SlugEnricher
::class)->resolveSlugFieldNames($table));
1394 $shadowColumns = array_unique(GeneralUtility
::trimExplode(',', $shadowCols, true));
1395 foreach ($shadowColumns as $fieldName) {
1396 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1397 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1400 if (!empty($newRecord)) {
1401 if ($this->enableLogging
) {
1402 $this->log($table, $liveRec['uid'], 0, 0, 0, 'Shadowing done on fields <i>' . implode(',', array_keys($newRecord)) . '</i> in placeholder record ' . $table . ':' . $liveRec['uid'] . ' (offline version UID=' . $id . ')', -1, [], $this->eventPid($table, $liveRec['uid'], $liveRec['pid']));
1404 $this->updateDB($table, $liveRec['uid'], $newRecord);
1411 * Create a placeholder title for the label field that does match the field requirements
1413 * @param string $table The table name
1414 * @param string $placeholderContent Placeholder content to be used
1415 * @return string placeholder value
1417 public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1419 if ($placeholderContent === null) {
1420 $placeholderContent = 'PLACEHOLDER';
1423 $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER
->workspace
. ']';
1424 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1425 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1426 return $labelPlaceholder;
1428 $evalCodesArray = GeneralUtility
::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1429 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '', $table);
1430 return $transformedLabel['value'] ??
$labelPlaceholder;
1434 * Filling in the field array
1435 * $this->excludedTablesAndFields is used to filter fields if needed.
1437 * @param string $table Table name
1438 * @param int $id Record ID
1439 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1440 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1441 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1442 * @param string $status Is 'new' or 'update'
1443 * @param int $tscPID TSconfig PID
1444 * @return array Field Array
1446 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1449 $originalLanguageRecord = null;
1450 $originalLanguage_diffStorage = null;
1451 $diffStorageFlag = false;
1452 // Setting 'currentRecord' and 'checkValueRecord':
1453 if (strpos($id, 'NEW') !== false) {
1454 // Must have the 'current' array - not the values after processing below...
1455 $checkValueRecord = $fieldArray;
1456 // IF $incomingFieldArray is an array, overlay it.
1457 // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
1458 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1459 ArrayUtility
::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1461 $currentRecord = $checkValueRecord;
1463 // We must use the current values as basis for this!
1464 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1465 // This is done to make the pid positive for offline versions; Necessary to have diff-view for page translations in workspaces.
1466 BackendUtility
::fixVersioningPid($table, $currentRecord);
1469 // Get original language record if available:
1470 if (is_array($currentRecord)
1471 && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
1472 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1473 && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
1474 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1475 && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
1477 $originalLanguageRecord = $this->recordInfo($table, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1478 BackendUtility
::workspaceOL($table, $originalLanguageRecord);
1479 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1482 $this->checkValue_currentRecord
= $checkValueRecord;
1483 // In the following all incoming value-fields are tested:
1484 // - Are the user allowed to change the field?
1485 // - Is the field uid/pid (which are already set)
1486 // - perms-fields for pages-table, then do special things...
1487 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1488 // If everything is OK, the field is entered into $fieldArray[]
1489 foreach ($incomingFieldArray as $field => $fieldValue) {
1490 if (isset($this->excludedTablesAndFields
[$table . '-' . $field]) ||
$this->data_disableFields
[$table][$id][$field]) {
1494 // The field must be editable.
1495 // Checking if a value for language can be changed:
1496 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER
->checkLanguageAccess($fieldValue);
1497 if ($languageDeny) {
1504 // Nothing happens, already set
1506 case 'perms_userid':
1507 case 'perms_groupid':
1510 case 'perms_everybody':
1511 // Permissions can be edited by the owner or the administrator
1512 if ($table === 'pages' && ($this->admin ||
$status === 'new' ||
$this->pageInfo($id, 'perms_userid') == $this->userid
)) {
1513 $value = (int)$fieldValue;
1515 case 'perms_userid':
1516 case 'perms_groupid':
1517 $fieldArray[$field] = $value;
1520 if ($value >= 0 && $value < (2 ** 5)) {
1521 $fieldArray[$field] = $value;
1532 case 't3ver_tstamp':
1533 // t3ver_label is not here because it CAN be edited as a regular field!
1536 $fieldArray[$field] = $fieldValue;
1539 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1540 // Evaluating the value
1541 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID, $incomingFieldArray);
1542 if (array_key_exists('value', $res)) {
1543 $fieldArray[$field] = $res['value'];
1545 // Add the value of the original record to the diff-storage content:
1546 if ($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1547 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ?
'' : $originalLanguageRecord[$field];
1548 $diffStorageFlag = true;
1550 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1551 // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied.
1552 // That should be TRUE for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
1553 // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
1554 // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
1555 if ($this->autoVersioningUpdate
=== true) {
1556 if (is_array($this->RTEmagic_copyIndex
[$table][$id][$field])) {
1557 foreach ($this->RTEmagic_copyIndex
[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1558 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1562 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1563 // Allow value for original UID to pass by...
1564 $fieldArray[$field] = $fieldValue;
1569 // Dealing with a page translation, setting "sorting", "pid", "perms_*" to the same values as the original record
1570 if ($table === 'pages' && is_array($originalLanguageRecord)) {
1571 $fieldArray['sorting'] = $originalLanguageRecord['sorting'];
1572 $fieldArray['perms_userid'] = $originalLanguageRecord['perms_userid'];
1573 $fieldArray['perms_groupid'] = $originalLanguageRecord['perms_groupid'];
1574 $fieldArray['perms_user'] = $originalLanguageRecord['perms_user'];
1575 $fieldArray['perms_group'] = $originalLanguageRecord['perms_group'];
1576 $fieldArray['perms_everybody'] = $originalLanguageRecord['perms_everybody'];
1579 // Add diff-storage information:
1580 if ($diffStorageFlag
1581 && !array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
1583 // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
1584 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1586 // Return fieldArray
1590 /*********************************************
1592 * Evaluation of input values
1594 ********************************************/
1596 * Evaluates a value according to $table/$field settings.
1597 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1598 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
1600 * @param string $table Table name
1601 * @param string $field Field name
1602 * @param string $value Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1603 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1604 * @param string $status 'update' or 'new' flag
1605 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1606 * @param int $tscPID TSconfig PID
1607 * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray)
1608 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1610 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID, $incomingFieldArray = [])
1615 // Processing special case of field pages.doktype
1616 if ($table === 'pages' && $field === 'doktype') {
1617 // If the user may not use this specific doktype, we issue a warning
1618 if (!($this->admin || GeneralUtility
::inList($this->BE_USER
->groupData
['pagetypes_select'], $value))) {
1619 if ($this->enableLogging
) {
1620 $propArr = $this->getRecordProperties($table, $id);
1621 $this->log($table, $id, 5, 0, 1, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, [$propArr['header']], $propArr['event_pid']);
1625 if ($status === 'update') {
1626 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1627 $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ??
$GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1628 if ($onlyAllowedTables) {
1629 // use the real page id (default language)
1630 $recordId = $this->getDefaultLanguagePageId($id);
1631 $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, $value);
1632 if ($theWrongTables) {
1633 if ($this->enableLogging
) {
1634 $propArr = $this->getRecordProperties($table, $id);
1635 $this->log($table, $id, 5, 0, 1, '\'doktype\' of page \'%s\' could not be changed because the page contains records from disallowed tables; %s', 2, [$propArr['header'], $theWrongTables], $propArr['event_pid']);
1644 if ((int)$id !== 0) {
1645 // Get current value:
1646 $curValueRec = $this->recordInfo($table, $id, $field);
1647 // isset() won't work here, since values can be NULL
1648 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1649 $curValue = $curValueRec[$field];
1653 if ($table === 'be_users'
1654 && ($field === 'admin' ||
$field === 'password')
1655 && $status === 'update'
1657 // Do not allow a non system maintainer admin to change admin flag and password of system maintainers
1658 $systemMaintainers = array_map('intval', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemMaintainers'] ??
[]);
1659 // False if current user is not in system maintainer list or if switch to user mode is active
1660 $isCurrentUserSystemMaintainer = $this->BE_USER
->isSystemMaintainer();
1661 $isTargetUserInSystemMaintainerList = in_array((int)$id, $systemMaintainers, true);
1662 if ($field === 'admin') {
1663 $isFieldChanged = (int)$curValueRec[$field] !== (int)$value;
1665 $isFieldChanged = $curValueRec[$field] !== $value;
1667 if (!$isCurrentUserSystemMaintainer && $isTargetUserInSystemMaintainerList && $isFieldChanged) {
1668 $value = $curValueRec[$field];
1669 $message = GeneralUtility
::makeInstance(
1670 FlashMessage
::class,
1671 $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.adminCanNotChangeSystemMaintainer'),
1673 FlashMessage
::ERROR
,
1676 $flashMessageService = GeneralUtility
::makeInstance(FlashMessageService
::class);
1677 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
1681 // Getting config for the field
1682 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1684 // Create $recFID only for those types that need it
1686 $tcaFieldConf['type'] === 'flex'
1687 ||
$tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' ||
$tcaFieldConf['internal_type'] === 'file_reference')
1689 // @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0. Deprecation logged by TcaMigration class. Remove type=group handling.
1690 $recFID = $table . ':' . $id . ':' . $field;
1695 // Perform processing:
1696 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray
[$table][$id][$field], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
1701 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1702 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1704 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1705 * @param string $value The value to set.
1706 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1707 * @param string $table Table name
1708 * @param int $id UID of record
1709 * @param mixed $curValue Current value of the field
1710 * @param string $status 'update' or 'new' flag
1711 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1712 * @param string $recFID Field identifier [table:uid:field] for flexforms
1713 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1714 * @param array $uploadedFiles
1715 * @param int $tscPID TSconfig PID
1716 * @param array $additionalData Additional data to be forwarded to sub-processors
1717 * @return array Returns the evaluated $value as key "value" in this array.
1719 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1721 // Convert to NULL value if defined in TCA
1722 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility
::inList($tcaFieldConf['eval'], 'null')) {
1723 $res = ['value' => null];
1727 switch ($tcaFieldConf['type']) {
1729 $res = $this->checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field);
1732 case 'imageManipulation':
1734 $res['value'] = $value;
1737 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1740 $res = $this->checkValueForSlug((string)$value, $tcaFieldConf, $table, $id, (int)$realPid, $field, $additionalData['incomingFieldArray'] ??
[]);
1743 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1746 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1750 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1753 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1756 // FlexForms are only allowed for real fields.
1758 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1764 $res = $this->checkValueForInternalReferences($res, $value, $tcaFieldConf, $table, $id, $field);
1769 * Checks values that are used for internal references. If the provided $value
1770 * is a NEW-identifier, the direct processing is stopped. Instead, the value is
1771 * forwarded to the remap-stack to be post-processed and resolved into a proper
1772 * UID after all data has been resolved.
1774 * This method considers TCA types that cannot handle and resolve these internal
1775 * values directly, like 'passthrough', 'none' or 'user'. Values are only modified
1776 * here if the $field is used as 'transOrigPointerField' or 'translationSource'.
1778 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1779 * @param string $value The value to set.
1780 * @param array $tcaFieldConf Field configuration from TCA
1781 * @param string $table Table name
1782 * @param int $id UID of record
1783 * @param string $field The field name
1784 * @return array The result array. The processed value (if any!) is set in the "value" key.
1786 protected function checkValueForInternalReferences(array $res, $value, $tcaFieldConf, $table, $id, $field)
1788 $relevantFieldNames = [
1789 $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ??
null,
1790 $GLOBALS['TCA'][$table]['ctrl']['translationSource'] ??
null,
1794 // in case field is empty
1796 // in case the field is not relevant
1797 ||
!in_array($field, $relevantFieldNames)
1798 // in case the 'value' index has been unset already
1799 ||
!array_key_exists('value', $res)
1800 // in case it's not a NEW-identifier
1801 ||
strpos($value, 'NEW') === false
1806 $valueArray = [$value];
1807 $this->remapStackRecords
[$table][$id] = ['remapStackIndex' => count($this->remapStack
)];
1808 $this->addNewValuesToRemapStackChildIds($valueArray);
1809 $this->remapStack
[] = [
1810 'args' => [$valueArray, $tcaFieldConf, $id, $table, $field],
1811 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 3],
1814 unset($res['value']);
1820 * Evaluate "text" type values.
1822 * @param string $value The value to set.
1823 * @param array $tcaFieldConf Field configuration from TCA
1824 * @param string $table Table name
1825 * @param int $id UID of record
1826 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1827 * @param string $field Field name
1828 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1830 protected function checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field)
1832 if (isset($tcaFieldConf['eval']) && $tcaFieldConf['eval'] !== '') {
1833 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1834 $evalCodesArray = $this->runtimeCache
->get($cacheId);
1835 if (!is_array($evalCodesArray)) {
1836 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1837 $this->runtimeCache
->set($cacheId, $evalCodesArray);
1839 $valueArray = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1841 $valueArray = ['value' => $value];
1844 // Handle richtext transformations
1845 if ($this->dontProcessTransformations
) {
1848 $recordType = BackendUtility
::getTCAtypeValue($table, $this->checkValue_currentRecord
);
1849 $columnsOverridesConfigOfField = $GLOBALS['TCA'][$table]['types'][$recordType]['columnsOverrides'][$field]['config'] ??
null;
1850 if ($columnsOverridesConfigOfField) {
1851 ArrayUtility
::mergeRecursiveWithOverrule($tcaFieldConf, $columnsOverridesConfigOfField);
1853 if (isset($tcaFieldConf['enableRichtext']) && (bool)$tcaFieldConf['enableRichtext'] === true) {
1854 $richtextConfigurationProvider = GeneralUtility
::makeInstance(Richtext
::class);
1855 $richtextConfiguration = $richtextConfigurationProvider->getConfiguration($table, $field, $realPid, $recordType, $tcaFieldConf);
1856 $parseHTML = GeneralUtility
::makeInstance(RteHtmlParser
::class);
1857 $parseHTML->init($table . ':' . $field, $realPid);
1858 $valueArray['value'] = $parseHTML->RTE_transform($value, [], 'db', $richtextConfiguration);
1865 * Evaluate "input" type values.
1867 * @param string $value The value to set.
1868 * @param array $tcaFieldConf Field configuration from TCA
1869 * @param string $table Table name
1870 * @param int $id UID of record
1871 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1872 * @param string $field Field name
1873 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1875 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1877 // Handle native date/time fields
1878 $isDateOrDateTimeField = false;
1881 $dateTimeTypes = QueryHelper
::getDateTimeTypes();
1882 // normal integer "date" fields (timestamps) are handled in checkValue_input_Eval
1883 if (isset($tcaFieldConf['dbType']) && in_array($tcaFieldConf['dbType'], $dateTimeTypes, true)) {
1884 if (empty($value)) {
1887 $isDateOrDateTimeField = true;
1888 $dateTimeFormats = QueryHelper
::getDateTimeFormats();
1889 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1891 // Convert the date/time into a timestamp for the sake of the checks
1892 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1893 // We store UTC timestamps in the database, which is what getTimestamp() returns.
1894 $dateTime = new \
DateTime($value);
1895 $value = $value === $emptyValue ?
null : $dateTime->getTimestamp();
1898 // Secures the string-length to be less than max.
1899 if (isset($tcaFieldConf['max']) && (int)$tcaFieldConf['max'] > 0) {
1900 $value = mb_substr((string)$value, 0, (int)$tcaFieldConf['max'], 'utf-8');
1903 if (empty($tcaFieldConf['eval'])) {
1904 $res = ['value' => $value];
1906 // Process evaluation settings:
1907 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1908 $evalCodesArray = $this->runtimeCache
->get($cacheId);
1909 if (!is_array($evalCodesArray)) {
1910 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1911 $this->runtimeCache
->set($cacheId, $evalCodesArray);
1914 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in'] ??
'', $table);
1915 if (isset($tcaFieldConf['dbType']) && isset($res['value']) && !$res['value']) {
1916 // set the value to null if we have an empty value for a native field
1917 $res['value'] = null;
1920 // Process UNIQUE settings:
1921 // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
1922 if ($field && $realPid >= 0 && !empty($res['value'])) {
1923 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1924 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1926 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1927 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1932 // Checking range of value:
1933 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1935 isset($tcaFieldConf['range']) && $tcaFieldConf['range']
1936 && (!isset($tcaFieldConf['checkbox']) ||
$res['value'] != $tcaFieldConf['checkbox'])
1937 && (!isset($tcaFieldConf['default']) ||
(int)$res['value'] !== (int)$tcaFieldConf['default'])
1939 if (isset($tcaFieldConf['range']['upper']) && (int)$res['value'] > (int)$tcaFieldConf['range']['upper']) {
1940 $res['value'] = (int)$tcaFieldConf['range']['upper'];
1942 if (isset($tcaFieldConf['range']['lower']) && (int)$res['value'] < (int)$tcaFieldConf['range']['lower']) {
1943 $res['value'] = (int)$tcaFieldConf['range']['lower'];
1947 // Handle native date/time fields
1948 if ($isDateOrDateTimeField) {
1949 // Convert the timestamp back to a date/time
1950 $res['value'] = $res['value'] ?
gmdate($format, $res['value']) : $emptyValue;
1956 * Evaluate "slug" type values.
1958 * @param string $value The value to set.
1959 * @param array $tcaFieldConf Field configuration from TCA
1960 * @param string $table Table name
1961 * @param int $id UID of record
1962 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1963 * @param string $field Field name
1964 * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray) for the record
1965 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1966 * @see SlugEnricher, SlugHelper
1968 protected function checkValueForSlug(string $value, array $tcaFieldConf, string $table, $id, int $realPid, string $field, array $incomingFieldArray = []): array
1970 $workspaceId = $this->BE_USER
->workspace
;
1971 $helper = GeneralUtility
::makeInstance(SlugHelper
::class, $table, $field, $tcaFieldConf, $workspaceId);
1972 $fullRecord = array_replace_recursive($this->checkValue_currentRecord
, $incomingFieldArray ??
[]);
1973 // Generate a value if there is none, otherwise ensure that all characters are cleaned up
1974 if ($value === '') {
1975 $value = $helper->generate($fullRecord, $realPid);
1977 $value = $helper->sanitize($value);
1980 // In case a workspace is given, and the $realPid(!) still is negative
1981 // this is most probably triggered by versionizeRecord() and a raw record
1982 // copy - thus, uniqueness cannot be determined without having the
1984 // @todo This is still not explicit, but probably should be
1985 if ($workspaceId > 0 && $realPid === -1
1986 && !MathUtility
::canBeInterpretedAsInteger($id)
1988 return ['value' => $value];
1991 // Return directly in case no evaluations are defined
1992 if (empty($tcaFieldConf['eval'])) {
1993 return ['value' => $value];
1996 $state = RecordStateFactory
::forName($table)
1997 ->fromArray($fullRecord, $realPid, $id);
1998 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1999 if (in_array('uniqueInSite', $evalCodesArray, true)) {
2000 $value = $helper->buildSlugForUniqueInSite($value, $state);
2002 if (in_array('uniqueInPid', $evalCodesArray, true)) {
2003 $value = $helper->buildSlugForUniqueInPid($value, $state);
2006 return ['value' => $value];
2010 * Evaluates 'check' type values.
2012 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2013 * @param string $value The value to set.
2014 * @param array $tcaFieldConf Field configuration from TCA
2015 * @param string $table Table name
2016 * @param int $id UID of record
2017 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
2018 * @param string $field Field name
2019 * @return array Modified $res array
2021 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
2023 $items = $tcaFieldConf['items'];
2024 if (!empty($tcaFieldConf['itemsProcFunc'])) {
2025 /** @var ItemProcessingService $processingService */
2026 $processingService = GeneralUtility
::makeInstance(ItemProcessingService
::class);
2027 $items = $processingService->getProcessingItems(
2031 $this->checkValue_currentRecord
,
2033 $tcaFieldConf['items']
2038 if ($items !== null) {
2039 $itemC = count($items);
2044 $maxV = (2 ** $itemC) - 1;
2046 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
2049 if ($value > $maxV) {
2050 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
2051 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
2052 // @todo: are permanently removed from the value.
2053 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
2054 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
2055 $value = $value & $maxV;
2057 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
2058 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
2059 $otherRecordsWithSameValue = [];
2060 $maxCheckedRecords = 0;
2061 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
2062 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
2063 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
2065 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
2066 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
2067 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
2070 // there are more than enough records with value "1" in the DB
2071 // if so, set this value to "0" again
2072 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
2074 $this->log($table, $id, 5, 0, 1, 'Could not activate checkbox for field "%s". A total of %s record(s) can have this checkbox activated. Uncheck other records first in order to activate the checkbox of this record.', -1, [$this->getLanguageService()->sL(BackendUtility
::getItemLabel($table, $field)), $maxCheckedRecords]);
2077 $res['value'] = $value;
2082 * Evaluates 'radio' type values.
2084 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2085 * @param string $value The value to set.
2086 * @param array $tcaFieldConf Field configuration from TCA
2087 * @param string $table The table of the record
2088 * @param int $id The id of the record
2089 * @param int $pid The pid of the record
2090 * @param string $field The field to check
2091 * @return array Modified $res array
2093 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
2095 if (is_array($tcaFieldConf['items'])) {
2096 foreach ($tcaFieldConf['items'] as $set) {
2097 if ((string)$set[1] === (string)$value) {
2098 $res['value'] = $value;
2104 // if no value was found and an itemsProcFunc is defined, check that for the value
2105 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
2106 $processingService = GeneralUtility
::makeInstance(ItemProcessingService
::class);
2107 $processedItems = $processingService->getProcessingItems(
2111 $this->checkValue_currentRecord
,
2113 $tcaFieldConf['items']
2116 foreach ($processedItems as $set) {
2117 if ((string)$set[1] === (string)$value) {
2118 $res['value'] = $value;
2128 * Evaluates 'group' or 'select' type values.
2130 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2131 * @param string|array $value The value to set.
2132 * @param array $tcaFieldConf Field configuration from TCA
2133 * @param string $table Table name
2134 * @param int $id UID of record
2135 * @param mixed $curValue Current value of the field
2136 * @param string $status 'update' or 'new' flag
2137 * @param string $recFID Field identifier [table:uid:field] for flexforms
2138 * @param array $uploadedFiles
2139 * @param string $field Field name
2140 * @return array Modified $res array
2142 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
2144 // Detecting if value sent is an array and if so, implode it around a comma:
2145 if (is_array($value)) {
2146 $value = implode(',', $value);
2148 // This converts all occurrences of '{' to the byte 123 in the string - this is needed in very rare cases where file names with special characters (e.g. ???, umlaut) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
2149 // Anyway, this should NOT disturb anything else:
2150 $value = $this->convNumEntityToByteValue($value);
2151 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
2152 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
2153 // If multiple is not set, remove duplicates:
2154 if (!$tcaFieldConf['multiple']) {
2155 $valueArray = array_unique($valueArray);
2157 // If an exclusive key is found, discard all others:
2158 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['exclusiveKeys']) {
2159 $exclusiveKeys = GeneralUtility
::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
2160 foreach ($valueArray as $index => $key) {
2161 if (in_array($key, $exclusiveKeys, true)) {
2162 $valueArray = [$index => $key];
2167 // This could be a good spot for parsing the array through a validation-function which checks if the values are correct (except that database references are not in their final form - but that is the point, isn't it?)
2168 // NOTE!!! Must check max-items of files before the later check because that check would just leave out file names if there are too many!!
2169 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2170 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
2171 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['authMode']) {
2172 $preCount = count($valueArray);
2173 foreach ($valueArray as $index => $key) {
2174 if (!$this->BE_USER
->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
2175 unset($valueArray[$index]);
2178 // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
2179 if ($preCount && empty($valueArray)) {
2184 if ($tcaFieldConf['type'] === 'group'
2185 && in_array($tcaFieldConf['internal_type'], ['file', 'file_reference'], true)) {
2186 // @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0. Deprecation logged by TcaMigration class.
2187 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
2189 // For select types which has a foreign table attached:
2190 $unsetResult = false;
2192 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
2193 ||
$tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] ||
isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
2195 // check, if there is a NEW... id in the value, that should be substituted later
2196 if (strpos($value, 'NEW') !== false) {
2197 $this->remapStackRecords
[$table][$id] = ['remapStackIndex' => count($this->remapStack
)];
2198 $this->addNewValuesToRemapStackChildIds($valueArray);
2199 $this->remapStack
[] = [
2200 'func' => 'checkValue_group_select_processDBdata',
2201 'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
2202 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2205 $unsetResult = true;
2207 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2210 if (!$unsetResult) {
2211 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2212 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2214 unset($res['value']);
2220 * Applies the filter methods from a column's TCA configuration to a value array.
2222 * @param array $tcaFieldConfiguration
2223 * @param array $values
2224 * @return array|mixed
2225 * @throws \RuntimeException
2227 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2229 if (empty($tcaFieldConfiguration['filter']) ||
!is_array($tcaFieldConfiguration['filter'])) {
2232 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2233 if (empty($filter['userFunc'])) {
2236 $parameters = $filter['parameters'] ?
: [];
2237 $parameters['values'] = $values;
2238 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2239 $values = GeneralUtility
::callUserFunction($filter['userFunc'], $parameters, $this);
2240 if (!is_array($values)) {
2241 throw new \
RuntimeException('Failed calling filter userFunc.', 1336051942);
2248 * Handling files for group/select function
2250 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2251 * @param array $tcaFieldConf Configuration array from TCA of the field
2252 * @param string $curValue Current value of the field
2253 * @param array $uploadedFileArray Array of uploaded files, if any
2254 * @param string $status 'update' or 'new' flag
2255 * @param string $table tablename of record
2256 * @param int $id UID of record
2257 * @param string $recFID Field identifier [table:uid:field] for flexforms
2258 * @return array Modified value array
2260 * @throws \RuntimeException
2261 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0. Deprecation logged by TcaMigration class.
2263 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2265 // If file handling should NOT be bypassed, do processing:
2266 if (!$this->bypassFileHandling
) {
2267 // If any files are uploaded, add them to value array
2268 // Numeric index means that there are multiple files
2269 if (isset($uploadedFileArray[0])) {
2270 $uploadedFiles = $uploadedFileArray;
2272 // There is only one file
2273 $uploadedFiles = [$uploadedFileArray];
2275 foreach ($uploadedFiles as $uploadedFileArray) {
2276 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2277 $valueArray[] = $uploadedFileArray['tmp_name'];
2278 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2281 // Creating fileFunc object.
2282 if (!$this->fileFunc
) {
2283 $this->fileFunc
= GeneralUtility
::makeInstance(BasicFileUtility
::class);
2285 // Setting permitted extensions.
2286 $this->fileFunc
->setFileExtensionPermissions($tcaFieldConf['allowed'], $tcaFieldConf['disallowed'] ?
: '*');
2288 // If there is an upload folder defined:
2289 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] === 'file') {
2290 $currentFilesForHistory = null;
2291 // If filehandling should NOT be bypassed, do processing:
2292 if (!$this->bypassFileHandling
) {
2294 $propArr = $this->getRecordProperties($table, $id);
2295 // Get destination path:
2296 $dest = Environment
::getPublicPath() . '/' . $tcaFieldConf['uploadfolder'];
2297 // If we are updating:
2298 if ($status === 'update') {
2299 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2300 // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
2301 // The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
2302 // Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
2303 // Illustration of the problem comes here:
2304 // We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
2305 // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
2306 // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
2307 // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
2308 if ($this->autoVersioningUpdate
=== true) {
2309 foreach ($valueArray as $key => $theFile) {
2310 // If it is an already attached file...
2311 if ($theFile === PathUtility
::basename($theFile)) {
2312 $valueArray[$key] = Environment
::getPublicPath() . '/' . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2316 // Finding the CURRENT files listed, either from MM or from the current record.
2317 $theFileValues = [];
2318 // If MM relations for the files also!
2319 if ($tcaFieldConf['MM']) {
2320 $dbAnalysis = $this->createRelationHandlerInstance();
2321 /** @var RelationHandler $dbAnalysis */
2322 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2323 foreach ($dbAnalysis->itemArray
as $item) {
2325 $theFileValues[] = $item['id'];
2329 $theFileValues = GeneralUtility
::trimExplode(',', $curValue, true);
2331 $currentFilesForHistory = implode(',', $theFileValues);
2332 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2333 if (!empty($theFileValues)) {
2334 // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
2335 foreach ($valueArray as $key => $theFile) {
2336 if ($theFile && strpos(GeneralUtility
::fixWindowsFilePath($theFile), '/') === false) {
2337 $theFileValues = ArrayUtility
::removeArrayEntryByValue($theFileValues, $theFile);
2340 // This array contains the filenames in the uploadfolder that should be deleted:
2341 foreach ($theFileValues as $key => $theFile) {
2342 $theFile = trim($theFile);
2343 if (@is_file
($dest . '/' . $theFile)) {
2344 $this->removeFilesStore
[] = $dest . '/' . $theFile;
2345 } elseif ($theFile) {
2346 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, [$dest . '/' . $theFile, $recFID], $propArr['event_pid']);
2351 // Traverse the submitted values:
2352 foreach ($valueArray as $key => $theFile) {
2354 $maxSize = (int)$tcaFieldConf['max_size'];
2355 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2357 // a FAL file was added, now resolve the file object and get the absolute path
2358 // @todo in future versions this needs to be modified to handle FAL objects natively
2359 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
2360 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
2361 $theFile = $fileObject->getForLocalProcessing(false);
2363 // NEW FILES? If the value contains '/' it indicates, that the file
2364 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2365 if (strpos(GeneralUtility
::fixWindowsFilePath($theFile), '/') !== false) {
2366 // Check various things before copying file:
2367 // File and destination must exist
2368 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) {
2370 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2371 $fileSize = $uploadedFileArray['size'];
2373 $fileSize = filesize($theFile);
2376 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
2377 // Prepare filename:
2378 $theEndFileName = $this->alternativeFileName
[$theFile] ??
$theFile;
2379 $fI = GeneralUtility
::split_fileref($theEndFileName);
2380 // Check for allowed extension:
2381 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2382 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
2383 // If we have a unique destination filename, then write the file:
2385 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2386 // Hook for post-processing the upload action
2387 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] ??
[] as $className) {
2388 $hookObject = GeneralUtility
::makeInstance($className);
2389 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface
) {
2390 throw new \
UnexpectedValueException($className . ' must implement interface ' . DataHandlerProcessUploadHookInterface
::class, 1279962349);
2392 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2394 $this->copiedFileMap
[$theFile] = $theDestFile;
2396 if (!@is_file
($theDestFile)) {
2397 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, [$theFile, PathUtility
::dirname($theDestFile), $recFID], $propArr['event_pid']);
2400 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2403 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2406 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, [GeneralUtility
::formatSize($fileSize), $theFile, GeneralUtility
::formatSize($maxSize * 1024), $recFID], $propArr['event_pid']);
2409 $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, [$dest, $theFile, $recFID], $propArr['event_pid']);
2411 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2412 if (@is_file
($theDestFile)) {
2413 $info = GeneralUtility
::split_fileref($theDestFile);
2414 // The value is set to the new filename
2415 $valueArray[$key] = $info['file'];
2417 // The value is set to the new filename
2418 unset($valueArray[$key]);
2423 // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
2424 if ($tcaFieldConf['MM']) {
2425 /** @var RelationHandler $dbAnalysis */
2426 $dbAnalysis = $this->createRelationHandlerInstance();
2428 $dbAnalysis->tableArray
['files'] = [];
2429 foreach ($valueArray as $key => $theFile) {
2431 $dbAnalysis->itemArray
[]['id'] = $theFile;
2433 if ($status === 'update') {
2434 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2435 $newFiles = implode(',', $dbAnalysis->getValueArray());
2436 list(, , $recFieldName) = explode(':', $recFID);
2437 if ($currentFilesForHistory != $newFiles) {
2438 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2439 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2441 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2442 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2445 $this->dbAnalysisStore
[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, 0];
2447 $valueArray = $dbAnalysis->countItems();
2450 if (!empty($valueArray)) {
2451 // If filehandling should NOT be bypassed, do processing:
2452 if (!$this->bypassFileHandling
) {
2454 $propArr = $this->getRecordProperties($table, $id);
2455 foreach ($valueArray as &$theFile) {
2456 // FAL handling: it's a UID, thus it is resolved to the absolute path
2457 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
2458 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
2459 $theFile = $fileObject->getForLocalProcessing(false);
2461 if ($this->alternativeFilePath
[$theFile]) {
2462 // If alternative File Path is set for the file, then it was an import
2463 // don't import the file if it already exists
2464 if (@is_file
(Environment
::getPublicPath() . '/' . $this->alternativeFilePath
[$theFile])) {
2465 $theFile = Environment
::getPublicPath() . '/' . $this->alternativeFilePath
[$theFile];
2466 } elseif (@is_file
($theFile)) {
2467 $dest = PathUtility
::dirname(Environment
::getPublicPath() . '/' . $this->alternativeFilePath
[$theFile]);
2468 if (!@is_dir
($dest)) {
2469 GeneralUtility
::mkdir_deep($dest);
2472 $maxSize = (int)$tcaFieldConf['max_size'];
2473 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2475 $fileSize = filesize($theFile);
2477 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
2478 // Prepare filename:
2479 $theEndFileName = $this->alternativeFileName
[$theFile] ??
$theFile;
2480 $fI = GeneralUtility
::split_fileref($theEndFileName);
2481 // Check for allowed extension:
2482 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2483 $theDestFile = Environment
::getPublicPath() . '/' . $this->alternativeFilePath
[$theFile];
2486 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2487 $this->copiedFileMap
[$theFile] = $theDestFile;
2489 if (!@is_file
($theDestFile)) {
2490 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, [$theFile, PathUtility
::dirname($theDestFile), $recFID], $propArr['event_pid']);
2493 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2496 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2499 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, [GeneralUtility
::formatSize($fileSize), $theFile, GeneralUtility
::formatSize($maxSize * 1024), $recFID], $propArr['event_pid']);
2501 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2502 if (@is_file
($theDestFile)) {
2503 // The value is set to the new filename
2504 $theFile = $theDestFile;
2506 // The value is set to the new filename
2511 if (!empty($theFile)) {
2512 $theFile = GeneralUtility
::fixWindowsFilePath($theFile);
2513 if (GeneralUtility
::isFirstPartOfStr($theFile, Environment
::getPublicPath())) {
2514 $theFile = PathUtility
::stripPathSitePrefix($theFile);
2526 * Evaluates 'flex' type values.
2528 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2529 * @param string|array $value The value to set.
2530 * @param array $tcaFieldConf Field configuration from TCA
2531 * @param string $table Table name
2532 * @param int $id UID of record
2533 * @param mixed $curValue Current value of the field
2534 * @param string $status 'update' or 'new' flag
2535 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
2536 * @param string $recFID Field identifier [table:uid:field] for flexforms
2537 * @param int $tscPID TSconfig PID
2538 * @param array $uploadedFiles Uploaded files for the field
2539 * @param string $field Field name
2540 * @return array Modified $res array
2542 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2544 if (is_array($value)) {
2545 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2546 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord
2547 // does not have a uid or pid for that sake, the FlexFormTools->getDataStructureIdentifier() function returns no good DS. For new
2548 // records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
2549 $row = $this->checkValue_currentRecord
;
2550 if ($status === 'new') {
2551 $row['pid'] = $realPid;
2554 $flexFormTools = GeneralUtility
::makeInstance(FlexFormTools
::class);
2556 // Get data structure. The methods may throw various exceptions, with some of them being
2557 // ok in certain scenarios, for instance on new record rows. Those are ok to "eat" here
2558 // and substitute with a dummy DS.
2559 $dataStructureArray = ['sheets' => ['sDEF' => []]];
2561 $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
2562 ['config' => $tcaFieldConf],
2568 $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
2569 } catch (InvalidParentRowException
$e) {
2570 } catch (InvalidParentRowLoopException
$e) {
2571 } catch (InvalidParentRowRootException
$e) {
2572 } catch (InvalidPointerFieldValueException
$e) {
2573 } catch (InvalidIdentifierException
$e) {
2576 // Get current value array:
2577 $currentValueArray = (string)$curValue !== '' ? GeneralUtility
::xml2array($curValue) : [];
2578 if (!is_array($currentValueArray)) {
2579 $currentValueArray = [];
2581 // Remove all old meta for languages...
2582 // Evaluation of input values:
2583 $value['data'] = $this->checkValue_flex_procInData($value['data'] ??
[], $currentValueArray['data'] ??
[], $uploadedFiles['data'] ??
[], $dataStructureArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2584 // Create XML from input value:
2585 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2587 // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same
2588 // (provided that the current value was already stored IN the charset that the new value is converted to).
2589 $arrValue = GeneralUtility
::xml2array($xmlValue);
2591 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] ??
[] as $className) {
2592 $hookObject = GeneralUtility
::makeInstance($className);
2593 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2594 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2598 ArrayUtility
::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2599 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2601 // Action commands (sorting order and removals of elements) for flexform sections,
2602 // see FormEngine for the use of this GP parameter
2603 $actionCMDs = GeneralUtility
::_GP('_ACTION_FLEX_FORMdata');
2604 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2605 $arrValue = GeneralUtility
::xml2array($xmlValue);
2606 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2607 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2609 // Create the value XML:
2611 $res['value'] .= $xmlValue;
2614 $res['value'] = $value;
2621 * Converts an array to FlexForm XML
2623 * @param array $array Array with FlexForm data
2624 * @param bool $addPrologue If set, the XML prologue is returned as well.
2625 * @return string Input array converted to XML
2627 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2629 /** @var FlexFormTools $flexObj */
2630 $flexObj = GeneralUtility
::makeInstance(FlexFormTools
::class);
2631 return $flexObj->flexArray2Xml($array, $addPrologue);
2635 * Actions for flex form element (move, delete)
2636 * allows to remove and move flexform sections
2638 * @param array $valueArray by reference
2639 * @param array $actionCMDs
2641 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2643 if (!is_array($valueArray) ||
!is_array($actionCMDs)) {
2647 foreach ($actionCMDs as $key => $value) {
2648 if ($key === '_ACTION') {
2649 // First, check if there are "commands":
2650 if (current($actionCMDs[$key]) === '') {
2654 asort($actionCMDs[$key]);
2655 $newValueArray = [];
2656 foreach ($actionCMDs[$key] as $idx => $order) {
2657 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost
2658 // files unless we act on this delete operation by traversing and deleting files that were referred to.
2659 if ($order !== 'DELETE') {
2660 $newValueArray[$idx] = $valueArray[$idx];
2662 unset($valueArray[$idx]);
2664 $valueArray +
= $newValueArray;
2665 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2666 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2672 * Evaluates 'inline' type values.
2673 * (partly copied from the select_group function on this issue)
2675 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2676 * @param string $value The value to set.
2677 * @param array $tcaFieldConf Field configuration from TCA
2678 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2679 * @param string $field Field name
2680 * @param array $additionalData Additional data to be forwarded to sub-processors
2682 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2684 list($table, $id, , $status) = $PP;
2685 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2689 * Evaluates 'inline' type values.
2690 * (partly copied from the select_group function on this issue)
2692 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2693 * @param string $value The value to set.
2694 * @param array $tcaFieldConf Field configuration from TCA
2695 * @param string $table Table name
2696 * @param int $id UID of record
2697 * @param string $status 'update' or 'new' flag
2698 * @param string $field Field name
2699 * @param array $additionalData Additional data to be forwarded to sub-processors
2700 * @return array|bool Modified $res array
2702 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2704 if (!$tcaFieldConf['foreign_table']) {
2705 // Fatal error, inline fields should always have a foreign_table defined
2708 // When values are sent they come as comma-separated values which are exploded by this function:
2709 $valueArray = GeneralUtility
::trimExplode(',', $value);
2710 // Remove duplicates: (should not be needed)
2711 $valueArray = array_unique($valueArray);
2712 // Example for received data:
2713 // $value = 45,NEW4555fdf59d154,12,123
2714 // We need to decide whether we use the stack or can save the relation directly.
2715 if (!empty($value) && (strpos($value, 'NEW') !== false ||
!MathUtility
::canBeInterpretedAsInteger($id))) {
2716 $this->remapStackRecords
[$table][$id] = ['remapStackIndex' => count($this->remapStack
)];
2717 $this->addNewValuesToRemapStackChildIds($valueArray);
2718 $this->remapStack
[] = [
2719 'func' => 'checkValue_inline_processDBdata',
2720 'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2721 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2722 'additionalData' => $additionalData,
2725 unset($res['value']);
2726 } elseif ($value || MathUtility
::canBeInterpretedAsInteger($id)) {
2727 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2733 * Checks if a fields has more items than defined via TCA in maxitems.
2734 * If there are more items than allowed, the item list is truncated to the defined number.
2736 * @param array $tcaFieldConf Field configuration from TCA
2737 * @param array $valueArray Current value array of items
2738 * @return array The truncated value array of items
2740 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2742 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function
2743 // calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check
2744 // before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2745 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first,
2746 // if the field is actual used regarding the CType.
2747 $maxitems = isset($tcaFieldConf['maxitems']) ?
(int)$tcaFieldConf['maxitems'] : 99999;
2748 return array_slice($valueArray, 0, $maxitems);
2751 /*********************************************
2753 * Helper functions for evaluation functions.
2755 ********************************************/
2757 * Gets a unique value for $table/$id/$field based on $value
2759 * @param string $table Table name
2760 * @param string $field Field name for which $value must be unique
2761 * @param string $value Value string.
2762 * @param int $id UID to filter out in the lookup (the record itself...)
2763 * @param int $newPid If set, the value will be unique for this PID
2764 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2766 public function getUnique($table, $field, $value, $id, $newPid = 0)
2768 if (!is_array($GLOBALS['TCA'][$table]) ||
!is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2769 // Field is not configured in TCA
2773 if ((string)$GLOBALS['TCA'][$table]['columns'][$field]['l10n_mode'] === 'exclude') {
2774 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
2775 $l10nParent = (int)$this->checkValue_currentRecord
[$transOrigPointerField];
2776 if ($l10nParent > 0) {
2777 // Current record is a translation and l10n_mode "exclude" just copies the value from source language
2783 $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2784 // For as long as records with the test-value existing, try again (with incremented numbers appended)
2785 if ($statement->fetchColumn()) {
2786 for ($counter = 0; $counter <= 100; $counter++
) {
2787 $newValue = $value . $counter;
2788 $statement->bindValue(1, $newValue);
2789 $statement->execute();
2790 if (!$statement->fetchColumn()) {
2800 * Gets the count of records for a unique field
2802 * @param string $value The string value which should be unique
2803 * @param string $table Table name
2804 * @param string $field Field name for which $value must be unique
2805 * @param int $uid UID to filter out in the lookup (the record itself...)
2806 * @param int $pid If set, the value will be unique for this PID
2807 * @return \Doctrine\DBAL\Driver\Statement|int Return the prepared statement to check uniqueness
2809 protected function getUniqueCountStatement(
2816 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
2817 $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2822 $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value, \PDO
::PARAM_STR
)),
2823 $queryBuilder->expr()->neq('uid', $queryBuilder->createPositionalParameter($uid, \PDO
::PARAM_INT
))
2826 $queryBuilder->andWhere(
2827 $queryBuilder->expr()->eq('pid', $queryBuilder->createPositionalParameter($pid, \PDO
::PARAM_INT
))
2830 // pid>=0 for versioning
2831 $queryBuilder->andWhere(
2832 $queryBuilder->expr()->gte('pid', $queryBuilder->createPositionalParameter(0, \PDO
::PARAM_INT
))
2836 return $queryBuilder->execute();
2840 * gets all records that have the same value in a field
2841 * excluding the given uid
2843 * @param string $tableName Table name
2844 * @param int $uid UID to filter out in the lookup (the record itself...)
2845 * @param string $fieldName Field name for which $value must be unique
2846 * @param string $value Value string.
2847 * @param int $pageId If set, the value will be unique for this PID
2850 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2853 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2858 $pageId = (int)$pageId;
2860 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($tableName);
2861 $queryBuilder->getRestrictions()
2863 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class))
2864 ->add(GeneralUtility
::makeInstance(BackendWorkspaceRestriction
::class));
2866 $queryBuilder->select('*')
2869 $queryBuilder->expr()->eq(
2871 $queryBuilder->createNamedParameter($value, \PDO
::PARAM_STR
)
2873 $queryBuilder->expr()->neq(
2875 $queryBuilder->createNamedParameter($uid, \PDO
::PARAM_INT
)
2880 $queryBuilder->andWhere(
2881 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pageId, \PDO
::PARAM_INT
))
2884 $queryBuilder->andWhere(
2885 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
))
2889 $result = $queryBuilder->execute()->fetchAll();
2895 * @param string $value The field value to be evaluated
2896 * @param array $evalArray Array of evaluations to traverse.
2897 * @param string $is_in The "is_in" value of the field configuration from TCA