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