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