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