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