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