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\Types\IntegerType
;
20 use TYPO3\CMS\Backend\Utility\BackendUtility
;
21 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication
;
22 use TYPO3\CMS\Core\Cache\CacheManager
;
23 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
;
24 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
;
25 use TYPO3\CMS\Core\Database\Connection
;
26 use TYPO3\CMS\Core\Database\ConnectionPool
;
27 use TYPO3\CMS\Core\Database\Query\QueryBuilder
;
28 use TYPO3\CMS\Core\Database\Query\QueryHelper
;
29 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
;
30 use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface
;
31 use TYPO3\CMS\Core\Database\ReferenceIndex
;
32 use TYPO3\CMS\Core\Database\RelationHandler
;
33 use TYPO3\CMS\Core\Html\RteHtmlParser
;
34 use TYPO3\CMS\Core\Messaging\FlashMessage
;
35 use TYPO3\CMS\Core\Messaging\FlashMessageService
;
36 use TYPO3\CMS\Core\
Resource\ResourceFactory
;
37 use TYPO3\CMS\Core\Service\OpcodeCacheService
;
38 use TYPO3\CMS\Core\Type\Bitmask\Permission
;
39 use TYPO3\CMS\Core\Utility\ArrayUtility
;
40 use TYPO3\CMS\Core\Utility\File\BasicFileUtility
;
41 use TYPO3\CMS\Core\Utility\GeneralUtility
;
42 use TYPO3\CMS\Core\Utility\MathUtility
;
43 use TYPO3\CMS\Core\Utility\PathUtility
;
44 use TYPO3\CMS\Core\Utility\StringUtility
;
45 use TYPO3\CMS\Core\Versioning\VersionState
;
48 * The main data handler class which takes care of correctly updating and inserting records.
49 * This class was formerly known as TCEmain.
51 * This is the TYPO3 Core Engine class for manipulation of the database
52 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
55 * - $GLOBALS['TCA'] must exist
56 * - $GLOBALS['LANG'] must exist
58 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
62 // *********************
63 // Public variables you can configure before using the class:
64 // *********************
66 * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
67 * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
71 public $storeLogMessages = true;
74 * If TRUE, actions are logged to sys_log.
78 public $enableLogging = true;
81 * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
86 public $reverseOrder = false;
89 * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
90 * is similar, it's not saved then.
94 public $checkSimilar = true;
97 * This will read the record after having updated or inserted it. If anything is not properly submitted an error
98 * is written to the log. This feature consumes extra time by selecting records
102 public $checkStoredRecords = true;
105 * If set, values '' and 0 will equal each other when the stored records are checked.
109 public $checkStoredRecords_loose = true;
112 * If this is set, then a page is deleted by deleting the whole branch under it (user must have
113 * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
117 public $deleteTree = false;
120 * If set, then the 'hideAtCopy' flag for tables will be ignored.
124 public $neverHideAtCopy = false;
127 * If set, then the TCE class has been instantiated during an import action of a T3D
131 public $isImporting = false;
134 * If set, then transformations are NOT performed on the input.
138 public $dontProcessTransformations = false;
141 * TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value.
142 * FALSE: Will not update anything.
143 * "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
147 public $updateModeL10NdiffData = true;
150 * If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again!
151 * It's meant as the opposite of declaring the record translated.
155 public $updateModeL10NdiffDataClear = false;
158 * If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()).
159 * YOU MUST KNOW what you do if you use this feature!
163 public $bypassWorkspaceRestrictions = false;
166 * If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away.
167 * YOU MUST KNOW what you are doing with this feature!
171 public $bypassFileHandling = false;
174 * If TRUE, access check, check for deleted etc. for records is bypassed.
175 * YOU MUST KNOW what you are doing if you use this feature!
179 public $bypassAccessCheckForRecords = false;
182 * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
183 * If '*' then all will (that the user has permission to of course)
187 public $copyWhichTables = '*';
190 * If 0 then branch is NOT copied.
191 * If 1 then pages on the 1st level is copied.
192 * If 2 then pages on the second level is copied ... and so on
196 public $copyTree = 0;
199 * [table][fields]=value: New records are created with default values and you can set this array on the
200 * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
201 * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
202 * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
206 public $defaultValues = [];
209 * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
210 * override the incoming data. You must set this externally. You must make sure the fields in this array are also
211 * found in the table, because it's not checked. All columns can be set by this array!
215 public $overrideValues = [];
218 * [filename]=alternative_filename: Use this array to force another name onto a file.
219 * Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field,
220 * then 'my_file.txt' will be used as the name instead.
224 public $alternativeFileName = [];
227 * Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
231 public $alternativeFilePath = [];
234 * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
235 * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
236 * Then an empty checkbox will disable the field.
240 public $data_disableFields = [];
243 * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
244 * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
245 * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
246 * The option is used for import of T3D files when synchronizing between two mirrored servers.
247 * As a security measure this feature is available only for Admin Users (for now)
251 public $suggestedInsertUids = [];
254 * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
255 * iteration functions inside DataHandler for traversing a FlexForm structure.
261 // *********************
262 // Internal variables (mapping arrays) which can be used (read-only) from outside
263 // *********************
265 * Contains mapping of auto-versionized records.
269 public $autoVersionIdMap = [];
272 * 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
276 public $substNEWwithIDs = [];
279 * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
283 public $substNEWwithIDs_table = [];
286 * Holds the tables and there the ids of newly created child records from IRRE
290 public $newRelatedIDs = [];
293 * This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
297 public $copyMappingArray_merged = [];
300 * Per-table array with UIDs that have been deleted.
304 protected $deletedRecords = [];
307 * A map between input file name and final destination for files being attached to records.
311 public $copiedFileMap = [];
314 * Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
318 public $RTEmagic_copyIndex = [];
321 * Errors are collected in this variable.
325 public $errorLog = [];
328 * Fields from the pages-table for which changes will trigger a pagetree refresh
332 public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid'];
335 * Indicates whether the pagetree needs a refresh because of important changes
339 public $pagetreeNeedsRefresh = false;
341 // *********************
342 // Internal Variables, do not touch.
343 // *********************
345 // Variables set in init() function:
348 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
350 * @var BackendUserAuthentication
355 * Will be set to uid of be_user executing this script
362 * Will be set to username of be_user executing this script
369 * Will be set if user is admin
376 * Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
380 public $defaultPermissions = [
381 'user' => 'show,edit,delete,new,editcontent',
382 'group' => 'show,edit,new,editcontent',
387 * 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.
391 protected $excludedTablesAndFields = [];
394 * Data submitted from the form view, used to control behaviours,
395 * e.g. this is used to activate/deactivate fields and thus store NULL values
399 protected $control = [];
402 * Set with incoming data array
406 public $datamap = [];
409 * Set with incoming cmd array
416 * List of changed old record ids to new records ids
420 protected $mmHistoryRecords = [];
423 * List of changed old record ids to new records ids
427 protected $historyRecords = [];
448 * Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
452 public $sortIntervals = 256;
454 // Internal caching arrays
456 * Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
460 public $recUpdateAccessCache = [];
463 * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
467 public $recInsertAccessCache = [];
470 * Caching array for check of whether records are in a webmount
474 public $isRecordInWebMount_Cache = [];
477 * Caching array for page ids in webmounts
481 public $isInWebMount_Cache = [];
484 * Caching for collecting TSconfig for page ids
488 public $cachedTSconfig = [];
491 * Used for caching page records in pageInfo()
495 public $pageCache = [];
498 * Array caching workspace access for BE_USER
502 public $checkWorkspaceCache = [];
506 * For accumulation of MM relations that must be written after new records are created.
510 public $dbAnalysisStore = [];
513 * For accumulation of files which must be deleted after processing of all input content
517 public $removeFilesStore = [];
520 * Uploaded files, set by process_uploads()
524 public $uploadedFileArray = [];
527 * Used for tracking references that might need correction after operations
531 public $registerDBList = [];
534 * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
538 public $registerDBPids = [];
541 * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
542 * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
543 * Read from copyMappingArray_merged instead which is accumulating this information.
545 * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
546 * are only available after an action has been completed.
550 public $copyMappingArray = [];
553 * Array used for remapping uids and values at the end of process_datamap
557 public $remapStack = [];
560 * Array used for remapping uids and values at the end of process_datamap
561 * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
565 public $remapStackRecords = [];
568 * Array used for checking whether new children need to be remapped
572 protected $remapStackChildIds = [];
575 * Array used for executing addition actions after remapping happened (set processRemapStack())
579 protected $remapStackActions = [];
582 * Array used for executing post-processing on the reference index
586 protected $remapStackRefIndex = [];
589 * Array used for additional calls to $this->updateRefIndex
593 public $updateRefIndexStack = [];
596 * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
597 * This variable is set by \TYPO3\CMS\Impext\ImportExport
601 public $callFromImpExp = false;
604 * Array for new flexform index mapping
608 public $newIndexMap = [];
612 * basicFileFunctions object
613 * For "singleton" file-manipulation object
615 * @var BasicFileUtility
620 * Set to "currentRecord" during checking of values.
624 public $checkValue_currentRecord = [];
627 * A signal flag used to tell file processing that auto versioning has happened and hence certain action should be applied.
631 public $autoVersioningUpdate = false;
634 * Disable delete clause
638 protected $disableDeleteClause = false;
643 protected $checkModifyAccessListHookObjects;
648 protected $version_remapMMForVersionSwap_reg;
651 * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
652 * This object instantiates itself on versioning and localization ...
654 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
656 protected $outerMostInstance = null;
659 * Internal cache for collecting records that should trigger cache clearing
663 protected static $recordsToClearCacheFor = [];
666 * Internal cache for pids of records which were deleted. It's not possible
667 * to retrieve the parent folder/page at a later stage
671 protected static $recordPidsForDeletedRecords = [];
674 * Runtime Cache to store and retrieve data computed for a single request
676 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
678 protected $runtimeCache = null;
681 * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
685 protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
690 public function __construct()
692 $this->runtimeCache
= $this->getRuntimeCache();
696 * @param array $control
698 public function setControl(array $control)
700 $this->control
= $control;
705 * For details, see 'TYPO3 Core API' document.
706 * This function does not start the processing of data, but merely initializes the object
708 * @param array $data Data to be modified or inserted in the database
709 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
710 * @param BackendUserAuthentication|NULL $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
713 public function start($data, $cmd, $altUserObject = null)
715 // Initializing BE_USER
716 $this->BE_USER
= is_object($altUserObject) ?
$altUserObject : $GLOBALS['BE_USER'];
717 $this->userid
= $this->BE_USER
->user
['uid'];
718 $this->username
= $this->BE_USER
->user
['username'];
719 $this->admin
= $this->BE_USER
->user
['admin'];
720 if ($this->BE_USER
->uc
['recursiveDelete']) {
721 $this->deleteTree
= 1;
723 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData
=== true) {
724 $this->updateModeL10NdiffData
= false;
726 // Initializing default permissions for pages
727 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
728 if (isset($defaultPermissions['user'])) {
729 $this->defaultPermissions
['user'] = $defaultPermissions['user'];
731 if (isset($defaultPermissions['group'])) {
732 $this->defaultPermissions
['group'] = $defaultPermissions['group'];
734 if (isset($defaultPermissions['everybody'])) {
735 $this->defaultPermissions
['everybody'] = $defaultPermissions['everybody'];
737 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
739 $this->excludedTablesAndFields
= array_flip($this->getExcludeListArray());
741 // Setting the data and cmd arrays
742 if (is_array($data)) {
744 $this->datamap
= $data;
746 if (is_array($cmd)) {
748 $this->cmdmap
= $cmd;
753 * Function that can mirror input values in datamap-array to other uid numbers.
754 * 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]
756 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
759 public function setMirror($mirror)
761 if (!is_array($mirror)) {
765 foreach ($mirror as $table => $uid_array) {
766 if (!isset($this->datamap
[$table])) {
770 foreach ($uid_array as $id => $uidList) {
771 if (!isset($this->datamap
[$table][$id])) {
775 $theIdsInArray = GeneralUtility
::trimExplode(',', $uidList, true);
776 foreach ($theIdsInArray as $copyToUid) {
777 $this->datamap
[$table][$copyToUid] = $this->datamap
[$table][$id];
784 * Initializes default values coming from User TSconfig
786 * @param array $userTS User TSconfig array
789 public function setDefaultsFromUserTS($userTS)
791 if (!is_array($userTS)) {
795 foreach ($userTS as $k => $v) {
796 $k = substr($k, 0, -1);
797 if (!$k ||
!is_array($v) ||
!isset($GLOBALS['TCA'][$k])) {
801 if (is_array($this->defaultValues
[$k])) {
802 $this->defaultValues
[$k] = array_merge($this->defaultValues
[$k], $v);
804 $this->defaultValues
[$k] = $v;
810 * Processing of uploaded files.
811 * 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.
813 * @param array $postFiles $_FILES array
816 public function process_uploads($postFiles)
818 if (!is_array($postFiles)) {
823 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
824 if ($this->enableLogging
) {
825 $this->newlog('All editing in this workspace has been frozen!', 1);
829 $subA = reset($postFiles);
830 if (is_array($subA)) {
831 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
832 // Initialize the uploadedFilesArray:
833 $this->uploadedFileArray
= [];
835 foreach ($subA as $key => $values) {
836 $this->process_uploads_traverseArray($this->uploadedFileArray
, $values, $key);
839 $this->uploadedFileArray
= $subA;
845 * Traverse the upload array if needed to rearrange values.
847 * @param array $outputArr $this->uploadedFileArray passed by reference
848 * @param array $inputArr Input array ($_FILES parts)
849 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
852 * @see process_uploads()
854 public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet)
856 if (is_array($inputArr)) {
857 foreach ($inputArr as $key => $value) {
858 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
861 $outputArr[$keyToSet] = $inputArr;
865 /*********************************************
869 *********************************************/
871 * Hook: processDatamap_afterDatabaseOperations
872 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
874 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
875 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
877 * @param array $hookObjectsArr (reference) Array with hook objects
878 * @param string $status (reference) Status of the current operation, 'new' or 'update
879 * @param string $table (reference) The table currently processing data for
880 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
881 * @param array $fieldArray (reference) The field array of a record
884 public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
886 // Process hook directly:
887 if (!isset($this->remapStackRecords
[$table][$id])) {
888 foreach ($hookObjectsArr as $hookObj) {
889 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
890 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
894 $this->remapStackRecords
[$table][$id]['processDatamap_afterDatabaseOperations'] = [
896 'fieldArray' => $fieldArray,
897 'hookObjectsArr' => $hookObjectsArr
903 * Gets the 'checkModifyAccessList' hook objects.
904 * The first call initializes the accordant objects.
906 * @return array The 'checkModifyAccessList' hook objects (if any)
907 * @throws \UnexpectedValueException
909 protected function getCheckModifyAccessListHookObjects()
911 if (!isset($this->checkModifyAccessListHookObjects
)) {
912 $this->checkModifyAccessListHookObjects
= [];
913 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
914 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
915 $hookObject = GeneralUtility
::getUserObj($classData);
916 if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface
) {
917 throw new \
UnexpectedValueException($classData . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface
::class, 1251892472);
919 $this->checkModifyAccessListHookObjects
[] = $hookObject;
923 return $this->checkModifyAccessListHookObjects
;
926 /*********************************************
930 *********************************************/
932 * Processing the data-array
933 * Call this function to process the data-array set by start()
937 public function process_datamap()
939 $this->controlActiveElements();
941 // Keep versionized(!) relations here locally:
942 $registerDBList = [];
943 $this->registerElementsToBeDeleted();
944 $this->datamap
= $this->unsetElementsToBeDeleted($this->datamap
);
946 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
947 if ($this->enableLogging
) {
948 $this->newlog('All editing in this workspace has been frozen!', 1);
952 // First prepare user defined objects (if any) for hooks which extend this function:
953 $hookObjectsArr = [];
954 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
955 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
956 $hookObject = GeneralUtility
::getUserObj($classRef);
957 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
958 $hookObject->processDatamap_beforeStart($this);
960 $hookObjectsArr[] = $hookObject;
963 // 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.
966 if (isset($this->datamap
['pages'])) {
967 $orderOfTables[] = 'pages';
969 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap
)));
970 // Process the tables...
971 foreach ($orderOfTables as $table) {
973 // - table is set in $GLOBALS['TCA'],
974 // - table is NOT readOnly
975 // - the table is set with content in the data-array (if not, there's nothing to process...)
976 // - permissions for tableaccess OK
977 $modifyAccessList = $this->checkModifyAccessList($table);
978 if ($this->enableLogging
&& !$modifyAccessList) {
979 $this->log($table, 0, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
981 if (!isset($GLOBALS['TCA'][$table]) ||
$this->tableReadOnly($table) ||
!is_array($this->datamap
[$table]) ||
!$modifyAccessList) {
985 if ($this->reverseOrder
) {
986 $this->datamap
[$table] = array_reverse($this->datamap
[$table], 1);
988 // For each record from the table, do:
989 // $id is the record uid, may be a string if new records...
990 // $incomingFieldArray is the array of fields
991 foreach ($this->datamap
[$table] as $id => $incomingFieldArray) {
992 if (!is_array($incomingFieldArray)) {
997 // Hook: processDatamap_preProcessFieldArray
998 foreach ($hookObjectsArr as $hookObj) {
999 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
1000 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
1003 // ******************************
1004 // Checking access to the record
1005 // ******************************
1006 $createNewVersion = false;
1007 $recordAccess = false;
1008 $old_pid_value = '';
1009 $this->autoVersioningUpdate
= false;
1010 // Is it a new record? (Then Id is a string)
1011 if (!MathUtility
::canBeInterpretedAsInteger($id)) {
1012 // Get a fieldArray with default values
1013 $fieldArray = $this->newFieldArray($table);
1014 // A pid must be set for new records.
1015 if (isset($incomingFieldArray['pid'])) {
1017 $pid_value = $incomingFieldArray['pid'];
1018 // Checking and finding numerical pid, it may be a string-reference to another value
1021 if (strstr($pid_value, 'NEW')) {
1022 if ($pid_value[0] === '-') {
1024 $pid_value = substr($pid_value, 1);
1028 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
1029 if (isset($this->substNEWwithIDs
[$pid_value])) {
1030 if ($negFlag === 1) {
1031 $old_pid_value = $this->substNEWwithIDs
[$pid_value];
1033 $pid_value = (int)($negFlag * $this->substNEWwithIDs
[$pid_value]);
1038 $pid_value = (int)$pid_value;
1039 // The $pid_value is now the numerical pid at this point
1041 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
1042 // Points to a page on which to insert the element, possibly in the top of the page
1043 if ($pid_value >= 0) {
1044 // If this table is sorted we better find the top sorting number
1046 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
1048 // The numerical pid is inserted in the data array
1049 $fieldArray['pid'] = $pid_value;
1051 // points to another record before ifself
1052 // If this table is sorted we better find the top sorting number
1054 // Because $pid_value is < 0, getSortNumber returns an array
1055 $tempArray = $this->getSortNumber($table, 0, $pid_value);
1056 $fieldArray['pid'] = $tempArray['pid'];
1057 $fieldArray[$sortRow] = $tempArray['sortNumber'];
1059 // Here we fetch the PID of the record that we point to...
1060 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
1061 $fieldArray['pid'] = $tempdata['pid'];
1066 $theRealPid = $fieldArray['pid'];
1067 // Now, check if we may insert records on this pid.
1068 if ($theRealPid >= 0) {
1069 // Checks if records can be inserted on this $pid.
1070 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
1071 if ($recordAccess) {
1072 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
1073 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $incomingFieldArray, true);
1074 if (!$recordAccess) {
1075 if ($this->enableLogging
) {
1076 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1078 } elseif (!$this->bypassWorkspaceRestrictions
) {
1079 // Workspace related processing:
1080 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1081 if ($res = $this->BE_USER
->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
1083 $recordAccess = false;
1084 if ($this->enableLogging
) {
1085 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
1089 // So, if no live records were allowed, we have to create a new version of this record:
1090 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1091 $createNewVersion = true;
1093 $recordAccess = false;
1094 if ($this->enableLogging
) {
1095 $this->newlog('Record could not be created in this workspace in this branch', 1);
1102 debug('Internal ERROR: pid should not be less than zero!');
1104 // Yes new record, change $record_status to 'insert'
1107 // Nope... $id is a number
1109 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
1110 if (!$recordAccess) {
1111 if ($this->enableLogging
) {
1112 $propArr = $this->getRecordProperties($table, $id);
1113 $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']);
1117 // Next check of the record permissions (internals)
1118 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $id);
1119 if (!$recordAccess) {
1120 if ($this->enableLogging
) {
1121 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1124 // Here we fetch the PID of the record that we point to...
1125 $tempdata = $this->recordInfo($table, $id, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ?
',t3ver_wsid,t3ver_stage' : ''));
1126 $theRealPid = $tempdata['pid'];
1127 // Use the new id of the versionized record we're trying to write to:
1128 // (This record is a child record of a parent and has already been versionized.)
1129 if ($this->autoVersionIdMap
[$table][$id]) {
1130 // For the reason that creating a new version of this record, automatically
1131 // created related child records (e.g. "IRRE"), update the accordant field:
1132 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1133 // Use the new id of the copied/versionized record:
1134 $id = $this->autoVersionIdMap
[$table][$id];
1135 $recordAccess = true;
1136 $this->autoVersioningUpdate
= true;
1137 } elseif (!$this->bypassWorkspaceRestrictions
&& ($errorCode = $this->BE_USER
->workspaceCannotEditRecord($table, $tempdata))) {
1138 $recordAccess = false;
1139 // Versioning is required and it must be offline version!
1140 // Check if there already is a workspace version
1141 $WSversion = BackendUtility
::getWorkspaceVersionOfRecord($this->BE_USER
->workspace
, $table, $id, 'uid,t3ver_oid');
1143 $id = $WSversion['uid'];
1144 $recordAccess = true;
1145 } elseif ($this->BE_USER
->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1146 // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1147 $this->pagetreeNeedsRefresh
= true;
1149 /** @var $tce DataHandler */
1150 $tce = GeneralUtility
::makeInstance(__CLASS__
);
1151 $tce->enableLogging
= $this->enableLogging
;
1152 // Setting up command for creating a new version of the record:
1154 $cmd[$table][$id]['version'] = [
1156 // Default is to create a version of the individual records... element versioning that is.
1157 'label' => 'Auto-created for WS #' . $this->BE_USER
->workspace
1159 $tce->start([], $cmd);
1160 $tce->process_cmdmap();
1161 $this->errorLog
= array_merge($this->errorLog
, $tce->errorLog
);
1162 // If copying was successful, share the new uids (also of related children):
1163 if ($tce->copyMappingArray
[$table][$id]) {
1164 foreach ($tce->copyMappingArray
as $origTable => $origIdArray) {
1165 foreach ($origIdArray as $origId => $newId) {
1166 $this->uploadedFileArray
[$origTable][$newId] = $this->uploadedFileArray
[$origTable][$origId];
1167 $this->autoVersionIdMap
[$origTable][$origId] = $newId;
1170 ArrayUtility
::mergeRecursiveWithOverrule($this->RTEmagic_copyIndex
, $tce->RTEmagic_copyIndex
);
1171 // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
1172 // Update registerDBList, that holds the copied relations to child records:
1173 $registerDBList = array_merge($registerDBList, $tce->registerDBList
);
1174 // For the reason that creating a new version of this record, automatically
1175 // created related child records (e.g. "IRRE"), update the accordant field:
1176 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1177 // Use the new id of the copied/versionized record:
1178 $id = $this->autoVersionIdMap
[$table][$id];
1179 $recordAccess = true;
1180 $this->autoVersioningUpdate
= true;
1181 } elseif ($this->enableLogging
) {
1182 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
1184 } elseif ($this->enableLogging
) {
1185 $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);
1189 // The default is 'update'
1192 // If access was granted above, proceed to create or update record:
1193 if (!$recordAccess) {
1197 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1198 list($tscPID) = BackendUtility
::getTSCpid($table, $id, $old_pid_value ?
$old_pid_value : $fieldArray['pid']);
1199 if ($status === 'new' && $table === 'pages') {
1200 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
1201 if (isset($TSConfig['permissions.']) && is_array($TSConfig['permissions.'])) {
1202 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
1205 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1206 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1207 $newVersion_placeholderFieldArray = [];
1208 if ($createNewVersion) {
1209 // create a placeholder array with already processed field content
1210 $newVersion_placeholderFieldArray = $fieldArray;
1212 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
1213 // Forcing some values unto field array:
1214 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1215 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1216 if ($createNewVersion) {
1217 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1219 // Setting system fields
1220 if ($status == 'new') {
1221 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1222 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1223 if ($createNewVersion) {
1224 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1227 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1228 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1229 if ($createNewVersion) {
1230 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1233 } elseif ($this->checkSimilar
) {
1234 // Removing fields which are equal to the current value:
1235 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1237 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1238 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1239 if ($createNewVersion) {
1240 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1243 // Set stage to "Editing" to make sure we restart the workflow
1244 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1245 $fieldArray['t3ver_stage'] = 0;
1247 // Hook: processDatamap_postProcessFieldArray
1248 foreach ($hookObjectsArr as $hookObj) {
1249 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1250 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1253 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1254 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
1255 if (is_array($fieldArray)) {
1256 if ($status == 'new') {
1257 if ($table === 'pages') {
1258 // for new pages always a refresh is needed
1259 $this->pagetreeNeedsRefresh
= true;
1262 // This creates a new version of the record with online placeholder and offline version
1263 if ($createNewVersion) {
1264 // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1265 $this->pagetreeNeedsRefresh
= true;
1267 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
1268 // Setting placeholder state value for temporary record
1269 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER
);
1270 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1271 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1272 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $this->getPlaceholderTitleForTableLabel($table);
1273 // Saving placeholder as 'original'
1274 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1275 // For the actual new offline version, set versioning values to point to placeholder:
1276 $fieldArray['pid'] = -1;
1277 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs
[$id];
1278 $fieldArray['t3ver_id'] = 1;
1279 // Setting placeholder state value for version (so it can know it is currently a new version...)
1280 $fieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER_VERSION
);
1281 $fieldArray['t3ver_label'] = 'First draft version';
1282 $fieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1283 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1284 $phShadowId = $this->insertDB($table, $id, $fieldArray, true, 0, true);
1286 // Processes fields of the placeholder record:
1287 $this->triggerRemapAction($table, $id, [$this, 'placeholderShadowing'], [$table, $phShadowId]);
1288 // Hold auto-versionized ids of placeholders:
1289 $this->autoVersionIdMap
[$table][$this->substNEWwithIDs
[$id]] = $phShadowId;
1292 $this->insertDB($table, $id, $fieldArray, false, $incomingFieldArray['uid']);
1295 if ($table === 'pages') {
1296 // only a certain number of fields needs to be checked for updates
1297 // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1298 $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages
, array_keys($fieldArray));
1299 if (!empty($fieldsToCheck)) {
1300 $this->pagetreeNeedsRefresh
= true;
1303 $this->updateDB($table, $id, $fieldArray);
1304 $this->placeholderShadowing($table, $id);
1307 // Hook: processDatamap_afterDatabaseOperations
1308 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1309 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1310 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1313 // Process the stack of relations to remap/correct
1314 $this->processRemapStack();
1315 $this->dbAnalysisStoreExec();
1316 $this->removeRegisteredFiles();
1317 // Hook: processDatamap_afterAllOperations
1318 // Note: When this hook gets called, all operations on the submitted data have been finished.
1319 foreach ($hookObjectsArr as $hookObj) {
1320 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1321 $hookObj->processDatamap_afterAllOperations($this);
1324 if ($this->isOuterMostInstance()) {
1325 $this->processClearCacheQueue();
1326 $this->resetElementsToBeDeleted();
1331 * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record:
1333 * @param string $table Table name
1334 * @param int $id Record uid
1337 public function placeholderShadowing($table, $id)
1339 if ($liveRec = BackendUtility
::getLiveVersionOfRecord($table, $id, '*')) {
1340 if (VersionState
::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1341 $justStoredRecord = BackendUtility
::getRecord($table, $id);
1343 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1344 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1345 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1346 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1347 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1348 $shadowColumns = array_unique(GeneralUtility
::trimExplode(',', $shadowCols, true));
1349 foreach ($shadowColumns as $fieldName) {
1350 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1351 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1354 if (!empty($newRecord)) {
1355 if ($this->enableLogging
) {
1356 $this->newlog2('Shadowing done on fields <i>' . implode(',', array_keys($newRecord)) . '</i> in placeholder record ' . $table . ':' . $liveRec['uid'] . ' (offline version UID=' . $id . ')', $table, $liveRec['uid'], $liveRec['pid']);
1358 $this->updateDB($table, $liveRec['uid'], $newRecord);
1365 * Create a placeholder title for the label field that does match the field requirements
1367 * @param string $table The table name
1368 * @param string $placeholderContent Placeholder content to be used
1369 * @return string placeholder value
1371 public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1373 if ($placeholderContent === null) {
1374 $placeholderContent = 'PLACEHOLDER';
1377 $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER
->workspace
. ']';
1378 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1379 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1380 return $labelPlaceholder;
1382 $evalCodesArray = GeneralUtility
::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1383 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '');
1384 return isset($transformedLabel['value']) ?
$transformedLabel['value'] : $labelPlaceholder;
1388 * Filling in the field array
1389 * $this->excludedTablesAndFields is used to filter fields if needed.
1391 * @param string $table Table name
1392 * @param int $id Record ID
1393 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1394 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1395 * @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.
1396 * @param string $status Is 'new' or 'update'
1397 * @param int $tscPID TSconfig PID
1398 * @return array Field Array
1400 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1403 $originalLanguageRecord = null;
1404 $originalLanguage_diffStorage = null;
1405 $diffStorageFlag = false;
1406 // Setting 'currentRecord' and 'checkValueRecord':
1407 if (strstr($id, 'NEW')) {
1408 // Must have the 'current' array - not the values after processing below...
1409 $currentRecord = ($checkValueRecord = $fieldArray);
1410 // IF $incomingFieldArray is an array, overlay it.
1411 // 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...
1412 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1413 ArrayUtility
::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1416 // We must use the current values as basis for this!
1417 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1418 // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
1419 BackendUtility
::fixVersioningPid($table, $currentRecord);
1420 // Get original language record if available:
1421 if (is_array($currentRecord) && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
1422 $lookUpTable = $table === 'pages_language_overlay' ?
'pages' : $table;
1423 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1424 BackendUtility
::workspaceOL($lookUpTable, $originalLanguageRecord);
1425 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1428 $this->checkValue_currentRecord
= $checkValueRecord;
1429 // In the following all incoming value-fields are tested:
1430 // - Are the user allowed to change the field?
1431 // - Is the field uid/pid (which are already set)
1432 // - perms-fields for pages-table, then do special things...
1433 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1434 // If everything is OK, the field is entered into $fieldArray[]
1435 foreach ($incomingFieldArray as $field => $fieldValue) {
1436 if (isset($this->excludedTablesAndFields
[$table . '-' . $field]) ||
$this->data_disableFields
[$table][$id][$field]) {
1440 // The field must be editable.
1441 // Checking if a value for language can be changed:
1442 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER
->checkLanguageAccess($fieldValue);
1443 if ($languageDeny) {
1450 // Nothing happens, already set
1452 case 'perms_userid':
1453 case 'perms_groupid':
1456 case 'perms_everybody':
1457 // Permissions can be edited by the owner or the administrator
1458 if ($table == 'pages' && ($this->admin ||
$status == 'new' ||
$this->pageInfo($id, 'perms_userid') == $this->userid
)) {
1459 $value = (int)$fieldValue;
1461 case 'perms_userid':
1462 $fieldArray[$field] = $value;
1464 case 'perms_groupid':
1465 $fieldArray[$field] = $value;
1468 if ($value >= 0 && $value < pow(2, 5)) {
1469 $fieldArray[$field] = $value;
1480 case 't3ver_tstamp':
1481 // t3ver_label is not here because it CAN be edited as a regular field!
1484 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1485 // Evaluating the value
1486 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1487 if (array_key_exists('value', $res)) {
1488 $fieldArray[$field] = $res['value'];
1490 // Add the value of the original record to the diff-storage content:
1491 if ($this->updateModeL10NdiffData
&& $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1492 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ?
'' : $originalLanguageRecord[$field];
1493 $diffStorageFlag = true;
1495 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1496 // 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.
1497 // 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.
1498 // 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.
1499 // 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 !
1500 if ($this->autoVersioningUpdate
=== true) {
1501 if (is_array($this->RTEmagic_copyIndex
[$table][$id][$field])) {
1502 foreach ($this->RTEmagic_copyIndex
[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1503 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1507 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1508 // Allow value for original UID to pass by...
1509 $fieldArray[$field] = $fieldValue;
1513 // Add diff-storage information:
1514 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1515 // 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...
1516 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1518 // Checking for RTE-transformations of fields:
1519 $types_fieldConfig = BackendUtility
::getTCAtypes($table, $this->checkValue_currentRecord
);
1520 $theTypeString = null;
1521 if (is_array($types_fieldConfig)) {
1522 foreach ($types_fieldConfig as $vconf) {
1523 // RTE transformations:
1524 if ($this->dontProcessTransformations ||
!isset($fieldArray[$vconf['field']])) {
1528 // Look for transformation flag:
1529 if ((string)$incomingFieldArray['_TRANSFORM_' . $vconf['field']] === 'RTE') {
1530 if ($theTypeString === null) {
1531 $theTypeString = BackendUtility
::getTCAtypeValue($table, $this->checkValue_currentRecord
);
1533 $RTEsetup = $this->BE_USER
->getTSConfig('RTE', BackendUtility
::getPagesTSconfig($tscPID));
1534 $thisConfig = BackendUtility
::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1535 $fieldArray[$vconf['field']] = $this->transformRichtextContentToDatabase(
1536 $fieldArray[$vconf['field']], $table, $vconf['field'], $vconf['spec'], $thisConfig, $this->checkValue_currentRecord
['pid']
1541 // Return fieldArray
1546 * Performs transformation of content from richtext element to database.
1548 * @param string $value Value to transform.
1549 * @param string $table The table name
1550 * @param string $field The field name
1551 * @param array $defaultExtras Default extras configuration of this field - typically "richtext:rte_transform"
1552 * @param array $thisConfig Configuration for RTEs; A mix between TSconfig and others. Configuration for additional transformation information
1553 * @param int $pid PID value of record (true parent page id)
1554 * @return string Transformed content
1556 protected function transformRichtextContentToDatabase($value, $table, $field, $defaultExtras, $thisConfig, $pid)
1558 if ($defaultExtras['rte_transform']) {
1559 // Initialize transformation:
1560 $parseHTML = GeneralUtility
::makeInstance(RteHtmlParser
::class);
1561 $parseHTML->init($table . ':' . $field, $pid);
1562 // Perform transformation:
1563 $value = $parseHTML->RTE_transform($value, $defaultExtras, 'db', $thisConfig);
1568 /*********************************************
1570 * Evaluation of input values
1572 ********************************************/
1574 * Evaluates a value according to $table/$field settings.
1575 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1576 * 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() )
1578 * @param string $table Table name
1579 * @param string $field Field name
1580 * @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.
1581 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1582 * @param string $status 'update' or 'new' flag
1583 * @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.
1584 * @param int $tscPID TSconfig PID
1585 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1587 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID)
1592 // Processing special case of field pages.doktype
1593 if (($table === 'pages' ||
$table === 'pages_language_overlay') && $field === 'doktype') {
1594 // If the user may not use this specific doktype, we issue a warning
1595 if (!($this->admin || GeneralUtility
::inList($this->BE_USER
->groupData
['pagetypes_select'], $value))) {
1596 if ($this->enableLogging
) {
1597 $propArr = $this->getRecordProperties($table, $id);
1598 $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']);
1602 if ($status == 'update') {
1603 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1604 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ?
$GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1605 if ($onlyAllowedTables) {
1606 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1607 if ($theWrongTables) {
1608 if ($this->enableLogging
) {
1609 $propArr = $this->getRecordProperties($table, $id);
1610 $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']);
1619 if ((int)$id !== 0) {
1620 // Get current value:
1621 $curValueRec = $this->recordInfo($table, $id, $field);
1622 // isset() won't work here, since values can be NULL
1623 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1624 $curValue = $curValueRec[$field];
1628 // Getting config for the field
1629 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1631 // Create $recFID only for those types that need it
1633 $tcaFieldConf['type'] === 'flex'
1634 ||
$tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' ||
$tcaFieldConf['internal_type'] === 'file_reference')
1636 $recFID = $table . ':' . $id . ':' . $field;
1641 // Perform processing:
1642 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray
[$table][$id][$field], $tscPID);
1647 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1648 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1650 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1651 * @param string $value The value to set.
1652 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1653 * @param string $table Table name
1654 * @param int $id UID of record
1655 * @param mixed $curValue Current value of the field
1656 * @param string $status 'update' or 'new' flag
1657 * @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.
1658 * @param string $recFID Field identifier [table:uid:field] for flexforms
1659 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1660 * @param array $uploadedFiles
1661 * @param int $tscPID TSconfig PID
1662 * @param array $additionalData Additional data to be forwarded to sub-processors
1663 * @return array Returns the evaluated $value as key "value" in this array.
1665 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1667 // Convert to NULL value if defined in TCA
1668 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility
::inList($tcaFieldConf['eval'], 'null')) {
1669 $res = ['value' => null];
1673 switch ($tcaFieldConf['type']) {
1675 $res = $this->checkValueForText($value, $tcaFieldConf);
1678 case 'imageManipulation':
1680 $res['value'] = $value;
1683 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1686 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1689 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1693 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1696 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1699 // FlexForms are only allowed for real fields.
1701 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1711 * Evaluate "text" type values.
1713 * @param string $value The value to set.
1714 * @param array $tcaFieldConf Field configuration from TCA
1715 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1717 protected function checkValueForText($value, $tcaFieldConf)
1719 if (!isset($tcaFieldConf['eval']) ||
$tcaFieldConf['eval'] === '') {
1720 return ['value' => $value];
1722 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1723 if ($this->runtimeCache
->has($cacheId)) {
1724 $evalCodesArray = $this->runtimeCache
->get($cacheId);
1726 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1727 $this->runtimeCache
->set($cacheId, $evalCodesArray);
1729 return $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1733 * Evaluate "input" type values.
1735 * @param string $value The value to set.
1736 * @param array $tcaFieldConf Field configuration from TCA
1737 * @param string $table Table name
1738 * @param int $id UID of record
1739 * @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.
1740 * @param string $field Field name
1741 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1743 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1745 // Handle native date/time fields
1746 $isDateOrDateTimeField = false;
1749 // normal integer "date" fields (timestamps) are handled in checkValue_input_Eval
1750 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' ||
$tcaFieldConf['dbType'] === 'datetime')) {
1751 if (empty($value)) {
1754 $isDateOrDateTimeField = true;
1755 $dateTimeFormats = QueryHelper
::getDateTimeFormats();
1756 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1758 // Convert the date/time into a timestamp for the sake of the checks
1759 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1760 // We store UTC timestamps in the database, which is what getTimestamp() returns.
1761 $dateTime = new \
DateTime($value);
1762 $value = $value === $emptyValue ?
0 : $dateTime->getTimestamp();
1765 // Secures the string-length to be less than max.
1766 if ((int)$tcaFieldConf['max'] > 0) {
1767 $value = mb_substr((string)$value, 0, (int)$tcaFieldConf['max'], 'utf-8');
1769 // Checking range of value:
1770 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1771 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1772 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1773 $value = $tcaFieldConf['range']['upper'];
1775 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1776 $value = $tcaFieldConf['range']['lower'];
1780 if (empty($tcaFieldConf['eval'])) {
1781 $res = ['value' => $value];
1783 // Process evaluation settings:
1784 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1785 if ($this->runtimeCache
->has($cacheId)) {
1786 $evalCodesArray = $this->runtimeCache
->get($cacheId);
1788 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1789 $this->runtimeCache
->set($cacheId, $evalCodesArray);
1792 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1794 // Process UNIQUE settings:
1795 // 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...
1796 if ($field && $realPid >= 0 && !empty($res['value'])) {
1797 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1798 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1800 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1801 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1806 // Handle native date/time fields
1807 if ($isDateOrDateTimeField) {
1808 // Convert the timestamp back to a date/time
1809 $res['value'] = $res['value'] ?
date($format, $res['value']) : $emptyValue;
1815 * Evaluates 'check' type values.
1817 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1818 * @param string $value The value to set.
1819 * @param array $tcaFieldConf Field configuration from TCA
1820 * @param string $table Table name
1821 * @param int $id UID of record
1822 * @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.
1823 * @param string $field Field name
1824 * @return array Modified $res array
1826 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1828 $items = $tcaFieldConf['items'];
1829 if ($tcaFieldConf['itemsProcFunc']) {
1830 /** @var ItemProcessingService $processingService */
1831 $processingService = GeneralUtility
::makeInstance(ItemProcessingService
::class);
1832 $items = $processingService->getProcessingItems($table, $realPid, $field,
1833 $this->checkValue_currentRecord
,
1834 $tcaFieldConf, $tcaFieldConf['items']);
1837 $itemC = count($items);
1841 $maxV = pow(2, $itemC) - 1;
1843 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
1846 if ($value > $maxV) {
1847 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
1848 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
1849 // @todo: are permanently removed from the value.
1850 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
1851 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
1852 $value = $value & $maxV;
1854 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1855 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], true);
1856 $otherRecordsWithSameValue = [];
1857 $maxCheckedRecords = 0;
1858 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
1859 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1860 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1862 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
1863 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1864 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1867 // there are more than enough records with value "1" in the DB
1868 // if so, set this value to "0" again
1869 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1871 if ($this->enableLogging
) {
1872 $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, [$GLOBALS['LANG']->sL(BackendUtility
::getItemLabel($table, $field)), $maxCheckedRecords]);
1876 $res['value'] = $value;
1881 * Evaluates 'radio' type values.
1883 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1884 * @param string $value The value to set.
1885 * @param array $tcaFieldConf Field configuration from TCA
1886 * @param array $table The table of the record
1887 * @param int $id The id of the record
1888 * @param int $pid The pid of the record
1889 * @param string $field The field to check
1890 * @return array Modified $res array
1892 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
1894 if (is_array($tcaFieldConf['items'])) {
1895 foreach ($tcaFieldConf['items'] as $set) {
1896 if ((string)$set[1] === (string)$value) {
1897 $res['value'] = $value;
1903 // if no value was found and an itemsProcFunc is defined, check that for the value
1904 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
1905 $processingService = GeneralUtility
::makeInstance(ItemProcessingService
::class);
1906 $processedItems = $processingService->getProcessingItems($table, $pid, $field, $this->checkValue_currentRecord
,
1907 $tcaFieldConf, $tcaFieldConf['items']);
1909 foreach ($processedItems as $set) {
1910 if ((string)$set[1] === (string)$value) {
1911 $res['value'] = $value;
1921 * Evaluates 'group' or 'select' type values.
1923 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1924 * @param string $value The value to set.
1925 * @param array $tcaFieldConf Field configuration from TCA
1926 * @param string $table Table name
1927 * @param int $id UID of record
1928 * @param mixed $curValue Current value of the field
1929 * @param string $status 'update' or 'new' flag
1930 * @param string $recFID Field identifier [table:uid:field] for flexforms
1931 * @param array $uploadedFiles
1932 * @param string $field Field name
1933 * @return array Modified $res array
1935 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
1937 // Detecting if value sent is an array and if so, implode it around a comma:
1938 if (is_array($value)) {
1939 $value = implode(',', $value);
1941 // 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.
1942 // Anyway, this should NOT disturb anything else:
1943 $value = $this->convNumEntityToByteValue($value);
1944 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1945 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1946 // If multiple is not set, remove duplicates:
1947 if (!$tcaFieldConf['multiple']) {
1948 $valueArray = array_unique($valueArray);
1950 // If an exclusive key is found, discard all others:
1951 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1952 $exclusiveKeys = GeneralUtility
::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1953 foreach ($valueArray as $index => $key) {
1954 if (in_array($key, $exclusiveKeys, true)) {
1955 $valueArray = [$index => $key];
1960 // 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?)
1961 // 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!!
1962 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1963 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1964 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1965 $preCount = count($valueArray);
1966 foreach ($valueArray as $index => $key) {
1967 if (!$this->BE_USER
->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1968 unset($valueArray[$index]);
1971 // 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.
1972 if ($preCount && empty($valueArray)) {
1977 if ($tcaFieldConf['type'] == 'group') {
1978 switch ($tcaFieldConf['internal_type']) {
1979 case 'file_reference':
1981 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
1985 // For select types which has a foreign table attached:
1986 $unsetResult = false;
1988 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
1989 ||
$tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] ||
isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
1991 // check, if there is a NEW... id in the value, that should be substituted later
1992 if (strpos($value, 'NEW') !== false) {
1993 $this->remapStackRecords
[$table][$id] = ['remapStackIndex' => count($this->remapStack
)];
1994 $this->addNewValuesToRemapStackChildIds($valueArray);
1995 $this->remapStack
[] = [
1996 'func' => 'checkValue_group_select_processDBdata',
1997 'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
1998 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2001 $unsetResult = true;
2003 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2006 if (!$unsetResult) {
2007 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2008 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2010 unset($res['value']);
2016 * Applies the filter methods from a column's TCA configuration to a value array.
2018 * @param array $tcaFieldConfiguration
2019 * @param array $values
2020 * @return array|mixed
2021 * @throws \RuntimeException
2023 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2025 if (empty($tcaFieldConfiguration['filter']) ||
!is_array($tcaFieldConfiguration['filter'])) {
2028 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2029 if (empty($filter['userFunc'])) {
2032 $parameters = $filter['parameters'] ?
: [];
2033 $parameters['values'] = $values;
2034 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2035 $values = GeneralUtility
::callUserFunction($filter['userFunc'], $parameters, $this);
2036 if (!is_array($values)) {
2037 throw new \
RuntimeException('Failed calling filter userFunc.', 1336051942);
2044 * Handling files for group/select function
2046 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2047 * @param array $tcaFieldConf Configuration array from TCA of the field
2048 * @param string $curValue Current value of the field
2049 * @param array $uploadedFileArray Array of uploaded files, if any
2050 * @param string $status 'update' or 'new' flag
2051 * @param string $table tablename of record
2052 * @param int $id UID of record
2053 * @param string $recFID Field identifier [table:uid:field] for flexforms
2054 * @return array Modified value array
2056 * @throws \RuntimeException
2058 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2060 // If file handling should NOT be bypassed, do processing:
2061 if (!$this->bypassFileHandling
) {
2062 // If any files are uploaded, add them to value array
2063 // Numeric index means that there are multiple files
2064 if (isset($uploadedFileArray[0])) {
2065 $uploadedFiles = $uploadedFileArray;
2067 // There is only one file
2068 $uploadedFiles = [$uploadedFileArray];
2070 foreach ($uploadedFiles as $uploadedFileArray) {
2071 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2072 $valueArray[] = $uploadedFileArray['tmp_name'];
2073 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2076 // Creating fileFunc object.
2077 if (!$this->fileFunc
) {
2078 $this->fileFunc
= GeneralUtility
::makeInstance(BasicFileUtility
::class);
2080 // Setting permitted extensions.
2081 $this->fileFunc
->setFileExtensionPermissions($tcaFieldConf['allowed'], $tcaFieldConf['disallowed'] ?
: '*');
2083 // If there is an upload folder defined:
2084 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
2085 $currentFilesForHistory = null;
2086 // If filehandling should NOT be bypassed, do processing:
2087 if (!$this->bypassFileHandling
) {
2089 $propArr = $this->getRecordProperties($table, $id);
2090 // Get destrination path:
2091 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
2092 // If we are updating:
2093 if ($status == 'update') {
2094 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2095 // 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!
2096 // 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_.
2097 // 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.
2098 // Illustration of the problem comes here:
2099 // 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.
2100 // 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.
2101 // 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.
2102 // 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.
2103 if ($this->autoVersioningUpdate
=== true) {
2104 foreach ($valueArray as $key => $theFile) {
2105 // If it is an already attached file...
2106 if ($theFile === basename($theFile)) {
2107 $valueArray[$key] = PATH_site
. $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2111 // Finding the CURRENT files listed, either from MM or from the current record.
2112 $theFileValues = [];
2113 // If MM relations for the files also!
2114 if ($tcaFieldConf['MM']) {
2115 $dbAnalysis = $this->createRelationHandlerInstance();
2116 /** @var $dbAnalysis RelationHandler */
2117 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2118 foreach ($dbAnalysis->itemArray
as $item) {
2120 $theFileValues[] = $item['id'];
2124 $theFileValues = GeneralUtility
::trimExplode(',', $curValue, true);
2126 $currentFilesForHistory = implode(',', $theFileValues);
2127 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2128 if (!empty($theFileValues)) {
2129 // 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!)
2130 foreach ($valueArray as $key => $theFile) {
2131 if ($theFile && !strstr(GeneralUtility
::fixWindowsFilePath($theFile), '/')) {
2132 $theFileValues = ArrayUtility
::removeArrayEntryByValue($theFileValues, $theFile);
2135 // This array contains the filenames in the uploadfolder that should be deleted:
2136 foreach ($theFileValues as $key => $theFile) {
2137 $theFile = trim($theFile);
2138 if (@is_file
(($dest . '/' . $theFile))) {
2139 $this->removeFilesStore
[] = $dest . '/' . $theFile;
2140 } elseif ($this->enableLogging
&& $theFile) {
2141 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, [$dest . '/' . $theFile, $recFID], $propArr['event_pid']);
2146 // Traverse the submitted values:
2147 foreach ($valueArray as $key => $theFile) {
2149 $maxSize = (int)$tcaFieldConf['max_size'];
2150 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2152 // a FAL file was added, now resolve the file object and get the absolute path
2153 // @todo in future versions this needs to be modified to handle FAL objects natively
2154 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
2155 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
2156 $theFile = $fileObject->getForLocalProcessing(false);
2158 // NEW FILES? If the value contains '/' it indicates, that the file
2159 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2160 if (strstr(GeneralUtility
::fixWindowsFilePath($theFile), '/')) {
2161 // Check various things before copying file:
2162 // File and destination must exist
2163 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) {
2165 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2166 $fileSize = $uploadedFileArray['size'];
2168 $fileSize = filesize($theFile);
2171 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
2172 // Prepare filename:
2173 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
2174 $fI = GeneralUtility
::split_fileref($theEndFileName);
2175 // Check for allowed extension:
2176 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2177 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
2178 // If we have a unique destination filename, then write the file:
2180 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2181 // Hook for post-processing the upload action
2182 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2183 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2184 $hookObject = GeneralUtility
::getUserObj($classRef);
2185 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface
) {
2186 throw new \
UnexpectedValueException($classRef . ' must implement interface ' . DataHandlerProcessUploadHookInterface
::class, 1279962349);
2188 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2191 $this->copiedFileMap
[$theFile] = $theDestFile;
2193 if ($this->enableLogging
&& !@is_file
($theDestFile)) {
2194 $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, dirname($theDestFile), $recFID], $propArr['event_pid']);
2196 } elseif ($this->enableLogging
) {
2197 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2199 } elseif ($this->enableLogging
) {
2200 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2202 } elseif ($this->enableLogging
) {
2203 $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']);
2205 } elseif ($this->enableLogging
) {
2206 $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']);
2208 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2209 if (@is_file
($theDestFile)) {
2210 $info = GeneralUtility
::split_fileref($theDestFile);
2211 // The value is set to the new filename
2212 $valueArray[$key] = $info['file'];
2214 // The value is set to the new filename
2215 unset($valueArray[$key]);
2220 // 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!
2221 if ($tcaFieldConf['MM']) {
2222 /** @var $dbAnalysis RelationHandler */
2223 $dbAnalysis = $this->createRelationHandlerInstance();
2225 $dbAnalysis->tableArray
['files'] = [];
2226 foreach ($valueArray as $key => $theFile) {
2228 $dbAnalysis->itemArray
[]['id'] = $theFile;
2230 if ($status == 'update') {
2231 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2232 $newFiles = implode(',', $dbAnalysis->getValueArray());
2233 list(, , $recFieldName) = explode(':', $recFID);
2234 if ($currentFilesForHistory != $newFiles) {
2235 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2236 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2238 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2239 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2242 $this->dbAnalysisStore
[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, 0];
2244 $valueArray = $dbAnalysis->countItems();
2247 if (!empty($valueArray)) {
2248 // If filehandling should NOT be bypassed, do processing:
2249 if (!$this->bypassFileHandling
) {
2251 $propArr = $this->getRecordProperties($table, $id);
2252 foreach ($valueArray as &$theFile) {
2253 // FAL handling: it's a UID, thus it is resolved to the absolute path
2254 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
2255 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
2256 $theFile = $fileObject->getForLocalProcessing(false);
2258 if ($this->alternativeFilePath
[$theFile]) {
2259 // If alternative File Path is set for the file, then it was an import
2260 // don't import the file if it already exists
2261 if (@is_file
((PATH_site
. $this->alternativeFilePath
[$theFile]))) {
2262 $theFile = PATH_site
. $this->alternativeFilePath
[$theFile];
2263 } elseif (@is_file
($theFile)) {
2264 $dest = dirname(PATH_site
. $this->alternativeFilePath
[$theFile]);
2265 if (!@is_dir
($dest)) {
2266 GeneralUtility
::mkdir_deep(PATH_site
, dirname($this->alternativeFilePath
[$theFile]) . '/');
2269 $maxSize = (int)$tcaFieldConf['max_size'];
2270 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2272 $fileSize = filesize($theFile);
2274 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
2275 // Prepare filename:
2276 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
2277 $fI = GeneralUtility
::split_fileref($theEndFileName);
2278 // Check for allowed extension:
2279 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2280 $theDestFile = PATH_site
. $this->alternativeFilePath
[$theFile];
2283 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2284 $this->copiedFileMap
[$theFile] = $theDestFile;
2286 if ($this->enableLogging
&& !@is_file
($theDestFile)) {
2287 $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, dirname($theDestFile), $recFID], $propArr['event_pid']);
2289 } elseif ($this->enableLogging
) {
2290 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2292 } elseif ($this->enableLogging
) {
2293 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2295 } elseif ($this->enableLogging
) {
2296 $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']);
2298 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2299 if (@is_file
($theDestFile)) {
2300 // The value is set to the new filename
2301 $theFile = $theDestFile;
2303 // The value is set to the new filename
2308 if (!empty($theFile)) {
2309 $theFile = GeneralUtility
::fixWindowsFilePath($theFile);
2310 if (GeneralUtility
::isFirstPartOfStr($theFile, PATH_site
)) {
2311 $theFile = PathUtility
::stripPathSitePrefix($theFile);
2323 * Evaluates 'flex' type values.
2325 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2326 * @param string|array $value The value to set.
2327 * @param array $tcaFieldConf Field configuration from TCA
2328 * @param string $table Table name
2329 * @param int $id UID of record
2330 * @param mixed $curValue Current value of the field
2331 * @param string $status 'update' or 'new' flag
2332 * @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.
2333 * @param string $recFID Field identifier [table:uid:field] for flexforms
2334 * @param int $tscPID TSconfig PID
2335 * @param array $uploadedFiles Uploaded files for the field
2336 * @param string $field Field name
2337 * @return array Modified $res array
2339 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2341 if (is_array($value)) {
2342 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2343 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord
2344 // does not have a uid or pid for that sake, the FlexFormTools->getDataStructureIdentifier() function returns no good DS. For new
2345 // records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
2346 $row = $this->checkValue_currentRecord
;
2347 if ($status === 'new') {
2348 $row['pid'] = $realPid;
2350 // Get current value array:
2351 $flexFormTools = GeneralUtility
::makeInstance(FlexFormTools
::class);
2352 $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
2353 [ 'config' => $tcaFieldConf ],
2358 $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
2359 $currentValueArray = (string)$curValue !== '' ? GeneralUtility
::xml2array($curValue) : [];
2360 if (!is_array($currentValueArray)) {
2361 $currentValueArray = [];
2363 // Remove all old meta for languages...
2364 // Evaluation of input values:
2365 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructureArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2366 // Create XML from input value:
2367 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2369 // 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
2370 // (provided that the current value was already stored IN the charset that the new value is converted to).
2371 $arrValue = GeneralUtility
::xml2array($xmlValue);
2373 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2374 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2375 $hookObject = GeneralUtility
::getUserObj($classRef);
2376 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2377 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2382 ArrayUtility
::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2383 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2385 // Action commands (sorting order and removals of elements) for flexform sections,
2386 // see FormEngine for the use of this GP parameter
2387 $actionCMDs = GeneralUtility
::_GP('_ACTION_FLEX_FORMdata');
2388 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2389 $arrValue = GeneralUtility
::xml2array($xmlValue);
2390 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2391 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2393 // Create the value XML:
2395 $res['value'] .= $xmlValue;
2398 $res['value'] = $value;
2405 * Converts an array to FlexForm XML
2407 * @param array $array Array with FlexForm data
2408 * @param bool $addPrologue If set, the XML prologue is returned as well.
2409 * @return string Input array converted to XML
2411 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2413 /** @var $flexObj FlexFormTools */
2414 $flexObj = GeneralUtility
::makeInstance(FlexFormTools
::class);
2415 return $flexObj->flexArray2Xml($array, $addPrologue);
2419 * Actions for flex form element (move, delete)
2420 * allows to remove and move flexform sections
2422 * @param array $valueArray by reference
2423 * @param array $actionCMDs
2425 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2427 if (!is_array($valueArray) ||
!is_array($actionCMDs)) {
2431 foreach ($actionCMDs as $key => $value) {
2432 if ($key == '_ACTION') {
2433 // First, check if there are "commands":
2434 if (current($actionCMDs[$key]) === '') {
2438 asort($actionCMDs[$key]);
2439 $newValueArray = [];
2440 foreach ($actionCMDs[$key] as $idx => $order) {
2441 if (substr($idx, 0, 3) == 'ID-') {
2442 $idx = $this->newIndexMap
[$idx];
2444 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost files unless we act on this delete operation by traversing and deleting files that were referred to.
2445 if ($order != 'DELETE') {
2446 $newValueArray[$idx] = $valueArray[$idx];
2448 unset($valueArray[$idx]);
2450 $valueArray = $valueArray +
$newValueArray;
2451 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2452 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2458 * Evaluates 'inline' type values.
2459 * (partly copied from the select_group function on this issue)
2461 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2462 * @param string $value The value to set.
2463 * @param array $tcaFieldConf Field configuration from TCA
2464 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2465 * @param string $field Field name
2466 * @param array $additionalData Additional data to be forwarded to sub-processors
2467 * @return array Modified $res array
2469 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2471 list($table, $id, , $status) = $PP;
2472 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2476 * Evaluates 'inline' type values.
2477 * (partly copied from the select_group function on this issue)
2479 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2480 * @param string $value The value to set.
2481 * @param array $tcaFieldConf Field configuration from TCA
2482 * @param string $table Table name
2483 * @param int $id UID of record
2484 * @param string $status 'update' or 'new' flag
2485 * @param string $field Field name
2486 * @param array $additionalData Additional data to be forwarded to sub-processors
2487 * @return array Modified $res array
2489 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2491 if (!$tcaFieldConf['foreign_table']) {
2492 // Fatal error, inline fields should always have a foreign_table defined
2495 // When values are sent they come as comma-separated values which are exploded by this function:
2496 $valueArray = GeneralUtility
::trimExplode(',', $value);
2497 // Remove duplicates: (should not be needed)
2498 $valueArray = array_unique($valueArray);
2499 // Example for received data:
2500 // $value = 45,NEW4555fdf59d154,12,123
2501 // We need to decide whether we use the stack or can save the relation directly.
2502 if (strpos($value, 'NEW') !== false ||
!MathUtility
::canBeInterpretedAsInteger($id)) {
2503 $this->remapStackRecords
[$table][$id] = ['remapStackIndex' => count($this->remapStack
)];
2504 $this->addNewValuesToRemapStackChildIds($valueArray);
2505 $this->remapStack
[] = [
2506 'func' => 'checkValue_inline_processDBdata',
2507 'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2508 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2509 'additionalData' => $additionalData,
2512 unset($res['value']);
2513 } elseif ($value || MathUtility
::canBeInterpretedAsInteger($id)) {
2514 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2520 * Checks if a fields has more items than defined via TCA in maxitems.
2521 * If there are more items than allowd, the item list is truncated to the defined number.
2523 * @param array $tcaFieldConf Field configuration from TCA
2524 * @param array $valueArray Current value array of items
2525 * @return array The truncated value array of items
2527 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2529 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2530 $valueArrayC = count($valueArray);
2531 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
2532 $maxI = isset($tcaFieldConf['maxitems']) ?
(int)$tcaFieldConf['maxitems'] : 1;
2533 if ($valueArrayC > $maxI) {
2534 $valueArrayC = $maxI;
2536 // Checking for not too many elements
2537 // Dumping array to list
2539 foreach ($valueArray as $nextVal) {
2540 if ($valueArrayC == 0) {
2544 $newVal[] = $nextVal;
2549 /*********************************************
2551 * Helper functions for evaluation functions.
2553 ********************************************/
2555 * Gets a unique value for $table/$id/$field based on $value
2557 * @param string $table Table name
2558 * @param string $field Field name for which $value must be unique
2559 * @param string $value Value string.
2560 * @param int $id UID to filter out in the lookup (the record itself...)
2561 * @param int $newPid If set, the value will be unique for this PID
2562 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2564 public function getUnique($table, $field, $value, $id, $newPid = 0)
2566 // If the field is configured in TCA, proceed:
2567 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2569 $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2570 // For as long as records with the test-value existing, try again (with incremented numbers appended)
2571 if ($statement->fetchColumn()) {
2572 $statement->bindParam(1, $newValue);
2573 for ($counter = 0; $counter <= 100; $counter++
) {
2574 $newValue = $value . $counter;
2575 $statement->execute();
2576 if (!$statement->fetchColumn()) {
2587 * Gets the count of records for a unique field
2589 * @param string $value The string value which should be unique
2590 * @param string $table Table name
2591 * @param string $field Field name for which $value must be unique
2592 * @param int $uid UID to filter out in the lookup (the record itself...)
2593 * @param int $pid If set, the value will be unique for this PID
2594 * @return \Doctrine\DBAL\Statement Return the prepared statement to check uniqueness
2596 protected function getUniqueCountStatement(
2603 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);
2604 $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2609 $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value, \PDO
::PARAM_STR
)),
2610 $queryBuilder->expr()->neq('uid', $queryBuilder->createPositionalParameter($uid, \PDO
::PARAM_INT
))
2613 $queryBuilder->andWhere(
2614 $queryBuilder->expr()->eq('pid', $queryBuilder->createPositionalParameter($pid, \PDO
::PARAM_INT
))
2617 // pid>=0 for versioning
2618 $queryBuilder->andWhere(
2619 $queryBuilder->expr()->gte('pid', $queryBuilder->createPositionalParameter(0, \PDO
::PARAM_INT
))
2623 return $queryBuilder->execute();
2627 * gets all records that have the same value in a field
2628 * excluding the given uid
2630 * @param string $tableName Table name
2631 * @param int $uid UID to filter out in the lookup (the record itself...)
2632 * @param string $fieldName Field name for which $value must be unique
2633 * @param string $value Value string.
2634 * @param int $pageId If set, the value will be unique for this PID
2637 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2640 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2642 $pageId = (int)$pageId;
2643 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ?
'pid = ' . $pageId : 'pid >= 0');
2644 $result = BackendUtility
::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2650 * @param string $value The field value to be evaluated
2651 * @param array $evalArray Array of evaluations to traverse.
2652 * @param string $is_in The "is_in" value of the field configuration from TCA
2655 public function checkValue_text_Eval($value, $evalArray, $is_in)
2659 foreach ($evalArray as $func) {
2662 $value = trim($value);
2670 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2671 if (class_exists($func)) {
2672 $evalObj = GeneralUtility
::makeInstance($func);
2673 if (method_exists($evalObj, 'evaluateFieldValue')) {
2674 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2681 $res['value'] = $value;
2687 * Evaluation of 'input'-type values based on 'eval' list
2689 * @param string $value Value to evaluate
2690 * @param array $evalArray Array of evaluations to traverse.
2691 * @param string $is_in Is-in string for 'is_in' evaluation
2692 * @return array Modified $value in key 'value' or empty array
2694 public function checkValue_input_Eval($value, $evalArray, $is_in)
2698 foreach ($evalArray as $func) {
2702 $value = (int)$value;
2708 // a hyphen as first character indicates a negative timestamp
2709 if ((strpos($value, '-') === false && strpos($value, ':') === false) ||
strpos($value, '-') === 0) {
2710 $value = (int)$value;
2713 $dateTime = new \
DateTime($value);
2714 // The returned timestamp is always UTC
2715 $value = $dateTime->getTimestamp();
2717 // $value is a UTC timestamp here.
2718 // The value will be stored in the server’s local timezone, but treated as UTC, so we brute force
2719 // subtract the offset here. The offset is subtracted instead of added because the value is stored
2720 // in the timezone, but interpreted as UTC, so if we switched the server to UTC, the correct
2721 // value would be returned.
2722 if ($value !== 0 && !$this->dontProcessTransformations
) {
2723 $value -= date('Z', $value);
2727 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2728 $negative = $value[0] === '-';
2729 $value = strtr($value, [',' => '.', '-' => '']);
2730 if (strpos($value, '.') === false) {
2733 $valueArray = explode('.', $value);
2734 $dec = array_pop($valueArray);
2735 $value = implode('', $valueArray) . '.' . $dec;
2739 $value = number_format($value, 2, '.', '');
2742 if (strlen($value) != 32) {
2747 $value = trim($value);
2750 $value = mb_strtoupper($value, 'utf-8');
2753 $value = mb_strtolower($value, 'utf-8');
2756 if (!isset($value) ||
$value === '') {
2761 $c = strlen($value);
2764 for ($a = 0; $a < $c; $a++
) {
2765 $char = substr($value, $a, 1);
2766 if (strpos($is_in, $char) !== false) {
2774 $value = str_replace(' ', '', $value);
2777 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2780 $value = preg_replace('/[^0-9]/', '', $value);
2783 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2786 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2789 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2790 $value = GeneralUtility
::idnaEncode($value);
2794 if ((string)$value !== '') {
2795 $this->checkValue_input_ValidateEmail($value, $set);
2799 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2800 if (class_exists($func)) {
2801 $evalObj = GeneralUtility
::makeInstance($func);
2802 if (method_exists($evalObj, 'evaluateFieldValue')) {
2803 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2810 $res['value'] = $value;
2816 * If $value is not a valid e-mail address,
2817 * $set will be set to false and a flash error
2818 * message will be added
2820 * @param string $value Value to evaluate
2821 * @param bool $set TRUE if an update should be done
2822 * @throws \InvalidArgumentException
2823 * @throws \TYPO3\CMS\Core\Exception
2826 protected function checkValue_input_ValidateEmail($value, &$set)
2828 if (GeneralUtility
::validEmail($value)) {
2833 /** @var FlashMessage $message */
2834 $message = GeneralUtility
::makeInstance(FlashMessage
::class,
2835 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:error.invalidEmail'), $value),
2836 '', // header is optional
2837 FlashMessage
::ERROR
,
2838 true // whether message should be stored in session
2840 /** @var $flashMessageService FlashMessageService */
2841 $flashMessageService = GeneralUtility
::makeInstance(FlashMessageService
::class);
2842 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2846 * Returns data for group/db and select fields
2848 * @param array $valueArray Current value array
2849 * @param array $tcaFieldConf TCA field config
2850 * @param int $id Record id, used for look-up of MM relations (local_uid)
2851 * @param string $status Status string ('update' or 'new')
2852 * @param string $type The type, either 'select', 'group' or 'inline'
2853 * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2854 * @param string $currentField field name, needs to be set for writing to sys_history
2855 * @return array Modified value array
2857 public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField)
2859 if ($type === 'group') {
2860 $tables = $tcaFieldConf['allowed'];
2861 } elseif (!empty($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages') {
2862 $tables = 'sys_language';
2864 $tables = $tcaFieldConf['foreign_table'];
2866 $prep = $type == 'group' ?
$tcaFieldConf['prepend_tname'] : '';
2867 $newRelations = implode(',', $valueArray);
2868 /** @var $dbAnalysis RelationHandler */
2869 $dbAnalysis = $this->createRelationHandlerInstance();
2870 $dbAnalysis->registerNonTableValues
= !empty($tcaFieldConf['allowNonIdValues']);
2871 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2872 if ($tcaFieldConf['MM']) {
2873 // convert submitted items to use version ids instead of live ids
2874 // (only required for MM relations in a workspace context)
2875 $dbAnalysis->convertItemArray();
2876 if ($status == 'update') {
2877 /** @var $oldRelations_dbAnalysis RelationHandler */
2878 $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2879 $oldRelations_dbAnalysis->registerNonTableValues
= !empty($tcaFieldConf['allowNonIdValues']);
2880 // Db analysis with $id will initialize with the existing relations
2881 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2882 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2883 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2884 if ($oldRelations != $newRelations) {
2885 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2886 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2888 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2889 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2892 $this->dbAnalysisStore
[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable];