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