[TASK] Remove global declarations inside methods
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tcemain.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
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.
13 *
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.
18 *
19 *
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.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains the TYPO3 Core Engine
29 *
30 * Revised for TYPO3 3.9 October 2005 by Kasper Skårhøj
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 242: class t3lib_TCEmain
40 * 367: function start($data,$cmd,$altUserObject='')
41 * 406: function setMirror($mirror)
42 * 431: function setDefaultsFromUserTS($userTS)
43 * 454: function process_uploads($postFiles)
44 * 492: function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
45 *
46 * SECTION: PROCESSING DATA
47 * 528: function process_datamap()
48 * 886: function placeholderShadowing($table,$id)
49 * 929: function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
50 *
51 * SECTION: Evaluation of input values
52 * 1152: function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
53 * 1212: function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
54 * 1261: function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
55 * 1299: function checkValue_check($res,$value,$tcaFieldConf,$PP)
56 * 1322: function checkValue_radio($res,$value,$tcaFieldConf,$PP)
57 * 1348: function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
58 * 1458: function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
59 * 1632: function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
60 * 1709: function checkValue_flexArray2Xml($array, $addPrologue=FALSE)
61 * 1721: function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
62 * 1743: function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)
63 * 1783: function checkValue_inline($res,$value,$tcaFieldConf,$PP,$field)
64 * 1825: function checkValue_checkMax($tcaFieldConf, $valueArray)
65 *
66 * SECTION: Helper functions for evaluation functions.
67 * 1877: function getUnique($table,$field,$value,$id,$newPid=0)
68 * 1915: function checkValue_input_Eval($value,$evalArray,$is_in)
69 * 2012: function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type,$currentTable)
70 * 2058: function checkValue_group_select_explodeSelectGroupValue($value)
71 * 2082: function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
72 * 2121: function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)
73 *
74 * SECTION: PROCESSING COMMANDS
75 * 2267: function process_cmdmap()
76 *
77 * SECTION: Cmd: Copying
78 * 2407: function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
79 * 2529: function copyPages($uid,$destPid)
80 * 2583: function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
81 * 2617: function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
82 * 2681: function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
83 * 2705: function insertNewCopyVersion($table,$fieldArray,$realPid)
84 * 2757: function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$realDestPid)
85 * 2836: function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
86 * 2864: function copyRecord_procFilesRefs($conf, $uid, $value)
87 *
88 * SECTION: Cmd: Moving, Localizing
89 * 2933: function moveRecord($table,$uid,$destPid)
90 * 3128: function moveRecord_procFields($table,$uid,$destPid)
91 * 3148: function moveRecord_procBasedOnFieldType($table,$uid,$destPid,$field,$value,$conf)
92 * 3182: function localize($table,$uid,$language)
93 *
94 * SECTION: Cmd: Deleting
95 * 3296: function deleteAction($table, $id)
96 * 3343: function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE)
97 * 3360: function deleteVersionsForRecord($table, $uid, $forceHardDelete)
98 * 3382: function undeleteRecord($table,$uid)
99 * 3399: function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)
100 * 3512: function deleteRecord_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)
101 * 3539: function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE)
102 * 3567: function deleteSpecificPage($uid,$forceHardDelete=FALSE)
103 * 3592: function canDeletePage($uid)
104 * 3619: function cannotDeleteRecord($table,$id)
105 * 3638: function deleteRecord_procFields($table, $uid, $undeleteRecord = FALSE)
106 * 3661: function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = FALSE)
107 *
108 * SECTION: Cmd: Versioning
109 * 3722: function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1)
110 * 3798: function versionizePages($uid,$label,$versionizeTree)
111 * 3861: function version_swap($table,$id,$swapWith,$swapIntoWS=0)
112 * 4032: function version_clearWSID($table,$id)
113 * 4066: function version_setStage($table,$id,$stageId,$comment='')
114 *
115 * SECTION: Cmd: Helper functions
116 * 4111: function remapListedDBRecords()
117 * 4192: function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
118 * 4219: function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
119 * 4265: function remapListedDBRecords_procInline($conf, $value, $uid, $table)
120 *
121 * SECTION: Access control / Checking functions
122 * 4308: function checkModifyAccessList($table)
123 * 4320: function isRecordInWebMount($table,$id)
124 * 4334: function isInWebMount($pid)
125 * 4348: function checkRecordUpdateAccess($table,$id)
126 * 4372: function checkRecordInsertAccess($insertTable,$pid,$action=1)
127 * 4406: function isTableAllowedForThisPage($page_uid, $checkTable)
128 * 4439: function doesRecordExist($table,$id,$perms)
129 * 4504: function doesRecordExist_pageLookUp($id, $perms)
130 * 4530: function doesBranchExist($inList,$pid,$perms,$recurse)
131 * 4564: function tableReadOnly($table)
132 * 4576: function tableAdminOnly($table)
133 * 4590: function destNotInsideSelf($dest,$id)
134 * 4622: function getExcludeListArray()
135 * 4645: function doesPageHaveUnallowedTables($page_uid,$doktype)
136 *
137 * SECTION: Information lookup
138 * 4694: function pageInfo($id,$field)
139 * 4714: function recordInfo($table,$id,$fieldList)
140 * 4735: function getRecordProperties($table,$id,$noWSOL=FALSE)
141 * 4751: function getRecordPropertiesFromRow($table,$row)
142 *
143 * SECTION: Storing data to Database Layer
144 * 4794: function updateDB($table,$id,$fieldArray)
145 * 4846: function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE)
146 * 4919: function checkStoredRecord($table,$id,$fieldArray,$action)
147 * 4956: function setHistory($table,$id,$logId)
148 * 4989: function clearHistory($maxAgeSeconds=604800,$table)
149 * 5003: function updateRefIndex($table,$id)
150 *
151 * SECTION: Misc functions
152 * 5035: function getSortNumber($table,$uid,$pid)
153 * 5108: function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
154 * 5139: function setTSconfigPermissions($fieldArray,$TSConfig_p)
155 * 5156: function newFieldArray($table)
156 * 5188: function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray)
157 * 5212: function overrideFieldArray($table,$data)
158 * 5228: function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
159 * 5274: function assemblePermissions($string)
160 * 5291: function rmComma($input)
161 * 5301: function convNumEntityToByteValue($input)
162 * 5323: function destPathFromUploadFolder($folder)
163 * 5333: function deleteClause($table)
164 * 5349: function getTCEMAIN_TSconfig($tscPID)
165 * 5364: function getTableEntries($table,$TSconfig)
166 * 5377: function getPID($table,$uid)
167 * 5390: function dbAnalysisStoreExec()
168 * 5406: function removeRegisteredFiles()
169 * 5418: function removeCacheFiles()
170 * 5432: function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
171 * 5453: function compileAdminTables()
172 * 5470: function fixUniqueInPid($table,$uid)
173 * 5506: function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
174 * 5531: function extFileFields($table)
175 * 5552: function getUniqueFields($table)
176 * 5577: function isReferenceField($conf)
177 * 5588: function getInlineFieldType($conf)
178 * 5611: function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
179 * 5640: function prependLabel($table)
180 * 5657: function resolvePid($table,$pid)
181 * 5687: function clearPrefixFromValue($table,$value)
182 * 5702: function extFileFunctions($table,$field,$filelist,$func)
183 * 5732: function noRecordsFromUnallowedTables($inList)
184 * 5758: function notifyStageChange($stat,$stageId,$table,$id,$comment)
185 * 5853: function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE)
186 *
187 * SECTION: Clearing cache
188 * 5899: function clear_cache($table,$uid)
189 * 6009: function clear_cacheCmd($cacheCmd)
190 *
191 * SECTION: Logging
192 * 6113: function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='')
193 * 6130: function newlog($message, $error=0)
194 * 6140: function printLogErrorMessages($redirect)
195 *
196 * SECTION: Internal (do not use outside Core!)
197 * 6202: function internal_clearPageCache()
198 *
199 * TOTAL FUNCTIONS: 126
200 * (This index is automatically created/updated by the extension "extdeveval")
201 *
202 */
203
204
205 /**
206 * This is the TYPO3 Core Engine class for manipulation of the database
207 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
208 *
209 * Dependencies:
210 * - $GLOBALS['TCA'] must exist
211 * - $GLOBALS['LANG'] must exist
212 *
213 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
214 *
215 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
216 * @package TYPO3
217 * @subpackage t3lib
218 */
219 class t3lib_TCEmain {
220
221
222 // *********************
223 // Public variables you can configure before using the class:
224 // *********************
225
226 var $storeLogMessages = TRUE; // 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.
227 var $enableLogging = TRUE; // Boolean: If TRUE, actions are logged to sys_log.
228 var $reverseOrder = FALSE; // 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.
229 var $checkSimilar = TRUE; // 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.
230 var $stripslashes_values = TRUE; // 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!
231 var $checkStoredRecords = TRUE; // 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
232 var $checkStoredRecords_loose = TRUE; // Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
233 var $deleteTree = FALSE; // 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
234 var $neverHideAtCopy = FALSE; // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
235 var $dontProcessTransformations = FALSE; // Boolean: If set, then transformations are NOT performed on the input.
236 var $clear_flexFormData_vDEFbase = FALSE; // Boolean: If set, .vDEFbase values are unset in flexforms.
237 var $updateModeL10NdiffData = TRUE; // 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
238 var $updateModeL10NdiffDataClear = FALSE; // 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.
239 var $bypassWorkspaceRestrictions = FALSE; // 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!
240 var $bypassFileHandling = FALSE; // 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!
241 var $bypassAccessCheckForRecords = FALSE; // 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!
242
243 var $copyWhichTables = '*'; // 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)
244
245 var $copyTree = 0; // 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
246
247 var $defaultValues = array(); // 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)
248 var $overrideValues = array(); // 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!
249 var $alternativeFileName = array(); // 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.
250 var $alternativeFilePath = array(); // Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
251 var $data_disableFields = array(); // 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.
252 var $suggestedInsertUids = array(); // 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)
253
254 var $callBackObj; // 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.
255
256
257 // *********************
258 // Internal variables (mapping arrays) which can be used (read-only) from outside
259 // *********************
260
261 var $autoVersionIdMap = array(); // Contains mapping of auto-versionized records.
262 var $substNEWwithIDs = array(); // 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
263 var $substNEWwithIDs_table = array(); // Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
264 var $newRelatedIDs = array(); // Holds the tables and there the ids of newly created child records from IRRE
265 var $copyMappingArray_merged = array(); // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
266 var $copiedFileMap = array(); // A map between input file name and final destination for files being attached to records.
267 var $RTEmagic_copyIndex = array(); // Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
268 var $errorLog = array(); // Errors are collected in this variable.
269
270
271 // *********************
272 // Internal Variables, do not touch.
273 // *********************
274
275 // Variables set in init() function:
276 /**
277 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
278 *
279 * @var t3lib_beUserAuth
280 */
281 var $BE_USER;
282 var $userid; // will be set to uid of be_user executing this script
283 var $username; // will be set to username of be_user executing this script
284 var $admin; // will be set if user is admin
285
286 var $defaultPermissions = array( // Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
287 'user' => 'show,edit,delete,new,editcontent',
288 'group' => 'show,edit,new,editcontent',
289 'everybody' => ''
290 );
291
292 var $exclude_array; // 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.
293 var $datamap = array(); // Set with incoming data array
294 var $cmdmap = array(); // Set with incoming cmd array
295
296 // Internal static:
297 var $pMap = array( // Permission mapping
298 'show' => 1, // 1st bit
299 'edit' => 2, // 2nd bit
300 'delete' => 4, // 3rd bit
301 'new' => 8, // 4th bit
302 'editcontent' => 16 // 5th bit
303 );
304 var $sortIntervals = 256; // Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
305
306 // Internal caching arrays
307 var $recUpdateAccessCache = array(); // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
308 var $recInsertAccessCache = array(); // User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
309 var $isRecordInWebMount_Cache = array(); // Caching array for check of whether records are in a webmount
310 var $isInWebMount_Cache = array(); // Caching array for page ids in webmounts
311 var $cachedTSconfig = array(); // Caching for collecting TSconfig for page ids
312 var $pageCache = array(); // Used for caching page records in pageInfo()
313 var $checkWorkspaceCache = array(); // Array caching workspace access for BE_USER
314
315 // Other arrays:
316 var $dbAnalysisStore = array(); // For accumulation of MM relations that must be written after new records are created.
317 var $removeFilesStore = array(); // For accumulation of files which must be deleted after processing of all input content
318 var $uploadedFileArray = array(); // Uploaded files, set by process_uploads()
319 var $registerDBList = array(); // Used for tracking references that might need correction after operations
320 var $registerDBPids = array(); // Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
321 var $copyMappingArray = array(); // 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.
322 var $remapStack = array(); // array used for remapping uids and values at the end of process_datamap
323 var $remapStackRecords = array(); // array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
324 protected $remapStackChildIds = array(); // array used for checking whether new children need to be remapped
325 protected $remapStackActions = array(); // array used for executing addition actions after remapping happened (sett processRemapStack())
326 protected $remapStackRefIndex = array(); // array used for executing post-processing on the reference index
327 var $updateRefIndexStack = array(); // array used for additional calls to $this->updateRefIndex
328 var $callFromImpExp = FALSE; // tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
329 var $newIndexMap = array(); // Array for new flexform index mapping
330
331 // Various
332 /**
333 * basicFileFunctions object
334 *
335 * @var t3lib_basicFileFunctions
336 */
337 var $fileFunc; // For "singleTon" file-manipulation object
338 var $checkValue_currentRecord = array(); // Set to "currentRecord" during checking of values.
339 var $autoVersioningUpdate = FALSE; // A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
340
341 protected $disableDeleteClause = FALSE; // Disable delete clause
342 protected $checkModifyAccessListHookObjects;
343 protected $version_remapMMForVersionSwap_reg;
344
345 /**
346 * The outer most instance of t3lib_TCEmain
347 * (t3lib_TCEmain instantiates itself on versioning and localization)
348 * @var t3lib_TCEmain
349 */
350 protected $outerMostInstance = NULL;
351
352 /**
353 * Initializing.
354 * For details, see 'TYPO3 Core API' document.
355 * This function does not start the processing of data, but merely initializes the object
356 *
357 * @param array Data to be modified or inserted in the database
358 * @param array Commands to copy, move, delete, localize, versionize records.
359 * @param object An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
360 * @return void
361 */
362 public function start($data, $cmd, $altUserObject = '') {
363
364 // Initializing BE_USER
365 $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
366 $this->userid = $this->BE_USER->user['uid'];
367 $this->username = $this->BE_USER->user['username'];
368 $this->admin = $this->BE_USER->user['admin'];
369
370 if ($this->BE_USER->uc['recursiveDelete']) {
371 $this->deleteTree = 1;
372 }
373
374 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData === TRUE) {
375 $this->updateModeL10NdiffData = FALSE;
376 }
377
378 // Initializing default permissions for pages
379 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
380 if (isset($defaultPermissions['user'])) {
381 $this->defaultPermissions['user'] = $defaultPermissions['user'];
382 }
383 if (isset($defaultPermissions['group'])) {
384 $this->defaultPermissions['group'] = $defaultPermissions['group'];
385 }
386 if (isset($defaultPermissions['everybody'])) {
387 $this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];
388 }
389
390 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
391 $this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();
392
393 // Setting the data and cmd arrays
394 if (is_array($data)) {
395 reset($data);
396 $this->datamap = $data;
397 }
398 if (is_array($cmd)) {
399 reset($cmd);
400 $this->cmdmap = $cmd;
401 }
402 }
403
404 /**
405 * Function that can mirror input values in datamap-array to other uid numbers.
406 * 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]
407 *
408 * @param array This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
409 * @return void
410 */
411 function setMirror($mirror) {
412 if (is_array($mirror)) {
413 foreach ($mirror as $table => $uid_array) {
414 if (isset($this->datamap[$table])) {
415 foreach ($uid_array as $id => $uidList) {
416 if (isset($this->datamap[$table][$id])) {
417 $theIdsInArray = t3lib_div::trimExplode(',', $uidList, 1);
418 foreach ($theIdsInArray as $copyToUid) {
419 $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
420 }
421 }
422 }
423 }
424 }
425 }
426 }
427
428 /**
429 * Initializes default values coming from User TSconfig
430 *
431 * @param array User TSconfig array
432 * @return void
433 */
434 function setDefaultsFromUserTS($userTS) {
435 if (is_array($userTS)) {
436 foreach ($userTS as $k => $v) {
437 $k = substr($k, 0, -1);
438 if ($k && is_array($v) && isset($GLOBALS['TCA'][$k])) {
439 if (is_array($this->defaultValues[$k])) {
440 $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
441 } else {
442 $this->defaultValues[$k] = $v;
443 }
444 }
445 }
446 }
447 }
448
449 /**
450 * Processing of uploaded files.
451 * 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.
452 *
453 * @param array $_FILES array
454 * @return void
455 */
456 function process_uploads($postFiles) {
457
458 if (is_array($postFiles)) {
459
460 // Editing frozen:
461 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
462 $this->newlog('All editing in this workspace has been frozen!', 1);
463 return FALSE;
464 }
465
466 $subA = reset($postFiles);
467 if (is_array($subA)) {
468 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
469 // Initialize the uploadedFilesArray:
470 $this->uploadedFileArray = array();
471
472 // For each entry:
473 foreach ($subA as $key => $values) {
474 $this->process_uploads_traverseArray($this->uploadedFileArray, $values, $key);
475 }
476 } else {
477 $this->uploadedFileArray = $subA;
478 }
479 }
480 }
481 }
482
483 /**
484 * Traverse the upload array if needed to rearrange values.
485 *
486 * @param array $this->uploadedFileArray passed by reference
487 * @param array Input array ($_FILES parts)
488 * @param string The current $_FILES array key to set on the outermost level.
489 * @return void
490 * @access private
491 * @see process_uploads()
492 */
493 function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet) {
494 if (is_array($inputArr)) {
495 foreach ($inputArr as $key => $value) {
496 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
497 }
498 } else {
499 $outputArr[$keyToSet] = $inputArr;
500 }
501 }
502
503
504 /*********************************************
505 *
506 * HOOKS
507 *
508 *********************************************/
509
510 /**
511 * Hook: processDatamap_afterDatabaseOperations
512 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
513 *
514 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
515 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
516 *
517 * @param object $hookObjectsArr: (reference) Array with hook objects
518 * @param string $status: (reference) Status of the current operation, 'new' or 'update
519 * @param string $table: (refrence) The table currently processing data for
520 * @param string $id: (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
521 * @param array $fieldArray: (reference) The field array of a record
522 * @return void
523 */
524 function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
525 // Process hook directly:
526 if (!isset($this->remapStackRecords[$table][$id])) {
527 foreach ($hookObjectsArr as $hookObj) {
528 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
529 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
530 }
531 }
532 // 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:
533 } else {
534 $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
535 'status' => $status,
536 'fieldArray' => $fieldArray,
537 'hookObjectsArr' => $hookObjectsArr,
538 );
539 }
540 }
541
542 /**
543 * Gets the 'checkModifyAccessList' hook objects.
544 * The first call initializes the accordant objects.
545 *
546 * @return array The 'checkModifyAccessList' hook objects (if any)
547 */
548 protected function getCheckModifyAccessListHookObjects() {
549 if (!isset($this->checkModifyAccessListHookObjects)) {
550 $this->checkModifyAccessListHookObjects = array();
551
552 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
553 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
554 $hookObject = t3lib_div::getUserObj($classData);
555
556 if (!($hookObject instanceof t3lib_TCEmain_checkModifyAccessListHook)) {
557 throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
558 }
559
560 $this->checkModifyAccessListHookObjects[] = $hookObject;
561 }
562 }
563 }
564
565 return $this->checkModifyAccessListHookObjects;
566 }
567
568
569 /*********************************************
570 *
571 * PROCESSING DATA
572 *
573 *********************************************/
574
575 /**
576 * Processing the data-array
577 * Call this function to process the data-array set by start()
578 *
579 * @return void
580 */
581 public function process_datamap() {
582 // Keep versionized(!) relations here locally:
583 $registerDBList = array();
584
585 $this->registerElementsToBeDeleted();
586 $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
587
588 // Editing frozen:
589 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
590 $this->newlog('All editing in this workspace has been frozen!', 1);
591 return FALSE;
592 }
593
594 // First prepare user defined objects (if any) for hooks which extend this function:
595 $hookObjectsArr = array();
596 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
597 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
598 $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
599 }
600 }
601
602 // 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.
603 $orderOfTables = array();
604 if (isset($this->datamap['pages'])) { // Set pages first.
605 $orderOfTables[] = 'pages';
606 }
607 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
608
609 // Process the tables...
610 foreach ($orderOfTables as $table) {
611 /* Check if
612 - table is set in $GLOBALS['TCA'],
613 - table is NOT readOnly
614 - the table is set with content in the data-array (if not, there's nothing to process...)
615 - permissions for tableaccess OK
616 */
617 $modifyAccessList = $this->checkModifyAccessList($table);
618 if (!$modifyAccessList) {
619 $id = 0;
620 $this->log($table, $id, 2, 0, 1, "Attempt to modify table '%s' without permission", 1, array($table));
621 }
622 if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList) {
623 if ($this->reverseOrder) {
624 $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
625 }
626
627 // For each record from the table, do:
628 // $id is the record uid, may be a string if new records...
629 // $incomingFieldArray is the array of fields
630 foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
631 if (is_array($incomingFieldArray)) {
632
633 // Hook: processDatamap_preProcessFieldArray
634 foreach ($hookObjectsArr as $hookObj) {
635 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
636 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
637 }
638 }
639
640 // ******************************
641 // Checking access to the record
642 // ******************************
643 $createNewVersion = FALSE;
644 $recordAccess = FALSE;
645 $old_pid_value = '';
646 $this->autoVersioningUpdate = FALSE;
647
648 if (!t3lib_div::testInt($id)) { // Is it a new record? (Then Id is a string)
649 $fieldArray = $this->newFieldArray($table); // Get a fieldArray with default values
650 if (isset($incomingFieldArray['pid'])) { // A pid must be set for new records.
651 // $value = the pid
652 $pid_value = $incomingFieldArray['pid'];
653
654 // Checking and finding numerical pid, it may be a string-reference to another value
655 $OK = 1;
656 if (strstr($pid_value, 'NEW')) { // If a NEW... id
657 if (substr($pid_value, 0, 1) == '-') {
658 $negFlag = -1;
659 $pid_value = substr($pid_value, 1);
660 } else {
661 $negFlag = 1;
662 }
663 if (isset($this->substNEWwithIDs[$pid_value])) { // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
664 if ($negFlag === 1) {
665 $old_pid_value = $this->substNEWwithIDs[$pid_value];
666 }
667 $pid_value = intval($negFlag * $this->substNEWwithIDs[$pid_value]);
668 } else {
669 $OK = 0;
670 } // If not found in the substArray we must stop the process...
671 } elseif ($pid_value >= 0 && $this->BE_USER->workspace !== 0
672 && $GLOBALS['TCA'][$table]['ctrl']['versioning_followPages']) {
673 // PID points to page, the workspace is an offline space and the table follows
674 // page during versioning: This means we must check if the PID page has a version
675 // in the workspace with swapmode set to 0 (zero = page+content) and if so, change
676 // the pid to the uid of that version.
677 if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid_value, 'uid,t3ver_swapmode')) { // Looks for workspace version of page.
678 if ($WSdestPage['t3ver_swapmode'] == 0) { // if swapmode is zero, then change pid value.
679 $pid_value = $WSdestPage['uid'];
680 }
681 }
682 }
683 $pid_value = intval($pid_value);
684
685 // The $pid_value is now the numerical pid at this point
686 if ($OK) {
687 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
688 if ($pid_value >= 0) { // Points to a page on which to insert the element, possibly in the top of the page
689 if ($sortRow) { // If this table is sorted we better find the top sorting number
690 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
691 }
692 $fieldArray['pid'] = $pid_value; // The numerical pid is inserted in the data array
693 } else { // points to another record before ifself
694 if ($sortRow) { // If this table is sorted we better find the top sorting number
695 $tempArray = $this->getSortNumber($table, 0, $pid_value); // Because $pid_value is < 0, getSortNumber returns an array
696 $fieldArray['pid'] = $tempArray['pid'];
697 $fieldArray[$sortRow] = $tempArray['sortNumber'];
698 } else { // Here we fetch the PID of the record that we point to...
699 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
700 $fieldArray['pid'] = $tempdata['pid'];
701 }
702 }
703 }
704 }
705 $theRealPid = $fieldArray['pid'];
706
707 // Now, check if we may insert records on this pid.
708 if ($theRealPid >= 0) {
709 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid); // Checks if records can be inserted on this $pid.
710 if ($recordAccess) {
711 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
712 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, TRUE);
713 if (!$recordAccess) {
714 $this->newlog("recordEditAccessInternals() check failed. [" . $this->BE_USER->errorMsg . "]", 1);
715 } elseif (!$this->bypassWorkspaceRestrictions) {
716 // Workspace related processing:
717 if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid, $table)) { // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
718 if ($res < 0) {
719 $recordAccess = FALSE;
720 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
721 }
722 } else { // So, if no live records were allowed, we have to create a new version of this record:
723 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
724 $createNewVersion = TRUE;
725 } else {
726 $recordAccess = FALSE;
727 $this->newlog('Record could not be created in this workspace in this branch', 1);
728 }
729 }
730 }
731 }
732 } else {
733 debug('Internal ERROR: pid should not be less than zero!');
734 }
735 $status = 'new'; // Yes new record, change $record_status to 'insert'
736 } else { // Nope... $id is a number
737 $fieldArray = array();
738 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
739 if (!$recordAccess) {
740 $propArr = $this->getRecordProperties($table, $id);
741 $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']);
742 } else { // Next check of the record permissions (internals)
743 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
744 if (!$recordAccess) {
745 $propArr = $this->getRecordProperties($table, $id);
746 $this->newlog("recordEditAccessInternals() check failed. [" . $this->BE_USER->errorMsg . "]", 1);
747 } else { // Here we fetch the PID of the record that we point to...
748 $tempdata = $this->recordInfo($table, $id, 'pid' .
749 ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : '')
750 );
751 $theRealPid = $tempdata['pid'];
752
753 // Use the new id of the versionized record we're trying to write to:
754 // (This record is a child record of a parent and has already been versionized.)
755 if ($this->autoVersionIdMap[$table][$id]) {
756 // For the reason that creating a new version of this record, automatically
757 // created related child records (e.g. "IRRE"), update the accordant field:
758 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
759
760 // Use the new id of the copied/versionized record:
761 $id = $this->autoVersionIdMap[$table][$id];
762 $recordAccess = TRUE;
763 $this->autoVersioningUpdate = TRUE;
764
765 // Checking access in case of offline workspace:
766 } elseif (!$this->bypassWorkspaceRestrictions && $errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata)) {
767 $recordAccess = FALSE; // Versioning is required and it must be offline version!
768
769 // 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.
770 if ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
771 /** @var $tce t3lib_TCEmain */
772 $tce = t3lib_div::makeInstance('t3lib_TCEmain');
773 /* @var $tce t3lib_TCEmain */
774 $tce->stripslashes_values = 0;
775
776 // Setting up command for creating a new version of the record:
777 $cmd = array();
778 $cmd[$table][$id]['version'] = array(
779 'action' => 'new',
780 'treeLevels' => -1, // Default is to create a version of the individual records... element versioning that is.
781 'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
782 );
783 $tce->start(array(), $cmd);
784 $tce->process_cmdmap();
785 $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
786
787 // If copying was successful, share the new uids (also of related children):
788 if ($tce->copyMappingArray[$table][$id]) {
789 foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
790 foreach ($origIdArray as $origId => $newId) {
791 $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
792 $this->autoVersionIdMap[$origTable][$origId] = $newId;
793 }
794 }
795 $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...
796
797 // Update registerDBList, that holds the copied relations to child records:
798 $registerDBList = array_merge($registerDBList, $tce->registerDBList);
799 // For the reason that creating a new version of this record, automatically
800 // created related child records (e.g. "IRRE"), update the accordant field:
801 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
802
803 // Use the new id of the copied/versionized record:
804 $id = $this->autoVersionIdMap[$table][$id];
805 $recordAccess = TRUE;
806 $this->autoVersioningUpdate = TRUE;
807 } else {
808 $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '" . $errorCode . "'). Auto-creation of version failed!", 1);
809 }
810 } else {
811 $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);
812 }
813 }
814 }
815 }
816 $status = 'update'; // the default is 'update'
817 }
818
819 // If access was granted above, proceed to create or update record:
820 if ($recordAccess) {
821
822 list($tscPID) = t3lib_BEfunc::getTSCpid($table, $id, $old_pid_value ? $old_pid_value : $fieldArray['pid']); // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
823 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
824 if ($status == 'new' && $table == 'pages' && is_array($TSConfig['permissions.'])) {
825 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
826 }
827 if ($createNewVersion) {
828 $newVersion_placeholderFieldArray = $fieldArray;
829 }
830
831 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
832 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
833
834 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
835
836 // Forcing some values unto field array:
837 $fieldArray = $this->overrideFieldArray($table, $fieldArray); // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
838 if ($createNewVersion) {
839 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
840 }
841
842 // Setting system fields
843 if ($status == 'new') {
844 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
845 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
846 if ($createNewVersion) {
847 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
848 }
849 }
850 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
851 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
852 if ($createNewVersion) {
853 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
854 }
855 }
856 } elseif ($this->checkSimilar) { // Removing fields which are equal to the current value:
857 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
858 }
859 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && count($fieldArray)) {
860 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
861 if ($createNewVersion) {
862 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
863 }
864 }
865 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
866 $fieldArray['t3ver_stage'] = 0;
867 }
868
869 // Hook: processDatamap_postProcessFieldArray
870 foreach ($hookObjectsArr as $hookObj) {
871 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
872 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
873 }
874 }
875
876 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
877 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
878 if (is_array($fieldArray)) {
879 if ($status == 'new') {
880 if ($createNewVersion) { // This creates a new version of the record with online placeholder and offline version
881 $versioningType = ($table === 'pages'
882 ? $this->BE_USER->workspaceVersioningTypeGetClosest(
883 t3lib_div::intInRange($GLOBALS['TYPO3_CONF_VARS']['BE']['newPagesVersioningType'], -1, 1))
884 : -1);
885 if ($this->BE_USER->workspaceVersioningTypeAccess($versioningType)) {
886 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
887 $newVersion_placeholderFieldArray['t3ver_state'] = 1; // Setting placeholder state value for temporary record
888 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace; // Setting workspace - only so display of place holders can filter out those from other workspaces.
889 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = '[PLACEHOLDER, WS#' . $this->BE_USER->workspace . ']';
890 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, FALSE); // Saving placeholder as 'original'
891
892 // For the actual new offline version, set versioning values to point to placeholder:
893 $fieldArray['pid'] = -1;
894 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
895 $fieldArray['t3ver_id'] = 1;
896 $fieldArray['t3ver_state'] = -1; // Setting placeholder state value for version (so it can know it is currently a new version...)
897 $fieldArray['t3ver_label'] = 'First draft version';
898 $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
899 if ($table === 'pages') { // Swap mode set to "branch" so we can build branches for pages.
900 $fieldArray['t3ver_swapmode'] = $versioningType;
901 }
902 $phShadowId = $this->insertDB($table, $id, $fieldArray, TRUE, 0, TRUE); // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
903 if ($phShadowId) {
904 // Processes fields of the placeholder record:
905 $this->triggerRemapAction(
906 $table,
907 $id,
908 array($this, 'placeholderShadowing'),
909 array($table, $phShadowId)
910 );
911 // Hold auto-versionized ids of placeholders:
912 $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
913 }
914 } else {
915 $this->newlog('Versioning type "' . $versioningType . '" was not allowed, so could not create new record.', 1);
916 }
917 } else {
918 $this->insertDB($table, $id, $fieldArray, FALSE, $incomingFieldArray['uid']);
919 }
920 } else {
921 $this->updateDB($table, $id, $fieldArray);
922 $this->placeholderShadowing($table, $id);
923 }
924 }
925
926 /*
927 * Hook: processDatamap_afterDatabaseOperations
928 *
929 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
930 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
931 */
932 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
933 } // if ($recordAccess) {
934 } // if (is_array($incomingFieldArray)) {
935 }
936 }
937 }
938
939 // Process the stack of relations to remap/correct
940 $this->processRemapStack();
941 $this->dbAnalysisStoreExec();
942 $this->removeRegisteredFiles();
943
944 /*
945 * Hook: processDatamap_afterAllOperations
946 *
947 * Note: When this hook gets called, all operations on the submitted data have been finished.
948 */
949 foreach ($hookObjectsArr as $hookObj) {
950 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
951 $hookObj->processDatamap_afterAllOperations($this);
952 }
953 }
954
955 if ($this->isOuterMostInstance()) {
956 $this->resetElementsToBeDeleted();
957 }
958 }
959
960 /**
961 * Fix shadowing of data in case we are editing a offline version of a live "New" placeholder record:
962 *
963 * @param string Table name
964 * @param integer Record uid
965 * @return void
966 */
967 function placeholderShadowing($table, $id) {
968 t3lib_div::loadTCA($table);
969 if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table, $id, '*')) {
970 if ((int) $liveRec['t3ver_state'] > 0) {
971 $justStoredRecord = t3lib_BEfunc::getRecord($table, $id);
972 $newRecord = array();
973
974 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
975 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
976 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
977 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
978 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
979
980 $shadowColumns = array_unique(t3lib_div::trimExplode(',', $shadowCols, 1));
981 foreach ($shadowColumns as $fieldName) {
982 if (strcmp($justStoredRecord[$fieldName], $liveRec[$fieldName])
983 && isset($GLOBALS['TCA'][$table]['columns'][$fieldName])
984 && $fieldName !== 'uid' && $fieldName !== 'pid') {
985 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
986 }
987 }
988
989 if (count($newRecord)) {
990 $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']);
991 $this->updateDB($table, $liveRec['uid'], $newRecord);
992 }
993 }
994 }
995 }
996
997 /**
998 * Filling in the field array
999 * $this->exclude_array is used to filter fields if needed.
1000 *
1001 * @param string Table name
1002 * @param integer Record ID
1003 * @param array Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1004 * @param array $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
1005 * @param integer 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.
1006 * @param string $status = 'new' or 'update'
1007 * @param integer $tscPID: TSconfig PID
1008 * @return array Field Array
1009 */
1010 function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID) {
1011
1012 // Initialize:
1013 t3lib_div::loadTCA($table);
1014 $originalLanguageRecord = NULL;
1015 $originalLanguage_diffStorage = NULL;
1016 $diffStorageFlag = FALSE;
1017
1018 // Setting 'currentRecord' and 'checkValueRecord':
1019 if (strstr($id, 'NEW')) {
1020 $currentRecord = $checkValueRecord = $fieldArray; // must have the 'current' array - not the values after processing below...
1021
1022 // IF $incomingFieldArray is an array, overlay it.
1023 // 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...
1024 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1025 $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
1026 }
1027 } else {
1028 $currentRecord = $checkValueRecord = $this->recordInfo($table, $id, '*'); // We must use the current values as basis for this!
1029
1030 t3lib_BEfunc::fixVersioningPid($table, $currentRecord); // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
1031
1032 // Get original language record if available:
1033 if (is_array($currentRecord)
1034 && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
1035 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1036 && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
1037 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1038 && intval($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]) > 0) {
1039
1040 $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] : $table;
1041 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1042 t3lib_BEfunc::workspaceOL($lookUpTable, $originalLanguageRecord);
1043 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1044 }
1045 }
1046 $this->checkValue_currentRecord = $checkValueRecord;
1047
1048 /*
1049 In the following all incoming value-fields are tested:
1050 - Are the user allowed to change the field?
1051 - Is the field uid/pid (which are already set)
1052 - perms-fields for pages-table, then do special things...
1053 - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1054
1055 If everything is OK, the field is entered into $fieldArray[]
1056 */
1057 foreach ($incomingFieldArray as $field => $fieldValue) {
1058 if (!in_array($table . '-' . $field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) { // The field must be editable.
1059
1060 // Checking if a value for language can be changed:
1061 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField']
1062 && !strcmp($GLOBALS['TCA'][$table]['ctrl']['languageField'], $field)
1063 && !$this->BE_USER->checkLanguageAccess($fieldValue);
1064
1065 if (!$languageDeny) {
1066 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
1067 if ($this->stripslashes_values) {
1068 if (is_array($fieldValue)) {
1069 t3lib_div::stripSlashesOnArray($fieldValue);
1070 } else {
1071 $fieldValue = stripslashes($fieldValue);
1072 }
1073 }
1074
1075 switch ($field) {
1076 case 'uid':
1077 case 'pid':
1078 // Nothing happens, already set
1079 break;
1080 case 'perms_userid':
1081 case 'perms_groupid':
1082 case 'perms_user':
1083 case 'perms_group':
1084 case 'perms_everybody':
1085 // Permissions can be edited by the owner or the administrator
1086 if ($table == 'pages' && ($this->admin || $status == 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
1087 $value = intval($fieldValue);
1088 switch ($field) {
1089 case 'perms_userid':
1090 $fieldArray[$field] = $value;
1091 break;
1092 case 'perms_groupid':
1093 $fieldArray[$field] = $value;
1094 break;
1095 default:
1096 if ($value >= 0 && $value < pow(2, 5)) {
1097 $fieldArray[$field] = $value;
1098 }
1099 break;
1100 }
1101 }
1102 break;
1103 case 't3ver_oid':
1104 case 't3ver_id':
1105 case 't3ver_wsid':
1106 case 't3ver_state':
1107 case 't3ver_swapmode':
1108 case 't3ver_count':
1109 case 't3ver_stage':
1110 case 't3ver_tstamp':
1111 // t3ver_label is not here because it CAN be edited as a regular field!
1112 break;
1113 default:
1114 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1115 // Evaluating the value
1116 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1117 if (isset($res['value'])) {
1118 $fieldArray[$field] = $res['value'];
1119 }
1120
1121 // Add the value of the original record to the diff-storage content:
1122 if ($this->updateModeL10NdiffData && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1123 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
1124 $diffStorageFlag = TRUE;
1125 }
1126
1127 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1128 // 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. 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.
1129 // 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.
1130 // 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 !
1131 if ($this->autoVersioningUpdate === TRUE) {
1132 if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
1133 foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1134 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1135 }
1136 }
1137 }
1138
1139 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1140 // Allow value for original UID to pass by...
1141 $fieldArray[$field] = $fieldValue;
1142 }
1143 break;
1144 }
1145 } // Checking language.
1146 } // Check exclude fields / disabled fields...
1147 }
1148 // Add diff-storage information:
1149 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1150 // 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...
1151 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1152 }
1153
1154 // Checking for RTE-transformations of fields:
1155 $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table, $currentRecord);
1156 $theTypeString = t3lib_BEfunc::getTCAtypeValue($table, $currentRecord);
1157 if (is_array($types_fieldConfig)) {
1158 foreach ($types_fieldConfig as $vconf) {
1159 // Write file configuration:
1160 $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'], array_merge($currentRecord, $fieldArray)); // inserted array_merge($currentRecord,$fieldArray) 170502
1161
1162 // RTE transformations:
1163 if (!$this->dontProcessTransformations) {
1164 if (isset($fieldArray[$vconf['field']])) {
1165 // Look for transformation flag:
1166 switch ((string) $incomingFieldArray['_TRANSFORM_' . $vconf['field']]) {
1167 case 'RTE':
1168 $RTEsetup = $this->BE_USER->getTSConfig('RTE', t3lib_BEfunc::getPagesTSconfig($tscPID));
1169 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1170
1171 // Set alternative relative path for RTE images/links:
1172 $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
1173
1174 // Get RTE object, draw form and set flag:
1175 $RTEobj = t3lib_BEfunc::RTEgetObj();
1176 if (is_object($RTEobj)) {
1177 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db', $fieldArray[$vconf['field']], $table, $vconf['field'], $currentRecord, $vconf['spec'], $thisConfig, $RTErelPath, $currentRecord['pid']);
1178 } else {
1179 debug('NO RTE OBJECT FOUND!');
1180 }
1181 break;
1182 }
1183 }
1184 }
1185
1186 // Write file configuration:
1187 if (is_array($eFile)) {
1188 $mixedRec = array_merge($currentRecord, $fieldArray);
1189 $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
1190 $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
1191 /* @var $parseHTML t3lib_parsehtml_proc */
1192 $parseHTML->init('', '');
1193
1194 $eFileMarker = $eFile['markerField'] && trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
1195 $insertContent = str_replace($eFileMarker, '', $mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
1196
1197 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, LF . $insertContent . LF, 1, 1);
1198 t3lib_div::writeFile($eFile['editFile'], $SW_fileNewContent);
1199
1200 // Write status:
1201 if (!strstr($id, 'NEW') && $eFile['statusField']) {
1202 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
1203 $table,
1204 'uid=' . intval($id),
1205 array(
1206 $eFile['statusField'] => $eFile['relEditFile'] . ' updated ' . date('d-m-Y H:i:s') . ', bytes ' . strlen($mixedRec[$eFile['contentField']])
1207 )
1208 );
1209 }
1210 } elseif ($eFile && is_string($eFile)) {
1211 $this->log($table, $id, 2, 0, 1, "Write-file error: '%s'", 13, array($eFile), $realPid);
1212 }
1213 }
1214 }
1215 // Return fieldArray
1216 return $fieldArray;
1217 }
1218
1219
1220 /*********************************************
1221 *
1222 * Evaluation of input values
1223 *
1224 ********************************************/
1225
1226 /**
1227 * Evaluates a value according to $table/$field settings.
1228 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1229 * 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() )
1230 *
1231 * @param string Table name
1232 * @param string Field name
1233 * @param string 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.
1234 * @param string The record-uid, mainly - but not exclusively - used for logging
1235 * @param string 'update' or 'new' flag
1236 * @param integer 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.
1237 * @param integer $tscPID
1238 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1239 */
1240 function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID) {
1241 t3lib_div::loadTCA($table);
1242
1243 $res = array(); // result array
1244 $recFID = $table . ':' . $id . ':' . $field;
1245
1246 // Processing special case of field pages.doktype
1247 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1248 // If the user may not use this specific doktype, we issue a warning
1249 if (!($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1250 $propArr = $this->getRecordProperties($table, $id);
1251 $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']);
1252 return $res;
1253 }
1254 ;
1255 if ($status == 'update') {
1256 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1257 $onlyAllowedTables = (isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'])
1258 ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']
1259 : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables']);
1260 if ($onlyAllowedTables) {
1261 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1262 if ($theWrongTables) {
1263 $propArr = $this->getRecordProperties($table, $id);
1264 $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']);
1265 return $res;
1266 }
1267 }
1268 }
1269 }
1270
1271 // Get current value:
1272 $curValueRec = $this->recordInfo($table, $id, $field);
1273 $curValue = $curValueRec[$field];
1274
1275 // Getting config for the field
1276 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1277
1278 // Preform processing:
1279 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1280
1281 return $res;
1282 }
1283
1284 /**
1285 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1286 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1287 *
1288 * @param array The result array. The processed value (if any!) is set in the "value" key.
1289 * @param string The value to set.
1290 * @param array Field configuration from $GLOBALS['TCA']
1291 * @param string Table name
1292 * @param integer Return UID
1293 * @param [type] $curValue: ...
1294 * @param [type] $status: ...
1295 * @param integer 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.
1296 * @param [type] $recFID: ...
1297 * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1298 * @param [type] $uploadedFiles: ...
1299 * @param [type] $tscPID: ...
1300 * @return array Returns the evaluated $value as key "value" in this array.
1301 */
1302 function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID) {
1303
1304 $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
1305
1306 switch ($tcaFieldConf['type']) {
1307 case 'text':
1308 $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
1309 break;
1310 case 'passthrough':
1311 case 'user':
1312 $res['value'] = $value;
1313 break;
1314 case 'input':
1315 $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
1316 break;
1317 case 'check':
1318 $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP);
1319 break;
1320 case 'radio':
1321 $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
1322 break;
1323 case 'group':
1324 case 'select':
1325 $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1326 break;
1327 case 'inline':
1328 $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field);
1329 break;
1330 case 'flex':
1331 if ($field) { // FlexForms are only allowed for real fields.
1332 $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1333 }
1334 break;
1335 default:
1336 #debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
1337 break;
1338 }
1339
1340 return $res;
1341 }
1342
1343
1344 /**
1345 * Evaluate "text" type values.
1346 *
1347 * @param array The result array. The processed value (if any!) is set in the "value" key.
1348 * @param string The value to set.
1349 * @param array Field configuration from TCA
1350 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1351 * @param string Field name
1352 * @return array Modified $res array
1353 */
1354 function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1355 $evalCodesArray = t3lib_div::trimExplode(',', $tcaFieldConf['eval'], 1);
1356 $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1357 return $res;
1358 }
1359
1360 /**
1361 * Evaluate "input" type values.
1362 *
1363 * @param array The result array. The processed value (if any!) is set in the "value" key.
1364 * @param string The value to set.
1365 * @param array Field configuration from TCA
1366 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1367 * @param string Field name
1368 * @return array Modified $res array
1369 */
1370 function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1371 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1372
1373 // Secures the string-length to be less than max.
1374 if (intval($tcaFieldConf['max']) > 0) {
1375 $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, $value, 0, intval($tcaFieldConf['max']));
1376 }
1377
1378 // Checking range of value:
1379 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && $value != $tcaFieldConf['default']) {
1380 if (isset($tcaFieldConf['range']['upper']) && $value > $tcaFieldConf['range']['upper']) {
1381 $value = $tcaFieldConf['range']['upper'];
1382 }
1383 if (isset($tcaFieldConf['range']['lower']) && $value < $tcaFieldConf['range']['lower']) {
1384 $value = $tcaFieldConf['range']['lower'];
1385 }
1386 }
1387
1388 // Process evaluation settings:
1389 $evalCodesArray = t3lib_div::trimExplode(',', $tcaFieldConf['eval'], 1);
1390 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1391
1392 // Process UNIQUE settings:
1393 if ($field && $realPid >= 0) { // 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...
1394 if ($res['value'] && in_array('uniqueInPid', $evalCodesArray)) {
1395 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1396 }
1397 if ($res['value'] && in_array('unique', $evalCodesArray)) {
1398 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1399 }
1400 }
1401
1402 return $res;
1403 }
1404
1405 /**
1406 * Evaluates 'check' type values.
1407 *
1408 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1409 * @param string The value to set.
1410 * @param array Field configuration from TCA
1411 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1412 * @return array Modified $res array
1413 */
1414 function checkValue_check($res, $value, $tcaFieldConf, $PP) {
1415 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1416
1417 $itemC = count($tcaFieldConf['items']);
1418 if (!$itemC) {
1419 $itemC = 1;
1420 }
1421 $maxV = pow(2, $itemC);
1422
1423 if ($value < 0) {
1424 $value = 0;
1425 }
1426 if ($value > $maxV) {
1427 $value = $maxV;
1428 }
1429 $res['value'] = $value;
1430
1431 return $res;
1432 }
1433
1434 /**
1435 * Evaluates 'radio' type values.
1436 *
1437 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1438 * @param string The value to set.
1439 * @param array Field configuration from TCA
1440 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1441 * @return array Modified $res array
1442 */
1443 function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1444 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1445
1446 if (is_array($tcaFieldConf['items'])) {
1447 foreach ($tcaFieldConf['items'] as $set) {
1448 if (!strcmp($set[1], $value)) {
1449 $res['value'] = $value;
1450 break;
1451 }
1452 }
1453 }
1454
1455 return $res;
1456 }
1457
1458 /**
1459 * Evaluates 'group' or 'select' type values.
1460 *
1461 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1462 * @param string The value to set.
1463 * @param array Field configuration from TCA
1464 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1465 * @param [type] $uploadedFiles: ...
1466 * @param string Field name
1467 * @return array Modified $res array
1468 */
1469 function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1470
1471 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1472
1473 // Detecting if value sent is an array and if so, implode it around a comma:
1474 if (is_array($value)) {
1475 $value = implode(',', $value);
1476 }
1477
1478 // This converts all occurencies of '&#123;' 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.
1479 // Anyways, this should NOT disturb anything else:
1480 $value = $this->convNumEntityToByteValue($value);
1481
1482 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1483 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1484
1485 // If not multiple is set, then remove duplicates:
1486 if (!$tcaFieldConf['multiple']) {
1487 $valueArray = array_unique($valueArray);
1488 }
1489
1490 // If an exclusive key is found, discard all others:
1491 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1492 $exclusiveKeys = t3lib_div::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1493 foreach ($valueArray as $kk => $vv) {
1494 if (in_array($vv, $exclusiveKeys)) { // $vv is the item key!
1495 $valueArray = array($kk => $vv);
1496 break;
1497 }
1498 }
1499 }
1500
1501 // 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?)
1502 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1503
1504 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1505 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1506 $preCount = count($valueArray);
1507 foreach ($valueArray as $kk => $vv) {
1508 if (!$this->BE_USER->checkAuthMode($table, $field, $vv, $tcaFieldConf['authMode'])) {
1509 unset($valueArray[$kk]);
1510 }
1511 }
1512
1513 // 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.
1514 if ($preCount && !count($valueArray)) {
1515 return array();
1516 }
1517 }
1518
1519 // For group types:
1520 if ($tcaFieldConf['type'] == 'group') {
1521 switch ($tcaFieldConf['internal_type']) {
1522 case 'file_reference':
1523 case 'file':
1524 $valueArray = $this->checkValue_group_select_file(
1525 $valueArray,
1526 $tcaFieldConf,
1527 $curValue,
1528 $uploadedFiles,
1529 $status,
1530 $table,
1531 $id,
1532 $recFID
1533 );
1534 break;
1535 case 'db':
1536 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
1537 break;
1538 }
1539 }
1540 // For select types which has a foreign table attached:
1541 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
1542 // check, if there is a NEW... id in the value, that should be substituded later
1543 if (strpos($value, 'NEW') !== FALSE) {
1544 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
1545 $this->addNewValuesToRemapStackChildIds($valueArray);
1546 $this->remapStack[] = array(
1547 'func' => 'checkValue_group_select_processDBdata',
1548 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
1549 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
1550 'field' => $field
1551 );
1552 $unsetResult = TRUE;
1553 } else {
1554 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
1555 }
1556 }
1557
1558 if (!$unsetResult) {
1559 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
1560 $res['value'] = implode(',', $newVal);
1561 } else {
1562 unset($res['value']);
1563 }
1564
1565 return $res;
1566 }
1567
1568 /**
1569 * Handling files for group/select function
1570 *
1571 * @param array Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
1572 * @param array Configuration array from TCA of the field
1573 * @param string Current value of the field
1574 * @param array Array of uploaded files, if any
1575 * @param string Status ("update" or ?)
1576 * @param string tablename of record
1577 * @param integer UID of record
1578 * @param string Field identifier ([table:uid:field:....more for flexforms?]
1579 * @return array Modified value array
1580 * @see checkValue_group_select()
1581 */
1582 function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
1583
1584 if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
1585
1586 // If any files are uploaded, add them to value array
1587 if (is_array($uploadedFileArray) &&
1588 $uploadedFileArray['name'] &&
1589 strcmp($uploadedFileArray['tmp_name'], 'none')) {
1590 $valueArray[] = $uploadedFileArray['tmp_name'];
1591 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1592 }
1593
1594 // Creating fileFunc object.
1595 if (!$this->fileFunc) {
1596 $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
1597 $this->include_filefunctions = 1;
1598 }
1599 // Setting permitted extensions.
1600 $all_files = array();
1601 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1602 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
1603 $all_files['ftpspace'] = $all_files['webspace'];
1604 $this->fileFunc->init('', $all_files);
1605 }
1606
1607 // If there is an upload folder defined:
1608 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
1609 if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
1610 // For logging..
1611 $propArr = $this->getRecordProperties($table, $id);
1612
1613 // Get destrination path:
1614 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1615
1616 // If we are updating:
1617 if ($status == 'update') {
1618
1619 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
1620 // 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!
1621 // 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_.
1622 // 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.
1623 // Illustration of the problem comes here:
1624 // 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.
1625 // 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.
1626 // 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.
1627 // 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.
1628 if ($this->autoVersioningUpdate === TRUE) {
1629 foreach ($valueArray as $key => $theFile) {
1630 if ($theFile === basename($theFile)) { // If it is an already attached file...
1631 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
1632 }
1633 }
1634 }
1635
1636 // Finding the CURRENT files listed, either from MM or from the current record.
1637 $theFileValues = array();
1638 if ($tcaFieldConf['MM']) { // If MM relations for the files also!
1639 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1640 /* @var $dbAnalysis t3lib_loadDBGroup */
1641 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
1642 foreach ($dbAnalysis->itemArray as $item) {
1643 if ($item['id']) {
1644 $theFileValues[] = $item['id'];
1645 }
1646 }
1647 } else {
1648 $theFileValues = t3lib_div::trimExplode(',', $curValue, 1);
1649 }
1650 $currentFilesForHistory = implode(',', $theFileValues);
1651
1652 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1653 if (count($theFileValues)) {
1654 // 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!)
1655 foreach ($valueArray as $key => $theFile) {
1656 if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile), '/')) {
1657 $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues, $theFile);
1658 }
1659 }
1660
1661 // This array contains the filenames in the uploadfolder that should be deleted:
1662 foreach ($theFileValues as $key => $theFile) {
1663 $theFile = trim($theFile);
1664 if (@is_file($dest . '/' . $theFile)) {
1665 $this->removeFilesStore[] = $dest . '/' . $theFile;
1666 } elseif ($theFile) {
1667 $this->log($table, $id, 5, 0, 1, "Could not delete file '%s' (does not exist). (%s)", 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
1668 }
1669 }
1670 }
1671 }
1672
1673 // Traverse the submitted values:
1674 foreach ($valueArray as $key => $theFile) {
1675 // NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1676 if (strstr(t3lib_div::fixWindowsFilePath($theFile), '/')) {
1677 // Init:
1678 $maxSize = intval($tcaFieldConf['max_size']);
1679 $cmd = '';
1680 $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1681
1682 // Check various things before copying file:
1683 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist
1684
1685 // Finding size.
1686 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
1687 $fileSize = $uploadedFileArray['size'];
1688 } else {
1689 $fileSize = filesize($theFile);
1690 }
1691
1692 if (!$maxSize || $fileSize <= ($maxSize * 1024)) { // Check file size:
1693 // Prepare filename:
1694 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
1695 $fI = t3lib_div::split_fileref($theEndFileName);
1696
1697 // Check for allowed extension:
1698 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1699 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
1700
1701 // If we have a unique destination filename, then write the file:
1702 if ($theDestFile) {
1703 t3lib_div::upload_copy_move($theFile, $theDestFile);
1704
1705 // Hook for post-processing the upload action
1706 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
1707 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
1708 $hookObject = t3lib_div::getUserObj($classRef);
1709
1710 if (!($hookObject instanceof t3lib_TCEmain_processUploadHook)) {
1711 throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_processUploadHook', 1279962349);
1712 }
1713
1714 $hookObject->processUpload_postProcessAction($theDestFile, $this);
1715 }
1716 }
1717
1718 $this->copiedFileMap[$theFile] = $theDestFile;
1719 clearstatcache();
1720 if (!@is_file($theDestFile)) {
1721 $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']);
1722 }
1723 } else {
1724 $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']);
1725 }
1726 } else {
1727 $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
1728 }
1729 } else {
1730 $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']);
1731 }
1732 } else {
1733 $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']);
1734 }
1735
1736 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1737 if (@is_file($theDestFile)) {
1738 $info = t3lib_div::split_fileref($theDestFile);
1739 $valueArray[$key] = $info['file']; // The value is set to the new filename
1740 } else {
1741 unset($valueArray[$key]); // The value is set to the new filename
1742 }
1743 }
1744 }
1745 }
1746
1747 // 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!
1748 if ($tcaFieldConf['MM']) {
1749 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1750 /* @var $dbAnalysis t3lib_loadDBGroup */
1751 $dbAnalysis->tableArray['files'] = array(); // dummy
1752
1753 foreach ($valueArray as $key => $theFile) {
1754 // explode files
1755 $dbAnalysis->itemArray[]['id'] = $theFile;
1756 }
1757 if ($status == 'update') {
1758 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
1759 $newFiles = implode(',', $dbAnalysis->getValueArray());
1760 list(, , $recFieldName) = explode(':', $recFID);
1761 if ($currentFilesForHistory != $newFiles) {
1762 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
1763 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
1764 } else {
1765 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
1766 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
1767 }
1768 } else {
1769 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1770 }
1771 $valueArray = $dbAnalysis->countItems();
1772 }
1773 //store path relative to site root (if uploadfolder is not set or internal_type is file_reference)
1774 } else {
1775 if (count($valueArray)) {
1776 if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
1777 $propArr = $this->getRecordProperties($table, $id); // For logging..
1778 foreach ($valueArray as &$theFile) {
1779
1780 // if alernative File Path is set for the file, then it was an import
1781 if ($this->alternativeFilePath[$theFile]) {
1782
1783 // don't import the file if it already exists
1784 if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
1785 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
1786
1787 // import the file
1788 } elseif (@is_file($theFile)) {
1789 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
1790 if (!@is_dir($dest)) {
1791 t3lib_div::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
1792 }
1793
1794 // Init:
1795 $maxSize = intval($tcaFieldConf['max_size']);
1796 $cmd = '';
1797 $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1798 $fileSize = filesize($theFile);
1799
1800 if (!$maxSize || $fileSize <= ($maxSize * 1024)) { // Check file size:
1801 // Prepare filename:
1802 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
1803 $fI = t3lib_div::split_fileref($theEndFileName);
1804
1805 // Check for allowed extension:
1806 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1807 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
1808
1809 // Write the file:
1810 if ($theDestFile) {
1811 t3lib_div::upload_copy_move($theFile, $theDestFile);
1812 $this->copiedFileMap[$theFile] = $theDestFile;
1813 clearstatcache();
1814 if (!@is_file($theDestFile)) {
1815 $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']);
1816 }
1817 } else {
1818 $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']);
1819 }
1820 } else {
1821 $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
1822 }
1823 } else {
1824 $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']);
1825 }
1826
1827 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1828 if (@is_file($theDestFile)) {
1829 $theFile = $theDestFile; // The value is set to the new filename
1830 } else {
1831 unset($theFile); // The value is set to the new filename
1832 }
1833 }
1834 }
1835 $theFile = t3lib_div::fixWindowsFilePath($theFile);
1836 if (t3lib_div::isFirstPartOfStr($theFile, PATH_site)) {
1837 $theFile = substr($theFile, strlen(PATH_site));
1838 }
1839 }
1840 unset($theFile);
1841 }
1842 }
1843 }
1844
1845 return $valueArray;
1846 }
1847
1848 /**
1849 * Evaluates 'flex' type values.
1850 *
1851 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1852 * @param string The value to set.
1853 * @param array Field configuration from TCA
1854 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1855 * @param array Uploaded files for the field
1856 * @param array Current record array.
1857 * @param string Field name
1858 * @return array Modified $res array
1859 */
1860 function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1861 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1862
1863 if (is_array($value)) {
1864
1865 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
1866 // 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.
1867 $newRecordPidValue = $status == 'new' ? $realPid : 0;
1868
1869 // Get current value array:
1870 $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, '', TRUE, $newRecordPidValue);
1871
1872 $currentValueArray = t3lib_div::xml2array($curValue);
1873 if (!is_array($currentValueArray)) {
1874 $currentValueArray = array();
1875 }
1876 if (is_array($currentValueArray['meta']['currentLangId'])) {
1877 unset($currentValueArray['meta']['currentLangId']);
1878 } // Remove all old meta for languages...
1879
1880 // Evaluation of input values:
1881 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
1882
1883 // Create XML and convert charsets from input value:
1884 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
1885
1886 // If we wanted to set UTF fixed:
1887 // $storeInCharset='utf-8';
1888 // $currentCharset=$GLOBALS['LANG']->charSet;
1889 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1890 $storeInCharset = $GLOBALS['LANG']->charSet;
1891
1892 // Merge them together IF they are both arrays:
1893 // 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).
1894 if (is_array($currentValueArray)) {
1895 $arrValue = t3lib_div::xml2array($xmlValue);
1896 $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray, $arrValue);
1897 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
1898 }
1899
1900 // Action commands (sorting order and removals of elements)
1901 $actionCMDs = t3lib_div::_GP('_ACTION_FLEX_FORMdata');
1902 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
1903 $arrValue = t3lib_div::xml2array($xmlValue);
1904 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
1905 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
1906 }
1907
1908 // Create the value XML:
1909 $res['value'] = '';
1910 $res['value'] .= $xmlValue;
1911 } else { // Passthrough...:
1912 $res['value'] = $value;
1913 }
1914
1915 return $res;
1916 }
1917
1918 /**
1919 * Converts an array to FlexForm XML
1920 *
1921 * @param array Array with FlexForm data
1922 * @param boolean If set, the XML prologue is returned as well.
1923 * @return string Input array converted to XML
1924 */
1925 function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
1926 $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
1927 /* @var $flexObj t3lib_flexformtools */
1928 return $flexObj->flexArray2Xml($array, $addPrologue);
1929 }
1930
1931 /**
1932 * Actions for flex form element (move, delete)
1933 *
1934 * @param array &$valueArrayToRemoveFrom: by reference
1935 * @param array $deleteCMDS: ... *
1936 * @return void
1937 */
1938 function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
1939 if (is_array($valueArray) && is_array($actionCMDs)) {
1940 foreach ($actionCMDs as $key => $value) {
1941 if ($key == '_ACTION') {
1942 // First, check if there are "commands":
1943 if (current($actionCMDs[$key]) !== "") {
1944 asort($actionCMDs[$key]);
1945 $newValueArray = array();
1946 foreach ($actionCMDs[$key] as $idx => $order) {
1947 if (substr($idx, 0, 3) == "ID-") {
1948 $idx = $this->newIndexMap[$idx];
1949 }
1950 if ($order != "DELETE") { // 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.
1951 $newValueArray[$idx] = $valueArray[$idx];
1952 }
1953 unset($valueArray[$idx]);
1954 }
1955 $valueArray = t3lib_div::array_merge($newValueArray, $valueArray);
1956 }
1957 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
1958 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
1959 }
1960 }
1961 }
1962 }
1963
1964 /**
1965 * Evaluates 'inline' type values.
1966 * (partly copied from the select_group function on this issue)
1967 *
1968 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1969 * @param string The value to set.
1970 * @param array Field configuration from TCA
1971 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1972 * @param string Field name
1973 * @return array Modified $res array
1974 */
1975 function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field) {
1976 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1977
1978 if (!$tcaFieldConf['foreign_table']) {
1979 return FALSE; // Fatal error, inline fields should always have a foreign_table defined
1980 }
1981
1982 // When values are sent they come as comma-separated values which are exploded by this function:
1983 $valueArray = t3lib_div::trimExplode(',', $value);
1984
1985 // Remove duplicates: (should not be needed)
1986 $valueArray = array_unique($valueArray);
1987
1988 // Example for received data:
1989 // $value = 45,NEW4555fdf59d154,12,123
1990 // We need to decide whether we use the stack or can save the relation directly.
1991 if (strpos($value, 'NEW') !== FALSE || !t3lib_div::testInt($id)) {
1992 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
1993 $this->addNewValuesToRemapStackChildIds($valueArray);
1994 $this->remapStack[] = array(
1995 'func' => 'checkValue_inline_processDBdata',
1996 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
1997 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
1998 'field' => $field
1999 );
2000 unset($res['value']);
2001 } elseif ($value || t3lib_div::testInt($id)) {
2002 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
2003 }
2004
2005 return $res;
2006 }
2007
2008 /**
2009 * Checks if a fields has more items than defined via TCA in maxitems.
2010 * If there are more items than allowd, the item list is truncated to the defined number.
2011 *
2012 * @param array $tcaFieldConf: Field configuration from TCA
2013 * @param array $valueArray: Current value array of items
2014 * @return array The truncated value array of items
2015 */
2016 function checkValue_checkMax($tcaFieldConf, $valueArray) {
2017 // 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...
2018
2019 $valueArrayC = count($valueArray);
2020
2021 // 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.
2022 $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']) : 1;
2023 if ($valueArrayC > $maxI) {
2024 $valueArrayC = $maxI;
2025 } // Checking for not too many elements
2026
2027 // Dumping array to list
2028 $newVal = array();
2029 foreach ($valueArray as $nextVal) {
2030 if ($valueArrayC == 0) {
2031 break;
2032 }
2033 $valueArrayC--;
2034 $newVal[] = $nextVal;
2035 }
2036
2037 return $newVal;
2038 }
2039
2040
2041 /*********************************************
2042 *
2043 * Helper functions for evaluation functions.
2044 *
2045 ********************************************/
2046
2047 /**
2048 * Gets a unique value for $table/$id/$field based on $value
2049 *
2050 * @param string Table name
2051 * @param string Field name for which $value must be unique
2052 * @param string Value string.
2053 * @param integer UID to filter out in the lookup (the record itself...)
2054 * @param integer If set, the value will be unique for this PID
2055 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2056 */
2057 function getUnique($table, $field, $value, $id, $newPid = 0) {
2058
2059 // Initialize:
2060 t3lib_div::loadTCA($table);
2061 $whereAdd = '';
2062 $newValue = '';
2063 if (intval($newPid)) {
2064 $whereAdd .= ' AND pid=' . intval($newPid);
2065 } else {
2066 $whereAdd .= ' AND pid>=0';
2067 } // "AND pid>=0" for versioning
2068 $whereAdd .= $this->deleteClause($table);
2069
2070 // If the field is configured in TCA, proceed:
2071 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2072
2073 // Look for a record which might already have the value:
2074 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table) . ' AND uid!=' . intval($id) . $whereAdd);
2075 $counter = 0;
2076
2077 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2078 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
2079 $newValue = $value . $counter;
2080 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table) . ' AND uid!=' . intval($id) . $whereAdd);
2081 $counter++;
2082 if ($counter > 100) {
2083 break;
2084 } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
2085 }
2086 // If the new value is there:
2087 $value = strlen($newValue) ? $newValue : $value;
2088 }
2089 return $value;
2090 }
2091
2092 function checkValue_text_Eval($value, $evalArray, $is_in) {
2093 $res = array();
2094 $newValue = $value;
2095 $set = TRUE;
2096
2097 foreach ($evalArray as $func) {
2098 switch ($func) {
2099 case 'trim':
2100 $value = trim($value);
2101 break;
2102 case 'required':
2103 if (!$value) {
2104 $set = 0;
2105 }
2106 break;
2107 default:
2108 if (t3lib_div::hasValidClassPrefix($func)) {
2109 $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2110 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2111 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2112 }
2113 }
2114 break;
2115 }
2116 }
2117 if ($set) {
2118 $res['value'] = $value;
2119 }
2120 return $res;
2121 }
2122
2123 /**
2124 * Evaluation of 'input'-type values based on 'eval' list
2125 *
2126 * @param string Value to evaluate
2127 * @param array Array of evaluations to traverse.
2128 * @param string Is-in string for 'is_in' evaluation
2129 * @return array Modified $value in key 'value' or empty array
2130 */
2131 function checkValue_input_Eval($value, $evalArray, $is_in) {
2132 $res = array();
2133 $newValue = $value;
2134 $set = TRUE;
2135
2136 foreach ($evalArray as $func) {
2137 switch ($func) {
2138 case 'int':
2139 case 'year':
2140 case 'time':
2141 case 'timesec':
2142 $value = intval($value);
2143 break;
2144 case 'date':
2145 case 'datetime':
2146 $value = intval($value);
2147 if ($value > 0 && !$this->dontProcessTransformations) {
2148 $value -= date('Z', $value);
2149 }
2150 break;
2151 case 'double2':
2152 $value = preg_replace('/[^0-9,\.-]/', '', $value);
2153 $negative = substr($value, 0, 1) == '-';
2154 $value = strtr($value, array(',' => '.', '-' => ''));
2155 if (strpos($value, '.') === FALSE) {
2156 $value .= '.0';
2157 }
2158 $valueArray = explode('.', $value);
2159 $dec = array_pop($valueArray);
2160 $value = join('', $valueArray) . '.' . $dec;
2161 if ($negative) {
2162 $value *= -1;
2163 }
2164 $value = number_format($value, 2, '.', '');
2165 break;
2166 case 'md5':
2167 if (strlen($value) != 32) {
2168 $set = FALSE;
2169 }
2170 break;
2171 case 'trim':
2172 $value = trim($value);
2173 break;
2174 case 'upper':
2175 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
2176 break;
2177 case 'lower':
2178 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
2179 break;
2180 case 'required':
2181 if (!isset($value) || $value === '') {
2182 $set = FALSE;
2183 }
2184 break;
2185 case 'is_in':
2186 $c = strlen($value);
2187 if ($c) {
2188 $newVal = '';
2189 for ($a = 0; $a < $c; $a++) {
2190 $char = substr($value, $a, 1);
2191 if (strpos($is_in, $char) !== FALSE) {
2192 $newVal .= $char;
2193 }
2194 }
2195 $value = $newVal;
2196 }
2197 break;
2198 case 'nospace':
2199 $value = str_replace(' ', '', $value);
2200 break;
2201 case 'alpha':
2202 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2203 break;
2204 case 'num':
2205 $value = preg_replace('/[^0-9]/', '', $value);
2206 break;
2207 case 'alphanum':
2208 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2209 break;
2210 case 'alphanum_x':
2211 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2212 break;
2213 default:
2214 if (t3lib_div::hasValidClassPrefix($func)) {
2215 $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2216 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2217 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2218 }
2219 }
2220 break;
2221 }
2222 }
2223 if ($set) {
2224 $res['value'] = $value;
2225 }
2226 return $res;
2227 }
2228
2229 /**
2230 * Returns data for group/db and select fields
2231 *
2232 * @param array Current value array
2233 * @param array TCA field config
2234 * @param integer Record id, used for look-up of MM relations (local_uid)
2235 * @param string Status string ('update' or 'new')
2236 * @param string The type, either 'select', 'group' or 'inline'
2237 * @param string Table name, needs to be passed to t3lib_loadDBGroup
2238 * @param string field name, needs to be set for writing to sys_history
2239 * @return array Modified value array
2240 */
2241 function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
2242 $tables = $type == 'group' ? $tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'] . ',' . $tcaFieldConf['neg_foreign_table'];
2243 $prep = $type == 'group' ? $tcaFieldConf['prepend_tname'] : $tcaFieldConf['neg_foreign_table'];
2244 $newRelations = implode(',', $valueArray);
2245
2246 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
2247 /* @var $dbAnalysis t3lib_loadDBGroup */
2248 $dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2249 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2250
2251 if ($tcaFieldConf['MM']) {
2252 if ($status == 'update') {
2253 $oldRelations_dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
2254 /* @var $oldRelations_dbAnalysis t3lib_loadDBGroup */
2255 $oldRelations_dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2256 // db analysis with $id will initialize with the existing relations
2257 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2258 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2259 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2260 if ($oldRelations != $newRelations) {
2261 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2262 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2263 } else {
2264 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2265 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2266 }
2267 } else {
2268 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable); // This will be traversed later to execute the actions
2269 }
2270 $valueArray = $dbAnalysis->countItems();
2271 } else {
2272 $valueArray = $dbAnalysis->getValueArray($prep);
2273 if ($type == 'select' && $prep) {
2274 $valueArray = $dbAnalysis->convertPosNeg($valueArray, $tcaFieldConf['foreign_table'], $tcaFieldConf['neg_foreign_table']);
2275 }
2276 }
2277
2278 // 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.
2279 return $valueArray;
2280 }
2281
2282 /**
2283 * Explodes the $value, which is a list of files/uids (group select)
2284 *
2285 * @param string 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.
2286 * @return array The value array.
2287 */
2288 function checkValue_group_select_explodeSelectGroupValue($value) {
2289 $valueArray = t3lib_div::trimExplode(',', $value, 1);
2290 foreach ($valueArray as &$newVal) {
2291 $temp = explode('|', $newVal, 2);
2292 $newVal = str_replace(
2293 ',',
2294 '',
2295 str_replace('|', '', rawurldecode($temp[0]))
2296 );
2297 }
2298 unset($newVal);
2299 return $valueArray;
2300 }
2301
2302 /**
2303 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2304 * See checkValue_flex_procInData_travDS() for more details.
2305 * 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
2306 *
2307 * @param array The 'data' part of the INPUT flexform data
2308 * @param array The 'data' part of the CURRENT flexform data
2309 * @param array The uploaded files for the 'data' part of the INPUT flexform data
2310 * @param array 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.
2311 * @param array A set of parameters to pass through for the calling of the evaluation functions
2312 * @param string Optional call back function, see checkValue_flex_procInData_travDS() DEPRICATED, use class.t3lib_flexformtools.php instead for traversal!
2313 * @return array The modified 'data' part.
2314 * @see checkValue_flex_procInData_travDS()
2315 */
2316 function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructArray, $pParams, $callBackFunc = '') {
2317 if (is_array($dataPart)) {
2318 foreach ($dataPart as $sKey => $sheetDef) {
2319 list ($dataStruct, $actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray, $sKey);
2320 if (is_array($dataStruct) && $actualSheet == $sKey && is_array($sheetDef)) {
2321 foreach ($sheetDef as $lKey => $lData) {
2322 $this->checkValue_flex_procInData_travDS(
2323 $dataPart[$sKey][$lKey],
2324 $dataPart_current[$sKey][$lKey],
2325 $uploadedFiles[$sKey][$lKey],
2326 $dataStruct['ROOT']['el'],
2327 $pParams,
2328 $callBackFunc,
2329 $sKey . '/' . $lKey . '/'
2330 );
2331 }
2332 }
2333 }
2334 }
2335
2336 return $dataPart;
2337 }
2338
2339 /**
2340 * Processing of the sheet/language data array
2341 * 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.
2342 *
2343 * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2344 * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2345 * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2346 * @param array Data structure which fits the data array
2347 * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
2348 * @param string Call back function, default is checkValue_SW(). If $this->callBackObj is set to an object, the callback function in that object is called instead.
2349 * @param [type] $structurePath: ...
2350 * @return void
2351 * @see checkValue_flex_procInData()
2352 */
2353 function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath) {
2354 if (is_array($DSelements)) {
2355
2356 // For each DS element:
2357 foreach ($DSelements as $key => $dsConf) {
2358
2359 // Array/Section:
2360 if ($DSelements[$key]['type'] == 'array') {
2361 if (is_array($dataValues[$key]['el'])) {
2362 if ($DSelements[$key]['section']) {
2363 $newIndexCounter = 0;
2364 foreach ($dataValues[$key]['el'] as $ik => $el) {
2365 if (is_array($el)) {
2366 if (!is_array($dataValues_current[$key]['el'])) {
2367 $dataValues_current[$key]['el'] = array();
2368 }
2369
2370 $theKey = key($el);
2371
2372 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2373 $this->checkValue_flex_procInData_travDS(
2374 $dataValues[$key]['el'][$ik][$theKey]['el'],
2375 is_array($dataValues_current[$key]['el'][$ik]) ? $dataValues_current[$key]['el'][$ik][$theKey]['el'] : array(),
2376 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2377 $DSelements[$key]['el'][$theKey]['el'],
2378 $pParams,
2379 $callBackFunc,
2380 $structurePath . $key . '/el/' . $ik . '/' . $theKey . '/el/'
2381 );
2382
2383 // 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:
2384 // The fact that the order changes is not important since order is controlled by a separately submitted index.
2385
2386 if (substr($ik, 0, 3) == "ID-") {
2387 $newIndexCounter++;
2388 $this->newIndexMap[$ik] = (is_array($dataValues_current[$key]['el']) && count($dataValues_current[$key]['el']) ? max(array_keys($dataValues_current[$key]['el'])) : 0) + $newIndexCounter; // Set mapping index
2389 $dataValues[$key]['el'][$this->newIndexMap[$ik]] = $dataValues[$key]['el'][$ik]; // Transfer values
2390 unset($dataValues[$key]['el'][$ik]); // Unset original
2391 }
2392 }
2393 }
2394 }
2395 } else {
2396 if (!isset($dataValues[$key]['el'])) {
2397 $dataValues[$key]['el'] = array();
2398 }
2399 $this->checkValue_flex_procInData_travDS(
2400 $dataValues[$key]['el'],
2401 $dataValues_current[$key]['el'],
2402 $uploadedFiles[$key]['el'],
2403 $DSelements[$key]['el'],
2404 $pParams,
2405 $callBackFunc,
2406 $structurePath . $key . '/el/'
2407 );
2408 }
2409 }
2410 } else {
2411 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2412 foreach ($dataValues[$key] as $vKey => $data) {
2413
2414 if ($callBackFunc) {
2415 if (is_object($this->callBackObj)) {
2416 $res = $this->callBackObj->$callBackFunc(
2417 $pParams,
2418 $dsConf['TCEforms']['config'],
2419 $dataValues[$key][$vKey],
2420 $dataValues_current[$key][$vKey],
2421 $uploadedFiles[$key][$vKey],
2422 $structurePath . $key . '/' . $vKey . '/'
2423 );
2424 } else {
2425 $res = $this->$callBackFunc(
2426 $pParams,
2427 $dsConf['TCEforms']['config'],
2428 $dataValues[$key][$vKey],
2429 $dataValues_current[$key][$vKey],
2430 $uploadedFiles[$key][$vKey],
2431 $structurePath . $key . '/' . $vKey . '/'
2432 );
2433 }
2434 } else { // Default
2435 list($CVtable, $CVid, $CVcurValue, $CVstatus, $CVrealPid, $CVrecFID, $CVtscPID) = $pParams;
2436
2437 $res = $this->checkValue_SW(
2438 array(),
2439 $dataValues[$key][$vKey],
2440 $dsConf['TCEforms']['config'],
2441 $CVtable,
2442 $CVid,
2443 $dataValues_current[$key][$vKey],
2444 $CVstatus,
2445 $CVrealPid,
2446 $CVrecFID,
2447 '',
2448 $uploadedFiles[$key][$vKey],
2449 array(),
2450 $CVtscPID
2451 );
2452
2453 // Look for RTE transformation of field:
2454 if ($dataValues[$key]['_TRANSFORM_' . $vKey] == 'RTE' && !$this->dontProcessTransformations) {
2455
2456 // Unsetting trigger field - we absolutely don't want that into the data storage!
2457 unset($dataValues[$key]['_TRANSFORM_' . $vKey]);
2458
2459 if (isset($res['value'])) {
2460
2461 // Calculating/Retrieving some values here:
2462 list(, , $recFieldName) = explode(':', $CVrecFID);
2463 $theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable, $this->checkValue_currentRecord);
2464 $specConf = t3lib_BEfunc::getSpecConfParts('', $dsConf['TCEforms']['defaultExtras']);
2465
2466 // Find, thisConfig:
2467 $RTEsetup = $this->BE_USER->getTSConfig('RTE', t3lib_BEfunc::getPagesTSconfig($CVtscPID));
2468 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'], $CVtable, $recFieldName, $theTypeString);
2469
2470 // Get RTE object, draw form and set flag:
2471 $RTEobj = t3lib_BEfunc::RTEgetObj();
2472 if (is_object($RTEobj)) {
2473 $res['value'] = $RTEobj->transformContent('db', $res['value'], $CVtable, $recFieldName, $this->checkValue_currentRecord, $specConf, $thisConfig, '', $CVrealPid);
2474 } else {
2475 debug('NO RTE OBJECT FOUND!');
2476 }
2477 }
2478 }
2479 }
2480
2481 // Adding the value:
2482 if (isset($res['value'])) {
2483 $dataValues[$key][$vKey] = $res['value'];
2484 }
2485
2486 // 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.
2487 // 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).
2488 if (substr($vKey, -9) != '.vDEFbase') {
2489 if ($this->clear_flexFormData_vDEFbase) {
2490 $dataValues[$key][$vKey . '.vDEFbase'] = '';
2491 } 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')) {
2492 // 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:
2493 if (isset($dataValues[$key]['vDEF'])) {
2494 $diffValue = $dataValues[$key]['vDEF'];
2495 } else { // If not found (for translators with no access to the default language) we use the one from the current-value data set:
2496 $diffValue = $dataValues_current[$key]['vDEF'];
2497 }
2498 // 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.
2499 $dataValues[$key][$vKey . '.vDEFbase'] = $this->updateModeL10NdiffDataClear ? '' : $diffValue;
2500 }
2501 }
2502 }
2503 }
2504 }
2505 }
2506 }
2507 }
2508
2509 /**
2510 * Returns data for inline fields.
2511 *
2512 * @param array Current value array
2513 * @param array TCA field config
2514 * @param integer Record id
2515 * @param string Status string ('update' or 'new')
2516 * @param string Table name, needs to be passed to t3lib_loadDBGroup
2517 * @param string The current field the values are modified for
2518 * @return string Modified values
2519 */
2520 protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field) {
2521 $newValue = '';
2522 $foreignTable = $tcaFieldConf['foreign_table'];
2523
2524 /*
2525 * Fetch the related child records by using t3lib_loadDBGroup:
2526 * @var $dbAnalysis t3lib_loadDBGroup
2527 */
2528 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
2529 $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
2530 // If the localizationMode is set to 'keep', the children for the localized parent are kept as in the original untranslated record:
2531 $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $tcaFieldConf);
2532 if ($localizationMode == 'keep' && $status == 'update') {
2533 // Fetch the current record and determine the original record:
2534 $row = t3lib_BEfunc::getRecordWSOL($table, $id);
2535 if (is_array($row)) {
2536 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
2537 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
2538 // If language is set (e.g. 1) and also transOrigPointer (e.g. 123), use transOrigPointer as uid:
2539 if ($language > 0 && $transOrigPointer) {
2540 $id = $transOrigPointer;
2541 // If we're in active localizationMode 'keep', prevent from writing data to the field of the parent record:
2542 // (on removing the localized parent, the original (untranslated) children would then also be removed)
2543 $keepTranslation = TRUE;
2544 }
2545 }
2546 }
2547 // IRRE with a pointer field (database normalization):
2548 if ($tcaFieldConf['foreign_field']) {
2549 // if the record was imported, sorting was also imported, so skip this
2550 $skipSorting = ($this->callFromImpExp ? TRUE : FALSE);
2551 // update record in intermediate table (sorting & pointer uid to parent record)
2552 $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
2553 $newValue = ($keepTranslation ? 0 : $dbAnalysis->countItems(FALSE));
2554 // IRRE with MM relation:
2555 } else {
2556 if ($this->getInlineFieldType($tcaFieldConf) == 'mm') {
2557 // in order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
2558 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
2559 $newValue = ($keepTranslation ? 0 : $valueArray[0]);
2560 // IRRE with comma separated values:
2561 } else {
2562 $valueArray = $dbAnalysis->getValueArray();
2563 // Checking that the number of items is correct:
2564 $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2565 // If a valid translation of the 'keep' mode is active, update relations in the original(!) record:
2566 if ($keepTranslation) {
2567 $this->updateDB($table, $transOrigPointer, array($field => implode(',', $valueArray)));
2568 } else {
2569 $newValue = implode(',', $valueArray);
2570 }
2571 }
2572 }
2573
2574 return $newValue;
2575 }
2576
2577
2578 /*********************************************
2579 *
2580 * PROCESSING COMMANDS
2581 *
2582 ********************************************/
2583
2584 /**
2585 * Processing the cmd-array
2586 * See "TYPO3 Core API" for a description of the options.
2587 *
2588 * @return void
2589 */
2590 public function process_cmdmap() {
2591
2592 // Editing frozen:
2593 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
2594 $this->newlog('All editing in this workspace has been frozen!', 1);
2595 return FALSE;
2596 }
2597
2598 // Hook initialization:
2599 $hookObjectsArr = array();
2600 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'])) {
2601 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] as $classRef) {
2602 $hookObj = t3lib_div::getUserObj($classRef);
2603 if (method_exists($hookObj, 'processCmdmap_beforeStart')) {
2604 $hookObj->processCmdmap_beforeStart($this);
2605 }
2606 $hookObjectsArr[] = $hookObj;
2607 }
2608 }
2609
2610 // Traverse command map:
2611 foreach (array_keys($this->cmdmap) as $table) {
2612
2613 // Check if the table may be modified!
2614 $modifyAccessList = $this->checkModifyAccessList($table);
2615 if (!$modifyAccessList) {
2616 $id = 0;
2617 $this->log($table, $id, 2, 0, 1, "Attempt to modify table '%s' without permission", 1, array($table));
2618 } // FIXME: $id not set here (Comment added by Sebastian Kurfürst)
2619
2620 // Check basic permissions and circumstances:
2621 if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap[$table]) && $modifyAccessList) {
2622
2623 // Traverse the command map:
2624 foreach ($this->cmdmap[$table] as $id => $incomingCmdArray) {
2625 if (is_array($incomingCmdArray)) { // have found a command.
2626
2627 // Get command and value (notice, only one command is observed at a time!):
2628 reset($incomingCmdArray);
2629 $command = key($incomingCmdArray);
2630 $value = current($incomingCmdArray);
2631
2632 foreach ($hookObjectsArr as $hookObj) {
2633 if (method_exists($hookObj, 'processCmdmap_preProcess')) {
2634 $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this);
2635 }
2636 }
2637
2638 // Init copyMapping array:
2639 // Must clear this array before call from here to those functions:
2640 // Contains mapping information between new and old id numbers.
2641 $this->copyMappingArray = array();
2642
2643 // process the command
2644 $commandIsProcessed = FALSE;
2645 foreach ($hookObjectsArr as $hookObj) {
2646 if (method_exists($hookObj, 'processCmdmap')) {
2647 $hookObj->processCmdmap($command, $table, $id, $value, $commandIsProcessed, $this);
2648 }
2649 }
2650
2651 // only execute default commands if a hook hasn't been processed the command already
2652 if (!$commandIsProcessed) {
2653 // Branch, based on command
2654 switch ($command) {
2655 case 'move':
2656 $this->moveRecord($table, $id, $value);
2657 break;
2658 case 'copy':
2659 if ($table === 'pages') {
2660 $this->copyPages($id, $value);
2661 } else {
2662 $this->copyRecord($table, $id, $value, 1);
2663 }
2664 break;
2665 case 'localize':
2666 $this->localize($table, $id, $value);
2667 break;
2668 case 'inlineLocalizeSynchronize':
2669 $this->inlineLocalizeSynchronize($table, $id, $value);
2670 break;
2671 case 'delete':
2672 $this->deleteAction($table, $id);
2673 break;
2674 case 'undelete':
2675 $this->undeleteRecord($table, $id);
2676 break;
2677 }
2678 }
2679
2680 foreach ($hookObjectsArr as $hookObj) {
2681 if (method_exists($hookObj, 'processCmdmap_postProcess')) {
2682 $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this);
2683 }
2684 }
2685
2686 // Merging the copy-array info together for remapping purposes.
2687 $this->copyMappingArray_merged = t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged, $this->copyMappingArray);
2688 }
2689 }
2690 }
2691 }
2692
2693 // Finally, before exit, check if there are ID references to remap.
2694 // This might be the case if versioning or copying has taken place!
2695 $this->remapListedDBRecords();
2696 $this->processRemapStack();
2697
2698 foreach ($hookObjectsArr as $hookObj) {
2699 if (method_exists($hookObj, 'processCmdmap_afterFinish')) {
2700 $hookObj->processCmdmap_afterFinish($this);
2701 }
2702 }
2703
2704 }
2705
2706
2707 /*********************************************
2708 *
2709 * Cmd: Copying
2710 *
2711 ********************************************/
2712
2713 /**
2714 * Copying a single record
2715 *
2716 * @param string Element table
2717 * @param integer Element UID
2718 * @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
2719 * @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
2720 * @param array Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!
2721 * @param string Commalist of fields to exclude from the copy process (might get default values)
2722 * @param integer Language ID (from sys_language table)
2723 * @return integer ID of new record, if any
2724 */
2725 function copyRecord($table, $uid, $destPid, $first = 0, $overrideValues = array(), $excludeFields = '', $language = 0) {
2726 $uid = $origUid = intval($uid);
2727 // Only copy if the table is defined in $GLOBALS['TCA'], a uid is given and the record wasn't copied before:
2728 if ($GLOBALS['TCA'][$table] && $uid && !$this->isRecordCopied($table, $uid)) {
2729 t3lib_div::loadTCA($table);
2730 /*
2731 // In case the record to be moved turns out to be an offline version, we have to find the live version and work on that one (this case happens for pages with "branch" versioning type)
2732 if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$uid,'uid')) {
2733 $uid = $lookForLiveVersion['uid'];
2734 }
2735 // Get workspace version of the source record, if any: Then we will copy workspace version instead:
2736 if ($WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid')) {
2737 $uid = $WSversion['uid'];
2738 }
2739 // Now, the $uid is the actual record we will copy while $origUid is the record we asked to get copied - but that could be a live version.
2740 */
2741 if ($this->doesRecordExist($table, $uid, 'show')) { // This checks if the record can be selected which is all that a copy action requires.
2742 $fullLanguageCheckNeeded = ($table != 'pages');
2743 if (($language > 0 && $this->BE_USER->checkLanguageAccess($language)) ||
2744 $this->BE_USER->recordEditAccessInternals(
2745 $table, $uid, FALSE, FALSE, $fullLanguageCheckNeeded
2746 )
2747 ) { //Used to check language and general editing rights
2748 $data = array();
2749
2750 $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_swapmode,t3ver_count,t3ver_stage,t3ver_tstamp,' . $excludeFields, 1));
2751
2752 // $row = $this->recordInfo($table,$uid,'*');
2753 $row = t3lib_BEfunc::getRecordWSOL($table, $uid); // So it copies (and localized) content from workspace...
2754 if (is_array($row)) {
2755
2756 // Initializing:
2757 $theNewID = uniqid('NEW');
2758 $enableField = isset($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']) ? $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] : '';
2759 $headerField = $GLOBALS['TCA'][$table]['ctrl']['label'];
2760
2761 // Getting default data:
2762 $defaultData = $this->newFieldArray($table);
2763
2764 // Getting "copy-after" fields if applicable:
2765 $copyAfterFields = $destPid < 0 ? $this->fixCopyAfterDuplFields($table, $uid, abs($destPid), 0) : array();
2766
2767 // Page TSconfig related:
2768 $tscPID = t3lib_BEfunc::getTSconfig_pidValue($table, $uid, $destPid); // NOT using t3lib_BEfunc::getTSCpid() because we need the real pid - not the ID of a page, if the input is a page...
2769 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2770 $tE = $this->getTableEntries($table, $TSConfig);
2771
2772 // Traverse ALL fields of the selected record:
2773 foreach ($row as $field => $value) {
2774 if (!in_array($field, $nonFields)) {
2775
2776 // Get TCA configuration for the field:
2777 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2778
2779 // Preparation/Processing of the value:
2780 if ($field == 'pid') { // "pid" is hardcoded of course:
2781 $value = $destPid;
2782 } elseif (isset($overrideValues[$field])) { // Override value...
2783 $value = $overrideValues[$field];
2784 } elseif (isset($copyAfterFields[$field])) { // Copy-after value if available:
2785 $value = $copyAfterFields[$field];
2786 } elseif ($GLOBALS['TCA'][$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div::inList($GLOBALS['TCA'][$table]['ctrl']['setToDefaultOnCopy'], $field)) { // Revert to default for some fields:
2787 $value = $defaultData[$field];
2788 } else {
2789 // Hide at copy may override:
2790 if ($first && $field == $enableField && $GLOBALS['TCA'][$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy']) {
2791 $value = 1;
2792 }
2793 // Prepend label on copy:
2794 if ($first && $field == $headerField && $GLOBALS['TCA'][$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
2795 $value = $this->getCopyHeader($table, $this->resolvePid($table, $destPid), $field, $this->clearPrefixFromValue($table, $value), 0);
2796 }
2797 // Processing based on the TCA config field type (files, references, flexforms...)
2798 $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
2799 }
2800
2801 // Add value to array.
2802 $data[$table][$theNewID][$field] = $value;
2803 }
2804 }
2805 // Overriding values:
2806 if ($GLOBALS['TCA'][$table]['ctrl']['editlock']) {
2807 $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['editlock']] = 0;
2808 }
2809
2810 // Setting original UID:
2811 if ($GLOBALS['TCA'][$table]['ctrl']['origUid']) {
2812 $data[$table][$theNewID][$GLOBALS['TCA'][$table]['ctrl']['origUid']] = $uid;
2813 }
2814