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