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 TYPO3\CMS\Backend\Utility\BackendUtility
;
18 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication
;
19 use TYPO3\CMS\Core\Cache\CacheManager
;
20 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
;
21 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
;
22 use TYPO3\CMS\Core\Database\DatabaseConnection
;
23 use TYPO3\CMS\Core\Database\ReferenceIndex
;
24 use TYPO3\CMS\Core\Database\RelationHandler
;
25 use TYPO3\CMS\Core\Messaging\FlashMessage
;
26 use TYPO3\CMS\Core\Messaging\FlashMessageService
;
27 use TYPO3\CMS\Core\
Resource\ResourceFactory
;
28 use TYPO3\CMS\Core\Utility\ArrayUtility
;
29 use TYPO3\CMS\Core\Utility\File\BasicFileUtility
;
30 use TYPO3\CMS\Core\Utility\GeneralUtility
;
31 use TYPO3\CMS\Core\Utility\MathUtility
;
32 use TYPO3\CMS\Core\Utility\PathUtility
;
33 use TYPO3\CMS\Core\Versioning\VersionState
;
36 * The main data handler class which takes care of correctly updating and inserting records.
37 * This class was formerly known as TCEmain.
39 * This is the TYPO3 Core Engine class for manipulation of the database
40 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
43 * - $GLOBALS['TCA'] must exist
44 * - $GLOBALS['LANG'] must exist
46 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
48 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
52 // *********************
53 // Public variables you can configure before using the class:
54 // *********************
56 * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
57 * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
61 public $storeLogMessages = TRUE;
64 * If TRUE, actions are logged to sys_log.
68 public $enableLogging = TRUE;
71 * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
76 public $reverseOrder = FALSE;
79 * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
80 * is similar, it's not saved then.
84 public $checkSimilar = TRUE;
87 * If TRUE, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an
88 * unescaped data array instead. This switch may totally disappear in future versions of this class!
92 public $stripslashes_values = TRUE;
95 * This will read the record after having updated or inserted it. If anything is not properly submitted an error
96 * is written to the log. This feature consumes extra time by selecting records
100 public $checkStoredRecords = TRUE;
103 * If set, values '' and 0 will equal each other when the stored records are checked.
107 public $checkStoredRecords_loose = TRUE;
110 * If this is set, then a page is deleted by deleting the whole branch under it (user must have
111 * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
115 public $deleteTree = FALSE;
118 * If set, then the 'hideAtCopy' flag for tables will be ignored.
122 public $neverHideAtCopy = FALSE;
125 * If set, then the TCE class has been instantiated during an import action of a T3D
129 public $isImporting = FALSE;
132 * If set, then transformations are NOT performed on the input.
136 public $dontProcessTransformations = FALSE;
139 * If set, .vDEFbase values are unset in flexforms.
143 public $clear_flexFormData_vDEFbase = FALSE;
146 * TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value.
147 * FALSE: Will not update anything.
148 * "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
152 public $updateModeL10NdiffData = TRUE;
155 * If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again!
156 * It's meant as the opposite of declaring the record translated.
160 public $updateModeL10NdiffDataClear = FALSE;
163 * If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()).
164 * YOU MUST KNOW what you do if you use this feature!
168 public $bypassWorkspaceRestrictions = FALSE;
171 * If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away.
172 * YOU MUST KNOW what you are doing with this feature!
176 public $bypassFileHandling = FALSE;
179 * If TRUE, access check, check for deleted etc. for records is bypassed.
180 * YOU MUST KNOW what you are doing if you use this feature!
184 public $bypassAccessCheckForRecords = FALSE;
187 * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
188 * If '*' then all will (that the user has permission to of course)
192 public $copyWhichTables = '*';
195 * If 0 then branch is NOT copied.
196 * If 1 then pages on the 1st level is copied.
197 * If 2 then pages on the second level is copied ... and so on
201 public $copyTree = 0;
204 * [table][fields]=value: New records are created with default values and you can set this array on the
205 * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
206 * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
207 * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
211 public $defaultValues = array();
214 * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
215 * override the incoming data. You must set this externally. You must make sure the fields in this array are also
216 * found in the table, because it's not checked. All columns can be set by this array!
220 public $overrideValues = array();
223 * [filename]=alternative_filename: Use this array to force another name onto a file.
224 * Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field,
225 * then 'my_file.txt' will be used as the name instead.
229 public $alternativeFileName = array();
232 * Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
236 public $alternativeFilePath = array();
239 * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
240 * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
241 * Then an empty checkbox will disable the field.
245 public $data_disableFields = array();
248 * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
249 * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
250 * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
251 * The option is used for import of T3D files when synchronizing between two mirrored servers.
252 * As a security measure this feature is available only for Admin Users (for now)
256 public $suggestedInsertUids = array();
259 * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
260 * iteration functions inside DataHandler for traversing a FlexForm structure.
266 // *********************
267 // Internal variables (mapping arrays) which can be used (read-only) from outside
268 // *********************
270 * Contains mapping of auto-versionized records.
274 public $autoVersionIdMap = array();
277 * 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
281 public $substNEWwithIDs = array();
284 * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
288 public $substNEWwithIDs_table = array();
291 * Holds the tables and there the ids of newly created child records from IRRE
295 public $newRelatedIDs = array();
298 * This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
302 public $copyMappingArray_merged = array();
305 * A map between input file name and final destination for files being attached to records.
309 public $copiedFileMap = array();
312 * Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
316 public $RTEmagic_copyIndex = array();
319 * Errors are collected in this variable.
323 public $errorLog = array();
326 * Fields from the pages-table for which changes will trigger a pagetree refresh
330 public $pagetreeRefreshFieldsFromPages = array('pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime');
333 * Indicates whether the pagetree needs a refresh because of important changes
337 public $pagetreeNeedsRefresh = FALSE;
340 // *********************
341 // Internal Variables, do not touch.
342 // *********************
344 // Variables set in init() function:
347 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
349 * @var BackendUserAuthentication
354 * Will be set to uid of be_user executing this script
361 * Will be set to username of be_user executing this script
368 * Will be set if user is admin
375 * Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
379 public $defaultPermissions = array(
380 'user' => 'show,edit,delete,new,editcontent',
381 'group' => 'show,edit,new,editcontent',
386 * 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.
390 public $exclude_array;
393 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
396 public $include_filefunctions;
399 * Data submitted from the form view, used to control behaviours,
400 * e.g. this is used to activate/deactivate fields and thus store NULL values
404 protected $control = array();
407 * Set with incoming data array
411 public $datamap = array();
414 * Set with incoming cmd array
418 public $cmdmap = array();
426 public $pMap = array(
439 * Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
443 public $sortIntervals = 256;
445 // Internal caching arrays
447 * Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
451 public $recUpdateAccessCache = array();
454 * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
458 public $recInsertAccessCache = array();
461 * Caching array for check of whether records are in a webmount
465 public $isRecordInWebMount_Cache = array();
468 * Caching array for page ids in webmounts
472 public $isInWebMount_Cache = array();
475 * Caching for collecting TSconfig for page ids
479 public $cachedTSconfig = array();
482 * Used for caching page records in pageInfo()
486 public $pageCache = array();
489 * Array caching workspace access for BE_USER
493 public $checkWorkspaceCache = array();
497 * For accumulation of MM relations that must be written after new records are created.
501 public $dbAnalysisStore = array();
504 * For accumulation of files which must be deleted after processing of all input content
508 public $removeFilesStore = array();
511 * Uploaded files, set by process_uploads()
515 public $uploadedFileArray = array();
518 * Used for tracking references that might need correction after operations
522 public $registerDBList = array();
525 * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
529 public $registerDBPids = array();
532 * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
533 * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
534 * Read from copyMappingArray_merged instead which is accumulating this information.
536 * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
537 * are only available after an action has been completed.
541 public $copyMappingArray = array();
544 * Array used for remapping uids and values at the end of process_datamap
548 public $remapStack = array();
551 * Array used for remapping uids and values at the end of process_datamap
552 * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
556 public $remapStackRecords = array();
559 * Array used for checking whether new children need to be remapped
563 protected $remapStackChildIds = array();
566 * Array used for executing addition actions after remapping happened (set processRemapStack())
570 protected $remapStackActions = array();
573 * Array used for executing post-processing on the reference index
577 protected $remapStackRefIndex = array();
580 * Array used for additional calls to $this->updateRefIndex
584 public $updateRefIndexStack = array();
587 * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
588 * This variable is set by \TYPO3\CMS\Impext\ImportExport
592 public $callFromImpExp = FALSE;
595 * Array for new flexform index mapping
599 public $newIndexMap = array();
603 * basicFileFunctions object
604 * For "singleton" file-manipulation object
606 * @var BasicFileUtility
611 * Set to "currentRecord" during checking of values.
615 public $checkValue_currentRecord = array();
618 * A signal flag used to tell file processing that auto versioning has happened and hence certain action should be applied.
622 public $autoVersioningUpdate = FALSE;
625 * Disable delete clause
629 protected $disableDeleteClause = FALSE;
634 protected $checkModifyAccessListHookObjects;
639 protected $version_remapMMForVersionSwap_reg;
642 * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
643 * This object instantiates itself on versioning and localization ...
645 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
647 protected $outerMostInstance = NULL;
650 * Internal cache for collecting records that should trigger cache clearing
654 protected static $recordsToClearCacheFor = array();
657 * Database layer. Identical to $GLOBALS['TYPO3_DB']
659 * @var DatabaseConnection
661 protected $databaseConnection;
666 public function __construct() {
667 $this->databaseConnection
= $GLOBALS['TYPO3_DB'];
671 * @param array $control
673 public function setControl(array $control) {
674 $this->control
= $control;
679 * For details, see 'TYPO3 Core API' document.
680 * This function does not start the processing of data, but merely initializes the object
682 * @param array $data Data to be modified or inserted in the database
683 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
684 * @param BackendUserAuthentication|NULL $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
687 public function start($data, $cmd, $altUserObject = NULL) {
688 // Initializing BE_USER
689 $this->BE_USER
= is_object($altUserObject) ?
$altUserObject : $GLOBALS['BE_USER'];
690 $this->userid
= $this->BE_USER
->user
['uid'];
691 $this->username
= $this->BE_USER
->user
['username'];
692 $this->admin
= $this->BE_USER
->user
['admin'];
693 if ($this->BE_USER
->uc
['recursiveDelete']) {
694 $this->deleteTree
= 1;
696 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData
=== TRUE) {
697 $this->updateModeL10NdiffData
= FALSE;
699 // Initializing default permissions for pages
700 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
701 if (isset($defaultPermissions['user'])) {
702 $this->defaultPermissions
['user'] = $defaultPermissions['user'];
704 if (isset($defaultPermissions['group'])) {
705 $this->defaultPermissions
['group'] = $defaultPermissions['group'];
707 if (isset($defaultPermissions['everybody'])) {
708 $this->defaultPermissions
['everybody'] = $defaultPermissions['everybody'];
710 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
711 $this->exclude_array
= $this->admin ?
array() : $this->getExcludeListArray();
712 // Setting the data and cmd arrays
713 if (is_array($data)) {
715 $this->datamap
= $data;
717 if (is_array($cmd)) {
719 $this->cmdmap
= $cmd;
724 * Function that can mirror input values in datamap-array to other uid numbers.
725 * 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]
727 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
730 public function setMirror($mirror) {
731 if (is_array($mirror)) {
732 foreach ($mirror as $table => $uid_array) {
733 if (isset($this->datamap
[$table])) {
734 foreach ($uid_array as $id => $uidList) {
735 if (isset($this->datamap
[$table][$id])) {
736 $theIdsInArray = GeneralUtility
::trimExplode(',', $uidList, TRUE);
737 foreach ($theIdsInArray as $copyToUid) {
738 $this->datamap
[$table][$copyToUid] = $this->datamap
[$table][$id];
748 * Initializes default values coming from User TSconfig
750 * @param array $userTS User TSconfig array
753 public function setDefaultsFromUserTS($userTS) {
754 if (is_array($userTS)) {
755 foreach ($userTS as $k => $v) {
756 $k = substr($k, 0, -1);
757 if ($k && is_array($v) && isset($GLOBALS['TCA'][$k])) {
758 if (is_array($this->defaultValues
[$k])) {
759 $this->defaultValues
[$k] = array_merge($this->defaultValues
[$k], $v);
761 $this->defaultValues
[$k] = $v;
769 * Processing of uploaded files.
770 * 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.
772 * @param array $postFiles $_FILES array
775 public function process_uploads($postFiles) {
776 if (is_array($postFiles)) {
778 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
779 $this->newlog('All editing in this workspace has been frozen!', 1);
782 $subA = reset($postFiles);
783 if (is_array($subA)) {
784 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
785 // Initialize the uploadedFilesArray:
786 $this->uploadedFileArray
= array();
788 foreach ($subA as $key => $values) {
789 $this->process_uploads_traverseArray($this->uploadedFileArray
, $values, $key);
792 $this->uploadedFileArray
= $subA;
799 * Traverse the upload array if needed to rearrange values.
801 * @param array $outputArr $this->uploadedFileArray passed by reference
802 * @param array $inputArr Input array ($_FILES parts)
803 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
806 * @see process_uploads()
808 public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet) {
809 if (is_array($inputArr)) {
810 foreach ($inputArr as $key => $value) {
811 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
814 $outputArr[$keyToSet] = $inputArr;
818 /*********************************************
822 *********************************************/
824 * Hook: processDatamap_afterDatabaseOperations
825 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
827 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
828 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
830 * @param array $hookObjectsArr (reference) Array with hook objects
831 * @param string $status (reference) Status of the current operation, 'new' or 'update
832 * @param string $table (reference) The table currently processing data for
833 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
834 * @param array $fieldArray (reference) The field array of a record
837 public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
838 // Process hook directly:
839 if (!isset($this->remapStackRecords
[$table][$id])) {
840 foreach ($hookObjectsArr as $hookObj) {
841 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
842 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
846 $this->remapStackRecords
[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
848 'fieldArray' => $fieldArray,
849 'hookObjectsArr' => $hookObjectsArr
855 * Gets the 'checkModifyAccessList' hook objects.
856 * The first call initializes the accordant objects.
858 * @return array The 'checkModifyAccessList' hook objects (if any)
860 protected function getCheckModifyAccessListHookObjects() {
861 if (!isset($this->checkModifyAccessListHookObjects
)) {
862 $this->checkModifyAccessListHookObjects
= array();
863 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
864 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
865 $hookObject = GeneralUtility
::getUserObj($classData);
866 if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface
) {
867 throw new \
UnexpectedValueException('$hookObject must implement interface \\TYPO3\\CMS\\Core\\DataHandling\\DataHandlerCheckModifyAccessListHookInterface', 1251892472);
869 $this->checkModifyAccessListHookObjects
[] = $hookObject;
873 return $this->checkModifyAccessListHookObjects
;
876 /*********************************************
880 *********************************************/
882 * Processing the data-array
883 * Call this function to process the data-array set by start()
887 public function process_datamap() {
888 $this->controlActiveElements();
890 // Keep versionized(!) relations here locally:
891 $registerDBList = array();
892 $this->registerElementsToBeDeleted();
893 $this->datamap
= $this->unsetElementsToBeDeleted($this->datamap
);
895 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
896 $this->newlog('All editing in this workspace has been frozen!', 1);
899 // First prepare user defined objects (if any) for hooks which extend this function:
900 $hookObjectsArr = array();
901 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
902 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
903 $hookObject = GeneralUtility
::getUserObj($classRef);
904 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
905 $hookObject->processDatamap_beforeStart($this);
907 $hookObjectsArr[] = $hookObject;
910 // 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.
911 $orderOfTables = array();
913 if (isset($this->datamap
['pages'])) {
914 $orderOfTables[] = 'pages';
916 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap
)));
917 // Process the tables...
918 foreach ($orderOfTables as $table) {
920 // - table is set in $GLOBALS['TCA'],
921 // - table is NOT readOnly
922 // - the table is set with content in the data-array (if not, there's nothing to process...)
923 // - permissions for tableaccess OK
924 $modifyAccessList = $this->checkModifyAccessList($table);
925 if (!$modifyAccessList) {
927 $this->log($table, $id, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, array($table));
929 if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->datamap
[$table]) && $modifyAccessList) {
930 if ($this->reverseOrder
) {
931 $this->datamap
[$table] = array_reverse($this->datamap
[$table], 1);
933 // For each record from the table, do:
934 // $id is the record uid, may be a string if new records...
935 // $incomingFieldArray is the array of fields
936 foreach ($this->datamap
[$table] as $id => $incomingFieldArray) {
937 if (is_array($incomingFieldArray)) {
938 // Handle native date/time fields
939 $dateTimeFormats = $this->databaseConnection
->getDateTimeFormats($table);
940 foreach ($GLOBALS['TCA'][$table]['columns'] as $column => $config) {
941 if (isset($incomingFieldArray[$column])) {
942 if (isset($config['config']['dbType']) && ($config['config']['dbType'] === 'date' ||
$config['config']['dbType'] === 'datetime')) {
943 $emptyValue = $dateTimeFormats[$config['config']['dbType']]['empty'];
944 $format = $dateTimeFormats[$config['config']['dbType']]['format'];
945 $incomingFieldArray[$column] = $incomingFieldArray[$column] ?
gmdate($format, $incomingFieldArray[$column]) : $emptyValue;
949 // Hook: processDatamap_preProcessFieldArray
950 foreach ($hookObjectsArr as $hookObj) {
951 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
952 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
955 // ******************************
956 // Checking access to the record
957 // ******************************
958 $createNewVersion = FALSE;
959 $recordAccess = FALSE;
961 $this->autoVersioningUpdate
= FALSE;
962 // Is it a new record? (Then Id is a string)
963 if (!MathUtility
::canBeInterpretedAsInteger($id)) {
964 // Get a fieldArray with default values
965 $fieldArray = $this->newFieldArray($table);
966 // A pid must be set for new records.
967 if (isset($incomingFieldArray['pid'])) {
969 $pid_value = $incomingFieldArray['pid'];
970 // Checking and finding numerical pid, it may be a string-reference to another value
973 if (strstr($pid_value, 'NEW')) {
974 if ($pid_value[0] === '-') {
976 $pid_value = substr($pid_value, 1);
980 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
981 if (isset($this->substNEWwithIDs
[$pid_value])) {
982 if ($negFlag === 1) {
983 $old_pid_value = $this->substNEWwithIDs
[$pid_value];
985 $pid_value = (int)($negFlag * $this->substNEWwithIDs
[$pid_value]);
990 $pid_value = (int)$pid_value;
991 // The $pid_value is now the numerical pid at this point
993 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
994 // Points to a page on which to insert the element, possibly in the top of the page
995 if ($pid_value >= 0) {
996 // If this table is sorted we better find the top sorting number
998 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
1000 // The numerical pid is inserted in the data array
1001 $fieldArray['pid'] = $pid_value;
1003 // points to another record before ifself
1004 // If this table is sorted we better find the top sorting number
1006 // Because $pid_value is < 0, getSortNumber returns an array
1007 $tempArray = $this->getSortNumber($table, 0, $pid_value);
1008 $fieldArray['pid'] = $tempArray['pid'];
1009 $fieldArray[$sortRow] = $tempArray['sortNumber'];
1011 // Here we fetch the PID of the record that we point to...
1012 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
1013 $fieldArray['pid'] = $tempdata['pid'];
1018 $theRealPid = $fieldArray['pid'];
1019 // Now, check if we may insert records on this pid.
1020 if ($theRealPid >= 0) {
1021 // Checks if records can be inserted on this $pid.
1022 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
1023 if ($recordAccess) {
1024 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
1025 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $incomingFieldArray, TRUE);
1026 if (!$recordAccess) {
1027 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1028 } elseif (!$this->bypassWorkspaceRestrictions
) {
1029 // Workspace related processing:
1030 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1031 if ($res = $this->BE_USER
->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
1033 $recordAccess = FALSE;
1034 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
1037 // So, if no live records were allowed, we have to create a new version of this record:
1038 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1039 $createNewVersion = TRUE;
1041 $recordAccess = FALSE;
1042 $this->newlog('Record could not be created in this workspace in this branch', 1);
1048 debug('Internal ERROR: pid should not be less than zero!');
1050 // Yes new record, change $record_status to 'insert'
1053 // Nope... $id is a number
1054 $fieldArray = array();
1055 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
1056 if (!$recordAccess) {
1057 $propArr = $this->getRecordProperties($table, $id);
1058 $this->log($table, $id, 2, 0, 1, 'Attempt to modify record \'%s\' (%s) without permission. Or non-existing page.', 2, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']);
1060 // Next check of the record permissions (internals)
1061 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $id);
1062 if (!$recordAccess) {
1063 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
1065 // Here we fetch the PID of the record that we point to...
1066 $tempdata = $this->recordInfo($table, $id, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ?
',t3ver_wsid,t3ver_stage' : ''));
1067 $theRealPid = $tempdata['pid'];
1068 // Use the new id of the versionized record we're trying to write to:
1069 // (This record is a child record of a parent and has already been versionized.)
1070 if ($this->autoVersionIdMap
[$table][$id]) {
1071 // For the reason that creating a new version of this record, automatically
1072 // created related child records (e.g. "IRRE"), update the accordant field:
1073 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1074 // Use the new id of the copied/versionized record:
1075 $id = $this->autoVersionIdMap
[$table][$id];
1076 $recordAccess = TRUE;
1077 $this->autoVersioningUpdate
= TRUE;
1078 } elseif (!$this->bypassWorkspaceRestrictions
&& ($errorCode = $this->BE_USER
->workspaceCannotEditRecord($table, $tempdata))) {
1079 $recordAccess = FALSE;
1080 // Versioning is required and it must be offline version!
1081 // Check if there already is a workspace version
1082 $WSversion = BackendUtility
::getWorkspaceVersionOfRecord($this->BE_USER
->workspace
, $table, $id, 'uid,t3ver_oid');
1084 $id = $WSversion['uid'];
1085 $recordAccess = TRUE;
1086 } elseif ($this->BE_USER
->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1087 // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1088 $this->pagetreeNeedsRefresh
= TRUE;
1090 /** @var $tce DataHandler */
1091 $tce = GeneralUtility
::makeInstance(self
::class);
1092 $tce->stripslashes_values
= 0;
1093 // Setting up command for creating a new version of the record:
1095 $cmd[$table][$id]['version'] = array(
1098 // Default is to create a version of the individual records... element versioning that is.
1099 'label' => 'Auto-created for WS #' . $this->BE_USER
->workspace
1101 $tce->start(array(), $cmd);
1102 $tce->process_cmdmap();
1103 $this->errorLog
= array_merge($this->errorLog
, $tce->errorLog
);
1104 // If copying was successful, share the new uids (also of related children):
1105 if ($tce->copyMappingArray
[$table][$id]) {
1106 foreach ($tce->copyMappingArray
as $origTable => $origIdArray) {
1107 foreach ($origIdArray as $origId => $newId) {
1108 $this->uploadedFileArray
[$origTable][$newId] = $this->uploadedFileArray
[$origTable][$origId];
1109 $this->autoVersionIdMap
[$origTable][$origId] = $newId;
1112 ArrayUtility
::mergeRecursiveWithOverrule($this->RTEmagic_copyIndex
, $tce->RTEmagic_copyIndex
);
1113 // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
1114 // Update registerDBList, that holds the copied relations to child records:
1115 $registerDBList = array_merge($registerDBList, $tce->registerDBList
);
1116 // For the reason that creating a new version of this record, automatically
1117 // created related child records (e.g. "IRRE"), update the accordant field:
1118 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1119 // Use the new id of the copied/versionized record:
1120 $id = $this->autoVersionIdMap
[$table][$id];
1121 $recordAccess = TRUE;
1122 $this->autoVersioningUpdate
= TRUE;
1124 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
1127 $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);
1132 // The default is 'update'
1135 // If access was granted above, proceed to create or update record:
1136 if ($recordAccess) {
1137 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1138 list($tscPID) = BackendUtility
::getTSCpid($table, $id, $old_pid_value ?
$old_pid_value : $fieldArray['pid']);
1139 if ($status === 'new' && $table === 'pages') {
1140 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
1141 if (isset($TSConfig['permissions.']) && is_array($TSConfig['permissions.'])) {
1142 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
1145 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1146 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1147 if ($createNewVersion) {
1148 // create a placeholder array with already processed field content
1149 $newVersion_placeholderFieldArray = $fieldArray;
1151 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
1152 // Forcing some values unto field array:
1153 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1154 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1155 if ($createNewVersion) {
1156 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1158 // Setting system fields
1159 if ($status == 'new') {
1160 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1161 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1162 if ($createNewVersion) {
1163 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1166 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1167 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1168 if ($createNewVersion) {
1169 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
1172 } elseif ($this->checkSimilar
) {
1173 // Removing fields which are equal to the current value:
1174 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1176 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && count($fieldArray)) {
1177 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1178 if ($createNewVersion) {
1179 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1182 // Set stage to "Editing" to make sure we restart the workflow
1183 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1184 $fieldArray['t3ver_stage'] = 0;
1186 // Hook: processDatamap_postProcessFieldArray
1187 foreach ($hookObjectsArr as $hookObj) {
1188 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1189 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1192 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1193 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
1194 if (is_array($fieldArray)) {
1195 if ($status == 'new') {
1196 if ($table === 'pages') {
1197 // for new pages always a refresh is needed
1198 $this->pagetreeNeedsRefresh
= TRUE;
1201 // This creates a new version of the record with online placeholder and offline version
1202 if ($createNewVersion) {
1203 // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1204 $this->pagetreeNeedsRefresh
= TRUE;
1206 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
1207 // Setting placeholder state value for temporary record
1208 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER
);
1209 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1210 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1211 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $this->getPlaceholderTitleForTableLabel($table);
1212 // Saving placeholder as 'original'
1213 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, FALSE);
1214 // For the actual new offline version, set versioning values to point to placeholder:
1215 $fieldArray['pid'] = -1;
1216 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs
[$id];
1217 $fieldArray['t3ver_id'] = 1;
1218 // Setting placeholder state value for version (so it can know it is currently a new version...)
1219 $fieldArray['t3ver_state'] = (string)new VersionState(VersionState
::NEW_PLACEHOLDER_VERSION
);
1220 $fieldArray['t3ver_label'] = 'First draft version';
1221 $fieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
1222 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1223 $phShadowId = $this->insertDB($table, $id, $fieldArray, TRUE, 0, TRUE);
1225 // Processes fields of the placeholder record:
1226 $this->triggerRemapAction($table, $id, array($this, 'placeholderShadowing'), array($table, $phShadowId));
1227 // Hold auto-versionized ids of placeholders:
1228 $this->autoVersionIdMap
[$table][$this->substNEWwithIDs
[$id]] = $phShadowId;
1231 $this->insertDB($table, $id, $fieldArray, FALSE, $incomingFieldArray['uid']);
1234 if ($table === 'pages') {
1235 // only a certain number of fields needs to be checked for updates
1236 // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1237 $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages
, array_keys($fieldArray));
1238 if (count($fieldsToCheck)) {
1239 $this->pagetreeNeedsRefresh
= TRUE;
1242 $this->updateDB($table, $id, $fieldArray);
1243 $this->placeholderShadowing($table, $id);
1246 // Hook: processDatamap_afterDatabaseOperations
1247 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1248 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1249 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1255 // Process the stack of relations to remap/correct
1256 $this->processRemapStack();
1257 $this->dbAnalysisStoreExec();
1258 $this->removeRegisteredFiles();
1259 // Hook: processDatamap_afterAllOperations
1260 // Note: When this hook gets called, all operations on the submitted data have been finished.
1261 foreach ($hookObjectsArr as $hookObj) {
1262 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1263 $hookObj->processDatamap_afterAllOperations($this);
1266 if ($this->isOuterMostInstance()) {
1267 $this->processClearCacheQueue();
1268 $this->resetElementsToBeDeleted();
1273 * Fix shadowing of data in case we are editing a offline version of a live "New" placeholder record:
1275 * @param string $table Table name
1276 * @param int $id Record uid
1279 public function placeholderShadowing($table, $id) {
1280 if ($liveRec = BackendUtility
::getLiveVersionOfRecord($table, $id, '*')) {
1281 if (VersionState
::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1282 $justStoredRecord = BackendUtility
::getRecord($table, $id);
1283 $newRecord = array();
1284 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1285 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1286 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1287 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1288 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1289 $shadowColumns = array_unique(GeneralUtility
::trimExplode(',', $shadowCols, TRUE));
1290 foreach ($shadowColumns as $fieldName) {
1291 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1292 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1295 if (count($newRecord)) {
1296 $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']);
1297 $this->updateDB($table, $liveRec['uid'], $newRecord);
1304 * Create a placeholder title for the label field that does match the field requirements
1306 * @param string $table The table name
1307 * @return string placeholder value
1309 protected function getPlaceholderTitleForTableLabel($table) {
1310 $labelPlaceholder = '[PLACEHOLDER, WS#' . $this->BE_USER
->workspace
. ']';
1311 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1312 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1313 return $labelPlaceholder;
1315 $evalCodesArray = GeneralUtility
::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], TRUE);
1316 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '');
1317 return isset($transformedLabel['value']) ?
$transformedLabel['value'] : $labelPlaceholder;
1321 * Filling in the field array
1322 * $this->exclude_array is used to filter fields if needed.
1324 * @param string $table Table name
1325 * @param int $id Record ID
1326 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1327 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1328 * @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.
1329 * @param string $status Is 'new' or 'update'
1330 * @param int $tscPID TSconfig PID
1331 * @return array Field Array
1333 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID) {
1335 $originalLanguageRecord = NULL;
1336 $originalLanguage_diffStorage = NULL;
1337 $diffStorageFlag = FALSE;
1338 // Setting 'currentRecord' and 'checkValueRecord':
1339 if (strstr($id, 'NEW')) {
1340 // Must have the 'current' array - not the values after processing below...
1341 $currentRecord = ($checkValueRecord = $fieldArray);
1342 // IF $incomingFieldArray is an array, overlay it.
1343 // 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...
1344 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1345 ArrayUtility
::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1348 // We must use the current values as basis for this!
1349 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1350 // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
1351 BackendUtility
::fixVersioningPid($table, $currentRecord);
1352 // Get original language record if available:
1353 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) {
1354 $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ?
: $table;
1355 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1356 BackendUtility
::workspaceOL($lookUpTable, $originalLanguageRecord);
1357 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1360 $this->checkValue_currentRecord
= $checkValueRecord;
1361 // In the following all incoming value-fields are tested:
1362 // - Are the user allowed to change the field?
1363 // - Is the field uid/pid (which are already set)
1364 // - perms-fields for pages-table, then do special things...
1365 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1366 // If everything is OK, the field is entered into $fieldArray[]
1367 foreach ($incomingFieldArray as $field => $fieldValue) {
1368 if (!in_array(($table . '-' . $field), $this->exclude_array
, TRUE) && !$this->data_disableFields
[$table][$id][$field]) {
1369 // The field must be editable.
1370 // Checking if a value for language can be changed:
1371 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER
->checkLanguageAccess($fieldValue);
1372 if (!$languageDeny) {
1373 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
1374 if ($this->stripslashes_values
) {
1375 if (is_array($fieldValue)) {
1376 GeneralUtility
::stripSlashesOnArray($fieldValue);
1378 $fieldValue = stripslashes($fieldValue);
1384 // Nothing happens, already set
1386 case 'perms_userid':
1387 case 'perms_groupid':
1390 case 'perms_everybody':
1391 // Permissions can be edited by the owner or the administrator
1392 if ($table == 'pages' && ($this->admin ||
$status == 'new' ||
$this->pageInfo($id, 'perms_userid') == $this->userid
)) {
1393 $value = (int)$fieldValue;
1395 case 'perms_userid':
1396 $fieldArray[$field] = $value;
1398 case 'perms_groupid':
1399 $fieldArray[$field] = $value;
1402 if ($value >= 0 && $value < pow(2, 5)) {
1403 $fieldArray[$field] = $value;
1414 case 't3ver_tstamp':
1415 // t3ver_label is not here because it CAN be edited as a regular field!
1418 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1419 // Evaluating the value
1420 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1421 if (array_key_exists('value', $res)) {
1422 $fieldArray[$field] = $res['value'];
1424 // Add the value of the original record to the diff-storage content:
1425 if ($this->updateModeL10NdiffData
&& $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1426 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ?
'' : $originalLanguageRecord[$field];
1427 $diffStorageFlag = TRUE;
1429 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1430 // 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.
1431 // 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.
1432 // 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.
1433 // 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 !
1434 if ($this->autoVersioningUpdate
=== TRUE) {
1435 if (is_array($this->RTEmagic_copyIndex
[$table][$id][$field])) {
1436 foreach ($this->RTEmagic_copyIndex
[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1437 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1441 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1442 // Allow value for original UID to pass by...
1443 $fieldArray[$field] = $fieldValue;
1449 // Add diff-storage information:
1450 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1451 // 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...
1452 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1454 // Checking for RTE-transformations of fields:
1455 $types_fieldConfig = BackendUtility
::getTCAtypes($table, $currentRecord);
1456 $theTypeString = BackendUtility
::getTCAtypeValue($table, $currentRecord);
1457 if (is_array($types_fieldConfig)) {
1458 foreach ($types_fieldConfig as $vconf) {
1459 // RTE transformations:
1460 if (!$this->dontProcessTransformations
) {
1461 if (isset($fieldArray[$vconf['field']])) {
1462 // Look for transformation flag:
1463 switch ((string)$incomingFieldArray[('_TRANSFORM_' . $vconf['field'])]) {
1465 $RTEsetup = $this->BE_USER
->getTSConfig('RTE', BackendUtility
::getPagesTSconfig($tscPID));
1466 $thisConfig = BackendUtility
::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1467 // Get RTE object, draw form and set flag:
1468 $RTEobj = BackendUtility
::RTEgetObj();
1469 if (is_object($RTEobj)) {
1470 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db', $fieldArray[$vconf['field']], $table, $vconf['field'], $currentRecord, $vconf['spec'], $thisConfig, '', $currentRecord['pid']);
1472 debug('NO RTE OBJECT FOUND!');
1480 // Return fieldArray
1484 /*********************************************
1486 * Evaluation of input values
1488 ********************************************/
1490 * Evaluates a value according to $table/$field settings.
1491 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1492 * 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() )
1494 * @param string $table Table name
1495 * @param string $field Field name
1496 * @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.
1497 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1498 * @param string $status 'update' or 'new' flag
1499 * @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.
1500 * @param int $tscPID tscPID
1501 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1503 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID) {
1506 $recFID = $table . ':' . $id . ':' . $field;
1507 // Processing special case of field pages.doktype
1508 if (($table === 'pages' ||
$table === 'pages_language_overlay') && $field === 'doktype') {
1509 // If the user may not use this specific doktype, we issue a warning
1510 if (!($this->admin || GeneralUtility
::inList($this->BE_USER
->groupData
['pagetypes_select'], $value))) {
1511 $propArr = $this->getRecordProperties($table, $id);
1512 $this->log($table, $id, 5, 0, 1, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, array($propArr['header']), $propArr['event_pid']);
1515 if ($status == 'update') {
1516 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1517 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ?
$GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1518 if ($onlyAllowedTables) {
1519 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1520 if ($theWrongTables) {
1521 $propArr = $this->getRecordProperties($table, $id);
1522 $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, array($propArr['header'], $theWrongTables), $propArr['event_pid']);
1528 // Get current value:
1529 $curValueRec = $this->recordInfo($table, $id, $field);
1530 $curValue = $curValueRec[$field];
1531 // Getting config for the field
1532 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1533 // Preform processing:
1534 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray
[$table][$id][$field], $tscPID);
1539 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1540 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1542 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1543 * @param string $value The value to set.
1544 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1545 * @param string $table Table name
1546 * @param int $id UID of record
1547 * @param mixed $curValue Current value of the field
1548 * @param string $status 'update' or 'new' flag
1549 * @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.
1550 * @param string $recFID Field identifier [table:uid:field] for flexforms
1551 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1552 * @param array $uploadedFiles
1553 * @param int $tscPID TSconfig PID
1554 * @param array $additionalData Additional data to be forwarded to sub-processors
1555 * @return array Returns the evaluated $value as key "value" in this array.
1557 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = NULL) {
1558 // Convert to NULL value if defined in TCA
1559 if ($value === NULL && !empty($tcaFieldConf['eval']) && GeneralUtility
::inList($tcaFieldConf['eval'], 'null')) {
1560 $res = array('value' => NULL);
1564 $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
1565 switch ($tcaFieldConf['type']) {
1567 $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
1572 $res['value'] = $value;
1575 $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
1578 $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP, $field);
1581 $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
1586 $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1589 $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, $additionalData);
1592 // FlexForms are only allowed for real fields.
1594 $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1604 * Evaluate "text" type values.
1606 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1607 * @param string $value The value to set.
1608 * @param array $tcaFieldConf Field configuration from TCA
1609 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1610 * @param string $field Field name
1611 * @return array Modified $res array
1613 public function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1614 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1615 $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1620 * Evaluate "input" type values.
1622 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1623 * @param string $value The value to set.
1624 * @param array $tcaFieldConf Field configuration from TCA
1625 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1626 * @param string $field Field name
1627 * @return array Modified $res array
1629 public function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1630 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1631 // Handle native date/time fields
1632 $isDateOrDateTimeField = FALSE;
1633 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' ||
$tcaFieldConf['dbType'] === 'datetime')) {
1634 $isDateOrDateTimeField = TRUE;
1635 $dateTimeFormats = $this->databaseConnection
->getDateTimeFormats($table);
1636 // Convert the date/time into a timestamp for the sake of the checks
1637 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1638 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1639 // At this point in the processing, the timestamps are still based on UTC
1640 $timeZone = new \
DateTimeZone('UTC');
1641 $dateTime = \DateTime
::createFromFormat('!' . $format, $value, $timeZone);
1642 $value = $value === $emptyValue ?
0 : $dateTime->getTimestamp();
1644 // Secures the string-length to be less than max.
1645 if ((int)$tcaFieldConf['max'] > 0) {
1646 $value = $GLOBALS['LANG']->csConvObj
->substr($GLOBALS['LANG']->charSet
, $value, 0, (int)$tcaFieldConf['max']);
1648 // Checking range of value:
1649 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1650 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1651 $value = $tcaFieldConf['range']['upper'];
1653 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1654 $value = $tcaFieldConf['range']['lower'];
1657 // Process evaluation settings:
1658 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1659 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1660 // Process UNIQUE settings:
1661 // 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...
1662 if ($field && $realPid >= 0) {
1663 if ($res['value'] && in_array('uniqueInPid', $evalCodesArray, TRUE)) {
1664 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1666 if ($res['value'] && in_array('unique', $evalCodesArray, TRUE)) {
1667 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1670 // Handle native date/time fields
1671 if ($isDateOrDateTimeField) {
1672 // Convert the timestamp back to a date/time
1673 $res['value'] = $res['value'] ?
date($format, $res['value']) : $emptyValue;
1679 * Evaluates 'check' type values.
1681 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1682 * @param string $value The value to set.
1683 * @param array $tcaFieldConf Field configuration from TCA
1684 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1685 * @param string $field Field name
1686 * @return array Modified $res array
1688 public function checkValue_check($res, $value, $tcaFieldConf, $PP, $field = '') {
1689 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1690 $itemC = count($tcaFieldConf['items']);
1694 $maxV = pow(2, $itemC) - 1;
1698 if ($value > $maxV) {
1701 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1702 $evalCodesArray = GeneralUtility
::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1703 $otherRecordsWithSameValue = array();
1704 $maxCheckedRecords = 0;
1705 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, TRUE)) {
1706 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1707 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1709 if (in_array('maximumRecordsChecked', $evalCodesArray, TRUE)) {
1710 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1711 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1714 // there are more than enough records with value "1" in the DB
1715 // if so, set this value to "0" again
1716 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1718 $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, array($GLOBALS['LANG']->sL(BackendUtility
::getItemLabel($table, $field)), $maxCheckedRecords));
1721 $res['value'] = $value;
1726 * Evaluates 'radio' type values.
1728 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1729 * @param string $value The value to set.
1730 * @param array $tcaFieldConf Field configuration from TCA
1731 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1732 * @return array Modified $res array
1734 public function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1735 if (is_array($tcaFieldConf['items'])) {
1736 foreach ($tcaFieldConf['items'] as $set) {
1737 if ((string)$set[1] === (string)$value) {
1738 $res['value'] = $value;
1747 * Evaluates 'group' or 'select' type values.
1749 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1750 * @param string $value The value to set.
1751 * @param array $tcaFieldConf Field configuration from TCA
1752 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1753 * @param array $uploadedFiles
1754 * @param string $field Field name
1755 * @return array Modified $res array
1757 public function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1758 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1759 // Detecting if value sent is an array and if so, implode it around a comma:
1760 if (is_array($value)) {
1761 $value = implode(',', $value);
1763 // 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.
1764 // Anyway, this should NOT disturb anything else:
1765 $value = $this->convNumEntityToByteValue($value);
1766 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1767 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1768 // If multiple is not set, remove duplicates:
1769 if (!$tcaFieldConf['multiple']) {
1770 $valueArray = array_unique($valueArray);
1772 // If an exclusive key is found, discard all others:
1773 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1774 $exclusiveKeys = GeneralUtility
::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1775 foreach ($valueArray as $index => $key) {
1776 if (in_array($key, $exclusiveKeys, TRUE)) {
1777 $valueArray = array($index => $key);
1782 // 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?)
1783 // 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!!
1784 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1785 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1786 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1787 $preCount = count($valueArray);
1788 foreach ($valueArray as $index => $key) {
1789 if (!$this->BE_USER
->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1790 unset($valueArray[$index]);
1793 // 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.
1794 if ($preCount && !count($valueArray)) {
1799 if ($tcaFieldConf['type'] == 'group') {
1800 switch ($tcaFieldConf['internal_type']) {
1801 case 'file_reference':
1804 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
1807 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
1811 // For select types which has a foreign table attached:
1812 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
1813 // check, if there is a NEW... id in the value, that should be substituted later
1814 if (strpos($value, 'NEW') !== FALSE) {
1815 $this->remapStackRecords
[$table][$id] = array('remapStackIndex' => count($this->remapStack
));
1816 $this->addNewValuesToRemapStackChildIds($valueArray);
1817 $this->remapStack
[] = array(
1818 'func' => 'checkValue_group_select_processDBdata',
1819 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
1820 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
1823 $unsetResult = TRUE;
1825 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
1828 if (!$unsetResult) {
1829 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
1830 $res['value'] = implode(',', $newVal);
1832 unset($res['value']);
1838 * Applies the filter methods from a column's TCA configuration to a value array.
1840 * @param array $tcaFieldConfiguration
1841 * @param array $values
1842 * @return array|mixed
1843 * @throws \RuntimeException
1845 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values) {
1846 if (empty($tcaFieldConfiguration['filter']) ||
!is_array($tcaFieldConfiguration['filter'])) {
1849 foreach ($tcaFieldConfiguration['filter'] as $filter) {
1850 if (empty($filter['userFunc'])) {
1853 $parameters = $filter['parameters'] ?
: array();
1854 $parameters['values'] = $values;
1855 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
1856 $values = GeneralUtility
::callUserFunction($filter['userFunc'], $parameters, $this);
1857 if (!is_array($values)) {
1858 throw new \
RuntimeException('Failed calling filter userFunc.', 1336051942);
1865 * Handling files for group/select function
1867 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
1868 * @param array $tcaFieldConf Configuration array from TCA of the field
1869 * @param string $curValue Current value of the field
1870 * @param array $uploadedFileArray Array of uploaded files, if any
1871 * @param string $status Status ("update" or ?)
1872 * @param string $table tablename of record
1873 * @param int $id UID of record
1874 * @param string $recFID Field identifier ([table:uid:field:....more for flexforms?]
1875 * @return array Modified value array
1876 * @see checkValue_group_select()
1878 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
1879 // If file handling should NOT be bypassed, do processing:
1880 if (!$this->bypassFileHandling
) {
1881 // If any files are uploaded, add them to value array
1882 // Numeric index means that there are multiple files
1883 if (isset($uploadedFileArray[0])) {
1884 $uploadedFiles = $uploadedFileArray;
1886 // There is only one file
1887 $uploadedFiles = array($uploadedFileArray);
1889 foreach ($uploadedFiles as $uploadedFileArray) {
1890 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
1891 $valueArray[] = $uploadedFileArray['tmp_name'];
1892 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1895 // Creating fileFunc object.
1896 if (!$this->fileFunc
) {
1897 $this->fileFunc
= GeneralUtility
::makeInstance(BasicFileUtility
::class);
1898 $this->include_filefunctions
= 1;
1900 // Setting permitted extensions.
1901 $all_files = array();
1902 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1903 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?
: '*';
1904 $all_files['ftpspace'] = $all_files['webspace'];
1905 $this->fileFunc
->init('', $all_files);
1907 // If there is an upload folder defined:
1908 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
1909 // If filehandling should NOT be bypassed, do processing:
1910 if (!$this->bypassFileHandling
) {
1912 $propArr = $this->getRecordProperties($table, $id);
1913 // Get destrination path:
1914 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1915 // If we are updating:
1916 if ($status == 'update') {
1917 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
1918 // 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!
1919 // 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_.
1920 // 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.
1921 // Illustration of the problem comes here:
1922 // 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.
1923 // 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.
1924 // 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.
1925 // 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.
1926 if ($this->autoVersioningUpdate
=== TRUE) {
1927 foreach ($valueArray as $key => $theFile) {
1928 // If it is an already attached file...
1929 if ($theFile === basename($theFile)) {
1930 $valueArray[$key] = PATH_site
. $tcaFieldConf['uploadfolder'] . '/' . $theFile;
1934 // Finding the CURRENT files listed, either from MM or from the current record.
1935 $theFileValues = array();
1936 // If MM relations for the files also!
1937 if ($tcaFieldConf['MM']) {
1938 $dbAnalysis = $this->createRelationHandlerInstance();
1939 /** @var $dbAnalysis RelationHandler */
1940 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
1941 foreach ($dbAnalysis->itemArray
as $item) {
1943 $theFileValues[] = $item['id'];
1947 $theFileValues = GeneralUtility
::trimExplode(',', $curValue, TRUE);
1949 $currentFilesForHistory = implode(',', $theFileValues);
1950 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1951 if (count($theFileValues)) {
1952 // 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!)
1953 foreach ($valueArray as $key => $theFile) {
1954 if ($theFile && !strstr(GeneralUtility
::fixWindowsFilePath($theFile), '/')) {
1955 $theFileValues = ArrayUtility
::removeArrayEntryByValue($theFileValues, $theFile);
1958 // This array contains the filenames in the uploadfolder that should be deleted:
1959 foreach ($theFileValues as $key => $theFile) {
1960 $theFile = trim($theFile);
1961 if (@is_file
(($dest . '/' . $theFile))) {
1962 $this->removeFilesStore
[] = $dest . '/' . $theFile;
1963 } elseif ($theFile) {
1964 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
1969 // Traverse the submitted values:
1970 foreach ($valueArray as $key => $theFile) {
1972 $maxSize = (int)$tcaFieldConf['max_size'];
1973 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1975 // a FAL file was added, now resolve the file object and get the absolute path
1976 // @todo in future versions this needs to be modified to handle FAL objects natively
1977 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
1978 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
1979 $theFile = $fileObject->getForLocalProcessing(FALSE);
1981 // NEW FILES? If the value contains '/' it indicates, that the file
1982 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1983 if (strstr(GeneralUtility
::fixWindowsFilePath($theFile), '/')) {
1984 // Check various things before copying file:
1985 // File and destination must exist
1986 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) {
1988 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
1989 $fileSize = $uploadedFileArray['size'];
1991 $fileSize = filesize($theFile);
1994 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
1995 // Prepare filename:
1996 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
1997 $fI = GeneralUtility
::split_fileref($theEndFileName);
1998 // Check for allowed extension:
1999 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2000 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
2001 // If we have a unique destination filename, then write the file:
2003 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2004 // Hook for post-processing the upload action
2005 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2006 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2007 $hookObject = GeneralUtility
::getUserObj($classRef);
2008 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface
) {
2009 throw new \
UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
2011 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2014 $this->copiedFileMap
[$theFile] = $theDestFile;
2016 if (!@is_file
($theDestFile)) {
2017 $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, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
2020 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
2023 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2026 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility
::formatSize($fileSize), $theFile, GeneralUtility
::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
2029 $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, array($dest, $theFile, $recFID), $propArr['event_pid']);
2031 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2032 if (@is_file
($theDestFile)) {
2033 $info = GeneralUtility
::split_fileref($theDestFile);
2034 // The value is set to the new filename
2035 $valueArray[$key] = $info['file'];
2037 // The value is set to the new filename
2038 unset($valueArray[$key]);
2043 // 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!
2044 if ($tcaFieldConf['MM']) {
2045 /** @var $dbAnalysis RelationHandler */
2046 $dbAnalysis = $this->createRelationHandlerInstance();
2048 $dbAnalysis->tableArray
['files'] = array();
2049 foreach ($valueArray as $key => $theFile) {
2051 $dbAnalysis->itemArray
[]['id'] = $theFile;
2053 if ($status == 'update') {
2054 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2055 $newFiles = implode(',', $dbAnalysis->getValueArray());
2056 list(, , $recFieldName) = explode(':', $recFID);
2057 if ($currentFilesForHistory != $newFiles) {
2058 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2059 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2061 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2062 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2065 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
2067 $valueArray = $dbAnalysis->countItems();
2070 if (count($valueArray)) {
2071 // If filehandling should NOT be bypassed, do processing:
2072 if (!$this->bypassFileHandling
) {
2074 $propArr = $this->getRecordProperties($table, $id);
2075 foreach ($valueArray as &$theFile) {
2076 // FAL handling: it's a UID, thus it is resolved to the absolute path
2077 if (!empty($theFile) && MathUtility
::canBeInterpretedAsInteger($theFile)) {
2078 $fileObject = ResourceFactory
::getInstance()->getFileObject($theFile);
2079 $theFile = $fileObject->getForLocalProcessing(FALSE);
2081 if ($this->alternativeFilePath
[$theFile]) {
2082 // If alternative File Path is set for the file, then it was an import
2083 // don't import the file if it already exists
2084 if (@is_file
((PATH_site
. $this->alternativeFilePath
[$theFile]))) {
2085 $theFile = PATH_site
. $this->alternativeFilePath
[$theFile];
2086 } elseif (@is_file
($theFile)) {
2087 $dest = dirname(PATH_site
. $this->alternativeFilePath
[$theFile]);
2088 if (!@is_dir
($dest)) {
2089 GeneralUtility
::mkdir_deep(PATH_site
, dirname($this->alternativeFilePath
[$theFile]) . '/');
2092 $maxSize = (int)$tcaFieldConf['max_size'];
2093 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2095 $fileSize = filesize($theFile);
2097 if (!$maxSize ||
$fileSize <= $maxSize * 1024) {
2098 // Prepare filename:
2099 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
2100 $fI = GeneralUtility
::split_fileref($theEndFileName);
2101 // Check for allowed extension:
2102 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2103 $theDestFile = PATH_site
. $this->alternativeFilePath
[$theFile];
2106 GeneralUtility
::upload_copy_move($theFile, $theDestFile);
2107 $this->copiedFileMap
[$theFile] = $theDestFile;
2109 if (!@is_file
($theDestFile)) {
2110 $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, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
2113 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
2116 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2119 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility
::formatSize($fileSize), $theFile, GeneralUtility
::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
2121 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2122 if (@is_file
($theDestFile)) {
2123 // The value is set to the new filename
2124 $theFile = $theDestFile;
2126 // The value is set to the new filename
2131 $theFile = GeneralUtility
::fixWindowsFilePath($theFile);
2132 if (GeneralUtility
::isFirstPartOfStr($theFile, PATH_site
)) {
2133 $theFile = \TYPO3\CMS\Core\Utility\PathUtility
::stripPathSitePrefix($theFile);
2144 * Evaluates 'flex' type values.
2146 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2147 * @param string $value The value to set.
2148 * @param array $tcaFieldConf Field configuration from TCA
2149 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2150 * @param array $uploadedFiles Uploaded files for the field
2151 * @param string $field Field name
2152 * @return array Modified $res array
2154 public function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
2155 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2157 if (is_array($value)) {
2158 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2159 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that
2160 // sake, the BackendUtility::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter.
2161 // Only active when larger than zero.
2162 $newRecordPidValue = $status == 'new' ?
$realPid : 0;
2163 // Get current value array:
2164 $dataStructArray = BackendUtility
::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord
, $table, $field, TRUE, $newRecordPidValue);
2165 $currentValueArray = (string)$curValue !== '' ? GeneralUtility
::xml2array($curValue) : array();
2166 if (!is_array($currentValueArray)) {
2167 $currentValueArray = array();
2169 if (is_array($currentValueArray['meta']['currentLangId'])) {
2170 unset($currentValueArray['meta']['currentLangId']);
2172 // Remove all old meta for languages...
2173 // Evaluation of input values:
2174 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
2175 // Create XML from input value:
2176 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
2178 // 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
2179 // (provided that the current value was already stored IN the charset that the new value is converted to).
2180 $arrValue = GeneralUtility
::xml2array($xmlValue);
2182 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2183 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2184 $hookObject = GeneralUtility
::getUserObj($classRef);
2185 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2186 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2191 ArrayUtility
::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2192 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, TRUE);
2194 // Action commands (sorting order and removals of elements) for flexform sections,
2195 // see FormEngine for the use of this GP parameter
2196 $actionCMDs = GeneralUtility
::_GP('_ACTION_FLEX_FORMdata');
2197 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2198 $arrValue = GeneralUtility
::xml2array($xmlValue);
2199 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2200 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
2202 // Create the value XML:
2204 $res['value'] .= $xmlValue;
2207 $res['value'] = $value;
2214 * Converts an array to FlexForm XML
2216 * @param array $array Array with FlexForm data
2217 * @param bool $addPrologue If set, the XML prologue is returned as well.
2218 * @return string Input array converted to XML
2220 public function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
2221 /** @var $flexObj FlexFormTools */
2222 $flexObj = GeneralUtility
::makeInstance(FlexFormTools
::class);
2223 return $flexObj->flexArray2Xml($array, $addPrologue);
2227 * Actions for flex form element (move, delete)
2228 * allows to remove and move flexform sections
2230 * @param array $valueArray by reference
2231 * @param array $actionCMDs
2233 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
2234 if (is_array($valueArray) && is_array($actionCMDs)) {
2235 foreach ($actionCMDs as $key => $value) {
2236 if ($key == '_ACTION') {
2237 // First, check if there are "commands":
2238 if (current($actionCMDs[$key]) !== '') {
2239 asort($actionCMDs[$key]);
2240 $newValueArray = array();
2241 foreach ($actionCMDs[$key] as $idx => $order) {
2242 if (substr($idx, 0, 3) == 'ID-') {
2243 $idx = $this->newIndexMap
[$idx];
2245 // 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.
2246 if ($order != 'DELETE') {
2247 $newValueArray[$idx] = $valueArray[$idx];
2249 unset($valueArray[$idx]);
2251 $valueArray = $valueArray +
$newValueArray;
2253 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2254 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2261 * Evaluates 'inline' type values.
2262 * (partly copied from the select_group function on this issue)
2264 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2265 * @param string $value The value to set.
2266 * @param array $tcaFieldConf Field configuration from TCA
2267 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2268 * @param string $field Field name
2269 * @param array $additionalData Additional data to be forwarded to sub-processors
2270 * @return array Modified $res array
2272 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = NULL) {
2273 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2274 if (!$tcaFieldConf['foreign_table']) {
2275 // Fatal error, inline fields should always have a foreign_table defined
2278 // When values are sent they come as comma-separated values which are exploded by this function:
2279 $valueArray = GeneralUtility
::trimExplode(',', $value);
2280 // Remove duplicates: (should not be needed)
2281 $valueArray = array_unique($valueArray);
2282 // Example for received data:
2283 // $value = 45,NEW4555fdf59d154,12,123
2284 // We need to decide whether we use the stack or can save the relation directly.
2285 if (strpos($value, 'NEW') !== FALSE ||
!MathUtility
::canBeInterpretedAsInteger($id)) {
2286 $this->remapStackRecords
[$table][$id] = array('remapStackIndex' => count($this->remapStack
));
2287 $this->addNewValuesToRemapStackChildIds($valueArray);
2288 $this->remapStack
[] = array(
2289 'func' => 'checkValue_inline_processDBdata',
2290 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData),
2291 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
2292 'additionalData' => $additionalData,
2295 unset($res['value']);
2296 } elseif ($value || MathUtility
::canBeInterpretedAsInteger($id)) {
2297 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2303 * Checks if a fields has more items than defined via TCA in maxitems.
2304 * If there are more items than allowd, the item list is truncated to the defined number.
2306 * @param array $tcaFieldConf Field configuration from TCA
2307 * @param array $valueArray Current value array of items
2308 * @return array The truncated value array of items
2310 public function checkValue_checkMax($tcaFieldConf, $valueArray) {
2311 // 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...
2312 $valueArrayC = count($valueArray);
2313 // 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.
2314 $maxI = isset($tcaFieldConf['maxitems']) ?
(int)$tcaFieldConf['maxitems'] : 1;
2315 if ($valueArrayC > $maxI) {
2316 $valueArrayC = $maxI;
2318 // Checking for not too many elements
2319 // Dumping array to list
2321 foreach ($valueArray as $nextVal) {
2322 if ($valueArrayC == 0) {
2326 $newVal[] = $nextVal;
2331 /*********************************************
2333 * Helper functions for evaluation functions.
2335 ********************************************/
2337 * Gets a unique value for $table/$id/$field based on $value
2339 * @param string $table Table name
2340 * @param string $field Field name for which $value must be unique
2341 * @param string $value Value string.
2342 * @param int $id UID to filter out in the lookup (the record itself...)
2343 * @param int $newPid If set, the value will be unique for this PID
2344 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2346 public function getUnique($table, $field, $value, $id, $newPid = 0) {
2351 $whereAdd .= ' AND pid=' . (int)$newPid;
2353 $whereAdd .= ' AND pid>=0';
2355 // "AND pid>=0" for versioning
2356 $whereAdd .= $this->deleteClause($table);
2357 // If the field is configured in TCA, proceed:
2358 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2359 // Look for a record which might already have the value:
2360 $res = $this->databaseConnection
->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection
->fullQuoteStr($value, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2362 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2363 while ($this->databaseConnection
->sql_num_rows($res)) {
2364 $newValue = $value . $counter;
2365 $res = $this->databaseConnection
->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection
->fullQuoteStr($newValue, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2367 if ($counter > 100) {
2371 $this->databaseConnection
->sql_free_result($res);
2372 // If the new value is there:
2373 $value = $newValue !== '' ?
$newValue : $value;
2379 * gets all records that have the same value in a field
2380 * excluding the given uid
2382 * @param string $tableName Table name
2383 * @param int $uid UID to filter out in the lookup (the record itself...)
2384 * @param string $fieldName Field name for which $value must be unique
2385 * @param string $value Value string.
2386 * @param int $pageId If set, the value will be unique for this PID
2389 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0) {
2391 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2394 $pageId = (int)$pageId;
2395 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ?
'pid = ' . $pageId : 'pid >= 0');
2396 $result = BackendUtility
::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2402 * @param string $value The field value to be evaluated
2403 * @param array $evalArray Array of evaluations to traverse.
2404 * @param string $is_in The "is_in" value of the field configuration from TCA
2407 public function checkValue_text_Eval($value, $evalArray, $is_in) {
2410 foreach ($evalArray as $func) {
2413 $value = trim($value);
2421 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2424 $evalObj = GeneralUtility
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2425 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2426 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2431 $res['value'] = $value;
2437 * Evaluation of 'input'-type values based on 'eval' list
2439 * @param string $value Value to evaluate
2440 * @param array $evalArray Array of evaluations to traverse.
2441 * @param string $is_in Is-in string for 'is_in' evaluation
2442 * @return array Modified $value in key 'value' or empty array
2444 public function checkValue_input_Eval($value, $evalArray, $is_in) {
2447 foreach ($evalArray as $func) {
2453 $value = (int)$value;
2457 $value = (int)$value;
2458 if ($value > 0 && !$this->dontProcessTransformations
) {
2459 $value -= date('Z', $value);
2463 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2464 $negative = $value[0] === '-';
2465 $value = strtr($value, array(',' => '.', '-' => ''));
2466 if (strpos($value, '.') === FALSE) {
2469 $valueArray = explode('.', $value);
2470 $dec = array_pop($valueArray);
2471 $value = join('', $valueArray) . '.' . $dec;
2475 $value = number_format($value, 2, '.', '');
2478 if (strlen($value) != 32) {
2483 $value = trim($value);
2486 $value = $GLOBALS['LANG']->csConvObj
->conv_case($GLOBALS['LANG']->charSet
, $value, 'toUpper');
2489 $value = $GLOBALS['LANG']->csConvObj
->conv_case($GLOBALS['LANG']->charSet
, $value, 'toLower');
2492 if (!isset($value) ||
$value === '') {
2497 $c = strlen($value);
2500 for ($a = 0; $a < $c; $a++
) {
2501 $char = substr($value, $a, 1);
2502 if (strpos($is_in, $char) !== FALSE) {
2510 $value = str_replace(' ', '', $value);
2513 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2516 $value = preg_replace('/[^0-9]/', '', $value);
2519 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2522 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2525 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2526 $value = GeneralUtility
::idnaEncode($value);
2530 $this->checkValue_input_ValidateEmail($value, $set);
2533 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2536 $evalObj = GeneralUtility
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2537 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2538 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2543 $res['value'] = $value;
2549 * If $value is not a valid e-mail address,
2550 * $set will be set to false and a flash error
2551 * message will be added
2553 * @param string $value Value to evaluate
2554 * @param bool $set TRUE if an update should be done
2555 * @throws \InvalidArgumentException
2556 * @throws \TYPO3\CMS\Core\Exception
2559 protected function checkValue_input_ValidateEmail($value, &$set) {
2560 if (GeneralUtility
::validEmail($value)) {
2565 /** @var FlashMessage $message */
2566 $message = GeneralUtility
::makeInstance(FlashMessage
::class,
2567 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:error.invalidEmail'), $value),
2568 '', // header is optional
2569 FlashMessage
::ERROR
,
2570 TRUE // whether message should be stored in session
2572 /** @var $flashMessageService FlashMessageService */
2573 $flashMessageService = GeneralUtility
::makeInstance(FlashMessageService
::class);
2574 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2578 * Returns data for group/db and select fields
2580 * @param array $valueArray Current value array
2581 * @param array $tcaFieldConf TCA field config
2582 * @param int $id Record id, used for look-up of MM relations (local_uid)
2583 * @param string $status Status string ('update' or 'new')
2584 * @param string $type The type, either 'select', 'group' or 'inline'
2585 * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2586 * @param string $currentField field name, needs to be set for writing to sys_history
2587 * @return array Modified value array
2589 public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
2590 $tables = $type == 'group' ?
$tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'] . ',' . $tcaFieldConf['neg_foreign_table'];
2591 $prep = $type == 'group' ?
$tcaFieldConf['prepend_tname'] : $tcaFieldConf['neg_foreign_table'];
2592 $newRelations = implode(',', $valueArray);
2593 /** @var $dbAnalysis RelationHandler */
2594 $dbAnalysis = $this->createRelationHandlerInstance();
2595 $dbAnalysis->registerNonTableValues
= $tcaFieldConf['allowNonIdValues'] ?
1 : 0;
2596 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2597 if ($tcaFieldConf['MM']) {
2598 if ($status == 'update') {
2599 /** @var $oldRelations_dbAnalysis RelationHandler */
2600 $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2601 $oldRelations_dbAnalysis->registerNonTableValues
= $tcaFieldConf['allowNonIdValues'] ?
1 : 0;
2602 // Db analysis with $id will initialize with the existing relations
2603 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2604 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2605 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2606 if ($oldRelations != $newRelations) {
2607 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2608 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2610 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2611 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2614 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable);
2616 $valueArray = $dbAnalysis->countItems();
2618 $valueArray = $dbAnalysis->getValueArray($prep);
2619 if ($type == 'select' && $prep) {
2620 $valueArray = $dbAnalysis->convertPosNeg($valueArray, $tcaFieldConf['foreign_table'], $tcaFieldConf['neg_foreign_table']);
2623 // Here we should see if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
2628 * Explodes the $value, which is a list of files/uids (group select)
2630 * @param string $value Input string, comma separated values. For each part it will also be detected if a '|' is found and the first part will then be used if that is the case. Further the value will be rawurldecoded.
2631 * @return array The value array.
2633 public function checkValue_group_select_explodeSelectGroupValue($value) {
2634 $valueArray = GeneralUtility
::trimExplode(',', $value, TRUE);
2635 foreach ($valueArray as &$newVal) {
2636 $temp = explode('|', $newVal, 2);
2637 $newVal = str_replace(',', '', str_replace('|', '', rawurldecode($temp[0])));
2644 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2645 * See checkValue_flex_procInData_travDS() for more details.
2646 * WARNING: Currently, it traverses based on the actual _data_ array and NOT the _structure_. This means that values for non-valid fields, lKey/vKey/sKeys will be accepted! For traversal of data with a call back function you should rather use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools
2648 * @param array $dataPart The 'data' part of the INPUT flexform data
2649 * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2650 * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2651 * @param array $dataStructArray Data structure for the form (might be sheets or not). Only values in the data array which has a configuration in the data structure will be processed.
2652 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2653 * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS() DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2654 * @return array The modified 'data' part.
2655 * @see checkValue_flex_procInData_travDS()
2657 public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructArray, $pParams, $callBackFunc = '') {
2658 if (is_array($dataPart)) {
2659 foreach ($dataPart as $sKey => $sheetDef) {
2660 list($dataStruct, $actualSheet) = GeneralUtility
::resolveSheetDefInDS($dataStructArray, $sKey);
2661 if (is_array($dataStruct) && $actualSheet == $sKey && is_array($sheetDef)) {
2662 foreach ($sheetDef as $lKey => $lData) {
2663 $this->checkValue_flex_procInData_travDS($dataPart[$sKey][$lKey], $dataPart_current[$sKey][$lKey], $uploadedFiles[$sKey][$lKey], $dataStruct['ROOT']['el'], $pParams, $callBackFunc, $sKey . '/' . $lKey . '/');
2672 * Processing of the sheet/language data array
2673 * When it finds a field with a value the processing is done by ->checkValue_SW() by default but if a call back function name is given that method in this class will be called for the processing instead.
2675 * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2676 * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2677 * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2678 * @param array $DSelements Data structure which fits the data array
2679 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2680 * @param string $callBackFunc Call back function, default is checkValue_SW(). If $this->callBackObj is set to an object, the callback function in that object is called instead.
2681 * @param string $structurePath
2683 * @see checkValue_flex_procInData()
2685 public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath) {
2686 if (is_array($DSelements)) {
2687 // For each DS element:
2688 foreach ($DSelements as $key => $dsConf) {
2690 if ($DSelements[$key]['type'] == 'array') {
2691 if (is_array($dataValues[$key]['el'])) {
2692 if ($DSelements[$key]['section']) {
2693 $newIndexCounter = 0;
2694 foreach ($dataValues[$key]['el'] as $ik => $el) {
2695 if (is_array($el)) {
2696 if (!is_array($dataValues_current[$key]['el'])) {
2697 $dataValues_current[$key]['el'] = array();
2700 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2701 $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'][$ik][$theKey]['el'], is_array($dataValues_current[$key]['el'][$ik]) ?
$dataValues_current[$key]['el'][$ik][$theKey]['el'] : array(), $uploadedFiles[$key]['el'][$ik][$theKey]['el'], $DSelements[$key]['el'][$theKey]['el'