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