2 /***************************************************************
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains the TYPO3 Core Engine
30 * Revised for TYPO3 3.9 October 2005 by Kasper Skårhøj
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * This is the TYPO3 Core Engine class for manipulation of the database
37 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
40 * - $GLOBALS['TCA'] must exist
41 * - $GLOBALS['LANG'] must exist
43 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
45 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
52 // *********************
53 // Public variables you can configure before using the class:
54 // *********************
55 // Boolean: If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
56 var $storeLogMessages = TRUE;
57 // Boolean: If TRUE, actions are logged to sys_log.
58 var $enableLogging = TRUE;
59 // Boolean: If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
60 var $reverseOrder = FALSE;
61 // Boolean: If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array is similar, it's not saved then.
62 var $checkSimilar = TRUE;
63 // Boolean: If TRUE, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an unescaped data array instead. This switch may totally disappear in future versions of this class!
64 var $stripslashes_values = TRUE;
65 // Boolean: This will read the record after having updated or inserted it. If anything is not properly submitted an error is written to the log. This feature consumes extra time by selecting records
66 var $checkStoredRecords = TRUE;
67 // Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
68 var $checkStoredRecords_loose = TRUE;
69 // Boolean. If this is set, then a page is deleted by deleting the whole branch under it (user must have deletepermissions to it all). If not set, then the page is deleted ONLY if it has no branch
70 var $deleteTree = FALSE;
71 // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
72 var $neverHideAtCopy = FALSE;
73 // Boolean: If set, then transformations are NOT performed on the input.
74 var $dontProcessTransformations = FALSE;
75 // Boolean: If set, .vDEFbase values are unset in flexforms.
76 var $clear_flexFormData_vDEFbase = FALSE;
77 // Boolean/Mixed: TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value. FALSE: Will not update anything. "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
78 var $updateModeL10NdiffData = TRUE;
79 // Boolean: If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again! It's meant as the opposite of declaring the record translated.
80 var $updateModeL10NdiffDataClear = FALSE;
81 // Boolean: If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()). YOU MUST KNOW what you do if you use this feature!
82 var $bypassWorkspaceRestrictions = FALSE;
83 // Boolean: If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away. YOU MUST KNOW what you are doing with this feature!
84 var $bypassFileHandling = FALSE;
85 // Boolean: If TRUE, access check, check for deleted etc. for records is bypassed. YOU MUST KNOW what you are doing if you use this feature!
86 var $bypassAccessCheckForRecords = FALSE;
87 // String. Comma-list. This list of tables decides which tables will be copied. If empty then none will. If '*' then all will (that the user has permission to of course)
88 var $copyWhichTables = '*';
89 // Integer. If 0 then branch is NOT copied. If 1 then pages on the 1st level is copied. If 2 then pages on the second level is copied ... and so on
91 // Array [table][fields]=value: New records are created with default values and you can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
92 var $defaultValues = array();
93 // Array [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to override the incoming data. You must set this externally. You must make sure the fields in this array are also found in the table, because it's not checked. All columns can be set by this array!
94 var $overrideValues = array();
95 // Array [filename]=alternative_filename: Use this array to force another name onto a file. Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field, then 'my_file.txt' will be used as the name instead.
96 var $alternativeFileName = array();
97 // Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
98 var $alternativeFilePath = array();
99 // If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated. You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1. Then an empty checkbox will disable the field.
100 var $data_disableFields = array();
101 // Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)
102 var $suggestedInsertUids = array();
103 // Object. Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
107 // *********************
108 // Internal variables (mapping arrays) which can be used (read-only) from outside
109 // *********************
111 // Contains mapping of auto-versionized records.
112 var $autoVersionIdMap = array();
113 // 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
114 var $substNEWwithIDs = array();
115 // Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
116 var $substNEWwithIDs_table = array();
117 // Holds the tables and there the ids of newly created child records from IRRE
118 var $newRelatedIDs = array();
119 // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
120 var $copyMappingArray_merged = array();
121 // A map between input file name and final destination for files being attached to records.
122 var $copiedFileMap = array();
123 // Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
124 var $RTEmagic_copyIndex = array();
125 // Errors are collected in this variable.
126 var $errorLog = array();
128 // *********************
129 // Internal Variables, do not touch.
130 // *********************
132 // Variables set in init() function:
134 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
136 * @var t3lib_beUserAuth
139 // Will be set to uid of be_user executing this script
141 // Will be set to username of be_user executing this script
143 // Will be set if user is admin
145 // Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
146 var $defaultPermissions = array(
147 'user' => 'show,edit,delete,new,editcontent',
148 'group' => 'show,edit,new,editcontent',
151 // 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.
153 // Set with incoming data array
154 var $datamap = array();
155 // Set with incoming cmd array
156 var $cmdmap = array();
159 // Permission mapping
161 'show' => 1, // 1st bit
162 'edit' => 2, // 2nd bit
163 'delete' => 4, // 3rd bit
164 'new' => 8, // 4th bit
165 'editcontent' => 16 // 5th bit
167 // Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
168 var $sortIntervals = 256;
170 // Internal caching arrays
171 // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
172 var $recUpdateAccessCache = array();
173 // User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
174 var $recInsertAccessCache = array();
175 // Caching array for check of whether records are in a webmount
176 var $isRecordInWebMount_Cache = array();
177 // Caching array for page ids in webmounts
178 var $isInWebMount_Cache = array();
179 // Caching for collecting TSconfig for page ids
180 var $cachedTSconfig = array();
181 // Used for caching page records in pageInfo()
182 var $pageCache = array();
183 // Array caching workspace access for BE_USER
184 var $checkWorkspaceCache = array();
187 // For accumulation of MM relations that must be written after new records are created.
188 var $dbAnalysisStore = array();
189 // For accumulation of files which must be deleted after processing of all input content
190 var $removeFilesStore = array();
191 // Uploaded files, set by process_uploads()
192 var $uploadedFileArray = array();
193 // Used for tracking references that might need correction after operations
194 var $registerDBList = array();
195 // Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
196 var $registerDBPids = array();
197 // Used by the copy action to track the ids of new pages so subpages are correctly inserted! THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE! Read from copyMappingArray_merged instead which is accumulating this information.
198 var $copyMappingArray = array();
199 // array used for remapping uids and values at the end of process_datamap
200 var $remapStack = array();
201 // array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
202 var $remapStackRecords = array();
203 // array used for checking whether new children need to be remapped
204 protected $remapStackChildIds = array();
205 // array used for executing addition actions after remapping happened (sett processRemapStack())
206 protected $remapStackActions = array();
207 // array used for executing post-processing on the reference index
208 protected $remapStackRefIndex = array();
209 // array used for additional calls to $this->updateRefIndex
210 var $updateRefIndexStack = array();
211 // tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
212 var $callFromImpExp = FALSE;
213 // Array for new flexform index mapping
214 var $newIndexMap = array();
218 * basicFileFunctions object
219 * For "singleTon" file-manipulation object
221 * @var t3lib_basicFileFunctions
224 // Set to "currentRecord" during checking of values.
225 var $checkValue_currentRecord = array();
226 // A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
227 var $autoVersioningUpdate = FALSE;
228 // Disable delete clause
229 protected $disableDeleteClause = FALSE;
230 protected $checkModifyAccessListHookObjects;
231 protected $version_remapMMForVersionSwap_reg;
234 * The outer most instance of t3lib_TCEmain
235 * (t3lib_TCEmain instantiates itself on versioning and localization)
238 protected $outerMostInstance = NULL;
242 * For details, see 'TYPO3 Core API' document.
243 * This function does not start the processing of data, but merely initializes the object
245 * @param array $data Data to be modified or inserted in the database
246 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
247 * @param object $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
250 public function start($data, $cmd, $altUserObject = '') {
252 // Initializing BE_USER
253 $this->BE_USER
= is_object($altUserObject) ?
$altUserObject : $GLOBALS['BE_USER'];
254 $this->userid
= $this->BE_USER
->user
['uid'];
255 $this->username
= $this->BE_USER
->user
['username'];
256 $this->admin
= $this->BE_USER
->user
['admin'];
258 if ($this->BE_USER
->uc
['recursiveDelete']) {
259 $this->deleteTree
= 1;
262 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData
=== TRUE) {
263 $this->updateModeL10NdiffData
= FALSE;
266 // Initializing default permissions for pages
267 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
268 if (isset($defaultPermissions['user'])) {
269 $this->defaultPermissions
['user'] = $defaultPermissions['user'];
271 if (isset($defaultPermissions['group'])) {
272 $this->defaultPermissions
['group'] = $defaultPermissions['group'];
274 if (isset($defaultPermissions['everybody'])) {
275 $this->defaultPermissions
['everybody'] = $defaultPermissions['everybody'];
278 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
279 $this->exclude_array
= $this->admin ?
array() : $this->getExcludeListArray();
281 // Setting the data and cmd arrays
282 if (is_array($data)) {
284 $this->datamap
= $data;
286 if (is_array($cmd)) {
288 $this->cmdmap
= $cmd;
293 * Function that can mirror input values in datamap-array to other uid numbers.
294 * 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]
296 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
299 function setMirror($mirror) {
300 if (is_array($mirror)) {
301 foreach ($mirror as $table => $uid_array) {
302 if (isset($this->datamap
[$table])) {
303 foreach ($uid_array as $id => $uidList) {
304 if (isset($this->datamap
[$table][$id])) {
305 $theIdsInArray = t3lib_div
::trimExplode(',', $uidList, 1);
306 foreach ($theIdsInArray as $copyToUid) {
307 $this->datamap
[$table][$copyToUid] = $this->datamap
[$table][$id];
317 * Initializes default values coming from User TSconfig
319 * @param array $userTS User TSconfig array
322 function setDefaultsFromUserTS($userTS) {
323 if (is_array($userTS)) {
324 foreach ($userTS as $k => $v) {
325 $k = substr($k, 0, -1);
326 if ($k && is_array($v) && isset($GLOBALS['TCA'][$k])) {
327 if (is_array($this->defaultValues
[$k])) {
328 $this->defaultValues
[$k] = array_merge($this->defaultValues
[$k], $v);
330 $this->defaultValues
[$k] = $v;
338 * Processing of uploaded files.
339 * 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.
341 * @param array $postFiles $_FILES array
344 function process_uploads($postFiles) {
346 if (is_array($postFiles)) {
349 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
350 $this->newlog('All editing in this workspace has been frozen!', 1);
354 $subA = reset($postFiles);
355 if (is_array($subA)) {
356 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
357 // Initialize the uploadedFilesArray:
358 $this->uploadedFileArray
= array();
361 foreach ($subA as $key => $values) {
362 $this->process_uploads_traverseArray($this->uploadedFileArray
, $values, $key);
365 $this->uploadedFileArray
= $subA;
372 * Traverse the upload array if needed to rearrange values.
374 * @param array $outputArr $this->uploadedFileArray passed by reference
375 * @param array $inputArr Input array ($_FILES parts)
376 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
379 * @see process_uploads()
381 function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet) {
382 if (is_array($inputArr)) {
383 foreach ($inputArr as $key => $value) {
384 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
387 $outputArr[$keyToSet] = $inputArr;
391 /*********************************************
395 *********************************************/
398 * Hook: processDatamap_afterDatabaseOperations
399 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
401 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
402 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
404 * @param object $hookObjectsArr (reference) Array with hook objects
405 * @param string $status (reference) Status of the current operation, 'new' or 'update
406 * @param string $table (refrence) The table currently processing data for
407 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
408 * @param array $fieldArray (reference) The field array of a record
411 function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
412 // Process hook directly:
413 if (!isset($this->remapStackRecords
[$table][$id])) {
414 foreach ($hookObjectsArr as $hookObj) {
415 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
416 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
419 // If this record is in remapStack (e.g. when using IRRE), values will be updated/remapped later on. So the hook will also be called later:
421 $this->remapStackRecords
[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
423 'fieldArray' => $fieldArray,
424 'hookObjectsArr' => $hookObjectsArr,
430 * Gets the 'checkModifyAccessList' hook objects.
431 * The first call initializes the accordant objects.
433 * @return array The 'checkModifyAccessList' hook objects (if any)
435 protected function getCheckModifyAccessListHookObjects() {
436 if (!isset($this->checkModifyAccessListHookObjects
)) {
437 $this->checkModifyAccessListHookObjects
= array();
439 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
440 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
441 $hookObject = t3lib_div
::getUserObj($classData);
443 if (!($hookObject instanceof t3lib_TCEmain_checkModifyAccessListHook
)) {
444 throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
447 $this->checkModifyAccessListHookObjects
[] = $hookObject;
452 return $this->checkModifyAccessListHookObjects
;
455 /*********************************************
459 *********************************************/
462 * Processing the data-array
463 * Call this function to process the data-array set by start()
467 public function process_datamap() {
468 // Keep versionized(!) relations here locally:
469 $registerDBList = array();
471 $this->registerElementsToBeDeleted();
472 $this->datamap
= $this->unsetElementsToBeDeleted($this->datamap
);
475 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
476 $this->newlog('All editing in this workspace has been frozen!', 1);
480 // First prepare user defined objects (if any) for hooks which extend this function:
481 $hookObjectsArr = array();
482 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
483 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
484 $hookObject = t3lib_div
::getUserObj($classRef);
485 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
486 $hookObject->processDatamap_beforeStart($this);
488 $hookObjectsArr[] = $hookObject;
492 // 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.
493 $orderOfTables = array();
495 if (isset($this->datamap
['pages'])) {
496 $orderOfTables[] = 'pages';
498 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap
)));
500 // Process the tables...
501 foreach ($orderOfTables as $table) {
503 // - table is set in $GLOBALS['TCA'],
504 // - table is NOT readOnly
505 // - the table is set with content in the data-array (if not, there's nothing to process...)
506 // - permissions for tableaccess OK
507 $modifyAccessList = $this->checkModifyAccessList($table);
508 if (!$modifyAccessList) {
510 $this->log($table, $id, 2, 0, 1, "Attempt to modify table '%s' without permission", 1, array($table));
512 if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->datamap
[$table]) && $modifyAccessList) {
513 if ($this->reverseOrder
) {
514 $this->datamap
[$table] = array_reverse($this->datamap
[$table], 1);
517 // For each record from the table, do:
518 // $id is the record uid, may be a string if new records...
519 // $incomingFieldArray is the array of fields
520 foreach ($this->datamap
[$table] as $id => $incomingFieldArray) {
521 if (is_array($incomingFieldArray)) {
522 // Handle native date/time fields
523 $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
524 if (!isset($GLOBALS['TCA'][$table]['columns'])) {
525 t3lib_div
::loadTCA($table);
527 foreach ($GLOBALS['TCA'][$table]['columns'] as $column => $config) {
528 if (isset($incomingFieldArray[$column])) {
529 if (isset($config['config']['dbType']) && t3lib_div
::inList('date,datetime', $config['config']['dbType'])) {
530 $emptyValue = $dateTimeFormats[$config['config']['dbType']]['empty'];
531 $format = $dateTimeFormats[$config['config']['dbType']]['format'];
532 $incomingFieldArray[$column] = $incomingFieldArray[$column] ?
date($format, $incomingFieldArray[$column]) : $emptyValue;
537 // Hook: processDatamap_preProcessFieldArray
538 foreach ($hookObjectsArr as $hookObj) {
539 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
540 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
544 // ******************************
545 // Checking access to the record
546 // ******************************
547 $createNewVersion = FALSE;
548 $recordAccess = FALSE;
550 $this->autoVersioningUpdate
= FALSE;
552 // Is it a new record? (Then Id is a string)
553 if (!t3lib_utility_Math
::canBeInterpretedAsInteger($id)) {
554 // Get a fieldArray with default values
555 $fieldArray = $this->newFieldArray($table);
556 // A pid must be set for new records.
557 if (isset($incomingFieldArray['pid'])) {
559 $pid_value = $incomingFieldArray['pid'];
561 // Checking and finding numerical pid, it may be a string-reference to another value
564 if (strstr($pid_value, 'NEW')) {
565 if (substr($pid_value, 0, 1) == '-') {
567 $pid_value = substr($pid_value, 1);
571 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
572 if (isset($this->substNEWwithIDs
[$pid_value])) {
573 if ($negFlag === 1) {
574 $old_pid_value = $this->substNEWwithIDs
[$pid_value];
576 $pid_value = intval($negFlag * $this->substNEWwithIDs
[$pid_value]);
579 } // If not found in the substArray we must stop the process...
581 $pid_value = intval($pid_value);
583 // The $pid_value is now the numerical pid at this point
585 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
586 // Points to a page on which to insert the element, possibly in the top of the page
587 if ($pid_value >= 0) {
588 // If this table is sorted we better find the top sorting number
590 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
592 // The numerical pid is inserted in the data array
593 $fieldArray['pid'] = $pid_value;
594 } else { // points to another record before ifself
595 // If this table is sorted we better find the top sorting number
597 // Because $pid_value is < 0, getSortNumber returns an array
598 $tempArray = $this->getSortNumber($table, 0, $pid_value);
599 $fieldArray['pid'] = $tempArray['pid'];
600 $fieldArray[$sortRow] = $tempArray['sortNumber'];
601 } else { // Here we fetch the PID of the record that we point to...
602 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
603 $fieldArray['pid'] = $tempdata['pid'];
608 $theRealPid = $fieldArray['pid'];
610 // Now, check if we may insert records on this pid.
611 if ($theRealPid >= 0) {
612 // Checks if records can be inserted on this $pid.
613 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
615 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
616 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $incomingFieldArray, TRUE);
617 if (!$recordAccess) {
618 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
619 } elseif (!$this->bypassWorkspaceRestrictions
) {
620 // Workspace related processing:
621 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
622 if ($res = $this->BE_USER
->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
624 $recordAccess = FALSE;
625 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
627 } else { // So, if no live records were allowed, we have to create a new version of this record:
628 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
629 $createNewVersion = TRUE;
631 $recordAccess = FALSE;
632 $this->newlog('Record could not be created in this workspace in this branch', 1);
638 debug('Internal ERROR: pid should not be less than zero!');
640 // Yes new record, change $record_status to 'insert'
642 } else { // Nope... $id is a number
643 $fieldArray = array();
644 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
645 if (!$recordAccess) {
646 $propArr = $this->getRecordProperties($table, $id);
647 $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']);
648 } else { // Next check of the record permissions (internals)
649 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table, $id);
650 if (!$recordAccess) {
651 $propArr = $this->getRecordProperties($table, $id);
652 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER
->errorMsg
. ']', 1);
653 } else { // Here we fetch the PID of the record that we point to...
654 $tempdata = $this->recordInfo($table, $id, 'pid' .
655 ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ?
',t3ver_wsid,t3ver_stage' : '')
657 $theRealPid = $tempdata['pid'];
659 // Use the new id of the versionized record we're trying to write to:
660 // (This record is a child record of a parent and has already been versionized.)
661 if ($this->autoVersionIdMap
[$table][$id]) {
662 // For the reason that creating a new version of this record, automatically
663 // created related child records (e.g. "IRRE"), update the accordant field:
664 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
666 // Use the new id of the copied/versionized record:
667 $id = $this->autoVersionIdMap
[$table][$id];
668 $recordAccess = TRUE;
669 $this->autoVersioningUpdate
= TRUE;
671 // Checking access in case of offline workspace:
672 } elseif (!$this->bypassWorkspaceRestrictions
&& $errorCode = $this->BE_USER
->workspaceCannotEditRecord($table, $tempdata)) {
673 $recordAccess = FALSE; // Versioning is required and it must be offline version!
675 // Check if there already is a workspace version
676 $WSversion = t3lib_BEfunc
::getWorkspaceVersionOfRecord($this->BE_USER
->workspace
, $table, $id, 'uid,t3ver_oid');
678 $id = $WSversion['uid'];
679 $recordAccess = TRUE;
681 // Auto-creation of version: In offline workspace, test if versioning is enabled and look for workspace version of input record. If there is no versionized record found we will create one and save to that.
682 } elseif ($this->BE_USER
->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
683 $tce = t3lib_div
::makeInstance('t3lib_TCEmain');
684 /** @var $tce t3lib_TCEmain */
685 $tce->stripslashes_values
= 0;
687 // Setting up command for creating a new version of the record:
689 $cmd[$table][$id]['version'] = array(
691 'treeLevels' => -1, // Default is to create a version of the individual records... element versioning that is.
692 'label' => 'Auto-created for WS #' . $this->BE_USER
->workspace
694 $tce->start(array(), $cmd);
695 $tce->process_cmdmap();
696 $this->errorLog
= array_merge($this->errorLog
, $tce->errorLog
);
698 // If copying was successful, share the new uids (also of related children):
699 if ($tce->copyMappingArray
[$table][$id]) {
700 foreach ($tce->copyMappingArray
as $origTable => $origIdArray) {
701 foreach ($origIdArray as $origId => $newId) {
702 $this->uploadedFileArray
[$origTable][$newId] = $this->uploadedFileArray
[$origTable][$origId];
703 $this->autoVersionIdMap
[$origTable][$origId] = $newId;
706 $this->RTEmagic_copyIndex
= t3lib_div
::array_merge_recursive_overrule($this->RTEmagic_copyIndex
, $tce->RTEmagic_copyIndex
); // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
708 // Update registerDBList, that holds the copied relations to child records:
709 $registerDBList = array_merge($registerDBList, $tce->registerDBList
);
710 // For the reason that creating a new version of this record, automatically
711 // created related child records (e.g. "IRRE"), update the accordant field:
712 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
714 // Use the new id of the copied/versionized record:
715 $id = $this->autoVersionIdMap
[$table][$id];
716 $recordAccess = TRUE;
717 $this->autoVersioningUpdate
= TRUE;
719 $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '" . $errorCode . "'). Auto-creation of version failed!", 1);
722 $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);
727 // The default is 'update'
731 // If access was granted above, proceed to create or update record:
733 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
734 list($tscPID) = t3lib_BEfunc
::getTSCpid($table, $id, $old_pid_value ?
$old_pid_value : $fieldArray['pid']);
735 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
736 if ($status == 'new' && $table == 'pages' && is_array($TSConfig['permissions.'])) {
737 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
739 if ($createNewVersion) {
740 $newVersion_placeholderFieldArray = $fieldArray;
743 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
744 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
746 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
748 // Forcing some values unto field array:
749 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
750 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
751 if ($createNewVersion) {
752 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
755 // Setting system fields
756 if ($status == 'new') {
757 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
758 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
759 if ($createNewVersion) {
760 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
763 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
764 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
765 if ($createNewVersion) {
766 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid
;
769 } elseif ($this->checkSimilar
) { // Removing fields which are equal to the current value:
770 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
772 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && count($fieldArray)) {
773 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
774 if ($createNewVersion) {
775 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
778 // Set stage to "Editing" to make sure we restart the workflow
779 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
780 $fieldArray['t3ver_stage'] = 0;
783 // Hook: processDatamap_postProcessFieldArray
784 foreach ($hookObjectsArr as $hookObj) {
785 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
786 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
790 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
791 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
792 if (is_array($fieldArray)) {
793 if ($status == 'new') {
794 // This creates a new version of the record with online placeholder and offline version
795 if ($createNewVersion) {
796 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
797 // Setting placeholder state value for temporary record
798 $newVersion_placeholderFieldArray['t3ver_state'] = 1;
799 // Setting workspace - only so display of place holders can filter out those from other workspaces.
800 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
801 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = '[PLACEHOLDER, WS#' . $this->BE_USER
->workspace
. ']';
802 // Saving placeholder as 'original'
803 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, FALSE);
805 // For the actual new offline version, set versioning values to point to placeholder:
806 $fieldArray['pid'] = -1;
807 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs
[$id];
808 $fieldArray['t3ver_id'] = 1;
809 // Setting placeholder state value for version (so it can know it is currently a new version...)
810 $fieldArray['t3ver_state'] = -1;
811 $fieldArray['t3ver_label'] = 'First draft version';
812 $fieldArray['t3ver_wsid'] = $this->BE_USER
->workspace
;
813 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
814 $phShadowId = $this->insertDB($table, $id, $fieldArray, TRUE, 0, TRUE);
816 // Processes fields of the placeholder record:
817 $this->triggerRemapAction(
820 array($this, 'placeholderShadowing'),
821 array($table, $phShadowId)
823 // Hold auto-versionized ids of placeholders:
824 $this->autoVersionIdMap
[$table][$this->substNEWwithIDs
[$id]] = $phShadowId;
827 $this->insertDB($table, $id, $fieldArray, FALSE, $incomingFieldArray['uid']);
830 $this->updateDB($table, $id, $fieldArray);
831 $this->placeholderShadowing($table, $id);
835 // Hook: processDatamap_afterDatabaseOperations
836 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
837 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
838 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
839 } // if ($recordAccess) {
840 } // if (is_array($incomingFieldArray)) {
845 // Process the stack of relations to remap/correct
846 $this->processRemapStack();
847 $this->dbAnalysisStoreExec();
848 $this->removeRegisteredFiles();
850 // Hook: processDatamap_afterAllOperations
851 // Note: When this hook gets called, all operations on the submitted data have been finished.
852 foreach ($hookObjectsArr as $hookObj) {
853 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
854 $hookObj->processDatamap_afterAllOperations($this);
858 if ($this->isOuterMostInstance()) {
859 $this->resetElementsToBeDeleted();
864 * Fix shadowing of data in case we are editing a offline version of a live "New" placeholder record:
866 * @param string $table Table name
867 * @param integer $id Record uid
870 function placeholderShadowing($table, $id) {
871 t3lib_div
::loadTCA($table);
872 if ($liveRec = t3lib_BEfunc
::getLiveVersionOfRecord($table, $id, '*')) {
873 if ((int) $liveRec['t3ver_state'] > 0) {
874 $justStoredRecord = t3lib_BEfunc
::getRecord($table, $id);
875 $newRecord = array();
877 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
878 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
879 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
880 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
881 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
883 $shadowColumns = array_unique(t3lib_div
::trimExplode(',', $shadowCols, 1));
884 foreach ($shadowColumns as $fieldName) {
885 if (strcmp($justStoredRecord[$fieldName], $liveRec[$fieldName])
886 && isset($GLOBALS['TCA'][$table]['columns'][$fieldName])
887 && $fieldName !== 'uid' && $fieldName !== 'pid') {
888 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
892 if (count($newRecord)) {
893 $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']);
894 $this->updateDB($table, $liveRec['uid'], $newRecord);
901 * Filling in the field array
902 * $this->exclude_array is used to filter fields if needed.
904 * @param string $table Table name
905 * @param integer $id Record ID
906 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
907 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
908 * @param integer $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.
909 * @param string $status Is 'new' or 'update'
910 * @param integer $tscPID TSconfig PID
911 * @return array Field Array
913 function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID) {
916 t3lib_div
::loadTCA($table);
917 $originalLanguageRecord = NULL;
918 $originalLanguage_diffStorage = NULL;
919 $diffStorageFlag = FALSE;
921 // Setting 'currentRecord' and 'checkValueRecord':
922 if (strstr($id, 'NEW')) {
923 // Must have the 'current' array - not the values after processing below...
924 $currentRecord = $checkValueRecord = $fieldArray;
926 // IF $incomingFieldArray is an array, overlay it.
927 // 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...
928 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
929 $checkValueRecord = t3lib_div
::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
932 // We must use the current values as basis for this!
933 $currentRecord = $checkValueRecord = $this->recordInfo($table, $id, '*');
934 // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
935 t3lib_BEfunc
::fixVersioningPid($table, $currentRecord);
937 // Get original language record if available:
938 if (is_array($currentRecord)
939 && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
940 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
941 && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
942 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
943 && intval($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]) > 0) {
945 $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ?
$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] : $table;
946 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
947 t3lib_BEfunc
::workspaceOL($lookUpTable, $originalLanguageRecord);
948 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
951 $this->checkValue_currentRecord
= $checkValueRecord;
953 // In the following all incoming value-fields are tested:
954 // - Are the user allowed to change the field?
955 // - Is the field uid/pid (which are already set)
956 // - perms-fields for pages-table, then do special things...
957 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
958 // If everything is OK, the field is entered into $fieldArray[]
959 foreach ($incomingFieldArray as $field => $fieldValue) {
960 if (!in_array($table . '-' . $field, $this->exclude_array
) && !$this->data_disableFields
[$table][$id][$field]) { // The field must be editable.
962 // Checking if a value for language can be changed:
963 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField']
964 && !strcmp($GLOBALS['TCA'][$table]['ctrl']['languageField'], $field)
965 && !$this->BE_USER
->checkLanguageAccess($fieldValue);
967 if (!$languageDeny) {
968 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
969 if ($this->stripslashes_values
) {
970 if (is_array($fieldValue)) {
971 t3lib_div
::stripSlashesOnArray($fieldValue);
973 $fieldValue = stripslashes($fieldValue);
980 // Nothing happens, already set
983 case 'perms_groupid':
986 case 'perms_everybody':
987 // Permissions can be edited by the owner or the administrator
988 if ($table == 'pages' && ($this->admin ||
$status == 'new' ||
$this->pageInfo($id, 'perms_userid') == $this->userid
)) {
989 $value = intval($fieldValue);
992 $fieldArray[$field] = $value;
994 case 'perms_groupid':
995 $fieldArray[$field] = $value;
998 if ($value >= 0 && $value < pow(2, 5)) {
999 $fieldArray[$field] = $value;
1011 case 't3ver_tstamp':
1012 // t3ver_label is not here because it CAN be edited as a regular field!
1015 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1016 // Evaluating the value
1017 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1018 if (isset($res['value'])) {
1019 $fieldArray[$field] = $res['value'];
1022 // Add the value of the original record to the diff-storage content:
1023 if ($this->updateModeL10NdiffData
&& $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1024 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ?
'' : $originalLanguageRecord[$field];
1025 $diffStorageFlag = TRUE;
1028 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1029 // 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.
1030 // 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.
1031 // 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.
1032 // 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 !
1033 if ($this->autoVersioningUpdate
=== TRUE) {
1034 if (is_array($this->RTEmagic_copyIndex
[$table][$id][$field])) {
1035 foreach ($this->RTEmagic_copyIndex
[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1036 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1041 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1042 // Allow value for original UID to pass by...
1043 $fieldArray[$field] = $fieldValue;
1047 } // Checking language.
1048 } // Check exclude fields / disabled fields...
1050 // Add diff-storage information:
1051 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1052 // 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...
1053 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1056 // Checking for RTE-transformations of fields:
1057 $types_fieldConfig = t3lib_BEfunc
::getTCAtypes($table, $currentRecord);
1058 $theTypeString = t3lib_BEfunc
::getTCAtypeValue($table, $currentRecord);
1059 if (is_array($types_fieldConfig)) {
1060 foreach ($types_fieldConfig as $vconf) {
1061 // Write file configuration:
1062 // inserted array_merge($currentRecord,$fieldArray) 170502
1063 $eFile = t3lib_parsehtml_proc
::evalWriteFile($vconf['spec']['static_write'], array_merge($currentRecord, $fieldArray));
1065 // RTE transformations:
1066 if (!$this->dontProcessTransformations
) {
1067 if (isset($fieldArray[$vconf['field']])) {
1068 // Look for transformation flag:
1069 switch ((string) $incomingFieldArray['_TRANSFORM_' . $vconf['field']]) {
1071 $RTEsetup = $this->BE_USER
->getTSConfig('RTE', t3lib_BEfunc
::getPagesTSconfig($tscPID));
1072 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1074 // Set alternative relative path for RTE images/links:
1075 $RTErelPath = is_array($eFile) ?
dirname($eFile['relEditFile']) : '';
1077 // Get RTE object, draw form and set flag:
1078 $RTEobj = t3lib_BEfunc
::RTEgetObj();
1079 if (is_object($RTEobj)) {
1080 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db', $fieldArray[$vconf['field']], $table, $vconf['field'], $currentRecord, $vconf['spec'], $thisConfig, $RTErelPath, $currentRecord['pid']);
1082 debug('NO RTE OBJECT FOUND!');
1089 // Write file configuration:
1090 if (is_array($eFile)) {
1091 $mixedRec = array_merge($currentRecord, $fieldArray);
1092 $SW_fileContent = t3lib_div
::getUrl($eFile['editFile']);
1093 $parseHTML = t3lib_div
::makeInstance('t3lib_parsehtml_proc');
1094 /** @var $parseHTML t3lib_parsehtml_proc */
1095 $parseHTML->init('', '');
1097 $eFileMarker = $eFile['markerField'] && trim($mixedRec[$eFile['markerField']]) ?
trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
1098 // Must replace the marker if present in content!
1099 $insertContent = str_replace($eFileMarker, '', $mixedRec[$eFile['contentField']]);
1101 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, LF
. $insertContent . LF
, 1, 1);
1102 t3lib_div
::writeFile($eFile['editFile'], $SW_fileNewContent);
1105 if (!strstr($id, 'NEW') && $eFile['statusField']) {
1106 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
1108 'uid=' . intval($id),
1110 $eFile['statusField'] => $eFile['relEditFile'] . ' updated ' . date('d-m-Y H:i:s') . ', bytes ' . strlen($mixedRec[$eFile['contentField']])
1114 } elseif ($eFile && is_string($eFile)) {
1115 $this->log($table, $id, 2, 0, 1, "Write-file error: '%s'", 13, array($eFile), $realPid);
1119 // Return fieldArray
1123 /*********************************************
1125 * Evaluation of input values
1127 ********************************************/
1130 * Evaluates a value according to $table/$field settings.
1131 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1132 * 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() )
1134 * @param string $table Table name
1135 * @param string $field Field name
1136 * @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.
1137 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1138 * @param string $status 'update' or 'new' flag
1139 * @param integer $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.
1140 * @param integer $tscPID tscPID
1141 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1143 function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID) {
1144 t3lib_div
::loadTCA($table);
1147 $recFID = $table . ':' . $id . ':' . $field;
1149 // Processing special case of field pages.doktype
1150 if (($table === 'pages' ||
$table === 'pages_language_overlay') && $field === 'doktype') {
1151 // If the user may not use this specific doktype, we issue a warning
1152 if (!($this->admin || t3lib_div
::inList($this->BE_USER
->groupData
['pagetypes_select'], $value))) {
1153 $propArr = $this->getRecordProperties($table, $id);
1154 $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']);
1157 if ($status == 'update') {
1158 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1159 $onlyAllowedTables = (isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'])
1160 ?
$GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']
1161 : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables']);
1162 if ($onlyAllowedTables) {
1163 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1164 if ($theWrongTables) {
1165 $propArr = $this->getRecordProperties($table, $id);
1166 $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']);
1173 // Get current value:
1174 $curValueRec = $this->recordInfo($table, $id, $field);
1175 $curValue = $curValueRec[$field];
1177 // Getting config for the field
1178 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1180 // Preform processing:
1181 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray
[$table][$id][$field], $tscPID);
1187 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1188 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1190 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1191 * @param string $value The value to set.
1192 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1193 * @param string $table Table name
1194 * @param integer $id Return UID
1195 * @param [type] $curValue
1196 * @param [type] $status
1197 * @param integer $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.
1198 * @param [type] $recFID
1199 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1200 * @param [type] $uploadedFiles
1201 * @param [type] $tscPID
1202 * @return array Returns the evaluated $value as key "value" in this array.
1204 function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID) {
1206 $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
1208 switch ($tcaFieldConf['type']) {
1210 $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
1214 $res['value'] = $value;
1217 $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
1220 $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP);
1223 $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
1227 $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1230 $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field);
1233 // FlexForms are only allowed for real fields.
1235 $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1246 * Evaluate "text" type values.
1248 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1249 * @param string $value The value to set.
1250 * @param array $tcaFieldConf Field configuration from TCA
1251 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1252 * @param string $field Field name
1253 * @return array Modified $res array
1255 function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1256 $evalCodesArray = t3lib_div
::trimExplode(',', $tcaFieldConf['eval'], 1);
1257 $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1262 * Evaluate "input" type values.
1264 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1265 * @param string $value The value to set.
1266 * @param array $tcaFieldConf Field configuration from TCA
1267 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1268 * @param string $field Field name
1269 * @return array Modified $res array
1271 function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1272 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1274 // Handle native date/time fields
1275 $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
1276 if (isset($tcaFieldConf['dbType']) && t3lib_div
::inList('date,datetime', $tcaFieldConf['dbType'])) {
1277 // Convert the date/time into a timestamp for the sake of the checks
1278 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1279 $timeOffset = $tcaFieldConf['dbType'] === 'date' ?
3600 * $GLOBALS['TYPO3_CONF_VARS']['SYS']['serverTimeZone'] : 0;
1280 $value = $value === $emptyValue ?
0 : strtotime($value) +
$timeOffset;
1283 // Secures the string-length to be less than max.
1284 if (intval($tcaFieldConf['max']) > 0) {
1285 $value = $GLOBALS['LANG']->csConvObj
->substr($GLOBALS['LANG']->charSet
, $value, 0, intval($tcaFieldConf['max']));
1288 // Checking range of value:
1289 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && intval($value) !== intval($tcaFieldConf['default'])) {
1290 if (isset($tcaFieldConf['range']['upper']) && $value > $tcaFieldConf['range']['upper']) {
1291 $value = $tcaFieldConf['range']['upper'];
1293 if (isset($tcaFieldConf['range']['lower']) && $value < $tcaFieldConf['range']['lower']) {
1294 $value = $tcaFieldConf['range']['lower'];
1298 // Process evaluation settings:
1299 $evalCodesArray = t3lib_div
::trimExplode(',', $tcaFieldConf['eval'], 1);
1300 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1302 // Process UNIQUE settings:
1303 // 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...
1304 if ($field && $realPid >= 0) {
1305 if ($res['value'] && in_array('uniqueInPid', $evalCodesArray)) {
1306 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1308 if ($res['value'] && in_array('unique', $evalCodesArray)) {
1309 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1313 // Handle native date/time fields
1314 if (isset($tcaFieldConf['dbType']) && t3lib_div
::inList('date,datetime', $tcaFieldConf['dbType'])) {
1315 // Convert the timestamp back to a date/time
1316 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1317 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1318 $res['value'] = $res['value'] ?
date($format, $res['value']) : $emptyValue;
1325 * Evaluates 'check' type values.
1327 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1328 * @param string $value The value to set.
1329 * @param array $tcaFieldConf Field configuration from TCA
1330 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1331 * @return array Modified $res array
1333 function checkValue_check($res, $value, $tcaFieldConf, $PP) {
1334 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1336 $itemC = count($tcaFieldConf['items']);
1340 $maxV = pow(2, $itemC);
1345 if ($value > $maxV) {
1348 $res['value'] = $value;
1354 * Evaluates 'radio' type values.
1356 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1357 * @param string $value The value to set.
1358 * @param array $tcaFieldConf Field configuration from TCA
1359 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1360 * @return array Modified $res array
1362 function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1363 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1365 if (is_array($tcaFieldConf['items'])) {
1366 foreach ($tcaFieldConf['items'] as $set) {
1367 if (!strcmp($set[1], $value)) {
1368 $res['value'] = $value;
1378 * Evaluates 'group' or 'select' type values.
1380 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1381 * @param string $value The value to set.
1382 * @param array $tcaFieldConf Field configuration from TCA
1383 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1384 * @param array $uploadedFiles
1385 * @param string $field Field name
1386 * @return array Modified $res array
1388 function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1390 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1392 // Detecting if value sent is an array and if so, implode it around a comma:
1393 if (is_array($value)) {
1394 $value = implode(',', $value);
1397 // This converts all occurencies of '{' to the byte 123 in the string - this is needed in very rare cases where filenames with special characters (like ???, umlaud etc) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
1398 // Anyways, this should NOT disturb anything else:
1399 $value = $this->convNumEntityToByteValue($value);
1401 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1402 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1404 // If not multiple is set, then remove duplicates:
1405 if (!$tcaFieldConf['multiple']) {
1406 $valueArray = array_unique($valueArray);
1409 // If an exclusive key is found, discard all others:
1410 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1411 $exclusiveKeys = t3lib_div
::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1412 foreach ($valueArray as $kk => $vv) {
1413 // $vv is the item key!
1414 if (in_array($vv, $exclusiveKeys)) {
1415 $valueArray = array($kk => $vv);
1421 // This could be a good spot for parsing the array through a validation-function which checks if the values are alright (except that database references are not in their final form - but that is the point, isn't it?)
1422 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1424 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1426 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1427 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1428 $preCount = count($valueArray);
1429 foreach ($valueArray as $kk => $vv) {
1430 if (!$this->BE_USER
->checkAuthMode($table, $field, $vv, $tcaFieldConf['authMode'])) {
1431 unset($valueArray[$kk]);
1435 // 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.
1436 if ($preCount && !count($valueArray)) {
1442 if ($tcaFieldConf['type'] == 'group') {
1443 switch ($tcaFieldConf['internal_type']) {
1444 case 'file_reference':
1446 $valueArray = $this->checkValue_group_select_file(
1458 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
1462 // For select types which has a foreign table attached:
1463 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
1464 // check, if there is a NEW... id in the value, that should be substituded later
1465 if (strpos($value, 'NEW') !== FALSE) {
1466 $this->remapStackRecords
[$table][$id] = array('remapStackIndex' => count($this->remapStack
));
1467 $this->addNewValuesToRemapStackChildIds($valueArray);
1468 $this->remapStack
[] = array(
1469 'func' => 'checkValue_group_select_processDBdata',
1470 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
1471 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
1474 $unsetResult = TRUE;
1476 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
1480 if (!$unsetResult) {
1481 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
1482 $res['value'] = implode(',', $newVal);
1484 unset($res['value']);
1491 * Applies the filter methods from a column's TCA configuration to a value array.
1493 * @param array $tcaFieldConfiguration
1494 * @param array $values
1495 * @return array|mixed
1496 * @throws RuntimeException
1498 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values) {
1499 if (empty($tcaFieldConfiguration['filter']) ||
!is_array($tcaFieldConfiguration['filter'])) {
1503 foreach ($tcaFieldConfiguration['filter'] as $filter) {
1504 if (empty($filter['userFunc'])) {
1508 $parameters = $filter['parameters'] ?
$filter['parameters'] : array();
1509 $parameters['values'] = $values;
1510 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
1511 $values = t3lib_div
::callUserFunction($filter['userFunc'], $parameters, $this);
1513 if (!is_array($values)) {
1514 throw new RuntimeException('Failed calling filter userFunc.', 1336051942);
1521 * Handling files for group/select function
1523 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
1524 * @param array $tcaFieldConf Configuration array from TCA of the field
1525 * @param string $curValue Current value of the field
1526 * @param array $uploadedFileArray Array of uploaded files, if any
1527 * @param string $status Status ("update" or ?)
1528 * @param string $table tablename of record
1529 * @param integer $id UID of record
1530 * @param string $recFID Field identifier ([table:uid:field:....more for flexforms?]
1531 * @return array Modified value array
1532 * @see checkValue_group_select()
1534 function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
1536 // If file handling should NOT be bypassed, do processing:
1537 if (!$this->bypassFileHandling
) {
1539 // If any files are uploaded, add them to value array
1541 // Numeric index means that there are multiple files
1542 if (isset($uploadedFileArray[0])) {
1543 $uploadedFiles = $uploadedFileArray;
1545 // There is only one file
1546 $uploadedFiles = array($uploadedFileArray);
1548 foreach ($uploadedFiles as $uploadedFileArray) {
1549 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
1550 $valueArray[] = $uploadedFileArray['tmp_name'];
1551 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1555 // Creating fileFunc object.
1556 if (!$this->fileFunc
) {
1557 $this->fileFunc
= t3lib_div
::makeInstance('t3lib_basicFileFunctions');
1558 $this->include_filefunctions
= 1;
1560 // Setting permitted extensions.
1561 $all_files = array();
1562 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1563 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?
$tcaFieldConf['disallowed'] : '*';
1564 $all_files['ftpspace'] = $all_files['webspace'];
1565 $this->fileFunc
->init('', $all_files);
1568 // If there is an upload folder defined:
1569 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
1570 // If filehandling should NOT be bypassed, do processing:
1571 if (!$this->bypassFileHandling
) {
1573 $propArr = $this->getRecordProperties($table, $id);
1575 // Get destrination path:
1576 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1578 // If we are updating:
1579 if ($status == 'update') {
1581 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
1582 // 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!
1583 // 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_.
1584 // 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.
1585 // Illustration of the problem comes here:
1586 // 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.
1587 // 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.
1588 // 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.
1589 // 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.
1590 if ($this->autoVersioningUpdate
=== TRUE) {
1591 foreach ($valueArray as $key => $theFile) {
1592 // If it is an already attached file...
1593 if ($theFile === basename($theFile)) {
1594 $valueArray[$key] = PATH_site
. $tcaFieldConf['uploadfolder'] . '/' . $theFile;
1599 // Finding the CURRENT files listed, either from MM or from the current record.
1600 $theFileValues = array();
1601 // If MM relations for the files also!
1602 if ($tcaFieldConf['MM']) {
1603 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1604 /** @var $dbAnalysis t3lib_loadDBGroup */
1605 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
1606 foreach ($dbAnalysis->itemArray
as $item) {
1608 $theFileValues[] = $item['id'];
1612 $theFileValues = t3lib_div
::trimExplode(',', $curValue, 1);
1614 $currentFilesForHistory = implode(',', $theFileValues);
1616 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1617 if (count($theFileValues)) {
1618 // 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!)
1619 foreach ($valueArray as $key => $theFile) {
1620 if ($theFile && !strstr(t3lib_div
::fixWindowsFilePath($theFile), '/')) {
1621 $theFileValues = t3lib_div
::removeArrayEntryByValue($theFileValues, $theFile);
1625 // This array contains the filenames in the uploadfolder that should be deleted:
1626 foreach ($theFileValues as $key => $theFile) {
1627 $theFile = trim($theFile);
1628 if (@is_file
($dest . '/' . $theFile)) {
1629 $this->removeFilesStore
[] = $dest . '/' . $theFile;
1630 } elseif ($theFile) {
1631 $this->log($table, $id, 5, 0, 1, "Could not delete file '%s' (does not exist). (%s)", 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
1637 // Traverse the submitted values:
1638 foreach ($valueArray as $key => $theFile) {
1640 $maxSize = intval($tcaFieldConf['max_size']);
1641 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1644 // a FAL file was added, now resolve the file object and get the absolute path
1645 // @todo in future versions this needs to be modified to handle FAL objects natively
1646 if (t3lib_utility_Math
::canBeInterpretedAsInteger($theFile)) {
1647 $fileObject = t3lib_file_Factory
::getInstance()->getFileObject($theFile);
1648 $theFile = $fileObject->getForLocalProcessing(FALSE);
1651 // NEW FILES? If the value contains '/' it indicates, that the file
1652 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1653 if (strstr(t3lib_div
::fixWindowsFilePath($theFile), '/')) {
1655 // Check various things before copying file:
1656 // File and destination must exist
1657 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) {
1660 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
1661 $fileSize = $uploadedFileArray['size'];
1663 $fileSize = filesize($theFile);
1667 if (!$maxSize ||
$fileSize <= ($maxSize * 1024)) {
1668 // Prepare filename:
1669 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
1670 $fI = t3lib_div
::split_fileref($theEndFileName);
1672 // Check for allowed extension:
1673 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1674 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
1676 // If we have a unique destination filename, then write the file:
1678 t3lib_div
::upload_copy_move($theFile, $theDestFile);
1680 // Hook for post-processing the upload action
1681 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
1682 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
1683 $hookObject = t3lib_div
::getUserObj($classRef);
1685 if (!($hookObject instanceof t3lib_TCEmain_processUploadHook
)) {
1686 throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_processUploadHook', 1279962349);
1689 $hookObject->processUpload_postProcessAction($theDestFile, $this);
1693 $this->copiedFileMap
[$theFile] = $theDestFile;
1695 if (!@is_file
($theDestFile)) {
1696 $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']);
1699 $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']);
1702 $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
1705 $this->log($table, $id, 5, 0, 1, "Filesize (%s) of file '%s' exceeds limit (%s). (%s)", 13, array(t3lib_div
::formatSize($fileSize), $theFile, t3lib_div
::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
1708 $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']);
1711 // If the destination file was created, we will set the new filename in
1712 // the value array, otherwise unset the entry in the value array!
1713 if (@is_file
($theDestFile)) {
1714 $info = t3lib_div
::split_fileref($theDestFile);
1715 // The value is set to the new filename
1716 $valueArray[$key] = $info['file'];
1718 // The value is set to the new filename
1719 unset($valueArray[$key]);
1725 // 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!
1726 if ($tcaFieldConf['MM']) {
1727 /** @var $dbAnalysis t3lib_loadDBGroup */
1728 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1730 $dbAnalysis->tableArray
['files'] = array();
1732 foreach ($valueArray as $key => $theFile) {
1734 $dbAnalysis->itemArray
[]['id'] = $theFile;
1736 if ($status == 'update') {
1737 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
1738 $newFiles = implode(',', $dbAnalysis->getValueArray());
1739 list(, , $recFieldName) = explode(':', $recFID);
1740 if ($currentFilesForHistory != $newFiles) {
1741 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
1742 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
1744 $this->mmHistoryRecords
[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
1745 $this->mmHistoryRecords
[$table . ':' . $id]['newRecord'][$recFieldName] = '';
1748 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1750 $valueArray = $dbAnalysis->countItems();
1752 // Store path relative to site root (if uploadfolder is not set or internal_type is file_reference)
1754 if (count($valueArray)) {
1755 // If filehandling should NOT be bypassed, do processing:
1756 if (!$this->bypassFileHandling
) {
1758 $propArr = $this->getRecordProperties($table, $id);
1759 foreach ($valueArray as &$theFile) {
1761 // FAL handling: it's a UID, thus it is resolved to the absolute path
1762 if (t3lib_utility_Math
::canBeInterpretedAsInteger($theFile)) {
1763 $fileObject = t3lib_file_Factory
::getInstance()->getFileObject($theFile);
1764 $theFile = $fileObject->getForLocalProcessing(FALSE);
1767 if ($this->alternativeFilePath
[$theFile]) {
1768 // If alernative File Path is set for the file, then it was an import
1769 // don't import the file if it already exists
1770 if (@is_file
(PATH_site
. $this->alternativeFilePath
[$theFile])) {
1771 $theFile = PATH_site
. $this->alternativeFilePath
[$theFile];
1774 } elseif (@is_file
($theFile)) {
1775 $dest = dirname(PATH_site
. $this->alternativeFilePath
[$theFile]);
1776 if (!@is_dir
($dest)) {
1777 t3lib_div
::mkdir_deep(PATH_site
, dirname($this->alternativeFilePath
[$theFile]) . '/');
1781 $maxSize = intval($tcaFieldConf['max_size']);
1783 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1785 $fileSize = filesize($theFile);
1787 if (!$maxSize ||
$fileSize <= ($maxSize * 1024)) {
1788 // Prepare filename:
1789 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
1790 $fI = t3lib_div
::split_fileref($theEndFileName);
1792 // Check for allowed extension:
1793 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1794 $theDestFile = PATH_site
. $this->alternativeFilePath
[$theFile];
1798 t3lib_div
::upload_copy_move($theFile, $theDestFile);
1799 $this->copiedFileMap
[$theFile] = $theDestFile;
1801 if (!@is_file
($theDestFile)) {
1802 $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']);
1805 $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']);
1808 $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
1811 $this->log($table, $id, 5, 0, 1, "Filesize (%s) of file '%s' exceeds limit (%s). (%s)", 13, array(t3lib_div
::formatSize($fileSize), $theFile, t3lib_div
::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
1814 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1815 if (@is_file
($theDestFile)) {
1816 // The value is set to the new filename
1817 $theFile = $theDestFile;
1819 // The value is set to the new filename
1824 $theFile = t3lib_div
::fixWindowsFilePath($theFile);
1825 if (t3lib_div
::isFirstPartOfStr($theFile, PATH_site
)) {
1826 $theFile = substr($theFile, strlen(PATH_site
));
1838 * Evaluates 'flex' type values.
1840 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1841 * @param string $value The value to set.
1842 * @param array $tcaFieldConf Field configuration from TCA
1843 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1844 * @param array $uploadedFiles Uploaded files for the field
1845 * @param string $field Field name
1846 * @return array Modified $res array
1848 function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1849 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1851 if (is_array($value)) {
1853 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
1854 // The problem is, that when copying a page, flexfrom XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that sake, the t3lib_BEfunc::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
1855 $newRecordPidValue = $status == 'new' ?
$realPid : 0;
1857 // Get current value array:
1858 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord
, $table, '', TRUE, $newRecordPidValue);
1860 $currentValueArray = t3lib_div
::xml2array($curValue);
1861 if (!is_array($currentValueArray)) {
1862 $currentValueArray = array();
1864 if (is_array($currentValueArray['meta']['currentLangId'])) {
1865 unset($currentValueArray['meta']['currentLangId']);
1866 } // Remove all old meta for languages...
1868 // Evaluation of input values:
1869 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
1871 // Create XML and convert charsets from input value:
1872 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
1874 // If we wanted to set UTF fixed:
1875 // $storeInCharset='utf-8';
1876 // $currentCharset=$GLOBALS['LANG']->charSet;
1877 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1878 $storeInCharset = $GLOBALS['LANG']->charSet
;
1880 // Merge them together IF they are both arrays:
1881 // 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 (provided that the current value was already stored IN the charset that the new value is converted to).
1882 if (is_array($currentValueArray)) {
1883 $arrValue = t3lib_div
::xml2array($xmlValue);
1884 $arrValue = t3lib_div
::array_merge_recursive_overrule($currentValueArray, $arrValue);
1885 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
1888 // Action commands (sorting order and removals of elements)
1889 $actionCMDs = t3lib_div
::_GP('_ACTION_FLEX_FORMdata');
1890 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
1891 $arrValue = t3lib_div
::xml2array($xmlValue);
1892 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
1893 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
1896 // Create the value XML:
1898 $res['value'] .= $xmlValue;
1899 } else { // Passthrough...:
1900 $res['value'] = $value;
1907 * Converts an array to FlexForm XML
1909 * @param array $array Array with FlexForm data
1910 * @param boolean $addPrologue If set, the XML prologue is returned as well.
1911 * @return string Input array converted to XML
1913 function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
1914 /** @var $flexObj t3lib_flexformtools */
1915 $flexObj = t3lib_div
::makeInstance('t3lib_flexformtools');
1917 return $flexObj->flexArray2Xml($array, $addPrologue);
1921 * Actions for flex form element (move, delete)
1923 * @param array &$valueArrayToRemoveFrom by reference
1924 * @param array $deleteCMDS
1927 function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
1928 if (is_array($valueArray) && is_array($actionCMDs)) {
1929 foreach ($actionCMDs as $key => $value) {
1930 if ($key == '_ACTION') {
1931 // First, check if there are "commands":
1932 if (current($actionCMDs[$key]) !== '') {
1933 asort($actionCMDs[$key]);
1934 $newValueArray = array();
1935 foreach ($actionCMDs[$key] as $idx => $order) {
1936 if (substr($idx, 0, 3) == 'ID-') {
1937 $idx = $this->newIndexMap
[$idx];
1939 // 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.
1940 if ($order != 'DELETE') {
1941 $newValueArray[$idx] = $valueArray[$idx];
1943 unset($valueArray[$idx]);
1945 $valueArray = t3lib_div
::array_merge($newValueArray, $valueArray);
1947 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
1948 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
1955 * Evaluates 'inline' type values.
1956 * (partly copied from the select_group function on this issue)
1958 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1959 * @param string $value The value to set.
1960 * @param array $tcaFieldConf Field configuration from TCA
1961 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1962 * @param string $field Field name
1963 * @return array Modified $res array
1965 function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field) {
1966 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1968 if (!$tcaFieldConf['foreign_table']) {
1969 // Fatal error, inline fields should always have a foreign_table defined
1973 // When values are sent they come as comma-separated values which are exploded by this function:
1974 $valueArray = t3lib_div
::trimExplode(',', $value);
1976 // Remove duplicates: (should not be needed)
1977 $valueArray = array_unique($valueArray);
1979 // Example for received data:
1980 // $value = 45,NEW4555fdf59d154,12,123
1981 // We need to decide whether we use the stack or can save the relation directly.
1982 if (strpos($value, 'NEW') !== FALSE ||
!t3lib_utility_Math
::canBeInterpretedAsInteger($id)) {
1983 $this->remapStackRecords
[$table][$id] = array('remapStackIndex' => count($this->remapStack
));
1984 $this->addNewValuesToRemapStackChildIds($valueArray);
1985 $this->remapStack
[] = array(
1986 'func' => 'checkValue_inline_processDBdata',
1987 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
1988 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
1991 unset($res['value']);
1992 } elseif ($value || t3lib_utility_Math
::canBeInterpretedAsInteger($id)) {
1993 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
2000 * Checks if a fields has more items than defined via TCA in maxitems.
2001 * If there are more items than allowd, the item list is truncated to the defined number.
2003 * @param array $tcaFieldConf Field configuration from TCA
2004 * @param array $valueArray Current value array of items
2005 * @return array The truncated value array of items
2007 function checkValue_checkMax($tcaFieldConf, $valueArray) {
2008 // 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...
2010 $valueArrayC = count($valueArray);
2012 // 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.
2013 $maxI = isset($tcaFieldConf['maxitems']) ?
intval($tcaFieldConf['maxitems']) : 1;
2014 if ($valueArrayC > $maxI) {
2015 $valueArrayC = $maxI;
2016 } // Checking for not too many elements
2018 // Dumping array to list
2020 foreach ($valueArray as $nextVal) {
2021 if ($valueArrayC == 0) {
2025 $newVal[] = $nextVal;
2031 /*********************************************
2033 * Helper functions for evaluation functions.
2035 ********************************************/
2038 * Gets a unique value for $table/$id/$field based on $value
2040 * @param string $table Table name
2041 * @param string $field Field name for which $value must be unique
2042 * @param string $value Value string.
2043 * @param integer $id UID to filter out in the lookup (the record itself...)
2044 * @param integer $newPid If set, the value will be unique for this PID
2045 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2047 function getUnique($table, $field, $value, $id, $newPid = 0) {
2050 t3lib_div
::loadTCA($table);
2053 if (intval($newPid)) {
2054 $whereAdd .= ' AND pid=' . intval($newPid);
2056 $whereAdd .= ' AND pid>=0';
2057 } // "AND pid>=0" for versioning
2058 $whereAdd .= $this->deleteClause($table);
2060 // If the field is configured in TCA, proceed:
2061 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2063 // Look for a record which might already have the value:
2064 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table) . ' AND uid<>' . intval($id) . $whereAdd);
2067 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2068 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
2069 $newValue = $value . $counter;
2070 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table) . ' AND uid<>' . intval($id) . $whereAdd);
2072 if ($counter > 100) {
2074 } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
2077 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2078 // If the new value is there:
2079 $value = strlen($newValue) ?
$newValue : $value;
2087 * @param string $value The field value to be evaluated
2088 * @param array $evalArray Array of evaluations to traverse.
2089 * @param string $is_in The "is_in" value of the field configuration from TCA
2092 function checkValue_text_Eval($value, $evalArray, $is_in) {
2097 foreach ($evalArray as $func) {
2100 $value = trim($value);
2108 $evalObj = t3lib_div
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2109 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2110 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2116 $res['value'] = $value;
2122 * Evaluation of 'input'-type values based on 'eval' list
2124 * @param string $value Value to evaluate
2125 * @param array $evalArray Array of evaluations to traverse.
2126 * @param string $is_in Is-in string for 'is_in' evaluation
2127 * @return array Modified $value in key 'value' or empty array
2129 function checkValue_input_Eval($value, $evalArray, $is_in) {
2134 foreach ($evalArray as $func) {
2140 $value = intval($value);
2144 $value = intval($value);
2145 if ($value > 0 && !$this->dontProcessTransformations
) {
2146 $value -= date('Z', $value);
2150 $value = preg_replace('/[^0-9,\.-]/', '', $value);
2151 $negative = substr($value, 0, 1) == '-';
2152 $value = strtr($value, array(',' => '.', '-' => ''));
2153 if (strpos($value, '.') === FALSE) {
2156 $valueArray = explode('.', $value);
2157 $dec = array_pop($valueArray);
2158 $value = join('', $valueArray) . '.' . $dec;
2162 $value = number_format($value, 2, '.', '');
2165 if (strlen($value) != 32) {
2170 $value = trim($value);
2173 $value = $GLOBALS['LANG']->csConvObj
->conv_case($GLOBALS['LANG']->charSet
, $value, 'toUpper');
2176 $value = $GLOBALS['LANG']->csConvObj
->conv_case($GLOBALS['LANG']->charSet
, $value, 'toLower');
2179 if (!isset($value) ||
$value === '') {
2184 $c = strlen($value);
2187 for ($a = 0; $a < $c; $a++
) {
2188 $char = substr($value, $a, 1);
2189 if (strpos($is_in, $char) !== FALSE) {
2197 $value = str_replace(' ', '', $value);
2200 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2203 $value = preg_replace('/[^0-9]/', '', $value);
2206 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2209 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2212 if (!preg_match('/^[a-z0-9\.\-]*$/i', $value)) {
2213 t3lib_div
::requireOnce(PATH_typo3
. 'contrib/idna/idna_convert.class.php');
2214 $idnaConvert = new idna_convert();
2215 $idnaConvert->set_parameter('idn_version', '2008');
2216 $value = $idnaConvert->encode($value);
2217 unset($idnaConvert);
2221 $evalObj = t3lib_div
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2222 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2223 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2229 $res['value'] = $value;
2235 * Returns data for group/db and select fields
2237 * @param array $valueArray Current value array
2238 * @param array $tcaFieldConf TCA field config
2239 * @param integer $id Record id, used for look-up of MM relations (local_uid)
2240 * @param string $status Status string ('update' or 'new')
2241 * @param string $type The type, either 'select', 'group' or 'inline'
2242 * @param string $currentTable Table name, needs to be passed to t3lib_loadDBGroup
2243 * @param string $currentField field name, needs to be set for writing to sys_history
2244 * @return array Modified value array
2246 function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
2247 $tables = $type == 'group' ?
$tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'] . ',' . $tcaFieldConf['neg_foreign_table'];
2248 $prep = $type == 'group' ?
$tcaFieldConf['prepend_tname'] : $tcaFieldConf['neg_foreign_table'];
2249 $newRelations = implode(',', $valueArray);
2250 /** @var $dbAnalysis t3lib_loadDBGroup */
2251 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2253 $dbAnalysis->registerNonTableValues
= $tcaFieldConf['allowNonIdValues'] ?
1 : 0;
2254 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2256 if ($tcaFieldConf['MM']) {
2257 if ($status == 'update') {
2258 /** @var $oldRelations_dbAnalysis t3lib_loadDBGroup */
2259 $oldRelations_dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2261 $oldRelations_dbAnalysis->registerNonTableValues
= $tcaFieldConf['allowNonIdValues'] ?
1 : 0;
2262 // Db analysis with $id will initialize with the existing relations
2263 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2264 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2265 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2266 if ($oldRelations != $newRelations) {
2267 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2268 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2270 $this->mmHistoryRecords
[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2271 $this->mmHistoryRecords
[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2274 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable); // This will be traversed later to execute the actions
2276 $valueArray = $dbAnalysis->countItems();
2278 $valueArray = $dbAnalysis->getValueArray($prep);
2279 if ($type == 'select' && $prep) {
2280 $valueArray = $dbAnalysis->convertPosNeg($valueArray, $tcaFieldConf['foreign_table'], $tcaFieldConf['neg_foreign_table']);
2284 // 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.
2289 * Explodes the $value, which is a list of files/uids (group select)
2291 * @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.
2292 * @return array The value array.
2294 function checkValue_group_select_explodeSelectGroupValue($value) {
2295 $valueArray = t3lib_div
::trimExplode(',', $value, 1);
2296 foreach ($valueArray as &$newVal) {
2297 $temp = explode('|', $newVal, 2);
2298 $newVal = str_replace(
2301 str_replace('|', '', rawurldecode($temp[0]))
2309 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2310 * See checkValue_flex_procInData_travDS() for more details.
2311 * 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 class.t3lib_flexformtools.php
2313 * @param array $dataPart The 'data' part of the INPUT flexform data
2314 * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2315 * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2316 * @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.
2317 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2318 * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS() DEPRICATED, use class.t3lib_flexformtools.php instead for traversal!
2319 * @return array The modified 'data' part.
2320 * @see checkValue_flex_procInData_travDS()
2322 function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructArray, $pParams, $callBackFunc = '') {
2323 if (is_array($dataPart)) {
2324 foreach ($dataPart as $sKey => $sheetDef) {
2325 list ($dataStruct, $actualSheet) = t3lib_div
::resolveSheetDefInDS($dataStructArray, $sKey);
2326 if (is_array($dataStruct) && $actualSheet == $sKey && is_array($sheetDef)) {
2327 foreach ($sheetDef as $lKey => $lData) {
2328 $this->checkValue_flex_procInData_travDS(
2329 $dataPart[$sKey][$lKey],
2330 $dataPart_current[$sKey][$lKey],
2331 $uploadedFiles[$sKey][$lKey],
2332 $dataStruct['ROOT']['el'],
2335 $sKey . '/' . $lKey . '/'
2346 * Processing of the sheet/language data array
2347 * 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.
2349 * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2350 * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2351 * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2352 * @param array $DSelements Data structure which fits the data array
2353 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2354 * @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.
2355 * @param string $structurePath
2357 * @see checkValue_flex_procInData()
2359 function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath) {
2360 if (is_array($DSelements)) {
2362 // For each DS element:
2363 foreach ($DSelements as $key => $dsConf) {
2366 if ($DSelements[$key]['type'] == 'array') {
2367 if (is_array($dataValues[$key]['el'])) {
2368 if ($DSelements[$key]['section']) {
2369 $newIndexCounter = 0;
2370 foreach ($dataValues[$key]['el'] as $ik => $el) {
2371 if (is_array($el)) {
2372 if (!is_array($dataValues_current[$key]['el'])) {
2373 $dataValues_current[$key]['el'] = array();
2378 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2379 $this->checkValue_flex_procInData_travDS(
2380 $dataValues[$key]['el'][$ik][$theKey]['el'],
2381 is_array($dataValues_current[$key]['el'][$ik]) ?
$dataValues_current[$key]['el'][$ik][$theKey]['el'] : array(),
2382 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2383 $DSelements[$key]['el'][$theKey]['el'],
2386 $structurePath . $key . '/el/' . $ik . '/' . $theKey . '/el/'
2389 // If element is added dynamically in the flexform of TCEforms, we map the ID-string to the next numerical index we can have in that particular section of elements:
2390 // The fact that the order changes is not important since order is controlled by a separately submitted index.
2392 if (substr($ik, 0, 3) == 'ID-') {
2394 // Set mapping index
2395 $this->newIndexMap
[$ik] = (is_array($dataValues_current[$key]['el']) && count($dataValues_current[$key]['el']) ?
max(array_keys($dataValues_current[$key]['el'])) : 0) +
$newIndexCounter;
2397 $dataValues[$key]['el'][$this->newIndexMap
[$ik]] = $dataValues[$key]['el'][$ik];
2399 unset($dataValues[$key]['el'][$ik]);
2405 if (!isset($dataValues[$key]['el'])) {
2406 $dataValues[$key]['el'] = array();
2408 $this->checkValue_flex_procInData_travDS(
2409 $dataValues[$key]['el'],
2410 $dataValues_current[$key]['el'],
2411 $uploadedFiles[$key]['el'],
2412 $DSelements[$key]['el'],
2415 $structurePath . $key . '/el/'
2420 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2421 foreach ($dataValues[$key] as $vKey => $data) {
2423 if ($callBackFunc) {
2424 if (is_object($this->callBackObj
)) {
2425 $res = $this->callBackObj
->$callBackFunc(
2427 $dsConf['TCEforms']['config'],
2428 $dataValues[$key][$vKey],
2429 $dataValues_current[$key][$vKey],
2430 $uploadedFiles[$key][$vKey],
2431 $structurePath . $key . '/' . $vKey . '/'
2434 $res = $this->$callBackFunc(
2436 $dsConf['TCEforms']['config'],
2437 $dataValues[$key][$vKey],
2438 $dataValues_current[$key][$vKey],
2439 $uploadedFiles[$key][$vKey],
2440 $structurePath . $key . '/' . $vKey . '/'
2444 list($CVtable, $CVid, $CVcurValue, $CVstatus, $CVrealPid, $CVrecFID, $CVtscPID) = $pParams;
2446 $res = $this->checkValue_SW(
2448 $dataValues[$key][$vKey],
2449 $dsConf['TCEforms']['config'],
2452 $dataValues_current[$key][$vKey],
2457 $uploadedFiles[$key][$vKey],
2462 // Look for RTE transformation of field:
2463 if ($dataValues[$key]['_TRANSFORM_' . $vKey] == 'RTE' && !$this->dontProcessTransformations
) {
2465 // Unsetting trigger field - we absolutely don't want that into the data storage!
2466 unset($dataValues[$key]['_TRANSFORM_' . $vKey]);
2468 if (isset($res['value'])) {
2470 // Calculating/Retrieving some values here:
2471 list(, , $recFieldName) = explode(':', $CVrecFID);
2472 $theTypeString = t3lib_BEfunc
::getTCAtypeValue($CVtable, $this->checkValue_currentRecord
);
2473 $specConf = t3lib_BEfunc
::getSpecConfParts('', $dsConf['TCEforms']['defaultExtras']);
2475 // Find, thisConfig:
2476 $RTEsetup = $this->BE_USER
->getTSConfig('RTE', t3lib_BEfunc
::getPagesTSconfig($CVtscPID));
2477 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'], $CVtable, $recFieldName, $theTypeString);
2479 // Get RTE object, draw form and set flag:
2480 $RTEobj = t3lib_BEfunc
::RTEgetObj();
2481 if (is_object($RTEobj)) {
2482 $res['value'] = $RTEobj->transformContent('db', $res['value'], $CVtable, $recFieldName, $this->checkValue_currentRecord
, $specConf, $thisConfig, '', $CVrealPid);
2484 debug('NO RTE OBJECT FOUND!');
2490 // Adding the value:
2491 if (isset($res['value'])) {
2492 $dataValues[$key][$vKey] = $res['value'];
2495 // Finally, check if new and old values are different (or no .vDEFbase value is found) and if so, we record the vDEF value for diff'ing.
2496 // We do this after $dataValues has been updated since I expect that $dataValues_current holds evaluated values from database (so this must be the right value to compare with).
2497 if (substr($vKey, -9) != '.vDEFbase') {
2498 if ($this->clear_flexFormData_vDEFbase
) {
2499 $dataValues[$key][$vKey . '.vDEFbase'] = '';
2500 } elseif ($this->updateModeL10NdiffData
&& $GLOBALS['TYPO3_CONF_VARS']['BE']['flexFormXMLincludeDiffBase'] && $vKey !== 'vDEF' && (strcmp($dataValues[$key][$vKey], $dataValues_current[$key][$vKey]) ||
!isset($dataValues_current[$key][$vKey . '.vDEFbase']) ||
$this->updateModeL10NdiffData
=== 'FORCE_FFUPD')) {
2501 // Now, check if a vDEF value is submitted in the input data, if so we expect this has been processed prior to this operation (normally the case since those fields are higher in the form) and we can use that:
2502 if (isset($dataValues[$key]['vDEF'])) {
2503 $diffValue = $dataValues[$key]['vDEF'];
2504 } else { // If not found (for translators with no access to the default language) we use the one from the current-value data set:
2505 $diffValue = $dataValues_current[$key]['vDEF'];
2507 // Setting the reference value for vDEF for this translation. This will be used for translation tools to make a diff between the vDEF and vDEFbase to see if an update would be fitting.
2508 $dataValues[$key][$vKey . '.vDEFbase'] = $this->updateModeL10NdiffDataClear ?
'' : $diffValue;
2519 * Returns data for inline fields.
2521 * @param array $valueArray Current value array
2522 * @param array $tcaFieldConf TCA field config
2523 * @param integer $id Record id
2524 * @param string $status Status string ('update' or 'new')
2525 * @param string $table Table name, needs to be passed to t3lib_loadDBGroup
2526 * @param string $field The current field the values are modified for
2527 * @return string Modified values
2529 protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field) {
2531 $foreignTable = $tcaFieldConf['foreign_table'];
2533 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2535 // Fetch the related child records by using t3lib_loadDBGroup:
2536 /** @var $dbAnalysis t3lib_loadDBGroup */
2537 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2538 $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
2539 // If the localizationMode is set to 'keep', the children for the localized parent are kept as in the original untranslated record:
2540 $localizationMode = t3lib_BEfunc
::getInlineLocalizationMode($table, $tcaFieldConf);
2541 if ($localizationMode == 'keep' && $status == 'update') {
2542 // Fetch the current record and determine the original record:
2543 $row = t3lib_BEfunc
::getRecordWSOL($table, $id);
2544 if (is_array($row)) {
2545 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
2546 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
2547 // If language is set (e.g. 1) and also transOrigPointer (e.g. 123), use transOrigPointer as uid:
2548 if ($language > 0 && $transOrigPointer) {
2549 $id = $transOrigPointer;
2550 // If we're in active localizationMode 'keep', prevent from writing data to the field of the parent record:
2551 // (on removing the localized parent, the original (untranslated) children would then also be removed)
2552 $keepTranslation = TRUE;
2556 // IRRE with a pointer field (database normalization):
2557 if ($tcaFieldConf['foreign_field']) {
2558 // if the record was imported, sorting was also imported, so skip this
2559 $skipSorting = ($this->callFromImpExp ?
TRUE : FALSE);
2560 // update record in intermediate table (sorting & pointer uid to parent record)
2561 $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
2562 $newValue = ($keepTranslation ?
0 : $dbAnalysis->countItems(FALSE));
2563 // IRRE with MM relation:
2565 if ($this->getInlineFieldType($tcaFieldConf) == 'mm') {
2566 // In order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
2567 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
2568 $newValue = ($keepTranslation ?
0 : $valueArray[0]);
2569 // IRRE with comma separated values:
2571 $valueArray = $dbAnalysis->getValueArray();
2572 // Checking that the number of items is correct:
2573 $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2574 // If a valid translation of the 'keep' mode is active, update relations in the original(!) record:
2575 if ($keepTranslation) {
2576 $this->updateDB($table, $transOrigPointer, array($field => implode(',', $valueArray)));
2578 $newValue = implode(',', $valueArray);
2586 /*********************************************
2588 * PROCESSING COMMANDS
2590 ********************************************/
2593 * Processing the cmd-array
2594 * See "TYPO3 Core API" for a description of the options.
2598 public function process_cmdmap() {
2601 if ($this->BE_USER
->workspace
!== 0 && $this->BE_USER
->workspaceRec
['freeze']) {
2602 $this->newlog('All editing in this workspace has been frozen!', 1);
2606 // Hook initialization:
2607 $hookObjectsArr = array();
2608 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'])) {
2609 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] as $classRef) {
2610 $hookObj = t3lib_div
::getUserObj($classRef);
2611 if (method_exists($hookObj, 'processCmdmap_beforeStart')) {
2612 $hookObj->processCmdmap_beforeStart($this);
2614 $hookObjectsArr[] = $hookObj;
2618 // Traverse command map:
2619 foreach (array_keys($this->cmdmap
) as $table) {
2621 // Check if the table may be modified!
2622 $modifyAccessList = $this->checkModifyAccessList($table);
2623 if (!$modifyAccessList) {
2625 $this->log($table, $id, 2, 0, 1, "Attempt to modify table '%s' without permission", 1, array($table));
2626 } // FIXME: $id not set here (Comment added by Sebastian Kurfürst)
2628 // Check basic permissions and circumstances:
2629 if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap
[$table]) && $modifyAccessList) {
2631 // Traverse the command map:
2632 foreach ($this->cmdmap
[$table] as $id => $incomingCmdArray) {
2633 if (is_array($incomingCmdArray)) { // have found a command.
2635 // Get command and value (notice, only one command is observed at a time!):
2636 reset($incomingCmdArray);
2637 $command = key($incomingCmdArray);
2638 $value = current($incomingCmdArray);
2640 foreach ($hookObjectsArr as $hookObj) {
2641 if (method_exists($hookObj, 'processCmdmap_preProcess')) {
2642 $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this);
2646 // Init copyMapping array:
2647 // Must clear this array before call from here to those functions:
2648 // Contains mapping information between new and old id numbers.
2649 $this->copyMappingArray
= array();
2651 // process the command
2652 $commandIsProcessed = FALSE;
2653 foreach ($hookObjectsArr as $hookObj) {
2654 if (method_exists($hookObj, 'processCmdmap')) {
2655 $hookObj->processCmdmap($command, $table, $id, $value, $commandIsProcessed, $this);
2659 // Only execute default commands if a hook hasn't been processed the command already
2660 if (!$commandIsProcessed) {
2661 // Branch, based on command
2664 $this->moveRecord($table, $id, $value);
2667 if ($table === 'pages') {
2668 $this->copyPages($id, $value);
2670 $this->copyRecord($table, $id, $value, 1);
2674 $this->localize($table, $id, $value);
2676 case 'inlineLocalizeSynchronize':
2677 $this->inlineLocalizeSynchronize($table, $id, $value);
2680 $this->deleteAction($table, $id);
2683 $this->undeleteRecord($table, $id);
2688 foreach ($hookObjectsArr as $hookObj) {
2689 if (method_exists($hookObj, 'processCmdmap_postProcess')) {
2690 $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this);
2694 // Merging the copy-array info together for remapping purposes.
2695 $this->copyMappingArray_merged
= t3lib_div
::array_merge_recursive_overrule($this->copyMappingArray_merged
, $this->copyMappingArray
);
2701 // Finally, before exit, check if there are ID references to remap.
2702 // This might be the case if versioning or copying has taken place!
2703 $this->remapListedDBRecords();
2704 $this->processRemapStack();
2706 foreach ($hookObjectsArr as $hookObj) {
2707 if (method_exists($hookObj, 'processCmdmap_afterFinish')) {
2708 $hookObj->processCmdmap_afterFinish($this);
2712 if ($this->isOuterMostInstance()) {
2713 $this->resetNestedElementCalls();
2717 /*********************************************
2721 ********************************************/
2724 * Copying a single record
2726 * @param string $table Element table
2727 * @param integer $uid Element UID
2728 * @param integer $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
2729 * @param boolean $first Is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
2730 * @param array $overrideValues Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!
2731 * @param string $excludeFields Commalist of fields to exclude from the copy process (might get default values)
2732 * @param integer $language Language ID (from sys_language table)
2733 * @return integer ID of new record, if any
2735 function copyRecord($table, $uid, $destPid, $first = 0, $overrideValues = array(), $excludeFields = '', $language = 0) {
2736 $uid = $origUid = intval($uid);
2737 // Only copy if the table is defined in $GLOBALS['TCA'], a uid is given and the record wasn't copied before:
2738 if ($GLOBALS['TCA'][$table] && $uid && !$this->isRecordCopied($table, $uid)) {
2739 t3lib_div
::loadTCA($table);
2740 // This checks if the record can be selected which is all that a copy action requires.
2741 if ($this->doesRecordExist($table, $uid, 'show')) {
2742 $fullLanguageCheckNeeded = ($table != 'pages');
2743 //Used to check language and general editing rights
2744 if (($language > 0 && $this->BE_USER
->checkLanguageAccess($language)) ||
2745 $this->BE_USER
->recordEditAccessInternals(
2746 $table, $uid, FALSE, FALSE, $fullLanguageCheckNeeded
2751 $nonFields = array_unique(t3lib_div
::trimExplode(',', 'uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,t3ver_oid,t3ver_wsid,t3ver_id,t3ver_label,t3ver_state,t3ver_count,t3ver_stage,t3ver_tstamp,' . $excludeFields, 1));
2753 // So it copies (and localized) content from workspace...
2754 $row = t3lib_BEfunc
::getRecordWSOL($table, $uid);
2755 if (is_array($row)) {
2758 $theNewID = uniqid('NEW');
2759 $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ?
$GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
2760 $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
2762 // Getting default data:
2763 $defaultData = $this->newFieldArray($table);
2765 // Getting "copy-after" fields if applicable:
2766 $copyAfterFields = $destPid < 0 ?
$this->fixCopyAfterDuplFields($table, $uid, abs($destPid), 0) : array();
2768 // Page TSconfig related:
2769 // NOT using t3lib_BEfunc::getTSCpid() because we need the real pid - not the ID of a page, if the input is a page...
2770 $tscPID = t3lib_BEfunc
::getTSconfig_pidValue($table, $uid, $destPid);
2771 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2772 $tE = $this->getTableEntries($table, $TSConfig);
2774 // Traverse ALL fields of the selected record:
2775 foreach ($row as $field => $value) {
2776 if (!in_array($field, $nonFields)) {
2778 // Get TCA configuration for the field:
2779 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2781 // Preparation/Processing of the value:
2782 // "pid" is hardcoded of course:
2783 if ($field == 'pid') {