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