PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_tcemain.php

https://bitbucket.org/linxpinx/mercurial
PHP | 7828 lines | 4516 code | 1002 blank | 2310 comment | 1277 complexity | e84bb17658713a4bc785c78204eec1be MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Unlicense, LGPL-2.1, Apache-2.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
  6. * All rights reserved
  7. *
  8. * This script is part of the TYPO3 project. The TYPO3 project is
  9. * free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * The GNU General Public License can be found at
  15. * http://www.gnu.org/copyleft/gpl.html.
  16. * A copy is found in the textfile GPL.txt and important notices to the license
  17. * from the author is found in LICENSE.txt distributed with these scripts.
  18. *
  19. *
  20. * This script is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * This copyright notice MUST APPEAR in all copies of the script!
  26. ***************************************************************/
  27. /**
  28. * Contains the TYPO3 Core Engine
  29. *
  30. * $Id: class.t3lib_tcemain.php 8157 2010-07-11 12:45:16Z psychomieze $
  31. * Revised for TYPO3 3.9 October 2005 by Kasper Skaarhoj
  32. *
  33. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  34. */
  35. /**
  36. * [CLASS/FUNCTION INDEX of SCRIPT]
  37. *
  38. *
  39. *
  40. * 242: class t3lib_TCEmain
  41. * 367: function start($data,$cmd,$altUserObject='')
  42. * 406: function setMirror($mirror)
  43. * 431: function setDefaultsFromUserTS($userTS)
  44. * 454: function process_uploads($postFiles)
  45. * 492: function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
  46. *
  47. * SECTION: PROCESSING DATA
  48. * 528: function process_datamap()
  49. * 886: function placeholderShadowing($table,$id)
  50. * 929: function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
  51. *
  52. * SECTION: Evaluation of input values
  53. * 1152: function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
  54. * 1212: function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
  55. * 1261: function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
  56. * 1299: function checkValue_check($res,$value,$tcaFieldConf,$PP)
  57. * 1322: function checkValue_radio($res,$value,$tcaFieldConf,$PP)
  58. * 1348: function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
  59. * 1458: function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
  60. * 1632: function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
  61. * 1709: function checkValue_flexArray2Xml($array, $addPrologue=FALSE)
  62. * 1721: function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
  63. * 1743: function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)
  64. * 1783: function checkValue_inline($res,$value,$tcaFieldConf,$PP,$field)
  65. * 1825: function checkValue_checkMax($tcaFieldConf, $valueArray)
  66. *
  67. * SECTION: Helper functions for evaluation functions.
  68. * 1877: function getUnique($table,$field,$value,$id,$newPid=0)
  69. * 1915: function checkValue_input_Eval($value,$evalArray,$is_in)
  70. * 2012: function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type,$currentTable)
  71. * 2058: function checkValue_group_select_explodeSelectGroupValue($value)
  72. * 2082: function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
  73. * 2121: function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)
  74. *
  75. * SECTION: PROCESSING COMMANDS
  76. * 2267: function process_cmdmap()
  77. *
  78. * SECTION: Cmd: Copying
  79. * 2407: function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
  80. * 2529: function copyPages($uid,$destPid)
  81. * 2583: function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
  82. * 2617: function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
  83. * 2681: function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
  84. * 2705: function insertNewCopyVersion($table,$fieldArray,$realPid)
  85. * 2757: function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$realDestPid)
  86. * 2836: function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
  87. * 2864: function copyRecord_procFilesRefs($conf, $uid, $value)
  88. *
  89. * SECTION: Cmd: Moving, Localizing
  90. * 2933: function moveRecord($table,$uid,$destPid)
  91. * 3128: function moveRecord_procFields($table,$uid,$destPid)
  92. * 3148: function moveRecord_procBasedOnFieldType($table,$uid,$destPid,$field,$value,$conf)
  93. * 3182: function localize($table,$uid,$language)
  94. *
  95. * SECTION: Cmd: Deleting
  96. * 3296: function deleteAction($table, $id)
  97. * 3343: function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE)
  98. * 3360: function deleteVersionsForRecord($table, $uid, $forceHardDelete)
  99. * 3382: function undeleteRecord($table,$uid)
  100. * 3399: function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)
  101. * 3512: function deleteRecord_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)
  102. * 3539: function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE)
  103. * 3567: function deleteSpecificPage($uid,$forceHardDelete=FALSE)
  104. * 3592: function canDeletePage($uid)
  105. * 3619: function cannotDeleteRecord($table,$id)
  106. * 3638: function deleteRecord_procFields($table, $uid, $undeleteRecord = false)
  107. * 3661: function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false)
  108. *
  109. * SECTION: Cmd: Versioning
  110. * 3722: function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1)
  111. * 3798: function versionizePages($uid,$label,$versionizeTree)
  112. * 3861: function version_swap($table,$id,$swapWith,$swapIntoWS=0)
  113. * 4032: function version_clearWSID($table,$id)
  114. * 4066: function version_setStage($table,$id,$stageId,$comment='')
  115. *
  116. * SECTION: Cmd: Helper functions
  117. * 4111: function remapListedDBRecords()
  118. * 4192: function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
  119. * 4219: function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
  120. * 4265: function remapListedDBRecords_procInline($conf, $value, $uid, $table)
  121. *
  122. * SECTION: Access control / Checking functions
  123. * 4308: function checkModifyAccessList($table)
  124. * 4320: function isRecordInWebMount($table,$id)
  125. * 4334: function isInWebMount($pid)
  126. * 4348: function checkRecordUpdateAccess($table,$id)
  127. * 4372: function checkRecordInsertAccess($insertTable,$pid,$action=1)
  128. * 4406: function isTableAllowedForThisPage($page_uid, $checkTable)
  129. * 4439: function doesRecordExist($table,$id,$perms)
  130. * 4504: function doesRecordExist_pageLookUp($id, $perms)
  131. * 4530: function doesBranchExist($inList,$pid,$perms,$recurse)
  132. * 4564: function tableReadOnly($table)
  133. * 4576: function tableAdminOnly($table)
  134. * 4590: function destNotInsideSelf($dest,$id)
  135. * 4622: function getExcludeListArray()
  136. * 4645: function doesPageHaveUnallowedTables($page_uid,$doktype)
  137. *
  138. * SECTION: Information lookup
  139. * 4694: function pageInfo($id,$field)
  140. * 4714: function recordInfo($table,$id,$fieldList)
  141. * 4735: function getRecordProperties($table,$id,$noWSOL=FALSE)
  142. * 4751: function getRecordPropertiesFromRow($table,$row)
  143. *
  144. * SECTION: Storing data to Database Layer
  145. * 4794: function updateDB($table,$id,$fieldArray)
  146. * 4846: function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE)
  147. * 4919: function checkStoredRecord($table,$id,$fieldArray,$action)
  148. * 4956: function setHistory($table,$id,$logId)
  149. * 4989: function clearHistory($maxAgeSeconds=604800,$table)
  150. * 5003: function updateRefIndex($table,$id)
  151. *
  152. * SECTION: Misc functions
  153. * 5035: function getSortNumber($table,$uid,$pid)
  154. * 5108: function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
  155. * 5139: function setTSconfigPermissions($fieldArray,$TSConfig_p)
  156. * 5156: function newFieldArray($table)
  157. * 5188: function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray)
  158. * 5212: function overrideFieldArray($table,$data)
  159. * 5228: function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
  160. * 5274: function assemblePermissions($string)
  161. * 5291: function rmComma($input)
  162. * 5301: function convNumEntityToByteValue($input)
  163. * 5323: function destPathFromUploadFolder($folder)
  164. * 5333: function deleteClause($table)
  165. * 5349: function getTCEMAIN_TSconfig($tscPID)
  166. * 5364: function getTableEntries($table,$TSconfig)
  167. * 5377: function getPID($table,$uid)
  168. * 5390: function dbAnalysisStoreExec()
  169. * 5406: function removeRegisteredFiles()
  170. * 5418: function removeCacheFiles()
  171. * 5432: function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
  172. * 5453: function compileAdminTables()
  173. * 5470: function fixUniqueInPid($table,$uid)
  174. * 5506: function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
  175. * 5531: function extFileFields($table)
  176. * 5552: function getUniqueFields($table)
  177. * 5577: function isReferenceField($conf)
  178. * 5588: function getInlineFieldType($conf)
  179. * 5611: function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
  180. * 5640: function prependLabel($table)
  181. * 5657: function resolvePid($table,$pid)
  182. * 5687: function clearPrefixFromValue($table,$value)
  183. * 5702: function extFileFunctions($table,$field,$filelist,$func)
  184. * 5732: function noRecordsFromUnallowedTables($inList)
  185. * 5758: function notifyStageChange($stat,$stageId,$table,$id,$comment)
  186. * 5853: function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE)
  187. *
  188. * SECTION: Clearing cache
  189. * 5899: function clear_cache($table,$uid)
  190. * 6009: function clear_cacheCmd($cacheCmd)
  191. *
  192. * SECTION: Logging
  193. * 6113: function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='')
  194. * 6130: function newlog($message, $error=0)
  195. * 6140: function printLogErrorMessages($redirect)
  196. *
  197. * SECTION: Internal (do not use outside Core!)
  198. * 6202: function internal_clearPageCache()
  199. *
  200. * TOTAL FUNCTIONS: 126
  201. * (This index is automatically created/updated by the extension "extdeveval")
  202. *
  203. */
  204. /**
  205. * This is the TYPO3 Core Engine class for manipulation of the database
  206. * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
  207. *
  208. * Dependencies:
  209. * - $GLOBALS['TCA'] must exist
  210. * - $GLOBALS['LANG'] must exist
  211. *
  212. * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
  213. *
  214. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  215. * @package TYPO3
  216. * @subpackage t3lib
  217. */
  218. class t3lib_TCEmain {
  219. // *********************
  220. // Public variables you can configure before using the class:
  221. // *********************
  222. 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.
  223. var $enableLogging = TRUE; // Boolean: If true, actions are logged to sys_log.
  224. 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.
  225. 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.
  226. 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!
  227. 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
  228. var $checkStoredRecords_loose = TRUE; // Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
  229. 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
  230. var $neverHideAtCopy = FALSE; // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
  231. var $dontProcessTransformations = FALSE; // Boolean: If set, then transformations are NOT performed on the input.
  232. var $clear_flexFormData_vDEFbase = FALSE; // Boolean: If set, .vDEFbase values are unset in flexforms.
  233. 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
  234. 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.
  235. 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!
  236. 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!
  237. 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!
  238. 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)
  239. var $generalComment = ''; // General comment, eg. for staging in workspaces.
  240. 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
  241. 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)
  242. 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!
  243. 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.
  244. var $alternativeFilePath = array(); // Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
  245. 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.
  246. 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)
  247. 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.
  248. // *********************
  249. // Internal variables (mapping arrays) which can be used (read-only) from outside
  250. // *********************
  251. var $autoVersionIdMap = Array(); // Contains mapping of auto-versionized records.
  252. 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
  253. var $substNEWwithIDs_table = Array(); // Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
  254. var $newRelatedIDs = Array(); // Holds the tables and there the ids of newly created child records from IRRE
  255. var $copyMappingArray_merged = Array(); // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
  256. var $copiedFileMap = Array(); // A map between input file name and final destination for files being attached to records.
  257. 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.
  258. var $errorLog = Array(); // Errors are collected in this variable.
  259. var $accumulateForNotifEmail = Array(); // For accumulating information about workspace stages raised on elements so a single mail is sent as notification.
  260. // *********************
  261. // Internal Variables, do not touch.
  262. // *********************
  263. // Variables set in init() function:
  264. /**
  265. * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
  266. *
  267. * @var t3lib_beUserAuth
  268. */
  269. var $BE_USER;
  270. var $userid; // will be set to uid of be_user executing this script
  271. var $username; // will be set to username of be_user executing this script
  272. var $admin; // will be set if user is admin
  273. var $defaultPermissions = array( // Can be overridden from $TYPO3_CONF_VARS
  274. 'user' => 'show,edit,delete,new,editcontent',
  275. 'group' => 'show,edit,new,editcontent',
  276. 'everybody' => ''
  277. );
  278. 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.
  279. var $datamap = Array(); // Set with incoming data array
  280. var $cmdmap = Array(); // Set with incoming cmd array
  281. // Internal static:
  282. var $pMap = Array( // Permission mapping
  283. 'show' => 1, // 1st bit
  284. 'edit' => 2, // 2nd bit
  285. 'delete' => 4, // 3rd bit
  286. 'new' => 8, // 4th bit
  287. 'editcontent' => 16 // 5th bit
  288. );
  289. var $sortIntervals = 256; // Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
  290. // Internal caching arrays
  291. var $recUpdateAccessCache = Array(); // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
  292. var $recInsertAccessCache = Array(); // User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
  293. var $isRecordInWebMount_Cache=array(); // Caching array for check of whether records are in a webmount
  294. var $isInWebMount_Cache=array(); // Caching array for page ids in webmounts
  295. var $cachedTSconfig = array(); // Caching for collecting TSconfig for page ids
  296. var $pageCache = Array(); // Used for caching page records in pageInfo()
  297. var $checkWorkspaceCache = Array(); // Array caching workspace access for BE_USER
  298. // Other arrays:
  299. var $dbAnalysisStore=array(); // For accumulation of MM relations that must be written after new records are created.
  300. var $removeFilesStore=array(); // For accumulation of files which must be deleted after processing of all input content
  301. var $uploadedFileArray = array(); // Uploaded files, set by process_uploads()
  302. var $registerDBList=array(); // Used for tracking references that might need correction after operations
  303. var $registerDBPids=array(); // Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
  304. 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.
  305. var $remapStack = array(); // array used for remapping uids and values at the end of process_datamap
  306. var $remapStackRecords = array(); // array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
  307. var $updateRefIndexStack = array(); // array used for additional calls to $this->updateRefIndex
  308. var $callFromImpExp = false; // tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
  309. var $newIndexMap = array(); // Array for new flexform index mapping
  310. // Various
  311. /**
  312. * basicFileFunctions object
  313. *
  314. * @var t3lib_basicFileFunctions
  315. */
  316. var $fileFunc; // For "singleTon" file-manipulation object
  317. var $checkValue_currentRecord=array(); // Set to "currentRecord" during checking of values.
  318. var $autoVersioningUpdate = FALSE; // A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
  319. protected $disableDeleteClause = false; // Disable delete clause
  320. protected $checkModifyAccessListHookObjects;
  321. /**
  322. * Initializing.
  323. * For details, see 'TYPO3 Core API' document.
  324. * This function does not start the processing of data, but merely initializes the object
  325. *
  326. * @param array Data to be modified or inserted in the database
  327. * @param array Commands to copy, move, delete, localize, versionize records.
  328. * @param object An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
  329. * @return void
  330. */
  331. function start($data,$cmd,$altUserObject='') {
  332. // Initializing BE_USER
  333. $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
  334. $this->userid = $this->BE_USER->user['uid'];
  335. $this->username = $this->BE_USER->user['username'];
  336. $this->admin = $this->BE_USER->user['admin'];
  337. if ($this->BE_USER->uc['recursiveDelete']) {
  338. $this->deleteTree = 1;
  339. }
  340. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData===TRUE) {
  341. $this->updateModeL10NdiffData = FALSE;
  342. }
  343. // Initializing default permissions for pages
  344. $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
  345. if (isset($defaultPermissions['user'])) {$this->defaultPermissions['user'] = $defaultPermissions['user'];}
  346. if (isset($defaultPermissions['group'])) {$this->defaultPermissions['group'] = $defaultPermissions['group'];}
  347. if (isset($defaultPermissions['everybody'])) {$this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];}
  348. // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
  349. $this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();
  350. // Setting the data and cmd arrays
  351. if (is_array($data)) {
  352. reset($data);
  353. $this->datamap = $data;
  354. }
  355. if (is_array($cmd)) {
  356. reset($cmd);
  357. $this->cmdmap = $cmd;
  358. }
  359. }
  360. /**
  361. * Function that can mirror input values in datamap-array to other uid numbers.
  362. * 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]
  363. *
  364. * @param array This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
  365. * @return void
  366. */
  367. function setMirror($mirror) {
  368. if (is_array($mirror)) {
  369. foreach ($mirror as $table => $uid_array) {
  370. if (isset($this->datamap[$table])) {
  371. reset($uid_array);
  372. foreach ($uid_array as $id => $uidList) {
  373. if (isset($this->datamap[$table][$id])) {
  374. $theIdsInArray = t3lib_div::trimExplode(',',$uidList,1);
  375. foreach ($theIdsInArray as $copyToUid) {
  376. $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
  377. }
  378. }
  379. }
  380. }
  381. }
  382. }
  383. }
  384. /**
  385. * Initializes default values coming from User TSconfig
  386. *
  387. * @param array User TSconfig array
  388. * @return void
  389. */
  390. function setDefaultsFromUserTS($userTS) {
  391. global $TCA;
  392. if (is_array($userTS)) {
  393. foreach($userTS as $k => $v) {
  394. $k = substr($k,0,-1);
  395. if ($k && is_array($v) && isset($TCA[$k])) {
  396. if (is_array($this->defaultValues[$k])) {
  397. $this->defaultValues[$k] = array_merge($this->defaultValues[$k],$v);
  398. } else {
  399. $this->defaultValues[$k] = $v;
  400. }
  401. }
  402. }
  403. }
  404. }
  405. /**
  406. * Processing of uploaded files.
  407. * 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.
  408. *
  409. * @param array $_FILES array
  410. * @return void
  411. */
  412. function process_uploads($postFiles) {
  413. if (is_array($postFiles)) {
  414. // Editing frozen:
  415. if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze']) {
  416. $this->newlog('All editing in this workspace has been frozen!',1);
  417. return FALSE;
  418. }
  419. reset($postFiles);
  420. $subA = current($postFiles);
  421. if (is_array($subA)) {
  422. if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
  423. // Initialize the uploadedFilesArray:
  424. $this->uploadedFileArray=array();
  425. // For each entry:
  426. foreach($subA as $key => $values) {
  427. $this->process_uploads_traverseArray($this->uploadedFileArray,$values,$key);
  428. }
  429. } else {
  430. $this->uploadedFileArray=$subA;
  431. }
  432. }
  433. }
  434. }
  435. /**
  436. * Traverse the upload array if needed to rearrange values.
  437. *
  438. * @param array $this->uploadedFileArray passed by reference
  439. * @param array Input array ($_FILES parts)
  440. * @param string The current $_FILES array key to set on the outermost level.
  441. * @return void
  442. * @access private
  443. * @see process_uploads()
  444. */
  445. function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet) {
  446. if (is_array($inputArr)) {
  447. foreach($inputArr as $key => $value) {
  448. $this->process_uploads_traverseArray($outputArr[$key],$inputArr[$key],$keyToSet);
  449. }
  450. } else {
  451. $outputArr[$keyToSet]=$inputArr;
  452. }
  453. }
  454. /*********************************************
  455. *
  456. * HOOKS
  457. *
  458. *********************************************/
  459. /**
  460. * Hook: processDatamap_afterDatabaseOperations
  461. * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
  462. *
  463. * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
  464. * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
  465. *
  466. * @param object $hookObjectsArr: (reference) Array with hook objects
  467. * @param string $status: (reference) Status of the current operation, 'new' or 'update
  468. * @param string $table: (refrence) The table currently processing data for
  469. * @param string $id: (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
  470. * @param array $fieldArray: (reference) The field array of a record
  471. * @return void
  472. */
  473. function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
  474. // Process hook directly:
  475. if (!isset($this->remapStackRecords[$table][$id])) {
  476. foreach($hookObjectsArr as $hookObj) {
  477. if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
  478. $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
  479. }
  480. }
  481. // 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:
  482. } else {
  483. $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
  484. 'status' => $status,
  485. 'fieldArray' => $fieldArray,
  486. 'hookObjectsArr' => $hookObjectsArr,
  487. );
  488. }
  489. }
  490. /**
  491. * Gets the 'checkModifyAccessList' hook objects.
  492. * The first call initializes the accordant objects.
  493. *
  494. * @return array The 'checkModifyAccessList' hook objects (if any)
  495. */
  496. protected function getCheckModifyAccessListHookObjects() {
  497. if (!isset($this->checkModifyAccessListHookObjects)) {
  498. $this->checkModifyAccessListHookObjects = array();
  499. if(is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
  500. foreach($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
  501. $hookObject = t3lib_div::getUserObj($classData);
  502. if(!($hookObject instanceof t3lib_TCEmain_checkModifyAccessListHook)) {
  503. throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
  504. }
  505. $this->checkModifyAccessListHookObjects[] = $hookObject;
  506. }
  507. }
  508. }
  509. return $this->checkModifyAccessListHookObjects;
  510. }
  511. /*********************************************
  512. *
  513. * PROCESSING DATA
  514. *
  515. *********************************************/
  516. /**
  517. * Processing the data-array
  518. * Call this function to process the data-array set by start()
  519. *
  520. * @return void
  521. */
  522. function process_datamap() {
  523. global $TCA, $TYPO3_CONF_VARS;
  524. // Keep versionized(!) relations here locally:
  525. $registerDBList = array();
  526. // Editing frozen:
  527. if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze']) {
  528. $this->newlog('All editing in this workspace has been frozen!',1);
  529. return FALSE;
  530. }
  531. // First prepare user defined objects (if any) for hooks which extend this function:
  532. $hookObjectsArr = array();
  533. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
  534. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
  535. $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
  536. }
  537. }
  538. // 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.
  539. $orderOfTables = Array();
  540. if (isset($this->datamap['pages'])) { // Set pages first.
  541. $orderOfTables[]='pages';
  542. }
  543. $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
  544. // Process the tables...
  545. foreach($orderOfTables as $table) {
  546. /* Check if
  547. - table is set in $TCA,
  548. - table is NOT readOnly
  549. - the table is set with content in the data-array (if not, there's nothing to process...)
  550. - permissions for tableaccess OK
  551. */
  552. $modifyAccessList = $this->checkModifyAccessList($table);
  553. if (!$modifyAccessList) {
  554. $id = 0;
  555. $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
  556. }
  557. if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList) {
  558. if ($this->reverseOrder) {
  559. $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
  560. }
  561. // For each record from the table, do:
  562. // $id is the record uid, may be a string if new records...
  563. // $incomingFieldArray is the array of fields
  564. foreach($this->datamap[$table] as $id => $incomingFieldArray) {
  565. if (is_array($incomingFieldArray)) {
  566. // Hook: processDatamap_preProcessFieldArray
  567. foreach($hookObjectsArr as $hookObj) {
  568. if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
  569. $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
  570. }
  571. }
  572. // ******************************
  573. // Checking access to the record
  574. // ******************************
  575. $createNewVersion = FALSE;
  576. $recordAccess = FALSE;
  577. $old_pid_value = '';
  578. $this->autoVersioningUpdate = FALSE;
  579. if (!t3lib_div::testInt($id)) { // Is it a new record? (Then Id is a string)
  580. $fieldArray = $this->newFieldArray($table); // Get a fieldArray with default values
  581. if (isset($incomingFieldArray['pid'])) { // A pid must be set for new records.
  582. // $value = the pid
  583. $pid_value = $incomingFieldArray['pid'];
  584. // Checking and finding numerical pid, it may be a string-reference to another value
  585. $OK = 1;
  586. if (strstr($pid_value,'NEW')) { // If a NEW... id
  587. if (substr($pid_value,0,1)=='-') {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
  588. 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.
  589. $old_pid_value = $pid_value;
  590. $pid_value=intval($negFlag*$this->substNEWwithIDs[$pid_value]);
  591. } else {$OK = 0;} // If not found in the substArray we must stop the process...
  592. } 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.
  593. if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid_value, 'uid,t3ver_swapmode')) { // Looks for workspace version of page.
  594. if ($WSdestPage['t3ver_swapmode']==0) { // if swapmode is zero, then change pid value.
  595. $pid_value = $WSdestPage['uid'];
  596. }
  597. }
  598. }
  599. $pid_value = intval($pid_value);
  600. // The $pid_value is now the numerical pid at this point
  601. if ($OK) {
  602. $sortRow = $TCA[$table]['ctrl']['sortby'];
  603. if ($pid_value>=0) { // Points to a page on which to insert the element, possibly in the top of the page
  604. if ($sortRow) { // If this table is sorted we better find the top sorting number
  605. $fieldArray[$sortRow] = $this->getSortNumber($table,0,$pid_value);
  606. }
  607. $fieldArray['pid'] = $pid_value; // The numerical pid is inserted in the data array
  608. } else { // points to another record before ifself
  609. if ($sortRow) { // If this table is sorted we better find the top sorting number
  610. $tempArray=$this->getSortNumber($table,0,$pid_value); // Because $pid_value is < 0, getSortNumber returns an array
  611. $fieldArray['pid'] = $tempArray['pid'];
  612. $fieldArray[$sortRow] = $tempArray['sortNumber'];
  613. } else { // Here we fetch the PID of the record that we point to...
  614. $tempdata = $this->recordInfo($table,abs($pid_value),'pid');
  615. $fieldArray['pid']=$tempdata['pid'];
  616. }
  617. }
  618. }
  619. }
  620. $theRealPid = $fieldArray['pid'];
  621. // Now, check if we may insert records on this pid.
  622. if ($theRealPid>=0) {
  623. $recordAccess = $this->checkRecordInsertAccess($table,$theRealPid); // Checks if records can be inserted on this $pid.
  624. if ($recordAccess) {
  625. $this->addDefaultPermittedLanguageIfNotSet($table,$incomingFieldArray);
  626. $recordAccess = $this->BE_USER->recordEditAccessInternals($table,$incomingFieldArray,TRUE);
  627. if (!$recordAccess) {
  628. $this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
  629. } elseif(!$this->bypassWorkspaceRestrictions) {
  630. // Workspace related processing:
  631. 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
  632. if ($res<0) {
  633. $recordAccess = FALSE;
  634. $this->newlog('Stage for versioning root point and users access level did not allow for editing',1);
  635. }
  636. } else { // So, if no live records were allowed, we have to create a new version of this record:
  637. if ($TCA[$table]['ctrl']['versioningWS']) {
  638. $createNewVersion = TRUE;
  639. } else {
  640. $recordAccess = FALSE;
  641. $this->newlog('Record could not be created in this workspace in this branch',1);
  642. }
  643. }
  644. }
  645. }
  646. } else {
  647. debug('Internal ERROR: pid should not be less than zero!');
  648. }
  649. $status = 'new'; // Yes new record, change $record_status to 'insert'
  650. } else { // Nope... $id is a number
  651. $fieldArray = array();
  652. $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
  653. if (!$recordAccess) {
  654. $propArr = $this->getRecordProperties($table,$id);
  655. $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']);
  656. } else { // Next check of the record permissions (internals)
  657. $recordAccess = $this->BE_USER->recordEditAccessInternals($table,$id);
  658. if (!$recordAccess) {
  659. $propArr = $this->getRecordProperties($table,$id);
  660. $this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
  661. } else { // Here we fetch the PID of the record that we point to...
  662. $tempdata = $this->recordInfo($table,$id,'pid'.($TCA[$table]['ctrl']['versioningWS']?',t3ver_wsid,t3ver_stage':''));
  663. $theRealPid = $tempdata['pid'];
  664. // Use the new id of the versionized record we're trying to write to:
  665. // (This record is a child record of a parent and has already been versionized.)
  666. if ($this->autoVersionIdMap[$table][$id]) {
  667. // For the reason that creating a new version of this record, automatically
  668. // created related child records (e.g. "IRRE"), update the accordant field:
  669. $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
  670. // Use the new id of the copied/versionized record:
  671. $id = $this->autoVersionIdMap[$table][$id];
  672. $recordAccess = TRUE;
  673. $this->autoVersioningUpdate = TRUE;
  674. // Checking access in case of offline workspace:
  675. } elseif (!$this->bypassWorkspaceRestrictions && $errorCode = $this->BE_USER->workspaceCannotEditRecord($table,$tempdata)) {
  676. $recordAccess = FALSE; // Versioning is required and it must be offline version!
  677. // 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.
  678. if ($this->BE_USER->workspaceAllowAutoCreation($table,$id,$theRealPid)) {
  679. $tce = t3lib_div::makeInstance('t3lib_TCEmain');
  680. /* @var $tce t3lib_TCEmain */
  681. $tce->stripslashes_values = 0;
  682. // Setting up command for creating a new version of the record:
  683. $cmd = array();
  684. $cmd[$table][$id]['version'] = array(
  685. 'action' => 'new',
  686. 'treeLevels' => -1, // Default is to create a version of the individual records... element versioning that is.
  687. 'label' => 'Auto-created for WS #'.$this->BE_USER->workspace
  688. );
  689. $tce->start(array(),$cmd);
  690. $tce->process_cmdmap();
  691. $this->errorLog = array_merge($this->errorLog,$tce->errorLog);
  692. // If copying was successful, share the new uids (also of related children):
  693. if ($tce->copyMappingArray[$table][$id]) {
  694. foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
  695. foreach ($origIdArray as $origId => $newId) {
  696. $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
  697. $this->autoVersionIdMap[$origTable][$origId] = $newId;
  698. }
  699. }
  700. $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...
  701. // Update registerDBList, that holds the copied relations to child records:
  702. $registerDBList = array_merge($registerDBList, $tce->registerDBList);
  703. // For the reason that creating a new version of this record, automatically
  704. // created related child records (e.g. "IRRE"), update the accordant field:
  705. $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
  706. // Use the new id of the copied/versionized record:
  707. $id = $this->autoVersionIdMap[$table][$id];
  708. $recordAccess = TRUE;
  709. $this->autoVersioningUpdate = TRUE;
  710. } else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version failed!",1);
  711. } else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version not allowed in workspace!",1);
  712. }
  713. }
  714. }
  715. $status = 'update'; // the default is 'update'
  716. }
  717. // If access was granted above, proceed to create or update record:
  718. if ($recordAccess) {
  719. 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.
  720. $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
  721. if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.'])) {
  722. $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
  723. }
  724. if ($createNewVersion) {
  725. $newVersion_placeholderFieldArray = $fieldArray;
  726. }
  727. // Processing of all fields in incomingFieldArray and setting them in $fieldArray
  728. $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
  729. // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
  730. // Forcing some values unto field array:
  731. $fieldArray = $this->overrideFieldArray($table,$fieldArray); // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
  732. if ($createNewVersion) {
  733. $newVersion_placeholderFieldArray = $this->overrideFieldArray($table,$newVersion_placeholderFieldArray);
  734. }
  735. // Setting system fields
  736. if ($status=='new') {
  737. if ($TCA[$table]['ctrl']['crdate']) {
  738. $fieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
  739. if ($createNewVersion) {
  740. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
  741. }
  742. }
  743. if ($TCA[$table]['ctrl']['cruser_id']) {
  744. $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
  745. if ($createNewVersion) $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
  746. }
  747. } elseif ($this->checkSimilar) { // Removing fields which are equal to the current value:
  748. $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
  749. }
  750. if ($TCA[$table]['ctrl']['tstamp'] && count($fieldArray)) {
  751. $fieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  752. if ($createNewVersion) {
  753. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  754. }
  755. }
  756. if ($TCA[$table]['ctrl']['versioningWS']) {
  757. $fieldArray['t3ver_stage'] = 0;
  758. }
  759. // Hook: processDatamap_postProcessFieldArray
  760. foreach($hookObjectsArr as $hookObj) {
  761. if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
  762. $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
  763. }
  764. }
  765. // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
  766. // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
  767. if (is_array($fieldArray)) {
  768. if ($status=='new') {
  769. if ($createNewVersion) { // This creates a new version of the record with online placeholder and offline version
  770. $versioningType = $table==='pages' ? $this->BE_USER->workspaceVersioningTypeGetClosest(t3lib_div::intInRange($TYPO3_CONF_VARS['BE']['newPagesVersioningType'],-1,1)) : -1;
  771. if ($this->BE_USER->workspaceVersioningTypeAccess($versioningType)) {
  772. $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
  773. $newVersion_placeholderFieldArray['t3ver_state'] = 1; // Setting placeholder state value for temporary record
  774. $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace; // Setting workspace - only so display of place holders can filter out those from other workspaces.
  775. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['label']] = '[PLACEHOLDER, WS#'.$this->BE_USER->workspace.']';
  776. $this->insertDB($table,$id,$newVersion_placeholderFieldArray,FALSE); // Saving placeholder as 'original'
  777. // For the actual new offline version, set versioning values to point to placeholder:
  778. $fieldArray['pid'] = -1;
  779. $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
  780. $fieldArray['t3ver_id'] = 1;
  781. $fieldArray['t3ver_state'] = -1; // Setting placeholder state value for version (so it can know it is currently a new version...)
  782. $fieldArray['t3ver_label'] = 'First draft version';
  783. $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
  784. if ($table==='pages') { // Swap mode set to "branch" so we can build branches for pages.
  785. $fieldArray['t3ver_swapmode'] = $versioningType;
  786. }
  787. $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!
  788. if ($phShadowId) {
  789. $this->placeholderShadowing($table,$phShadowId);
  790. // Hold auto-versionized ids of placeholders:
  791. $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
  792. }
  793. } else $this->newlog('Versioning type "'.$versioningType.'" was not allowed, so could not create new record.',1);
  794. } else {
  795. $this->insertDB($table,$id,$fieldArray,FALSE,$incomingFieldArray['uid']);
  796. }
  797. } else {
  798. $this->updateDB($table,$id,$fieldArray);
  799. $this->placeholderShadowing($table,$id);
  800. }
  801. }
  802. /*
  803. * Hook: processDatamap_afterDatabaseOperations
  804. *
  805. * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
  806. * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
  807. */
  808. $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
  809. } // if ($recordAccess) {
  810. } // if (is_array($incomingFieldArray)) {
  811. }
  812. }
  813. }
  814. // Process the stack of relations to remap/correct
  815. $this->processRemapStack();
  816. $this->dbAnalysisStoreExec();
  817. $this->removeRegisteredFiles();
  818. /*
  819. * Hook: processDatamap_afterAllOperations
  820. *
  821. * Note: When this hook gets called, all operations on the submitted data have been finished.
  822. */
  823. foreach($hookObjectsArr as $hookObj) {
  824. if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
  825. $hookObj->processDatamap_afterAllOperations($this);
  826. }
  827. }
  828. }
  829. /**
  830. * Fix shadowing of data in case we are editing a offline version of a live "New" placeholder record:
  831. *
  832. * @param string Table name
  833. * @param integer Record uid
  834. * @return void
  835. */
  836. function placeholderShadowing($table,$id) {
  837. global $TCA;
  838. t3lib_div::loadTCA($table);
  839. if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'*')) {
  840. if ((int)$liveRec['t3ver_state']>0) {
  841. $justStoredRecord = t3lib_BEfunc::getRecord($table,$id);
  842. $newRecord = array();
  843. $shadowCols = $TCA[$table]['ctrl']['shadowColumnsForNewPlaceholders'];
  844. $shadowCols.= ','.$TCA[$table]['ctrl']['languageField'];
  845. $shadowCols.= ','.$TCA[$table]['ctrl']['transOrigPointerField'];
  846. $shadowCols.= ','.$TCA[$table]['ctrl']['type'];
  847. $shadowCols.= ','.$TCA[$table]['ctrl']['label'];
  848. $shadowColumns = array_unique(t3lib_div::trimExplode(',', $shadowCols,1));
  849. foreach($shadowColumns as $fieldName) {
  850. if (strcmp($justStoredRecord[$fieldName],$liveRec[$fieldName]) && isset($TCA[$table]['columns'][$fieldName]) && $fieldName!=='uid' && $fieldName!=='pid') {
  851. $newRecord[$fieldName] = $justStoredRecord[$fieldName];
  852. }
  853. }
  854. if (count($newRecord)) {
  855. $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']);
  856. $this->updateDB($table,$liveRec['uid'],$newRecord);
  857. }
  858. }
  859. }
  860. }
  861. /**
  862. * Filling in the field array
  863. * $this->exclude_array is used to filter fields if needed.
  864. *
  865. * @param string Table name
  866. * @param integer Record ID
  867. * @param array Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
  868. * @param array $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
  869. * @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.
  870. * @param string $status = 'new' or 'update'
  871. * @param integer $tscPID: TSconfig PID
  872. * @return array Field Array
  873. */
  874. function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID) {
  875. global $TCA;
  876. // Initialize:
  877. t3lib_div::loadTCA($table);
  878. $originalLanguageRecord = NULL;
  879. $originalLanguage_diffStorage = NULL;
  880. $diffStorageFlag = FALSE;
  881. // Setting 'currentRecord' and 'checkValueRecord':
  882. if (strstr($id,'NEW')) {
  883. $currentRecord = $checkValueRecord = $fieldArray; // must have the 'current' array - not the values after processing below...
  884. // IF $incomingFieldArray is an array, overlay it.
  885. // 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...
  886. if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
  887. $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
  888. }
  889. } else {
  890. $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
  891. 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.
  892. // Get original language record if available:
  893. if (is_array($currentRecord)
  894. && $TCA[$table]['ctrl']['transOrigDiffSourceField']
  895. && $TCA[$table]['ctrl']['languageField']
  896. && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
  897. && $TCA[$table]['ctrl']['transOrigPointerField']
  898. && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0) {
  899. $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
  900. $originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
  901. t3lib_BEfunc::workspaceOL($lookUpTable,$originalLanguageRecord);
  902. $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
  903. }
  904. }
  905. $this->checkValue_currentRecord = $checkValueRecord;
  906. /*
  907. In the following all incoming value-fields are tested:
  908. - Are the user allowed to change the field?
  909. - Is the field uid/pid (which are already set)
  910. - perms-fields for pages-table, then do special things...
  911. - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
  912. If everything is OK, the field is entered into $fieldArray[]
  913. */
  914. foreach($incomingFieldArray as $field => $fieldValue) {
  915. if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) { // The field must be editable.
  916. // Checking if a value for language can be changed:
  917. $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);
  918. if (!$languageDeny) {
  919. // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
  920. if ($this->stripslashes_values) {
  921. if (is_array($fieldValue)) {
  922. t3lib_div::stripSlashesOnArray($fieldValue);
  923. } else $fieldValue = stripslashes($fieldValue);
  924. }
  925. switch ($field) {
  926. case 'uid':
  927. case 'pid':
  928. // Nothing happens, already set
  929. break;
  930. case 'perms_userid':
  931. case 'perms_groupid':
  932. case 'perms_user':
  933. case 'perms_group':
  934. case 'perms_everybody':
  935. // Permissions can be edited by the owner or the administrator
  936. if ($table=='pages' && ($this->admin || $status=='new' || $this->pageInfo($id,'perms_userid')==$this->userid) ) {
  937. $value=intval($fieldValue);
  938. switch($field) {
  939. case 'perms_userid':
  940. $fieldArray[$field]=$value;
  941. break;
  942. case 'perms_groupid':
  943. $fieldArray[$field]=$value;
  944. break;
  945. default:
  946. if ($value>=0 && $value<pow(2,5)) {
  947. $fieldArray[$field]=$value;
  948. }
  949. break;
  950. }
  951. }
  952. break;
  953. case 't3ver_oid':
  954. case 't3ver_id':
  955. case 't3ver_wsid':
  956. case 't3ver_state':
  957. case 't3ver_swapmode':
  958. case 't3ver_count':
  959. case 't3ver_stage':
  960. case 't3ver_tstamp':
  961. // t3ver_label is not here because it CAN be edited as a regular field!
  962. break;
  963. default:
  964. if (isset($TCA[$table]['columns'][$field])) {
  965. // Evaluating the value
  966. $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
  967. if (isset($res['value'])) {
  968. $fieldArray[$field] = $res['value'];
  969. }
  970. // Add the value of the original record to the diff-storage content:
  971. if ($this->updateModeL10NdiffData && $TCA[$table]['ctrl']['transOrigDiffSourceField']) {
  972. $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
  973. $diffStorageFlag = TRUE;
  974. }
  975. // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
  976. // 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.
  977. // 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.
  978. // 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 !
  979. if ($this->autoVersioningUpdate===TRUE) {
  980. if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
  981. foreach($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
  982. $fieldArray[$field] = str_replace(' src="'.$oldRTEmagicName.'"',' src="'.$newRTEmagicName.'"',$fieldArray[$field]);
  983. }
  984. }
  985. }
  986. } elseif ($TCA[$table]['ctrl']['origUid']===$field) { // Allow value for original UID to pass by...
  987. $fieldArray[$field] = $fieldValue;
  988. }
  989. break;
  990. }
  991. } // Checking language.
  992. } // Check exclude fields / disabled fields...
  993. }
  994. // Add diff-storage information:
  995. 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...
  996. $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
  997. }
  998. // Checking for RTE-transformations of fields:
  999. $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
  1000. $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
  1001. if (is_array($types_fieldConfig)) {
  1002. foreach ($types_fieldConfig as $vconf) {
  1003. // Write file configuration:
  1004. $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray)); // inserted array_merge($currentRecord,$fieldArray) 170502
  1005. // RTE transformations:
  1006. if (!$this->dontProcessTransformations) {
  1007. if (isset($fieldArray[$vconf['field']])) {
  1008. // Look for transformation flag:
  1009. switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']]) {
  1010. case 'RTE':
  1011. $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
  1012. $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
  1013. // Set alternative relative path for RTE images/links:
  1014. $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
  1015. // Get RTE object, draw form and set flag:
  1016. $RTEobj = t3lib_BEfunc::RTEgetObj();
  1017. if (is_object($RTEobj)) {
  1018. $fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
  1019. } else {
  1020. debug('NO RTE OBJECT FOUND!');
  1021. }
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. // Write file configuration:
  1027. if (is_array($eFile)) {
  1028. $mixedRec = array_merge($currentRecord,$fieldArray);
  1029. $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
  1030. $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
  1031. /* @var $parseHTML t3lib_parsehtml_proc */
  1032. $parseHTML->init('','');
  1033. $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
  1034. $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
  1035. $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, LF.$insertContent.LF, 1, 1);
  1036. t3lib_div::writeFile($eFile['editFile'],$SW_fileNewContent);
  1037. // Write status:
  1038. if (!strstr($id,'NEW') && $eFile['statusField']) {
  1039. $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
  1040. $table,
  1041. 'uid='.intval($id),
  1042. array(
  1043. $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
  1044. )
  1045. );
  1046. }
  1047. } elseif ($eFile && is_string($eFile)) {
  1048. $this->log($table,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
  1049. }
  1050. }
  1051. }
  1052. // Return fieldArray
  1053. return $fieldArray;
  1054. }
  1055. /*********************************************
  1056. *
  1057. * Evaluation of input values
  1058. *
  1059. ********************************************/
  1060. /**
  1061. * Evaluates a value according to $table/$field settings.
  1062. * This function is for real database fields - NOT FlexForm "pseudo" fields.
  1063. * 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() )
  1064. *
  1065. * @param string Table name
  1066. * @param string Field name
  1067. * @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.
  1068. * @param string The record-uid, mainly - but not exclusively - used for logging
  1069. * @param string 'update' or 'new' flag
  1070. * @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.
  1071. * @param integer $tscPID
  1072. * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
  1073. */
  1074. function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID) {
  1075. global $TCA, $PAGES_TYPES;
  1076. t3lib_div::loadTCA($table);
  1077. $res = Array(); // result array
  1078. $recFID = $table.':'.$id.':'.$field;
  1079. // Processing special case of field pages.doktype
  1080. if ($table=='pages' && $field=='doktype') {
  1081. // If the user may not use this specific doktype, we issue a warning
  1082. if (! ($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'],$value))) {
  1083. $propArr = $this->getRecordProperties($table,$id);
  1084. $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']);
  1085. return $res;
  1086. };
  1087. if ($status=='update') {
  1088. // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
  1089. $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ? $PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
  1090. if ($onlyAllowedTables) {
  1091. $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
  1092. if ($theWrongTables) {
  1093. $propArr = $this->getRecordProperties($table,$id);
  1094. $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']);
  1095. return $res;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. // Get current value:
  1101. $curValueRec = $this->recordInfo($table,$id,$field);
  1102. $curValue = $curValueRec[$field];
  1103. // Getting config for the field
  1104. $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
  1105. // Preform processing:
  1106. $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);
  1107. return $res;
  1108. }
  1109. /**
  1110. * Branches out evaluation of a field value based on its type as configured in TCA
  1111. * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
  1112. *
  1113. * @param array The result array. The processed value (if any!) is set in the "value" key.
  1114. * @param string The value to set.
  1115. * @param array Field configuration from TCA
  1116. * @param string Table name
  1117. * @param integer Return UID
  1118. * @param [type] $curValue: ...
  1119. * @param [type] $status: ...
  1120. * @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.
  1121. * @param [type] $recFID: ...
  1122. * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
  1123. * @param [type] $uploadedFiles: ...
  1124. * @param [type] $tscPID: ...
  1125. * @return array Returns the evaluated $value as key "value" in this array.
  1126. */
  1127. function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID) {
  1128. $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
  1129. switch ($tcaFieldConf['type']) {
  1130. case 'text':
  1131. $res = $this->checkValue_text($res,$value,$tcaFieldConf,$PP,$field);
  1132. break;
  1133. case 'passthrough':
  1134. case 'user':
  1135. $res['value'] = $value;
  1136. break;
  1137. case 'input':
  1138. $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
  1139. break;
  1140. case 'check':
  1141. $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
  1142. break;
  1143. case 'radio':
  1144. $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
  1145. break;
  1146. case 'group':
  1147. case 'select':
  1148. $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
  1149. break;
  1150. case 'inline':
  1151. $res = $this->checkValue_inline($res,$value,$tcaFieldConf,$PP,$field);
  1152. break;
  1153. case 'flex':
  1154. if ($field) { // FlexForms are only allowed for real fields.
  1155. $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
  1156. }
  1157. break;
  1158. default:
  1159. #debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
  1160. break;
  1161. }
  1162. return $res;
  1163. }
  1164. /**
  1165. * Evaluate "text" type values.
  1166. *
  1167. * @param array The result array. The processed value (if any!) is set in the "value" key.
  1168. * @param string The value to set.
  1169. * @param array Field configuration from TCA
  1170. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1171. * @param string Field name
  1172. * @return array Modified $res array
  1173. */
  1174. function checkValue_text($res,$value,$tcaFieldConf,$PP,$field='') {
  1175. $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
  1176. $res = $this->checkValue_text_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
  1177. return $res;
  1178. }
  1179. /**
  1180. * Evaluate "input" type values.
  1181. *
  1182. * @param array The result array. The processed value (if any!) is set in the "value" key.
  1183. * @param string The value to set.
  1184. * @param array Field configuration from TCA
  1185. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1186. * @param string Field name
  1187. * @return array Modified $res array
  1188. */
  1189. function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='') {
  1190. list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
  1191. // Secures the string-length to be less than max.
  1192. if (intval($tcaFieldConf['max']) > 0) {
  1193. $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, $value, 0, intval($tcaFieldConf['max']));
  1194. }
  1195. // Checking range of value:
  1196. if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox']) { // If value is not set to the allowed checkbox-value then it is checked against the ranges
  1197. if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper']) {$value=$tcaFieldConf['range']['upper'];}
  1198. if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower']) {$value=$tcaFieldConf['range']['lower'];}
  1199. }
  1200. // Process evaluation settings:
  1201. $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
  1202. $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
  1203. // Process UNIQUE settings:
  1204. 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...
  1205. if ($res['value'] && in_array('uniqueInPid',$evalCodesArray)) {
  1206. $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
  1207. }
  1208. if ($res['value'] && in_array('unique',$evalCodesArray)) {
  1209. $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
  1210. }
  1211. }
  1212. return $res;
  1213. }
  1214. /**
  1215. * Evaluates 'check' type values.
  1216. *
  1217. * @param array The result array. The processed value (if any!) is set in the 'value' key.
  1218. * @param string The value to set.
  1219. * @param array Field configuration from TCA
  1220. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1221. * @return array Modified $res array
  1222. */
  1223. function checkValue_check($res,$value,$tcaFieldConf,$PP) {
  1224. list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
  1225. $itemC = count($tcaFieldConf['items']);
  1226. if (!$itemC) {$itemC=1;}
  1227. $maxV = pow(2,$itemC);
  1228. if ($value<0) {$value=0;}
  1229. if ($value>$maxV) {$value=$maxV;}
  1230. $res['value'] = $value;
  1231. return $res;
  1232. }
  1233. /**
  1234. * Evaluates 'radio' type values.
  1235. *
  1236. * @param array The result array. The processed value (if any!) is set in the 'value' key.
  1237. * @param string The value to set.
  1238. * @param array Field configuration from TCA
  1239. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1240. * @return array Modified $res array
  1241. */
  1242. function checkValue_radio($res,$value,$tcaFieldConf,$PP) {
  1243. list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
  1244. if (is_array($tcaFieldConf['items'])) {
  1245. foreach($tcaFieldConf['items'] as $set) {
  1246. if (!strcmp($set[1],$value)) {
  1247. $res['value'] = $value;
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. return $res;
  1253. }
  1254. /**
  1255. * Evaluates 'group' or 'select' type values.
  1256. *
  1257. * @param array The result array. The processed value (if any!) is set in the 'value' key.
  1258. * @param string The value to set.
  1259. * @param array Field configuration from TCA
  1260. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1261. * @param [type] $uploadedFiles: ...
  1262. * @param string Field name
  1263. * @return array Modified $res array
  1264. */
  1265. function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
  1266. list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
  1267. // Detecting if value sent is an array and if so, implode it around a comma:
  1268. if (is_array($value)) {
  1269. $value = implode(',',$value);
  1270. }
  1271. // 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.
  1272. // Anyways, this should NOT disturb anything else:
  1273. $value = $this->convNumEntityToByteValue($value);
  1274. // When values are sent as group or select they come as comma-separated values which are exploded by this function:
  1275. $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
  1276. // If not multiple is set, then remove duplicates:
  1277. if (!$tcaFieldConf['multiple']) {
  1278. $valueArray = array_unique($valueArray);
  1279. }
  1280. // If an exclusive key is found, discard all others:
  1281. if ($tcaFieldConf['type']=='select' && $tcaFieldConf['exclusiveKeys']) {
  1282. $exclusiveKeys = t3lib_div::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
  1283. foreach($valueArray as $kk => $vv) {
  1284. if (in_array($vv, $exclusiveKeys)) { // $vv is the item key!
  1285. $valueArray = Array($kk => $vv);
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. // 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?)
  1291. // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
  1292. // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
  1293. if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode']) {
  1294. $preCount = count($valueArray);
  1295. foreach($valueArray as $kk => $vv) {
  1296. if (!$this->BE_USER->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode'])) {
  1297. unset($valueArray[$kk]);
  1298. }
  1299. }
  1300. // 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.
  1301. if ($preCount && !count($valueArray)) {
  1302. return array();
  1303. }
  1304. }
  1305. // For group types:
  1306. if ($tcaFieldConf['type']=='group') {
  1307. switch($tcaFieldConf['internal_type']) {
  1308. case 'file_reference':
  1309. case 'file':
  1310. $valueArray = $this->checkValue_group_select_file(
  1311. $valueArray,
  1312. $tcaFieldConf,
  1313. $curValue,
  1314. $uploadedFiles,
  1315. $status,
  1316. $table,
  1317. $id,
  1318. $recFID
  1319. );
  1320. break;
  1321. case 'db':
  1322. $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
  1323. break;
  1324. }
  1325. }
  1326. // For select types which has a foreign table attached:
  1327. if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table']) {
  1328. // check, if there is a NEW... id in the value, that should be substituded later
  1329. if (strpos($value, 'NEW') !== false) {
  1330. $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
  1331. $this->remapStack[] = array(
  1332. 'func' => 'checkValue_group_select_processDBdata',
  1333. 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
  1334. 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
  1335. 'field' => $field
  1336. );
  1337. $unsetResult = true;
  1338. } else {
  1339. $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
  1340. }
  1341. }
  1342. if (!$unsetResult) {
  1343. $newVal=$this->checkValue_checkMax($tcaFieldConf, $valueArray);
  1344. $res['value'] = implode(',',$newVal);
  1345. } else {
  1346. unset($res['value']);
  1347. }
  1348. return $res;
  1349. }
  1350. /**
  1351. * Handling files for group/select function
  1352. *
  1353. * @param array Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
  1354. * @param array Configuration array from TCA of the field
  1355. * @param string Current value of the field
  1356. * @param array Array of uploaded files, if any
  1357. * @param string Status ("update" or ?)
  1358. * @param string tablename of record
  1359. * @param integer UID of record
  1360. * @param string Field identifier ([table:uid:field:....more for flexforms?]
  1361. * @return array Modified value array
  1362. * @see checkValue_group_select()
  1363. */
  1364. function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID) {
  1365. if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
  1366. // If any files are uploaded, add them to value array
  1367. if (is_array($uploadedFileArray) &&
  1368. $uploadedFileArray['name'] &&
  1369. strcmp($uploadedFileArray['tmp_name'],'none')) {
  1370. $valueArray[]=$uploadedFileArray['tmp_name'];
  1371. $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
  1372. }
  1373. // Creating fileFunc object.
  1374. if (!$this->fileFunc) {
  1375. $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
  1376. $this->include_filefunctions=1;
  1377. }
  1378. // Setting permitted extensions.
  1379. $all_files = Array();
  1380. $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
  1381. $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
  1382. $all_files['ftpspace'] = $all_files['webspace'];
  1383. $this->fileFunc->init('', $all_files);
  1384. }
  1385. // If there is an upload folder defined:
  1386. if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
  1387. if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
  1388. // For logging..
  1389. $propArr = $this->getRecordProperties($table,$id);
  1390. // Get destrination path:
  1391. $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
  1392. // If we are updating:
  1393. if ($status=='update') {
  1394. // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
  1395. // 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!
  1396. // 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_.
  1397. // 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.
  1398. // Illustration of the problem comes here:
  1399. // 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.
  1400. // 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.
  1401. // 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.
  1402. // 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.
  1403. if ($this->autoVersioningUpdate===TRUE) {
  1404. foreach($valueArray as $key => $theFile) {
  1405. if ($theFile===basename($theFile)) { // If it is an already attached file...
  1406. $valueArray[$key] = PATH_site.$tcaFieldConf['uploadfolder'].'/'.$theFile;
  1407. }
  1408. }
  1409. }
  1410. // Finding the CURRENT files listed, either from MM or from the current record.
  1411. $theFileValues=array();
  1412. if ($tcaFieldConf['MM']) { // If MM relations for the files also!
  1413. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  1414. /* @var $dbAnalysis t3lib_loadDBGroup */
  1415. $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
  1416. foreach ($dbAnalysis->itemArray as $item) {
  1417. if ($item['id']) {
  1418. $theFileValues[] = $item['id'];
  1419. }
  1420. }
  1421. } else {
  1422. $theFileValues=t3lib_div::trimExplode(',',$curValue,1);
  1423. }
  1424. $currentFilesForHistory = implode(',', $theFileValues);
  1425. // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
  1426. if (count($theFileValues)) {
  1427. // 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!)
  1428. foreach($valueArray as $key => $theFile) {
  1429. if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
  1430. $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues,$theFile);
  1431. }
  1432. }
  1433. // This array contains the filenames in the uploadfolder that should be deleted:
  1434. foreach($theFileValues as $key => $theFile) {
  1435. $theFile = trim($theFile);
  1436. if (@is_file($dest.'/'.$theFile)) {
  1437. $this->removeFilesStore[]=$dest.'/'.$theFile;
  1438. } elseif ($theFile) {
  1439. $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
  1440. }
  1441. }
  1442. }
  1443. }
  1444. // Traverse the submitted values:
  1445. foreach($valueArray as $key => $theFile) {
  1446. // 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)
  1447. if (strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
  1448. // Init:
  1449. $maxSize = intval($tcaFieldConf['max_size']);
  1450. $cmd='';
  1451. $theDestFile=''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
  1452. // Check various things before copying file:
  1453. if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist
  1454. // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
  1455. if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name']) {
  1456. $fileSize = $uploadedFileArray['size'];
  1457. } else {
  1458. $fileSize = filesize($theFile);
  1459. }
  1460. if (!$maxSize || $fileSize<=($maxSize*1024)) { // Check file size:
  1461. // Prepare filename:
  1462. $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
  1463. $fI = t3lib_div::split_fileref($theEndFileName);
  1464. // Check for allowed extension:
  1465. if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
  1466. $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
  1467. // If we have a unique destination filename, then write the file:
  1468. if ($theDestFile) {
  1469. t3lib_div::upload_copy_move($theFile,$theDestFile);
  1470. $this->copiedFileMap[$theFile] = $theDestFile;
  1471. clearstatcache();
  1472. if (!@is_file($theDestFile)) $this->log($table,$id,5,0,1,"Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)",16,array($theFile, dirname($theDestFile), $recFID),$propArr['event_pid']);
  1473. } else $this->log($table,$id,5,0,1,"Copying file '%s' failed!: No destination file (%s) possible!. (%s)",11,array($theFile, $theDestFile, $recFID),$propArr['event_pid']);
  1474. } else $this->log($table,$id,5,0,1,"File extension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
  1475. } else $this->log($table,$id,5,0,1,"Filesize (%s) of file '%s' exceeds limit (%s). (%s)",13,array(t3lib_div::formatSize($fileSize),$theFile,t3lib_div::formatSize($maxSize*1024),$recFID),$propArr['event_pid']);
  1476. } else $this->log($table,$id,5,0,1,'The destination (%s) or the source file (%s) does not exist. (%s)',14,array($dest, $theFile, $recFID),$propArr['event_pid']);
  1477. // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
  1478. if (@is_file($theDestFile)) {
  1479. $info = t3lib_div::split_fileref($theDestFile);
  1480. $valueArray[$key]=$info['file']; // The value is set to the new filename
  1481. } else {
  1482. unset($valueArray[$key]); // The value is set to the new filename
  1483. }
  1484. }
  1485. }
  1486. }
  1487. // 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!
  1488. if ($tcaFieldConf['MM']) {
  1489. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  1490. /* @var $dbAnalysis t3lib_loadDBGroup */
  1491. $dbAnalysis->tableArray['files']=array(); // dummy
  1492. foreach ($valueArray as $key => $theFile) {
  1493. // explode files
  1494. $dbAnalysis->itemArray[]['id']=$theFile;
  1495. }
  1496. if ($status=='update') {
  1497. $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
  1498. $newFiles = implode(',', $dbAnalysis->getValueArray());
  1499. list(,,$recFieldName) = explode(':', $recFID);
  1500. if ($currentFilesForHistory != $newFiles) {
  1501. $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
  1502. $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
  1503. } else {
  1504. $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
  1505. $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
  1506. }
  1507. } else {
  1508. $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
  1509. }
  1510. $valueArray = $dbAnalysis->countItems();
  1511. }
  1512. //store path relative to site root (if uploadfolder is not set or internal_type is file_reference)
  1513. } else {
  1514. if (count($valueArray)){
  1515. if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
  1516. $propArr = $this->getRecordProperties($table, $id); // For logging..
  1517. foreach($valueArray as &$theFile){
  1518. // if alernative File Path is set for the file, then it was an import
  1519. if ($this->alternativeFilePath[$theFile]){
  1520. // don't import the file if it already exists
  1521. if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
  1522. $theFile = PATH_site . $this->alternativeFilePath[$theFile];
  1523. // import the file
  1524. } elseif (@is_file($theFile)){
  1525. $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
  1526. if (!@is_dir($dest)) {
  1527. t3lib_div::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
  1528. }
  1529. // Init:
  1530. $maxSize = intval($tcaFieldConf['max_size']);
  1531. $cmd = '';
  1532. $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
  1533. $fileSize = filesize($theFile);
  1534. if (!$maxSize || $fileSize <= ($maxSize * 1024)) { // Check file size:
  1535. // Prepare filename:
  1536. $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
  1537. $fI = t3lib_div::split_fileref($theEndFileName);
  1538. // Check for allowed extension:
  1539. if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
  1540. $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
  1541. // Write the file:
  1542. if ($theDestFile) {
  1543. t3lib_div::upload_copy_move($theFile, $theDestFile);
  1544. $this->copiedFileMap[$theFile] = $theDestFile;
  1545. clearstatcache();
  1546. if (!@is_file($theDestFile)) $this->log($table, $id, 5, 0, 1, "Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)", 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
  1547. } else $this->log($table, $id, 5, 0, 1, "Copying file '%s' failed!: No destination file (%s) possible!. (%s)", 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
  1548. } else $this->log($table, $id, 5, 0, 1, "File extension '%s' not allowed. (%s)", 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
  1549. } else $this->log($table, $id, 5, 0, 1, "Filesize (%s) of file '%s' exceeds limit (%s). (%s)", 13, array(t3lib_div::formatSize($fileSize), $theFile,t3lib_div::formatSize($maxSize * 1024),$recFID), $propArr['event_pid']);
  1550. // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
  1551. if (@is_file($theDestFile)) {
  1552. $theFile = $theDestFile; // The value is set to the new filename
  1553. } else {
  1554. unset($theFile); // The value is set to the new filename
  1555. }
  1556. }
  1557. }
  1558. $theFile = t3lib_div::fixWindowsFilePath($theFile);
  1559. if (t3lib_div::isFirstPartOfStr($theFile, PATH_site)) {
  1560. $theFile = substr($theFile, strlen(PATH_site));
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. return $valueArray;
  1567. }
  1568. /**
  1569. * Evaluates 'flex' type values.
  1570. *
  1571. * @param array The result array. The processed value (if any!) is set in the 'value' key.
  1572. * @param string The value to set.
  1573. * @param array Field configuration from TCA
  1574. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1575. * @param array Uploaded files for the field
  1576. * @param array Current record array.
  1577. * @param string Field name
  1578. * @return array Modified $res array
  1579. */
  1580. function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
  1581. list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
  1582. if (is_array($value)) {
  1583. // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
  1584. // 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.
  1585. $newRecordPidValue = $status=='new' ? $realPid : 0;
  1586. // Get current value array:
  1587. $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table,'',TRUE,$newRecordPidValue);
  1588. $currentValueArray = t3lib_div::xml2array($curValue);
  1589. if (!is_array($currentValueArray)) $currentValueArray = array();
  1590. if (is_array($currentValueArray['meta']['currentLangId'])) unset($currentValueArray['meta']['currentLangId']); // Remove all old meta for languages...
  1591. // Evaluation of input values:
  1592. $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
  1593. // Create XML and convert charsets from input value:
  1594. $xmlValue = $this->checkValue_flexArray2Xml($value,TRUE);
  1595. // If we wanted to set UTF fixed:
  1596. // $storeInCharset='utf-8';
  1597. // $currentCharset=$GLOBALS['LANG']->charSet;
  1598. // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
  1599. $storeInCharset=$GLOBALS['LANG']->charSet;
  1600. // Merge them together IF they are both arrays:
  1601. // 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).
  1602. if (is_array($currentValueArray)) {
  1603. $arrValue = t3lib_div::xml2array($xmlValue);
  1604. $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
  1605. $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
  1606. }
  1607. // Action commands (sorting order and removals of elements)
  1608. $actionCMDs = t3lib_div::_GP('_ACTION_FLEX_FORMdata');
  1609. if (is_array($actionCMDs[$table][$id][$field]['data'])) {
  1610. $arrValue = t3lib_div::xml2array($xmlValue);
  1611. $this->_ACTION_FLEX_FORMdata($arrValue['data'],$actionCMDs[$table][$id][$field]['data']);
  1612. $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
  1613. }
  1614. // Create the value XML:
  1615. $res['value']='';
  1616. $res['value'].=$xmlValue;
  1617. } else { // Passthrough...:
  1618. $res['value']=$value;
  1619. }
  1620. return $res;
  1621. }
  1622. /**
  1623. * Converts an array to FlexForm XML
  1624. *
  1625. * @param array Array with FlexForm data
  1626. * @param boolean If set, the XML prologue is returned as well.
  1627. * @return string Input array converted to XML
  1628. */
  1629. function checkValue_flexArray2Xml($array, $addPrologue=FALSE) {
  1630. $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
  1631. /* @var $flexObj t3lib_flexformtools */
  1632. return $flexObj->flexArray2Xml($array, $addPrologue);
  1633. }
  1634. /**
  1635. * Actions for flex form element (move, delete)
  1636. *
  1637. * @param array &$valueArrayToRemoveFrom: by reference
  1638. * @param array $deleteCMDS: ... *
  1639. * @return void
  1640. */
  1641. function _ACTION_FLEX_FORMdata(&$valueArray,$actionCMDs) {
  1642. if (is_array($valueArray) && is_array($actionCMDs)) {
  1643. foreach($actionCMDs as $key => $value) {
  1644. if ($key=='_ACTION') {
  1645. // First, check if there are "commands":
  1646. if (current($actionCMDs[$key])!=="") {
  1647. asort($actionCMDs[$key]);
  1648. $newValueArray = array();
  1649. foreach($actionCMDs[$key] as $idx => $order) {
  1650. if (substr($idx,0,3)=="ID-") {
  1651. $idx = $this->newIndexMap[$idx];
  1652. }
  1653. 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.
  1654. $newValueArray[$idx] = $valueArray[$idx];
  1655. }
  1656. unset($valueArray[$idx]);
  1657. }
  1658. $valueArray = t3lib_div::array_merge($newValueArray,$valueArray);
  1659. }
  1660. } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
  1661. $this->_ACTION_FLEX_FORMdata($valueArray[$key],$actionCMDs[$key]);
  1662. }
  1663. }
  1664. }
  1665. }
  1666. /**
  1667. * Evaluates 'inline' type values.
  1668. * (partly copied from the select_group function on this issue)
  1669. *
  1670. * @param array The result array. The processed value (if any!) is set in the 'value' key.
  1671. * @param string The value to set.
  1672. * @param array Field configuration from TCA
  1673. * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
  1674. * @param string Field name
  1675. * @return array Modified $res array
  1676. */
  1677. function checkValue_inline($res,$value,$tcaFieldConf,$PP,$field) {
  1678. list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
  1679. if (!$tcaFieldConf['foreign_table']) {
  1680. return false; // Fatal error, inline fields should always have a foreign_table defined
  1681. }
  1682. // When values are sent they come as comma-separated values which are exploded by this function:
  1683. $valueArray = t3lib_div::trimExplode(',', $value);
  1684. // Remove duplicates: (should not be needed)
  1685. $valueArray = array_unique($valueArray);
  1686. // Example for received data:
  1687. // $value = 45,NEW4555fdf59d154,12,123
  1688. // We need to decide whether we use the stack or can save the relation directly.
  1689. if(strpos($value, 'NEW') !== false || !t3lib_div::testInt($id)) {
  1690. $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
  1691. $this->remapStack[] = array(
  1692. 'func' => 'checkValue_inline_processDBdata',
  1693. 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
  1694. 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
  1695. 'field' => $field
  1696. );
  1697. unset($res['value']);
  1698. } elseif($value || t3lib_div::testInt($id)) {
  1699. $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
  1700. }
  1701. return $res;
  1702. }
  1703. /**
  1704. * Checks if a fields has more items than defined via TCA in maxitems.
  1705. * If there are more items than allowd, the item list is truncated to the defined number.
  1706. *
  1707. * @param array $tcaFieldConf: Field configuration from TCA
  1708. * @param array $valueArray: Current value array of items
  1709. * @return array The truncated value array of items
  1710. */
  1711. function checkValue_checkMax($tcaFieldConf, $valueArray) {
  1712. // 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...
  1713. $valueArrayC = count($valueArray);
  1714. // 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.
  1715. $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']):1;
  1716. if ($valueArrayC > $maxI) {$valueArrayC=$maxI;} // Checking for not too many elements
  1717. // Dumping array to list
  1718. $newVal=array();
  1719. foreach($valueArray as $nextVal) {
  1720. if ($valueArrayC==0) {break;}
  1721. $valueArrayC--;
  1722. $newVal[]=$nextVal;
  1723. }
  1724. return $newVal;
  1725. }
  1726. /*********************************************
  1727. *
  1728. * Helper functions for evaluation functions.
  1729. *
  1730. ********************************************/
  1731. /**
  1732. * Gets a unique value for $table/$id/$field based on $value
  1733. *
  1734. * @param string Table name
  1735. * @param string Field name for which $value must be unique
  1736. * @param string Value string.
  1737. * @param integer UID to filter out in the lookup (the record itself...)
  1738. * @param integer If set, the value will be unique for this PID
  1739. * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
  1740. */
  1741. function getUnique($table,$field,$value,$id,$newPid=0) {
  1742. global $TCA;
  1743. // Initialize:
  1744. t3lib_div::loadTCA($table);
  1745. $whereAdd='';
  1746. $newValue='';
  1747. if (intval($newPid)) { $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AND pid>=0'; } // "AND pid>=0" for versioning
  1748. $whereAdd.=$this->deleteClause($table);
  1749. // If the field is configured in TCA, proceed:
  1750. if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
  1751. // Look for a record which might already have the value:
  1752. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table).' AND uid!='.intval($id).$whereAdd);
  1753. $counter = 0;
  1754. // For as long as records with the test-value existing, try again (with incremented numbers appended).
  1755. while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
  1756. $newValue = $value.$counter;
  1757. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table).' AND uid!='.intval($id).$whereAdd);
  1758. $counter++;
  1759. if ($counter>100) { break; } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
  1760. }
  1761. // If the new value is there:
  1762. $value = strlen($newValue) ? $newValue : $value;
  1763. }
  1764. return $value;
  1765. }
  1766. function checkValue_text_Eval($value,$evalArray,$is_in) {
  1767. $res = Array();
  1768. $newValue = $value;
  1769. $set = true;
  1770. foreach ($evalArray as $func) {
  1771. switch ($func) {
  1772. case 'trim':
  1773. $value = trim($value);
  1774. break;
  1775. case 'required':
  1776. if (!$value) {$set=0;}
  1777. break;
  1778. default:
  1779. if (substr($func, 0, 3) == 'tx_') {
  1780. $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func].':&'.$func);
  1781. if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
  1782. $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
  1783. }
  1784. }
  1785. break;
  1786. }
  1787. }
  1788. if ($set) {$res['value'] = $value;}
  1789. return $res;
  1790. }
  1791. /**
  1792. * Evaluation of 'input'-type values based on 'eval' list
  1793. *
  1794. * @param string Value to evaluate
  1795. * @param array Array of evaluations to traverse.
  1796. * @param string Is-in string for 'is_in' evaluation
  1797. * @return array Modified $value in key 'value' or empty array
  1798. */
  1799. function checkValue_input_Eval($value,$evalArray,$is_in) {
  1800. $res = Array();
  1801. $newValue = $value;
  1802. $set = true;
  1803. foreach($evalArray as $func) {
  1804. switch($func) {
  1805. case 'int':
  1806. case 'year':
  1807. case 'time':
  1808. case 'timesec':
  1809. $value = intval($value);
  1810. break;
  1811. case 'date':
  1812. case 'datetime':
  1813. $value = intval($value);
  1814. if ($value>0 && !$this->dontProcessTransformations) {
  1815. $value -= date('Z', $value);
  1816. }
  1817. break;
  1818. case 'double2':
  1819. $value = preg_replace('/[^0-9,\.-]/', '', $value);
  1820. $negative = substr($value, 0, 1) == '-';
  1821. $value = strtr($value, array(',' => '.', '-' => ''));
  1822. if (strpos($value, '.') === false) {
  1823. $value .= '.0';
  1824. }
  1825. $valueArray = explode('.', $value);
  1826. $dec = array_pop($valueArray);
  1827. $value = join('', $valueArray) . '.' . $dec;
  1828. if ($negative) {
  1829. $value *= -1;
  1830. }
  1831. $value = number_format($value, 2, '.', '');
  1832. break;
  1833. case 'md5':
  1834. if (strlen($value)!=32){$set=false;}
  1835. break;
  1836. case 'trim':
  1837. $value = trim($value);
  1838. break;
  1839. case 'upper':
  1840. $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
  1841. break;
  1842. case 'lower':
  1843. $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
  1844. break;
  1845. case 'required':
  1846. if (!isset($value) || $value === '') {
  1847. $set = false;
  1848. }
  1849. break;
  1850. case 'is_in':
  1851. $c=strlen($value);
  1852. if ($c) {
  1853. $newVal = '';
  1854. for ($a=0;$a<$c;$a++) {
  1855. $char = substr($value,$a,1);
  1856. if (strpos($is_in,$char) !== false) {
  1857. $newVal.=$char;
  1858. }
  1859. }
  1860. $value = $newVal;
  1861. }
  1862. break;
  1863. case 'nospace':
  1864. $value = str_replace(' ','',$value);
  1865. break;
  1866. case 'alpha':
  1867. $value = preg_replace('/[^a-zA-Z]/','',$value);
  1868. break;
  1869. case 'num':
  1870. $value = preg_replace('/[^0-9]/','',$value);
  1871. break;
  1872. case 'alphanum':
  1873. $value = preg_replace('/[^a-zA-Z0-9]/','',$value);
  1874. break;
  1875. case 'alphanum_x':
  1876. $value = preg_replace('/[^a-zA-Z0-9_-]/','',$value);
  1877. break;
  1878. default:
  1879. if (substr($func, 0, 3) == 'tx_') {
  1880. $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func].':&'.$func);
  1881. if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
  1882. $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
  1883. }
  1884. }
  1885. break;
  1886. }
  1887. }
  1888. if ($set) {$res['value'] = $value;}
  1889. return $res;
  1890. }
  1891. /**
  1892. * Returns data for group/db and select fields
  1893. *
  1894. * @param array Current value array
  1895. * @param array TCA field config
  1896. * @param integer Record id, used for look-up of MM relations (local_uid)
  1897. * @param string Status string ('update' or 'new')
  1898. * @param string The type, either 'select', 'group' or 'inline'
  1899. * @param string Table name, needs to be passed to t3lib_loadDBGroup
  1900. * @param string field name, needs to be set for writing to sys_history
  1901. * @return array Modified value array
  1902. */
  1903. function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
  1904. $tables = $type=='group'?$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
  1905. $prep = $type=='group'?$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
  1906. $newRelations = implode(',', $valueArray);
  1907. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  1908. /* @var $dbAnalysis t3lib_loadDBGroup */
  1909. $dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
  1910. $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
  1911. if ($tcaFieldConf['MM']) {
  1912. if ($status=='update') {
  1913. $oldRelations_dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  1914. /* @var $oldRelations_dbAnalysis t3lib_loadDBGroup */
  1915. $oldRelations_dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
  1916. // db analysis with $id will initialize with the existing relations
  1917. $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
  1918. $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
  1919. $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
  1920. if ($oldRelations != $newRelations) {
  1921. $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
  1922. $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
  1923. } else {
  1924. $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
  1925. $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
  1926. }
  1927. } else {
  1928. $this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep,$currentTable); // This will be traversed later to execute the actions
  1929. }
  1930. $valueArray = $dbAnalysis->countItems();
  1931. } else {
  1932. $valueArray = $dbAnalysis->getValueArray($prep);
  1933. if ($type=='select' && $prep) {
  1934. $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
  1935. }
  1936. }
  1937. // 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.
  1938. return $valueArray;
  1939. }
  1940. /**
  1941. * Explodes the $value, which is a list of files/uids (group select)
  1942. *
  1943. * @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.
  1944. * @return array The value array.
  1945. */
  1946. function checkValue_group_select_explodeSelectGroupValue($value) {
  1947. $valueArray = t3lib_div::trimExplode(',',$value,1);
  1948. foreach ($valueArray as &$newVal) {
  1949. $temp=explode('|',$newVal,2);
  1950. $newVal = str_replace(
  1951. ',',
  1952. '',
  1953. str_replace('|', '', rawurldecode($temp[0]))
  1954. );
  1955. }
  1956. return $valueArray;
  1957. }
  1958. /**
  1959. * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
  1960. * See checkValue_flex_procInData_travDS() for more details.
  1961. * 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
  1962. *
  1963. * @param array The 'data' part of the INPUT flexform data
  1964. * @param array The 'data' part of the CURRENT flexform data
  1965. * @param array The uploaded files for the 'data' part of the INPUT flexform data
  1966. * @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.
  1967. * @param array A set of parameters to pass through for the calling of the evaluation functions
  1968. * @param string Optional call back function, see checkValue_flex_procInData_travDS() DEPRICATED, use class.t3lib_flexformtools.php instead for traversal!
  1969. * @return array The modified 'data' part.
  1970. * @see checkValue_flex_procInData_travDS()
  1971. */
  1972. function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='') {
  1973. if (is_array($dataPart)) {
  1974. foreach($dataPart as $sKey => $sheetDef) {
  1975. list ($dataStruct,$actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sKey);
  1976. if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef)) {
  1977. foreach($sheetDef as $lKey => $lData) {
  1978. $this->checkValue_flex_procInData_travDS(
  1979. $dataPart[$sKey][$lKey],
  1980. $dataPart_current[$sKey][$lKey],
  1981. $uploadedFiles[$sKey][$lKey],
  1982. $dataStruct['ROOT']['el'],
  1983. $pParams,
  1984. $callBackFunc,
  1985. $sKey.'/'.$lKey.'/'
  1986. );
  1987. }
  1988. }
  1989. }
  1990. }
  1991. return $dataPart;
  1992. }
  1993. /**
  1994. * Processing of the sheet/language data array
  1995. * 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.
  1996. *
  1997. * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
  1998. * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
  1999. * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
  2000. * @param array Data structure which fits the data array
  2001. * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
  2002. * @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.
  2003. * @param [type] $structurePath: ...
  2004. * @return void
  2005. * @see checkValue_flex_procInData()
  2006. */
  2007. function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath) {
  2008. if (is_array($DSelements)) {
  2009. // For each DS element:
  2010. foreach($DSelements as $key => $dsConf) {
  2011. // Array/Section:
  2012. if ($DSelements[$key]['type']=='array') {
  2013. if (is_array($dataValues[$key]['el'])) {
  2014. if ($DSelements[$key]['section']) {
  2015. $newIndexCounter=0;
  2016. foreach($dataValues[$key]['el'] as $ik => $el) {
  2017. if (is_array($el)) {
  2018. if (!is_array($dataValues_current[$key]['el'])) $dataValues_current[$key]['el']=array();
  2019. $theKey = key($el);
  2020. if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
  2021. $this->checkValue_flex_procInData_travDS(
  2022. $dataValues[$key]['el'][$ik][$theKey]['el'],
  2023. is_array($dataValues_current[$key]['el'][$ik]) ? $dataValues_current[$key]['el'][$ik][$theKey]['el'] : array(),
  2024. $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
  2025. $DSelements[$key]['el'][$theKey]['el'],
  2026. $pParams,
  2027. $callBackFunc,
  2028. $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
  2029. );
  2030. // 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:
  2031. // The fact that the order changes is not important since order is controlled by a separately submitted index.
  2032. if (substr($ik,0,3)=="ID-") {
  2033. $newIndexCounter++;
  2034. $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
  2035. $dataValues[$key]['el'][$this->newIndexMap[$ik]] = $dataValues[$key]['el'][$ik]; // Transfer values
  2036. unset($dataValues[$key]['el'][$ik]); // Unset original
  2037. }
  2038. }
  2039. }
  2040. }
  2041. } else {
  2042. if (!isset($dataValues[$key]['el'])) $dataValues[$key]['el']=array();
  2043. $this->checkValue_flex_procInData_travDS(
  2044. $dataValues[$key]['el'],
  2045. $dataValues_current[$key]['el'],
  2046. $uploadedFiles[$key]['el'],
  2047. $DSelements[$key]['el'],
  2048. $pParams,
  2049. $callBackFunc,
  2050. $structurePath.$key.'/el/'
  2051. );
  2052. }
  2053. }
  2054. } else {
  2055. if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
  2056. foreach($dataValues[$key] as $vKey => $data) {
  2057. if ($callBackFunc) {
  2058. if (is_object($this->callBackObj)) {
  2059. $res = $this->callBackObj->$callBackFunc(
  2060. $pParams,
  2061. $dsConf['TCEforms']['config'],
  2062. $dataValues[$key][$vKey],
  2063. $dataValues_current[$key][$vKey],
  2064. $uploadedFiles[$key][$vKey],
  2065. $structurePath.$key.'/'.$vKey.'/'
  2066. );
  2067. } else {
  2068. $res = $this->$callBackFunc(
  2069. $pParams,
  2070. $dsConf['TCEforms']['config'],
  2071. $dataValues[$key][$vKey],
  2072. $dataValues_current[$key][$vKey],
  2073. $uploadedFiles[$key][$vKey],
  2074. $structurePath.$key.'/'.$vKey.'/'
  2075. );
  2076. }
  2077. } else { // Default
  2078. list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
  2079. $res = $this->checkValue_SW(
  2080. array(),
  2081. $dataValues[$key][$vKey],
  2082. $dsConf['TCEforms']['config'],
  2083. $CVtable,
  2084. $CVid,
  2085. $dataValues_current[$key][$vKey],
  2086. $CVstatus,
  2087. $CVrealPid,
  2088. $CVrecFID,
  2089. '',
  2090. $uploadedFiles[$key][$vKey],
  2091. array(),
  2092. $CVtscPID
  2093. );
  2094. // Look for RTE transformation of field:
  2095. if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations) {
  2096. // Unsetting trigger field - we absolutely don't want that into the data storage!
  2097. unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
  2098. if (isset($res['value'])) {
  2099. // Calculating/Retrieving some values here:
  2100. list(,,$recFieldName) = explode(':', $CVrecFID);
  2101. $theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable,$this->checkValue_currentRecord);
  2102. $specConf = t3lib_BEfunc::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
  2103. // Find, thisConfig:
  2104. $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($CVtscPID));
  2105. $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
  2106. // Get RTE object, draw form and set flag:
  2107. $RTEobj = t3lib_BEfunc::RTEgetObj();
  2108. if (is_object($RTEobj)) {
  2109. $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord,$specConf,$thisConfig,'',$CVrealPid);
  2110. } else {
  2111. debug('NO RTE OBJECT FOUND!');
  2112. }
  2113. }
  2114. }
  2115. }
  2116. // Adding the value:
  2117. if (isset($res['value'])) {
  2118. $dataValues[$key][$vKey] = $res['value'];
  2119. }
  2120. // 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.
  2121. // 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).
  2122. if (substr($vKey,-9)!='.vDEFbase') {
  2123. if ($this->clear_flexFormData_vDEFbase) {
  2124. $dataValues[$key][$vKey.'.vDEFbase'] = '';
  2125. } 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')) {
  2126. // 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:
  2127. if (isset($dataValues[$key]['vDEF'])) {
  2128. $diffValue = $dataValues[$key]['vDEF'];
  2129. } else { // If not found (for translators with no access to the default language) we use the one from the current-value data set:
  2130. $diffValue = $dataValues_current[$key]['vDEF'];
  2131. }
  2132. // 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.
  2133. $dataValues[$key][$vKey.'.vDEFbase'] = $this->updateModeL10NdiffDataClear ? '' : $diffValue;
  2134. }
  2135. }
  2136. }
  2137. }
  2138. }
  2139. }
  2140. }
  2141. }
  2142. /**
  2143. * Returns data for inline fields.
  2144. *
  2145. * @param array Current value array
  2146. * @param array TCA field config
  2147. * @param integer Record id
  2148. * @param string Status string ('update' or 'new')
  2149. * @param string Table name, needs to be passed to t3lib_loadDBGroup
  2150. * @param string The current field the values are modified for
  2151. * @return string Modified values
  2152. */
  2153. protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field) {
  2154. $newValue = '';
  2155. $foreignTable = $tcaFieldConf['foreign_table'];
  2156. /*
  2157. * Fetch the related child records by using t3lib_loadDBGroup:
  2158. * @var $dbAnalysis t3lib_loadDBGroup
  2159. */
  2160. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  2161. $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
  2162. // If the localizationMode is set to 'keep', the children for the localized parent are kept as in the original untranslated record:
  2163. $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $tcaFieldConf);
  2164. if ($localizationMode=='keep' && $status=='update') {
  2165. // Fetch the current record and determine the original record:
  2166. $row = t3lib_BEfunc::getRecordWSOL($table, $id);
  2167. if (is_array($row)) {
  2168. $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
  2169. $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
  2170. // If language is set (e.g. 1) and also transOrigPointer (e.g. 123), use transOrigPointer as uid:
  2171. if ($language>0 && $transOrigPointer) {
  2172. $id = $transOrigPointer;
  2173. // If we're in active localizationMode 'keep', prevent from writing data to the field of the parent record:
  2174. // (on removing the localized parent, the original (untranslated) children would then also be removed)
  2175. $keepTranslation = true;
  2176. }
  2177. }
  2178. }
  2179. // IRRE with a pointer field (database normalization):
  2180. if ($tcaFieldConf['foreign_field']) {
  2181. // if the record was imported, sorting was also imported, so skip this
  2182. $skipSorting = ($this->callFromImpExp ? true : false);
  2183. // update record in intermediate table (sorting & pointer uid to parent record)
  2184. $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
  2185. $newValue = ($keepTranslation ? 0 : $dbAnalysis->countItems(false));
  2186. // IRRE with MM relation:
  2187. } else if ($this->getInlineFieldType($tcaFieldConf) == 'mm') {
  2188. // in order to fully support all the MM stuff, directly call checkValue_group_select_processDBdata instead of repeating the needed code here
  2189. $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
  2190. $newValue = ($keepTranslation ? 0 : $valueArray[0]);
  2191. // IRRE with comma separated values:
  2192. } else {
  2193. $valueArray = $dbAnalysis->getValueArray();
  2194. // Checking that the number of items is correct:
  2195. $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
  2196. // If a valid translation of the 'keep' mode is active, update relations in the original(!) record:
  2197. if ($keepTranslation) {
  2198. $this->updateDB($table, $transOrigPointer, array($field => implode(',', $valueArray)));
  2199. } else {
  2200. $newValue = implode(',', $valueArray);
  2201. }
  2202. }
  2203. return $newValue;
  2204. }
  2205. /*********************************************
  2206. *
  2207. * PROCESSING COMMANDS
  2208. *
  2209. ********************************************/
  2210. /**
  2211. * Processing the cmd-array
  2212. * See "TYPO3 Core API" for a description of the options.
  2213. *
  2214. * @return void
  2215. */
  2216. function process_cmdmap() {
  2217. global $TCA, $TYPO3_CONF_VARS;
  2218. // Editing frozen:
  2219. if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze']) {
  2220. $this->newlog('All editing in this workspace has been frozen!',1);
  2221. return FALSE;
  2222. }
  2223. // Hook initialization:
  2224. $hookObjectsArr = array();
  2225. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'])) {
  2226. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] as $classRef) {
  2227. $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
  2228. }
  2229. }
  2230. #debug($this->cmdmap);
  2231. $this->accumulateForNotifEmail = array(); // Reset notification array
  2232. // Traverse command map:
  2233. foreach (array_keys($this->cmdmap) as $table) {
  2234. // Check if the table may be modified!
  2235. $modifyAccessList = $this->checkModifyAccessList($table);
  2236. if (!$modifyAccessList) {
  2237. $id = 0;
  2238. $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
  2239. } // FIXME: $id not set here (Comment added by Sebastian Kurfuerst)
  2240. // Check basic permissions and circumstances:
  2241. if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap[$table]) && $modifyAccessList) {
  2242. // Traverse the command map:
  2243. foreach($this->cmdmap[$table] as $id => $incomingCmdArray) {
  2244. if (is_array($incomingCmdArray)) { // have found a command.
  2245. // Get command and value (notice, only one command is observed at a time!):
  2246. reset($incomingCmdArray);
  2247. $command = key($incomingCmdArray);
  2248. $value = current($incomingCmdArray);
  2249. foreach($hookObjectsArr as $hookObj) {
  2250. if (method_exists($hookObj, 'processCmdmap_preProcess')) {
  2251. $hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this);
  2252. }
  2253. }
  2254. // Init copyMapping array:
  2255. $this->copyMappingArray = Array(); // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
  2256. // Branch, based on command
  2257. switch ($command) {
  2258. case 'move':
  2259. $this->moveRecord($table,$id,$value);
  2260. break;
  2261. case 'copy':
  2262. if ($table === 'pages') {
  2263. $this->copyPages($id,$value);
  2264. } else {
  2265. $this->copyRecord($table,$id,$value,1);
  2266. }
  2267. break;
  2268. case 'localize':
  2269. $this->localize($table,$id,$value);
  2270. break;
  2271. case 'inlineLocalizeSynchronize':
  2272. $this->inlineLocalizeSynchronize($table, $id, $value);
  2273. break;
  2274. case 'version':
  2275. switch ((string)$value['action']) {
  2276. case 'new':
  2277. $versionizeTree = t3lib_div::intInRange(!isset($value['treeLevels'])?-1:$value['treeLevels'],-1,100);
  2278. if ($table == 'pages' && $versionizeTree>=0) {
  2279. $this->versionizePages($id,$value['label'],$versionizeTree);
  2280. } else {
  2281. $this->versionizeRecord($table,$id,$value['label']);
  2282. }
  2283. break;
  2284. case 'swap':
  2285. $swapMode = $this->BE_USER->getTSConfigVal('options.workspaces.swapMode');
  2286. $elementList = array();
  2287. if ($swapMode == 'any' || ($swapMode == 'page' && $table == 'pages')) {
  2288. // check if we are allowed to do synchronios publish. We must have a single element in the cmdmap to be allowed
  2289. if (count($this->cmdmap) == 1 && count($this->cmdmap[$table]) == 1) {
  2290. $elementList = $this->findPageElementsForVersionSwap($table, $id, $value['swapWith']);
  2291. }
  2292. }
  2293. if (count($elementList) == 0) {
  2294. $elementList[$table][] = array($id, $value['swapWith']);
  2295. }
  2296. foreach ($elementList as $tbl => $idList) {
  2297. foreach ($idList as $idKey => $idSet) {
  2298. $this->version_swap($tbl,$idSet[0],$idSet[1],$value['swapIntoWS']);
  2299. }
  2300. }
  2301. break;
  2302. case 'clearWSID':
  2303. $this->version_clearWSID($table,$id);
  2304. break;
  2305. case 'flush':
  2306. $this->version_clearWSID($table,$id,TRUE);
  2307. break;
  2308. case 'setStage':
  2309. $elementList = array();
  2310. $idList = $elementList[$table] = t3lib_div::trimExplode(',',$id,1);
  2311. $setStageMode = $this->BE_USER->getTSConfigVal('options.workspaces.changeStageMode');
  2312. if ($setStageMode == 'any' || $setStageMode == 'page') {
  2313. if (count($idList) == 1) {
  2314. $rec = t3lib_BEfunc::getRecord($table, $idList[0], 't3ver_wsid');
  2315. $workspaceId = $rec['t3ver_wsid'];
  2316. }
  2317. else {
  2318. $workspaceId = $this->BE_USER->workspace;
  2319. }
  2320. if ($table !== 'pages') {
  2321. if ($setStageMode == 'any') {
  2322. // (1) Find page to change stage and (2) find other elements from the same ws to change stage
  2323. $pageIdList = array();
  2324. $this->findPageIdsForVersionStateChange($table, $idList, $workspaceId, $pageIdList, $elementList);
  2325. $this->findPageElementsForVersionStageChange($pageIdList, $workspaceId, $elementList);
  2326. }
  2327. }
  2328. else {
  2329. // Find all elements from the same ws to change stage
  2330. $this->findRealPageIds($idList);
  2331. $this->findPageElementsForVersionStageChange($idList, $workspaceId, $elementList);
  2332. }
  2333. }
  2334. foreach ($elementList as $tbl => $elementIdList) {
  2335. foreach($elementIdList as $elementId) {
  2336. $this->version_setStage($tbl,$elementId,$value['stageId'],$value['comment']?$value['comment']:$this->generalComment, TRUE);
  2337. }
  2338. }
  2339. break;
  2340. }
  2341. break;
  2342. case 'delete':
  2343. $this->deleteAction($table, $id);
  2344. break;
  2345. case 'undelete':
  2346. $this->undeleteRecord($table, $id);
  2347. break;
  2348. }
  2349. foreach($hookObjectsArr as $hookObj) {
  2350. if (method_exists($hookObj, 'processCmdmap_postProcess')) {
  2351. $hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this);
  2352. }
  2353. }
  2354. // Merging the copy-array info together for remapping purposes.
  2355. $this->copyMappingArray_merged= t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged,$this->copyMappingArray);
  2356. }
  2357. }
  2358. }
  2359. }
  2360. // Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
  2361. $this->remapListedDBRecords();
  2362. // Empty accumulation array:
  2363. foreach($this->accumulateForNotifEmail as $notifItem) {
  2364. $this->notifyStageChange($notifItem['shared'][0],$notifItem['shared'][1],implode(', ',$notifItem['elements']),0,$notifItem['shared'][2]);
  2365. }
  2366. $this->accumulateForNotifEmail = array(); // Reset notification array
  2367. }
  2368. /*********************************************
  2369. *
  2370. * Cmd: Copying
  2371. *
  2372. ********************************************/
  2373. /**
  2374. * Copying a single record
  2375. *
  2376. * @param string Element table
  2377. * @param integer Element UID
  2378. * @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
  2379. * @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
  2380. * @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!
  2381. * @param string Commalist of fields to exclude from the copy process (might get default values)
  2382. * @param integer Language ID (from sys_language table)
  2383. * @return integer ID of new record, if any
  2384. */
  2385. function copyRecord($table, $uid, $destPid, $first=0, $overrideValues=array(), $excludeFields='', $language=0) {
  2386. global $TCA;
  2387. $uid = $origUid = intval($uid);
  2388. // Only copy if the table is defined in TCA, a uid is given and the record wasn't copied before:
  2389. if ($TCA[$table] && $uid && !$this->isRecordCopied($table, $uid)) {
  2390. t3lib_div::loadTCA($table);
  2391. /*
  2392. // 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)
  2393. if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$uid,'uid')) {
  2394. $uid = $lookForLiveVersion['uid'];
  2395. }
  2396. // Get workspace version of the source record, if any: Then we will copy workspace version instead:
  2397. if ($WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid')) {
  2398. $uid = $WSversion['uid'];
  2399. }
  2400. // 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.
  2401. */
  2402. if ($this->doesRecordExist($table,$uid,'show')) { // This checks if the record can be selected which is all that a copy action requires.
  2403. $fullLanguageCheckNeeded = ($table != 'pages');
  2404. if (($language > 0 && $this->BE_USER->checkLanguageAccess($language) ) ||
  2405. $this->BE_USER->recordEditAccessInternals(
  2406. $table, $uid, false, false, $fullLanguageCheckNeeded
  2407. )
  2408. ) { //Used to check language and general editing rights
  2409. $data = Array();
  2410. $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));
  2411. // $row = $this->recordInfo($table,$uid,'*');
  2412. $row = t3lib_BEfunc::getRecordWSOL($table,$uid); // So it copies (and localized) content from workspace...
  2413. if (is_array($row)) {
  2414. // Initializing:
  2415. $theNewID = uniqid('NEW');
  2416. $enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ? $TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
  2417. $headerField = $TCA[$table]['ctrl']['label'];
  2418. // Getting default data:
  2419. $defaultData = $this->newFieldArray($table);
  2420. // Getting "copy-after" fields if applicable:
  2421. $copyAfterFields = $destPid<0 ? $this->fixCopyAfterDuplFields($table,$uid,abs($destPid),0) : array();
  2422. // Page TSconfig related:
  2423. $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...
  2424. $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
  2425. $tE = $this->getTableEntries($table,$TSConfig);
  2426. // Traverse ALL fields of the selected record:
  2427. foreach($row as $field => $value) {
  2428. if (!in_array($field,$nonFields)) {
  2429. // Get TCA configuration for the field:
  2430. $conf = $TCA[$table]['columns'][$field]['config'];
  2431. // Preparation/Processing of the value:
  2432. if ($field=='pid') { // "pid" is hardcoded of course:
  2433. $value = $destPid;
  2434. } elseif (isset($overrideValues[$field])) { // Override value...
  2435. $value = $overrideValues[$field];
  2436. } elseif (isset($copyAfterFields[$field])) { // Copy-after value if available:
  2437. $value = $copyAfterFields[$field];
  2438. } elseif ($TCA[$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div::inList($TCA[$table]['ctrl']['setToDefaultOnCopy'],$field)) { // Revert to default for some fields:
  2439. $value = $defaultData[$field];
  2440. } else {
  2441. // Hide at copy may override:
  2442. if ($first && $field == $enableField && $TCA[$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy']) {
  2443. $value = 1;
  2444. }
  2445. // Prepend label on copy:
  2446. if ($first && $field == $headerField && $TCA[$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
  2447. $value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
  2448. }
  2449. // Processing based on the TCA config field type (files, references, flexforms...)
  2450. $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
  2451. }
  2452. // Add value to array.
  2453. $data[$table][$theNewID][$field] = $value;
  2454. }
  2455. }
  2456. // Overriding values:
  2457. if ($TCA[$table]['ctrl']['editlock']) {
  2458. $data[$table][$theNewID][$TCA[$table]['ctrl']['editlock']] = 0;
  2459. }
  2460. // Setting original UID:
  2461. if ($TCA[$table]['ctrl']['origUid']) {
  2462. $data[$table][$theNewID][$TCA[$table]['ctrl']['origUid']] = $uid;
  2463. }
  2464. // Do the copy by simply submitting the array through TCEmain:
  2465. $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
  2466. /* @var $copyTCE t3lib_TCEmain */
  2467. $copyTCE->stripslashes_values = 0;
  2468. $copyTCE->copyTree = $this->copyTree;
  2469. $copyTCE->cachedTSconfig = $this->cachedTSconfig; // Copy forth the cached TSconfig
  2470. $copyTCE->dontProcessTransformations=1; // Transformations should NOT be carried out during copy
  2471. $copyTCE->start($data,'',$this->BE_USER);
  2472. $copyTCE->process_datamap();
  2473. // Getting the new UID:
  2474. $theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
  2475. if ($theNewSQLID) {
  2476. $this->copyRecord_fixRTEmagicImages($table, t3lib_BEfunc::wsMapId($table, $theNewSQLID));
  2477. $this->copyMappingArray[$table][$origUid] = $theNewSQLID;
  2478. }
  2479. // Copy back the cached TSconfig
  2480. $this->cachedTSconfig = $copyTCE->cachedTSconfig;
  2481. $this->errorLog = array_merge($this->errorLog, $copyTCE->errorLog);
  2482. unset($copyTCE);
  2483. if($language == 0) {
  2484. //repointing the new translation records to the parent record we just created
  2485. $overrideValues[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $theNewSQLID;
  2486. $this->copyL10nOverlayRecords($table, $uid, $destPid<0 ? $tscPID : $destPid , $first, $overrideValues, $excludeFields);
  2487. }
  2488. return $theNewSQLID;
  2489. } else $this->log($table,$uid,3,0,1,'Attempt to copy record that did not exist!');
  2490. } else $this->log($table,$uid,3,0,1,'Attempt to copy record without having permissions to do so. ['.$this->BE_USER->errorMsg.'].');
  2491. } else $this->log($table,$uid,3,0,1,'Attempt to copy record without permission');
  2492. }
  2493. }
  2494. /**
  2495. * Copying pages
  2496. * Main function for copying pages.
  2497. *
  2498. * @param integer Page UID to copy
  2499. * @param integer Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
  2500. * @return void
  2501. */
  2502. function copyPages($uid,$destPid) {
  2503. // Initialize:
  2504. $uid = intval($uid);
  2505. $destPid = intval($destPid);
  2506. // Finding list of tables to copy.
  2507. $copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',',$this->BE_USER->groupData['tables_modify']); // These are the tables, the user may modify
  2508. if (!strstr($this->copyWhichTables,'*')) { // If not all tables are allowed then make a list of allowed tables: That is the tables that figure in both allowed tables AND the copyTable-list
  2509. foreach($copyTablesArray as $k => $table) {
  2510. if (!$table || !t3lib_div::inList($this->copyWhichTables.',pages',$table)) { // pages are always going...
  2511. unset($copyTablesArray[$k]);
  2512. }
  2513. }
  2514. }
  2515. $copyTablesArray = array_unique($copyTablesArray);
  2516. // Begin to copy pages if we're allowed to:
  2517. if ($this->admin || in_array('pages',$copyTablesArray)) {
  2518. // Copy this page we're on. And set first-flag (this will trigger that the record is hidden if that is configured)!
  2519. $theNewRootID = $this->copySpecificPage($uid,$destPid,$copyTablesArray,1);
  2520. // If we're going to copy recursively...:
  2521. if ($theNewRootID && $this->copyTree) {
  2522. // Get ALL subpages to copy (read-permissions are respected!):
  2523. $CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($this->copyTree), $theNewRootID);
  2524. // Now copying the subpages:
  2525. foreach($CPtable as $thePageUid => $thePagePid) {
  2526. $newPid = $this->copyMappingArray['pages'][$thePagePid];
  2527. if (isset($newPid)) {
  2528. $this->copySpecificPage($thePageUid,$newPid,$copyTablesArray);
  2529. } else {
  2530. $this->log('pages',$uid,5,0,1,'Something went wrong during copying branch');
  2531. break;
  2532. }
  2533. }
  2534. } // else the page was not copied. Too bad...
  2535. } else {
  2536. $this->log('pages',$uid,5,0,1,'Attempt to copy page without permission to this table');
  2537. }
  2538. }
  2539. /**
  2540. * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
  2541. *
  2542. * @param integer Page uid
  2543. * @param integer Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
  2544. * @param array Table on pages to copy along with the page.
  2545. * @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
  2546. * @return integer The id of the new page, if applicable.
  2547. */
  2548. function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0) {
  2549. global $TCA;
  2550. // Copy the page itself:
  2551. $theNewRootID = $this->copyRecord('pages',$uid,$destPid,$first);
  2552. // If a new page was created upon the copy operation we will proceed with all the tables ON that page:
  2553. if ($theNewRootID) {
  2554. foreach($copyTablesArray as $table) {
  2555. if ($table && is_array($TCA[$table]) && $table!='pages') { // all records under the page is copied.
  2556. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table), '', ($TCA[$table]['ctrl']['sortby'] ? $TCA[$table]['ctrl']['sortby'].' DESC' : ''));
  2557. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  2558. $this->copyRecord($table,$row['uid'], $theNewRootID); // Copying each of the underlying records...
  2559. }
  2560. $GLOBALS['TYPO3_DB']->sql_free_result($mres);
  2561. }
  2562. }
  2563. return $theNewRootID;
  2564. }
  2565. }
  2566. /**
  2567. * Copying records, but makes a "raw" copy of a record.
  2568. * Basically the only thing observed is field processing like the copying of files and correction of ids. All other fields are 1-1 copied.
  2569. * Technically the copy is made with THIS instance of the tcemain class contrary to copyRecord() which creates a new instance and uses the processData() function.
  2570. * The copy is created by insertNewCopyVersion() which bypasses most of the regular input checking associated with processData() - maybe copyRecord() should even do this as well!?
  2571. * This function is used to create new versions of a record.
  2572. * NOTICE: DOES NOT CHECK PERMISSIONS to create! And since page permissions are just passed through and not changed to the user who executes the copy we cannot enforce permissions without getting an incomplete copy - unless we change permissions of course.
  2573. *
  2574. * @param string Element table
  2575. * @param integer Element UID
  2576. * @param integer Element PID (real PID, not checked)
  2577. * @param array Override array - must NOT contain any fields not in the table!
  2578. * @return integer Returns the new ID of the record (if applicable)
  2579. */
  2580. function copyRecord_raw($table,$uid,$pid,$overrideArray=array()) {
  2581. global $TCA;
  2582. $uid = intval($uid);
  2583. // Only copy if the table is defined in TCA, a uid is given and the record wasn't copied before:
  2584. if ($TCA[$table] && $uid && !$this->isRecordCopied($table, $uid)) {
  2585. t3lib_div::loadTCA($table);
  2586. if ($this->doesRecordExist($table,$uid,'show')) {
  2587. // Set up fields which should not be processed. They are still written - just passed through no-questions-asked!
  2588. $nonFields = array('uid','pid','t3ver_id','t3ver_oid','t3ver_wsid','t3ver_label','t3ver_state','t3ver_swapmode','t3ver_count','t3ver_stage','t3ver_tstamp','perms_userid','perms_groupid','perms_user','perms_group','perms_everybody');
  2589. // Select main record:
  2590. $row = $this->recordInfo($table,$uid,'*');
  2591. if (is_array($row)) {
  2592. // Merge in override array.
  2593. $row = array_merge($row,$overrideArray);
  2594. // Traverse ALL fields of the selected record:
  2595. foreach($row as $field => $value) {
  2596. if (!in_array($field,$nonFields)) {
  2597. // Get TCA configuration for the field:
  2598. $conf = $TCA[$table]['columns'][$field]['config'];
  2599. if (is_array($conf)) {
  2600. // Processing based on the TCA config field type (files, references, flexforms...)
  2601. $value = $this->copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$pid);
  2602. }
  2603. // Add value to array.
  2604. $row[$field] = $value;
  2605. }
  2606. }
  2607. // Force versioning related fields:
  2608. $row['pid'] = $pid;
  2609. // Setting original UID:
  2610. if ($TCA[$table]['ctrl']['origUid']) {
  2611. $row[$TCA[$table]['ctrl']['origUid']] = $uid;
  2612. }
  2613. // Do the copy by internal function
  2614. $theNewSQLID = $this->insertNewCopyVersion($table,$row,$pid);
  2615. if ($theNewSQLID) {
  2616. $this->dbAnalysisStoreExec();
  2617. $this->dbAnalysisStore = array();
  2618. $this->copyRecord_fixRTEmagicImages($table,t3lib_BEfunc::wsMapId($table,$theNewSQLID));
  2619. return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
  2620. }
  2621. } else $this->log($table,$uid,3,0,1,'Attempt to rawcopy/versionize record that did not exist!');
  2622. } else $this->log($table,$uid,3,0,1,'Attempt to rawcopy/versionize record without copy permission');
  2623. }
  2624. }
  2625. /**
  2626. * Copies all records from tables in $copyTablesArray from page with $old_pid to page with $new_pid
  2627. * Uses raw-copy for the operation (meant for versioning!)
  2628. *
  2629. * @param integer Current page id.
  2630. * @param integer New page id
  2631. * @param array Array of tables from which to copy
  2632. * @return void
  2633. * @see versionizePages()
  2634. */
  2635. function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray) {
  2636. global $TCA;
  2637. if ($new_pid) {
  2638. foreach($copyTablesArray as $table) {
  2639. if ($table && is_array($TCA[$table]) && $table!='pages') { // all records under the page is copied.
  2640. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($old_pid).$this->deleteClause($table));
  2641. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  2642. // Check, if this record has already been copied by a parent record as relation:
  2643. if (!$this->copyMappingArray[$table][$row['uid']]) {
  2644. // Copying each of the underlying records (method RAW)
  2645. $this->copyRecord_raw($table,$row['uid'],$new_pid);
  2646. }
  2647. }
  2648. $GLOBALS['TYPO3_DB']->sql_free_result($mres);
  2649. }
  2650. }
  2651. }
  2652. }
  2653. /**
  2654. * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
  2655. * Passes the "version" parameter to insertDB() so the copy will look like a new version in the log - should probably be changed or modified a bit for more broad usage...
  2656. *
  2657. * @param string Table name
  2658. * @param array Field array to insert as a record
  2659. * @param integer The value of PID field. -1 is indication that we are creating a new version!
  2660. * @return integer Returns the new ID of the record (if applicable)
  2661. */
  2662. function insertNewCopyVersion($table,$fieldArray,$realPid) {
  2663. global $TCA;
  2664. $id = uniqid('NEW');
  2665. // $fieldArray is set as current record.
  2666. // 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...
  2667. $this->checkValue_currentRecord = $fieldArray;
  2668. // Makes sure that transformations aren't processed on the copy.
  2669. $backupDontProcessTransformations = $this->dontProcessTransformations;
  2670. $this->dontProcessTransformations = TRUE;
  2671. // Traverse record and input-process each value:
  2672. foreach($fieldArray as $field => $fieldValue) {
  2673. if (isset($TCA[$table]['columns'][$field])) {
  2674. // Evaluating the value.
  2675. $res = $this->checkValue($table,$field,$fieldValue,$id,'new',$realPid,0);
  2676. if (isset($res['value'])) {
  2677. $fieldArray[$field] = $res['value'];
  2678. }
  2679. }
  2680. }
  2681. // System fields being set:
  2682. if ($TCA[$table]['ctrl']['crdate']) {
  2683. $fieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
  2684. }
  2685. if ($TCA[$table]['ctrl']['cruser_id']) {
  2686. $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
  2687. }
  2688. if ($TCA[$table]['ctrl']['tstamp']) {
  2689. $fieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  2690. }
  2691. // Finally, insert record:
  2692. $this->insertDB($table,$id,$fieldArray, TRUE);
  2693. // Process the remap stack in case we dealed with relations:
  2694. $this->processRemapStack();
  2695. // Resets dontProcessTransformations to the previous state.
  2696. $this->dontProcessTransformations = $backupDontProcessTransformations;
  2697. // Return new id:
  2698. return $this->substNEWwithIDs[$id];
  2699. }
  2700. /**
  2701. * Processing/Preparing content for copyRecord() function
  2702. *
  2703. * @param string Table name
  2704. * @param integer Record uid
  2705. * @param string Field name being processed
  2706. * @param string Input value to be processed.
  2707. * @param array Record array
  2708. * @param array TCA field configuration
  2709. * @param integer Real page id (pid) the record is copied to
  2710. * @param integer Language ID (from sys_language table) used in the duplicated record
  2711. * @return mixed Processed value. Normally a string/integer, but can be an array for flexforms!
  2712. * @access private
  2713. * @see copyRecord()
  2714. */
  2715. function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language=0) {
  2716. global $TCA;
  2717. // Process references and files, currently that means only the files, prepending absolute paths (so the TCEmain engine will detect the file as new and one that should be made into a copy)
  2718. $value = $this->copyRecord_procFilesRefs($conf, $uid, $value);
  2719. $inlineSubType = $this->getInlineFieldType($conf);
  2720. // Register if there are references to take care of or MM is used on an inline field (no change to value):
  2721. if ($this->isReferenceField($conf) || $inlineSubType == 'mm') {
  2722. $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
  2723. $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
  2724. $localizeReferences = (isset($conf['foreign_table']) && t3lib_BEfunc::isTableLocalizable($conf['foreign_table']) && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization']);
  2725. if ($conf['MM'] || $language>0 && $localizeReferences) {
  2726. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  2727. /* @var $dbAnalysis t3lib_loadDBGroup */
  2728. $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
  2729. if (!$conf['MM']) {
  2730. // Localize referenced records of select fields:
  2731. foreach ($dbAnalysis->itemArray as $index => $item) {
  2732. // Since select fields can reference many records, check whether there's already a localization:
  2733. $recordLocalization = t3lib_BEfunc::getRecordLocalization($item['table'], $item['id'], $language);
  2734. if (!$recordLocalization) {
  2735. $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], $language);
  2736. } else {
  2737. $dbAnalysis->itemArray[$index]['id'] = $recordLocalization[0]['uid'];
  2738. }
  2739. }
  2740. }
  2741. $value = implode(',',$dbAnalysis->getValueArray($prependName));
  2742. }
  2743. if ($value) { // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
  2744. $this->registerDBList[$table][$uid][$field] = $value;
  2745. }
  2746. // If another inline subtype is used (comma-separated-values or the foreign_field property):
  2747. } elseif ($inlineSubType !== false) {
  2748. // Get the localization mode for the current (parent) record (keep|select|all):
  2749. $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $field);
  2750. // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
  2751. if ($language>0 && $localizationMode=='keep') {
  2752. $value = ($inlineSubType=='field' ? 0 : '');
  2753. // Execute copy or localization actions:
  2754. } else {
  2755. /*
  2756. * Fetch the related child records by using t3lib_loadDBGroup:
  2757. * @var $dbAnalysis t3lib_loadDBGroup
  2758. */
  2759. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  2760. $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
  2761. // Walk through the items, copy them and remember the new id:
  2762. foreach ($dbAnalysis->itemArray as $k => $v) {
  2763. // If language is set and differs from original record, this isn't a copy action but a localization of our parent/ancestor:
  2764. if ($language > 0 && t3lib_BEfunc::isTableLocalizable($table) && $language != $row[$TCA[$table]['ctrl']['languageField']]) {
  2765. // If children should be localized when the parent gets localized the first time, just do it:
  2766. if ($localizationMode!=false && isset($conf['behaviour']['localizeChildrenAtParentLocalization']) && $conf['behaviour']['localizeChildrenAtParentLocalization']) {
  2767. $newId = $this->localize($v['table'], $v['id'], $language);
  2768. }
  2769. // If no language it set, this is a regular copy action:
  2770. } else {
  2771. if (!t3lib_div::testInt($realDestPid)) {
  2772. $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
  2773. } elseif ($realDestPid == -1) {
  2774. $newId = $this->versionizeRecord($v['table'], $v['id'], 'Auto-created for WS #'.$this->BE_USER->workspace);
  2775. } else {
  2776. $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid);
  2777. }
  2778. }
  2779. // If the current field is set on a page record, update the pid of related child records:
  2780. if ($table == 'pages') {
  2781. $this->registerDBPids[$v['table']][$v['id']] = $uid;
  2782. // If the current field has ancestors that have a field on a page record, update the pid of related child records:
  2783. } elseif (isset($this->registerDBPids[$table][$uid])) {
  2784. $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
  2785. }
  2786. $dbAnalysis->itemArray[$k]['id'] = $newId;
  2787. }
  2788. // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
  2789. $value = implode(',',$dbAnalysis->getValueArray());
  2790. $this->registerDBList[$table][$uid][$field] = $value;
  2791. }
  2792. }
  2793. // For "flex" fieldtypes we need to traverse the structure for two reasons: If there are file references they have to be prepended with absolute paths and if there are database reference they MIGHT need to be remapped (still done in remapListedDBRecords())
  2794. if ($conf['type']=='flex') {
  2795. // Get current value array:
  2796. $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table);
  2797. $currentValueArray = t3lib_div::xml2array($value);
  2798. // Traversing the XML structure, processing files:
  2799. if (is_array($currentValueArray)) {
  2800. $currentValueArray['data'] = $this->checkValue_flex_procInData(
  2801. $currentValueArray['data'],
  2802. array(), // Not used.
  2803. array(), // Not used.
  2804. $dataStructArray,
  2805. array($table, $uid, $field, $realDestPid), // Parameters.
  2806. 'copyRecord_flexFormCallBack'
  2807. );
  2808. $value = $currentValueArray; // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
  2809. }
  2810. }
  2811. return $value;
  2812. }
  2813. /**
  2814. * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
  2815. *
  2816. * @param array Array of parameters in num-indexes: table, uid, field
  2817. * @param array TCA field configuration (from Data Structure XML)
  2818. * @param string The value of the flexForm field
  2819. * @param string Not used.
  2820. * @param string Not used.
  2821. * @return array Result array with key "value" containing the value of the processing.
  2822. * @see copyRecord(), checkValue_flex_procInData_travDS()
  2823. */
  2824. function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2) {
  2825. // Extract parameters:
  2826. list($table, $uid, $field, $realDestPid) = $pParams;
  2827. // Process references and files, currently that means only the files, prepending absolute paths:
  2828. $dataValue = $this->copyRecord_procFilesRefs($dsConf, $uid, $dataValue);
  2829. // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
  2830. if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
  2831. $dataValue = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $dataValue, array(), $dsConf, $realDestPid);
  2832. $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
  2833. }
  2834. // Return
  2835. return array('value' => $dataValue);
  2836. }
  2837. /**
  2838. * Modifying a field value for any situation regarding files/references:
  2839. * For attached files: take current filenames and prepend absolute paths so they get copied.
  2840. * For DB references: Nothing done.
  2841. *
  2842. * @param array TCE field config
  2843. * @param integer Record UID
  2844. * @param string Field value (eg. list of files)
  2845. * @return string The (possibly modified) value
  2846. * @see copyRecord(), copyRecord_flexFormCallBack()
  2847. */
  2848. function copyRecord_procFilesRefs($conf, $uid, $value) {
  2849. // Prepend absolute paths to files:
  2850. if ($conf['type'] == 'group' && ($conf['internal_type'] == 'file' || $conf['internal_type'] == 'file_reference')) {
  2851. // Get an array with files as values:
  2852. if ($conf['MM']) {
  2853. $theFileValues = array();
  2854. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  2855. /* @var $dbAnalysis t3lib_loadDBGroup */
  2856. $dbAnalysis->start('', 'files', $conf['MM'], $uid);
  2857. foreach($dbAnalysis->itemArray as $somekey => $someval) {
  2858. if ($someval['id']) {
  2859. $theFileValues[] = $someval['id'];
  2860. }
  2861. }
  2862. } else {
  2863. $theFileValues = t3lib_div::trimExplode(',',$value,1);
  2864. }
  2865. // Traverse this array of files:
  2866. $uploadFolder = $conf['internal_type'] == 'file' ? $conf['uploadfolder'] : '';
  2867. $dest = $this->destPathFromUploadFolder($uploadFolder);
  2868. $newValue = array();
  2869. foreach($theFileValues as $file) {
  2870. if (trim($file)) {
  2871. $realFile = str_replace('//', '/', $dest . '/' . trim($file));
  2872. if (@is_file($realFile)) {
  2873. $newValue[] = $realFile;
  2874. }
  2875. }
  2876. }
  2877. // Implode the new filelist into the new value (all files have absolute paths now which means they will get copied when entering TCEmain as new values...)
  2878. $value = implode(',',$newValue);
  2879. }
  2880. // Return the new value:
  2881. return $value;
  2882. }
  2883. /**
  2884. * Copies any "RTEmagic" image files found in record with table/id to new names.
  2885. * Usage: After copying a record this function should be called to search for "RTEmagic"-images inside the record. If such are found they should be duplicated to new names so all records have a 1-1 relation to them.
  2886. * Reason for copying RTEmagic files: a) if you remove an RTEmagic image from a record it will remove the file - any other record using it will have a lost reference! b) RTEmagic images keeps an original and a copy. The copy always is re-calculated to have the correct physical measures as the HTML tag inserting it defines. This is calculated from the original. Two records using the same image could have difference HTML-width/heights for the image and the copy could only comply with one of them. If you don't want a 1-1 relation you should NOT use RTEmagic files but just insert it as a normal file reference to a file inside fileadmin/ folder
  2887. *
  2888. * @param string Table name
  2889. * @param integer Record UID
  2890. * @return void
  2891. */
  2892. function copyRecord_fixRTEmagicImages($table,$theNewSQLID) {
  2893. global $TYPO3_DB;
  2894. // Creating fileFunc object.
  2895. if (!$this->fileFunc) {
  2896. $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
  2897. $this->include_filefunctions=1;
  2898. }
  2899. // Select all RTEmagic files in the reference table from the table/ID
  2900. /* @var $TYPO3_DB t3lib_DB */
  2901. $recs = $TYPO3_DB->exec_SELECTgetRows(
  2902. '*',
  2903. 'sys_refindex',
  2904. 'ref_table='.$TYPO3_DB->fullQuoteStr('_FILE', 'sys_refindex').
  2905. ' AND ref_string LIKE '.$TYPO3_DB->fullQuoteStr('%/RTEmagic%', 'sys_refindex').
  2906. ' AND softref_key='.$TYPO3_DB->fullQuoteStr('images', 'sys_refindex').
  2907. ' AND tablename='.$TYPO3_DB->fullQuoteStr($table, 'sys_refindex').
  2908. ' AND recuid='.intval($theNewSQLID),
  2909. '',
  2910. 'sorting DESC'
  2911. );
  2912. // Traverse the files found and copy them:
  2913. if (is_array($recs)) {
  2914. foreach($recs as $rec) {
  2915. $filename = basename($rec['ref_string']);
  2916. $fileInfo = array();
  2917. if (t3lib_div::isFirstPartOfStr($filename,'RTEmagicC_')) {
  2918. $fileInfo['exists'] = @is_file(PATH_site.$rec['ref_string']);
  2919. $fileInfo['original'] = substr($rec['ref_string'],0,-strlen($filename)).'RTEmagicP_'.preg_replace('/\.[[:alnum:]]+$/','',substr($filename,10));
  2920. $fileInfo['original_exists'] = @is_file(PATH_site.$fileInfo['original']);
  2921. // CODE from tx_impexp and class.rte_images.php adapted for use here:
  2922. if ($fileInfo['exists'] && $fileInfo['original_exists']) {
  2923. // Initialize; Get directory prefix for file and set the original name:
  2924. $dirPrefix = dirname($rec['ref_string']).'/';
  2925. $rteOrigName = basename($fileInfo['original']);
  2926. // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
  2927. if ($rteOrigName && t3lib_div::isFirstPartOfStr($dirPrefix,'uploads/') && @is_dir(PATH_site.$dirPrefix)) { // RTE:
  2928. // From the "original" RTE filename, produce a new "original" destination filename which is unused.
  2929. $origDestName = $this->fileFunc->getUniqueName($rteOrigName, PATH_site.$dirPrefix);
  2930. // Create copy file name:
  2931. $pI = pathinfo($rec['ref_string']);
  2932. $copyDestName = dirname($origDestName).'/RTEmagicC_'.substr(basename($origDestName),10).'.'.$pI['extension'];
  2933. if (!@is_file($copyDestName) && !@is_file($origDestName)
  2934. && $origDestName===t3lib_div::getFileAbsFileName($origDestName) && $copyDestName===t3lib_div::getFileAbsFileName($copyDestName)) {
  2935. // Making copies:
  2936. t3lib_div::upload_copy_move(PATH_site.$fileInfo['original'],$origDestName);
  2937. t3lib_div::upload_copy_move(PATH_site.$rec['ref_string'],$copyDestName);
  2938. clearstatcache();
  2939. // Register this:
  2940. $this->RTEmagic_copyIndex[$rec['tablename']][$rec['recuid']][$rec['field']][$rec['ref_string']] = substr($copyDestName,strlen(PATH_site));
  2941. // Check and update the record using the t3lib_refindex class:
  2942. if (@is_file($copyDestName)) {
  2943. $sysRefObj = t3lib_div::makeInstance('t3lib_refindex');
  2944. $error = $sysRefObj->setReferenceValue($rec['hash'],substr($copyDestName,strlen(PATH_site)),FALSE,TRUE);
  2945. if ($error) {
  2946. echo $this->newlog('t3lib_refindex::setReferenceValue(): '.$error,1);
  2947. }
  2948. } else $this->newlog('File "'.$copyDestName.'" was not created!',1);
  2949. } else $this->newlog('Could not construct new unique names for file!',1);
  2950. } else $this->newlog('Maybe directory of file was not within "uploads/"?',1);
  2951. } else $this->newlog('Trying to copy RTEmagic files ('.$rec['ref_string'].' / '.$fileInfo['original'].') but one or both were missing',1);
  2952. }
  2953. }
  2954. }
  2955. }
  2956. /**
  2957. * Find l10n-overlay records and perform the requested move action for these records.
  2958. *
  2959. * @param string $table: Record Table
  2960. * @param string $uid: Record UID
  2961. * @param string $destPid: Position to move to
  2962. * @return void
  2963. */
  2964. function copyL10nOverlayRecords($table, $uid, $destPid, $first=0, $overrideValues=array(), $excludeFields='') {
  2965. //there's no need to perform this for page-records
  2966. if (!t3lib_BEfunc::isTableLocalizable($table) || !empty($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) || !empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
  2967. return;
  2968. }
  2969. $where = '';
  2970. if (isset($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
  2971. $where = ' AND t3ver_oid=0';
  2972. }
  2973. $l10nRecords = t3lib_BEfunc::getRecordsByField($table, $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'], $uid, $where);
  2974. if (is_array($l10nRecords)) {
  2975. foreach ($l10nRecords as $record) {
  2976. $this->copyRecord($table, $record['uid'], $destPid, $first, $overrideValues, $excludeFields, $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
  2977. }
  2978. }
  2979. }
  2980. /*********************************************
  2981. *
  2982. * Cmd: Moving, Localizing
  2983. *
  2984. ********************************************/
  2985. /**
  2986. * Moving single records
  2987. *
  2988. * @param string Table name to move
  2989. * @param integer Record uid to move
  2990. * @param integer Position to move to: $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
  2991. * @return void
  2992. */
  2993. function moveRecord($table,$uid,$destPid) {
  2994. global $TCA;
  2995. if ($TCA[$table]) {
  2996. // 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)
  2997. if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$uid,'uid')) {
  2998. $uid = $lookForLiveVersion['uid'];
  2999. }
  3000. // Initialize:
  3001. $destPid = intval($destPid);
  3002. $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
  3003. $moveRec = $this->getRecordProperties($table,$uid,TRUE);
  3004. $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving to destination
  3005. // Finding out, if the record may be moved from where it is. If the record is a non-page, then it depends on edit-permissions.
  3006. // If the record is a page, then there are two options: If the page is moved within itself, (same pid) it's edit-perms of the pid. If moved to another place then its both delete-perms of the pid and new-page perms on the destination.
  3007. if ($table!='pages' || $resolvedPid==$moveRec['pid']) {
  3008. $mayMoveAccess = $this->checkRecordUpdateAccess($table,$uid); // Edit rights for the record...
  3009. } else {
  3010. $mayMoveAccess = $this->doesRecordExist($table,$uid,'delete');
  3011. }
  3012. // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new), unless the pages are moved on the same pid, then edit-rights are checked
  3013. if ($table!='pages' || $resolvedPid!=$moveRec['pid']) {
  3014. $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4); // Insert rights for the record...
  3015. } else {
  3016. $mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
  3017. }
  3018. // Checking if there is anything else disallowing moving the record by checking if editing is allowed
  3019. $fullLanguageCheckNeeded = ($table != 'pages');
  3020. $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, false, false, $fullLanguageCheckNeeded);
  3021. // If moving is allowed, begin the processing:
  3022. if ($mayEditAccess) {
  3023. if ($mayMoveAccess) {
  3024. if ($mayInsertAccess) {
  3025. if ($this->BE_USER->workspace!==0) { // Draft workspace...:
  3026. // Get workspace version of the source record, if any:
  3027. $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
  3028. // If no version exists and versioningWS is in version 2, a new placeholder is made automatically:
  3029. if (!$WSversion['uid'] && (int)$TCA[$table]['ctrl']['versioningWS']>=2 && (int)$moveRec['t3ver_state']!=3) {
  3030. $this->versionizeRecord($table,$uid,'Placeholder version for moving record');
  3031. $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid'); // Will not create new versions in live workspace though...
  3032. }
  3033. // Check workspace permissions:
  3034. $workspaceAccessBlocked = array();
  3035. $recIsNewVersion = (int)$moveRec['t3ver_state']>0; // Element was in "New/Deleted/Moved" so it can be moved...
  3036. $destRes = $this->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid,$table);
  3037. $canMoveRecord = $recIsNewVersion || (int)$TCA[$table]['ctrl']['versioningWS']>=2;
  3038. // Workspace source check:
  3039. if (!$recIsNewVersion) {
  3040. if ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid)) {
  3041. $workspaceAccessBlocked['src1']='Record could not be edited in workspace: '.$errorCode.' ';
  3042. } else {
  3043. if (!$canMoveRecord && $this->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'],$table)<=0) {
  3044. $workspaceAccessBlocked['src2']='Could not remove record from table "'.$table.'" from its page "'.$moveRec['pid'].'" ';
  3045. }
  3046. }
  3047. }
  3048. // Workspace destination check:
  3049. if (!($destRes>0 || ($canMoveRecord && !$destRes))) { // All records can be inserted if $destRes is greater than zero. Only new versions can be inserted if $destRes is false. NO RECORDS can be inserted if $destRes is negative which indicates a stage not allowed for use. If "versioningWS" is version 2, moving can take place of versions.
  3050. $workspaceAccessBlocked['dest1']='Could not insert record from table "'.$table.'" in destination PID "'.$resolvedPid.'" ';
  3051. } elseif ($destRes==1 && $WSversion['uid']) {
  3052. $workspaceAccessBlocked['dest2']='Could not insert other versions in destination PID ';
  3053. }
  3054. if (!count($workspaceAccessBlocked)) {
  3055. if ($WSversion['uid'] && !$recIsNewVersion && (int)$TCA[$table]['ctrl']['versioningWS']>=2) { // If the move operation is done on a versioned record, which is NOT new/deletd placeholder and versioningWS is in version 2, then...
  3056. $this->moveRecord_wsPlaceholders($table,$uid,$destPid,$WSversion['uid']);
  3057. } else {
  3058. $this->moveRecord_raw($table,$uid,$destPid);
  3059. }
  3060. } else {
  3061. $this->newlog("Move attempt failed due to workspace restrictions: ".implode(' // ',$workspaceAccessBlocked),1);
  3062. }
  3063. } else { // Live workspace - move it!
  3064. $this->moveRecord_raw($table,$uid,$destPid);
  3065. }
  3066. } else {
  3067. $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to insert.",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
  3068. }
  3069. } else {
  3070. $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so.",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
  3071. }
  3072. } else {
  3073. $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so. [".$this->BE_USER->errorMsg."]",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
  3074. }
  3075. }
  3076. }
  3077. /**
  3078. * Creates a move placeholder for workspaces.
  3079. * USE ONLY INTERNALLY
  3080. * Moving placeholder: Can be done because the system sees it as a placeholder for NEW elements like t3ver_state=1
  3081. * Moving original: Will either create the placeholder if it doesn't exist or move existing placeholder in workspace.
  3082. *
  3083. * @param string Table name to move
  3084. * @param integer Record uid to move (online record)
  3085. * @param integer Position to move to: $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
  3086. * @param integer UID of offline version of online record
  3087. * @return void
  3088. * @see moveRecord()
  3089. */
  3090. function moveRecord_wsPlaceholders($table,$uid,$destPid,$wsUid) {
  3091. global $TCA;
  3092. if ($plh = t3lib_BEfunc::getMovePlaceholder($table,$uid,'uid')) {
  3093. // If already a placeholder exists, move it:
  3094. $this->moveRecord_raw($table,$plh['uid'],$destPid);
  3095. } else {
  3096. // First, we create a placeholder record in the Live workspace that represents the position to where the record is eventually moved to.
  3097. $newVersion_placeholderFieldArray = array();
  3098. if ($TCA[$table]['ctrl']['crdate']) {
  3099. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
  3100. }
  3101. if ($TCA[$table]['ctrl']['cruser_id']) {
  3102. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['cruser_id']] = $this->userid;
  3103. }
  3104. if ($TCA[$table]['ctrl']['tstamp'] && count($fieldArray)) {
  3105. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  3106. }
  3107. if ($table == 'pages') {
  3108. // Copy page access settings from original page to placeholder
  3109. $perms_clause = $this->BE_USER->getPagePermsClause(1);
  3110. $access = t3lib_BEfunc::readPageAccess($uid, $perms_clause);
  3111. $newVersion_placeholderFieldArray['perms_userid'] = $access['perms_userid'];
  3112. $newVersion_placeholderFieldArray['perms_groupid'] = $access['perms_groupid'];
  3113. $newVersion_placeholderFieldArray['perms_user'] = $access['perms_user'];
  3114. $newVersion_placeholderFieldArray['perms_group'] = $access['perms_group'];
  3115. $newVersion_placeholderFieldArray['perms_everybody'] = $access['perms_everybody'];
  3116. }
  3117. $newVersion_placeholderFieldArray['t3ver_label'] = 'MOVE-TO PLACEHOLDER for #'.$uid;
  3118. $newVersion_placeholderFieldArray['t3ver_move_id'] = $uid;
  3119. $newVersion_placeholderFieldArray['t3ver_state'] = 3; // Setting placeholder state value for temporary record
  3120. $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace; // Setting workspace - only so display of place holders can filter out those from other workspaces.
  3121. $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['label']] = '[MOVE-TO PLACEHOLDER for #'.$uid.', WS#'.$this->BE_USER->workspace.']';
  3122. // moving localized records requires to keep localization-settings for the placeholder too
  3123. if (array_key_exists('languageField', $GLOBALS['TCA'][$table]['ctrl']) && array_key_exists('transOrigPointerField', $GLOBALS['TCA'][$table]['ctrl'])) {
  3124. $l10nParentRec = t3lib_BEfunc::getRecord($table, $uid);
  3125. $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
  3126. $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
  3127. unset($l10nParentRec);
  3128. }
  3129. $newVersion_placeholderFieldArray['pid'] = 0; // Initially, create at root level.
  3130. $id = 'NEW_MOVE_PLH';
  3131. $this->insertDB($table,$id,$newVersion_placeholderFieldArray,FALSE); // Saving placeholder as 'original'
  3132. // Move the new placeholder from temporary root-level to location:
  3133. $this->moveRecord_raw($table,$this->substNEWwithIDs[$id],$destPid);
  3134. // Move the workspace-version of the original to be the version of the move-to-placeholder:
  3135. $updateFields = array();
  3136. $updateFields['t3ver_state'] = 4; // Setting placeholder state value for version (so it can know it is currently a new version...)
  3137. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($wsUid), $updateFields);
  3138. }
  3139. //check for the localizations of that element and move them as well
  3140. $this->moveL10nOverlayRecords($table, $uid, $destPid);
  3141. }
  3142. /**
  3143. * Moves a record without checking security of any sort.
  3144. * USE ONLY INTERNALLY
  3145. *
  3146. * @param string Table name to move
  3147. * @param integer Record uid to move
  3148. * @param integer Position to move to: $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
  3149. * @return void
  3150. * @see moveRecord()
  3151. */
  3152. function moveRecord_raw($table,$uid,$destPid) {
  3153. global $TCA, $TYPO3_CONF_VARS;
  3154. $sortRow = $TCA[$table]['ctrl']['sortby'];
  3155. $origDestPid = $destPid;
  3156. $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving to destination
  3157. // Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid. Basically this check make the error message 4-13 meaning less... But you can always remove this check if you prefer the error instead of a no-good action (which is to move the record to its own page...)
  3158. if (($destPid<0 && !$sortRow) || $destPid>=0) { // $destPid>=0 because we must correct pid in case of versioning "page" types.
  3159. $destPid = $resolvedPid;
  3160. }
  3161. $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
  3162. $moveRec = $this->getRecordProperties($table,$uid,TRUE);
  3163. // Prepare user defined objects (if any) for hooks which extend this function:
  3164. $hookObjectsArr = array();
  3165. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'])) {
  3166. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] as $classRef) {
  3167. $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
  3168. }
  3169. }
  3170. // Timestamp field:
  3171. $updateFields = array();
  3172. if ($TCA[$table]['ctrl']['tstamp']) {
  3173. $updateFields[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  3174. }
  3175. if ($destPid>=0) { // insert as first element on page (where uid = $destPid)
  3176. if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid)) {
  3177. $this->clear_cache($table,$uid); // clear cache before moving
  3178. $updateFields['pid'] = $destPid; // Setting PID
  3179. // table is sorted by 'sortby'
  3180. if ($sortRow) {
  3181. $sortNumber = $this->getSortNumber($table,$uid,$destPid);
  3182. $updateFields[$sortRow] = $sortNumber;
  3183. }
  3184. // check for child records that have also to be moved
  3185. $this->moveRecord_procFields($table,$uid,$destPid);
  3186. // Create query for update:
  3187. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
  3188. // check for the localizations of that element
  3189. $this->moveL10nOverlayRecords($table, $uid, $destPid);
  3190. // Call post processing hooks:
  3191. foreach($hookObjectsArr as $hookObj) {
  3192. if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
  3193. $hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
  3194. }
  3195. }
  3196. // Logging...
  3197. $newPropArr = $this->getRecordProperties($table,$uid);
  3198. $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
  3199. $newpagePropArr = $this->getRecordProperties('pages',$destPid);
  3200. if ($destPid!=$propArr['pid']) {
  3201. $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
  3202. $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
  3203. } else {
  3204. $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
  3205. }
  3206. $this->clear_cache($table,$uid); // clear cache after moving
  3207. $this->fixUniqueInPid($table,$uid);
  3208. // fixCopyAfterDuplFields
  3209. if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);} // origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
  3210. } else {
  3211. $destPropArr = $this->getRecordProperties('pages',$destPid);
  3212. $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
  3213. }
  3214. } else { // Put after another record
  3215. if ($sortRow) { // table is being sorted
  3216. $sortInfo = $this->getSortNumber($table,$uid,$destPid);
  3217. $destPid = $sortInfo['pid']; // Setting the destPid to the new pid of the record.
  3218. if (is_array($sortInfo)) { // If not an array, there was an error (which is already logged)
  3219. if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid)) {
  3220. $this->clear_cache($table,$uid); // clear cache before moving
  3221. // We now update the pid and sortnumber
  3222. $updateFields['pid'] = $destPid;
  3223. $updateFields[$sortRow] = $sortInfo['sortNumber'];
  3224. // check for child records that have also to be moved
  3225. $this->moveRecord_procFields($table,$uid,$destPid);
  3226. // Create query for update:
  3227. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
  3228. // check for the localizations of that element
  3229. $this->moveL10nOverlayRecords($table, $uid, $destPid);
  3230. // Call post processing hooks:
  3231. foreach($hookObjectsArr as $hookObj) {
  3232. if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
  3233. $hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
  3234. }
  3235. }
  3236. // Logging...
  3237. $newPropArr = $this->getRecordProperties($table,$uid);
  3238. $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
  3239. if ($destPid!=$propArr['pid']) {
  3240. $newpagePropArr = $this->getRecordProperties('pages',$destPid);
  3241. $this->log($table,$uid,4,0,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
  3242. $this->log($table,$uid,4,0,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
  3243. } else {
  3244. $this->log($table,$uid,4,0,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
  3245. }
  3246. // clear cache after moving
  3247. $this->clear_cache($table,$uid);
  3248. // fixUniqueInPid
  3249. $this->fixUniqueInPid($table,$uid);
  3250. // fixCopyAfterDuplFields
  3251. if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
  3252. } else {
  3253. $destPropArr = $this->getRecordProperties('pages',$destPid);
  3254. $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
  3255. }
  3256. }
  3257. } else {
  3258. $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after another record, although the table has no sorting row.",13,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
  3259. }
  3260. }
  3261. }
  3262. /**
  3263. * Walk through all fields of the moved record and look for children of e.g. the inline type.
  3264. * If child records are found, they are also move to the new $destPid.
  3265. *
  3266. * @param string $table: Record Table
  3267. * @param string $uid: Record UID
  3268. * @param string $destPid: Position to move to
  3269. * @return void
  3270. */
  3271. function moveRecord_procFields($table,$uid,$destPid) {
  3272. t3lib_div::loadTCA($table);
  3273. $conf = $GLOBALS['TCA'][$table]['columns'];
  3274. $row = t3lib_BEfunc::getRecordWSOL($table,$uid);
  3275. if (is_array($row)) {
  3276. foreach ($row as $field => $value) {
  3277. $this->moveRecord_procBasedOnFieldType($table,$uid,$destPid,$field,$value,$conf[$field]['config']);
  3278. }
  3279. }
  3280. }
  3281. /**
  3282. * Move child records depending on the field type of the parent record.
  3283. *
  3284. * @param string $table: Record Table
  3285. * @param string $uid: Record UID
  3286. * @param string $destPid: Position to move to
  3287. * @param string $field: Record field
  3288. * @param string $value: Record field value
  3289. * @param array $conf: TCA configuration of current field
  3290. * @return void
  3291. */
  3292. function moveRecord_procBasedOnFieldType($table, $uid, $destPid, $field, $value, $conf) {
  3293. $moveTable = '';
  3294. $moveIds = array();
  3295. if ($conf['type'] == 'inline') {
  3296. $foreign_table = $conf['foreign_table'];
  3297. $moveChildrenWithParent = (!isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent']);
  3298. if ($foreign_table && $moveChildrenWithParent) {
  3299. $inlineType = $this->getInlineFieldType($conf);
  3300. if ($inlineType == 'list' || $inlineType == 'field') {
  3301. $moveTable = $foreign_table;
  3302. if ($table == 'pages') {
  3303. // If the inline elements are related to a page record,
  3304. // make sure they reside at that page and not at its parent
  3305. $destPid = $uid;
  3306. }
  3307. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  3308. $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
  3309. }
  3310. }
  3311. }
  3312. // Move the records
  3313. if (isset($dbAnalysis)) {
  3314. // Moving records to a positive destination will insert each
  3315. // record at the beginning, thus the order is reversed here:
  3316. foreach (array_reverse($dbAnalysis->itemArray) as $v) {
  3317. $this->moveRecord($v['table'], $v['id'], $destPid);
  3318. }
  3319. }
  3320. }
  3321. /**
  3322. * Find l10n-overlay records and perform the requested move action for these records.
  3323. *
  3324. * @param string $table: Record Table
  3325. * @param string $uid: Record UID
  3326. * @param string $destPid: Position to move to
  3327. * @return void
  3328. */
  3329. function moveL10nOverlayRecords($table, $uid, $destPid) {
  3330. //there's no need to perform this for page-records or not localizeable tables
  3331. if (!t3lib_BEfunc::isTableLocalizable($table) || !empty($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) || !empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
  3332. return;
  3333. }
  3334. $where = '';
  3335. if (isset($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
  3336. $where = ' AND t3ver_oid=0';
  3337. }
  3338. $l10nRecords = t3lib_BEfunc::getRecordsByField($table, $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'], $uid, $where);
  3339. if (is_array($l10nRecords)) {
  3340. foreach ($l10nRecords as $record) {
  3341. $this->moveRecord($table, $record['uid'], $destPid);
  3342. }
  3343. }
  3344. }
  3345. /**
  3346. * Localizes a record to another system language
  3347. * In reality it only works if transOrigPointerTable is not set. For "pages" the implementation is hardcoded
  3348. *
  3349. * @param string Table name
  3350. * @param integer Record uid (to be localized)
  3351. * @param integer Language ID (from sys_language table)
  3352. * @return mixed The uid (integer) of the new translated record or false (boolean) if something went wrong
  3353. */
  3354. function localize($table, $uid, $language) {
  3355. global $TCA;
  3356. $newId = false;
  3357. $uid = intval($uid);
  3358. if ($TCA[$table] && $uid) {
  3359. t3lib_div::loadTCA($table);
  3360. if (($TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField'] && !$TCA[$table]['ctrl']['transOrigPointerTable']) || $table==='pages') {
  3361. if ($langRec = t3lib_BEfunc::getRecord('sys_language',intval($language),'uid,title')) {
  3362. if ($this->doesRecordExist($table,$uid,'show')) {
  3363. $row = t3lib_BEfunc::getRecordWSOL($table,$uid); // Getting workspace overlay if possible - this will localize versions in workspace if any
  3364. if (is_array($row)) {
  3365. if ($row[$TCA[$table]['ctrl']['languageField']] <= 0 || $table==='pages') {
  3366. if ($row[$TCA[$table]['ctrl']['transOrigPointerField']] == 0 || $table==='pages') {
  3367. if ($table==='pages') {
  3368. $pass = $TCA[$table]['ctrl']['transForeignTable']==='pages_language_overlay' && !t3lib_BEfunc::getRecordsByField('pages_language_overlay','pid',$uid,' AND '.$TCA['pages_language_overlay']['ctrl']['languageField'].'='.intval($langRec['uid']));
  3369. $Ttable = 'pages_language_overlay';
  3370. t3lib_div::loadTCA($Ttable);
  3371. } else {
  3372. $pass = !t3lib_BEfunc::getRecordLocalization($table, $uid, $langRec['uid'], 'AND pid='.intval($row['pid']));
  3373. $Ttable = $table;
  3374. }
  3375. if ($pass) {
  3376. // Initialize:
  3377. $overrideValues = array();
  3378. $excludeFields = array();
  3379. // Set override values:
  3380. $overrideValues[$TCA[$Ttable]['ctrl']['languageField']] = $langRec['uid'];
  3381. $overrideValues[$TCA[$Ttable]['ctrl']['transOrigPointerField']] = $uid;
  3382. // Set exclude Fields:
  3383. foreach($TCA[$Ttable]['columns'] as $fN => $fCfg) {
  3384. if ($fCfg['l10n_mode']=='prefixLangTitle') { // Check if we are just prefixing:
  3385. if (($fCfg['config']['type']=='text' || $fCfg['config']['type']=='input') && strlen($row[$fN])) {
  3386. list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
  3387. $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
  3388. if (isset($TSConfig['translateToMessage']) && strlen($TSConfig['translateToMessage'])) {
  3389. $translateToMsg = @sprintf($TSConfig['translateToMessage'], $langRec['title']);
  3390. }
  3391. if (!strlen($translateToMsg)) {
  3392. $translateToMsg = 'Translate to '.$langRec['title'].':';
  3393. }
  3394. $overrideValues[$fN] = '['.$translateToMsg.'] '.$row[$fN];
  3395. }
  3396. } elseif (t3lib_div::inList('exclude,noCopy,mergeIfNotBlank',$fCfg['l10n_mode']) && $fN!=$TCA[$Ttable]['ctrl']['languageField'] && $fN!=$TCA[$Ttable]['ctrl']['transOrigPointerField']) { // Otherwise, do not copy field (unless it is the language field or pointer to the original language)
  3397. $excludeFields[] = $fN;
  3398. }
  3399. }
  3400. if ($Ttable === $table) {
  3401. // Execute the copy:
  3402. $newId = $this->copyRecord($table, $uid, -$uid, 1, $overrideValues, implode(',', $excludeFields), $language);
  3403. } else {
  3404. // Create new record:
  3405. $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
  3406. /* @var $copyTCE t3lib_TCEmain */
  3407. $copyTCE->stripslashes_values = 0;
  3408. $copyTCE->cachedTSconfig = $this->cachedTSconfig; // Copy forth the cached TSconfig
  3409. $copyTCE->dontProcessTransformations=1; // Transformations should NOT be carried out during copy
  3410. $copyTCE->start(array($Ttable=>array('NEW'=>$overrideValues)),'',$this->BE_USER);
  3411. $copyTCE->process_datamap();
  3412. // Getting the new UID as if it had been copied:
  3413. $theNewSQLID = $copyTCE->substNEWwithIDs['NEW'];
  3414. if ($theNewSQLID) {
  3415. // If is by design that $Ttable is used and not $table! See "l10nmgr" extension. Could be debated, but this is what I chose for this "pseudo case"
  3416. $this->copyMappingArray[$Ttable][$uid] = $theNewSQLID;
  3417. $newId = $theNewSQLID;
  3418. }
  3419. }
  3420. } else $this->newlog('Localization failed; There already was a localization for this language of the record!',1);
  3421. } else $this->newlog('Localization failed; Source record contained a reference to an original default record (which is strange)!',1);
  3422. } else $this->newlog('Localization failed; Source record had another language than "Default" or "All" defined!',1);
  3423. } else $this->newlog('Attempt to localize record that did not exist!',1);
  3424. } else $this->newlog('Attempt to localize record without permission',1);
  3425. } else $this->newlog('Sys language UID "'.$language.'" not found valid!',1);
  3426. } else $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table!',1);
  3427. }
  3428. return $newId;
  3429. }
  3430. /**
  3431. * Performs localization or synchronization of child records.
  3432. *
  3433. * @param string $table: The table of the localized parent record
  3434. * @param integer $id: The uid of the localized parent record
  3435. * @param mixed $command: Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
  3436. * @return void
  3437. */
  3438. protected function inlineLocalizeSynchronize($table, $id, $command) {
  3439. // <field>, (localize | synchronize | <uid>):
  3440. $parts = t3lib_div::trimExplode(',', $command);
  3441. $field = $parts[0];
  3442. $type = $parts[1];
  3443. if ($field && (t3lib_div::inList('localize,synchronize', $type) || t3lib_div::testInt($type)) && isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
  3444. $config = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
  3445. $foreignTable = $config['foreign_table'];
  3446. $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
  3447. if ($localizationMode=='select') {
  3448. $parentRecord = t3lib_BEfunc::getRecordWSOL($table, $id);
  3449. $language = intval($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
  3450. $transOrigPointer = intval($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
  3451. $childTransOrigPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
  3452. if ($parentRecord && is_array($parentRecord) && $language>0 && $transOrigPointer) {
  3453. $inlineSubType = $this->getInlineFieldType($config);
  3454. $transOrigRecord = t3lib_BEfunc::getRecordWSOL($table, $transOrigPointer);
  3455. if ($inlineSubType!==false) {
  3456. $removeArray = array();
  3457. // Fetch children from original language parent:
  3458. // @var $dbAnalysisOriginal t3lib_loadDBGroup
  3459. $dbAnalysisOriginal = t3lib_div::makeInstance('t3lib_loadDBGroup');
  3460. $dbAnalysisOriginal->start($transOrigRecord[$field], $foreignTable, '', $transOrigRecord['uid'], $table, $config);
  3461. $elementsOriginal = array();
  3462. foreach ($dbAnalysisOriginal->itemArray as $item) {
  3463. $elementsOriginal[$item['id']] = $item;
  3464. }
  3465. unset($dbAnalysisOriginal);
  3466. // Fetch children from current localized parent:
  3467. // @var $dbAnalysisCurrent t3lib_loadDBGroup
  3468. $dbAnalysisCurrent = t3lib_div::makeInstance('t3lib_loadDBGroup');
  3469. $dbAnalysisCurrent->start($parentRecord[$field], $foreignTable, '', $id, $table, $config);
  3470. // Perform synchronization: Possibly removal of already localized records:
  3471. if ($type=='synchronize') {
  3472. foreach ($dbAnalysisCurrent->itemArray as $index => $item) {
  3473. $childRecord = t3lib_BEfunc::getRecordWSOL($item['table'], $item['id']);
  3474. if (isset($childRecord[$childTransOrigPointerField]) && $childRecord[$childTransOrigPointerField]>0) {
  3475. $childTransOrigPointer = $childRecord[$childTransOrigPointerField];
  3476. // If snychronization is requested, child record was translated once, but original record does not exist anymore, remove it:
  3477. if (!isset($elementsOriginal[$childTransOrigPointer])) {
  3478. unset($dbAnalysisCurrent->itemArray[$index]);
  3479. $removeArray[$item['table']][$item['id']]['delete'] = 1;
  3480. }
  3481. }
  3482. }
  3483. }
  3484. // Perform synchronization/localization: Possibly add unlocalized records for original language:
  3485. if (t3lib_div::testInt($type) && isset($elementsOriginal[$type])) {
  3486. $item = $elementsOriginal[$type];
  3487. $item['id'] = $this->localize($item['table'], $item['id'], $language);
  3488. $dbAnalysisCurrent->itemArray[] = $item;
  3489. } elseif (t3lib_div::inList('localize,synchronize', $type)) {
  3490. foreach ($elementsOriginal as $originalId => $item) {
  3491. $item['id'] = $this->localize($item['table'], $item['id'], $language);
  3492. $dbAnalysisCurrent->itemArray[] = $item;
  3493. }
  3494. }
  3495. // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
  3496. $value = implode(',', $dbAnalysisCurrent->getValueArray());
  3497. $this->registerDBList[$table][$id][$field] = $value;
  3498. // Remove child records (if synchronization requested it):
  3499. if (is_array($removeArray) && count($removeArray)) {
  3500. $tce = t3lib_div::makeInstance('t3lib_TCEmain');
  3501. $tce->stripslashes_values = false;
  3502. $tce->start(array(), $removeArray);
  3503. $tce->process_cmdmap();
  3504. unset($tce);
  3505. }
  3506. // Handle, reorder and store relations:
  3507. if ($inlineSubType=='list') {
  3508. $updateFields = array($field => $value);
  3509. } elseif ($inlineSubType=='field') {
  3510. $dbAnalysisCurrent->writeForeignField($config, $id);
  3511. $updateFields = array($field => $dbAnalysisCurrent->countItems(false));
  3512. }
  3513. // Update field referencing to child records of localized parent record:
  3514. if (is_array($updateFields) && count($updateFields)) {
  3515. $this->updateDB($table, $id, $updateFields);
  3516. }
  3517. }
  3518. }
  3519. }
  3520. }
  3521. }
  3522. /*********************************************
  3523. *
  3524. * Cmd: Deleting
  3525. *
  3526. ********************************************/
  3527. /**
  3528. * Delete a single record
  3529. *
  3530. * @param string Table name
  3531. * @param integer Record UID
  3532. * @return void
  3533. */
  3534. function deleteAction($table, $id) {
  3535. global $TCA;
  3536. $delRec = t3lib_BEfunc::getRecord($table, $id);
  3537. if (is_array($delRec)) { // Record asked to be deleted was found:
  3538. // For Live version, try if there is a workspace version because if so, rather "delete" that instead
  3539. if ($delRec['pid']!=-1) { // Look, if record is an offline version, then delete directly:
  3540. if ($wsVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id)) {
  3541. $delRec = $wsVersion;
  3542. $id = $delRec['uid'];
  3543. }
  3544. }
  3545. if ($delRec['pid']==-1) { // Look, if record is an offline version, then delete directly:
  3546. if ($TCA[$table]['ctrl']['versioningWS']) {
  3547. if ($this->BE_USER->workspace==0 || (int)$delRec['t3ver_wsid']==$this->BE_USER->workspace) { // In Live workspace, delete any. In other workspaces there must be match.
  3548. $liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'uid,t3ver_state');
  3549. if ($delRec['t3ver_wsid']==0 || (int)$liveRec['t3ver_state']<=0) { // Delete those in WS 0 + if their live records state was not "Placeholder".
  3550. $this->deleteEl($table, $id);
  3551. } else { // If live record was placeholder (new/deleted), rather clear it from workspace (because it clears both version and placeholder).
  3552. $this->version_clearWSID($table,$id);
  3553. }
  3554. } else $this->newlog('Tried to delete record from another workspace',1);
  3555. } else $this->newlog('Versioning not enabled for record with PID = -1!',2);
  3556. } elseif ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($delRec['pid'], $table)) { // Look, if record is "online" or in a versionized branch, then delete directly.
  3557. if ($res>0) {
  3558. $this->deleteEl($table, $id);
  3559. } else $this->newlog('Stage of root point did not allow for deletion',1);
  3560. } elseif ((int)$delRec['t3ver_state']===3) { // Placeholders for moving operations are deletable directly.
  3561. // Get record which its a placeholder for and reset the t3ver_state of that:
  3562. if ($wsRec = t3lib_BEfunc::getWorkspaceVersionOfRecord($delRec['t3ver_wsid'], $table, $delRec['t3ver_move_id'], 'uid')) {
  3563. // Clear the state flag of the workspace version of the record
  3564. $updateFields = array();
  3565. $updateFields['t3ver_state'] = 0; // Setting placeholder state value for version (so it can know it is currently a new version...)
  3566. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($wsRec['uid']), $updateFields);
  3567. }
  3568. $this->deleteEl($table, $id);
  3569. } else {
  3570. // Otherwise, try to delete by versioning:
  3571. $this->versionizeRecord($table,$id,'DELETED!',TRUE);
  3572. $this->deleteL10nOverlayRecords($table, $id);
  3573. }
  3574. }
  3575. }
  3576. /**
  3577. * Delete element from any table
  3578. *
  3579. * @param string Table name
  3580. * @param integer Record UID
  3581. * @param boolean Flag: If $noRecordCheck is set, then the function does not check permission to delete record
  3582. * @param boolean If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
  3583. * @return void
  3584. */
  3585. function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE) {
  3586. if ($table == 'pages') {
  3587. $this->deletePages($uid, $noRecordCheck, $forceHardDelete);
  3588. } else {
  3589. $this->deleteVersionsForRecord($table,$uid,$forceHardDelete);
  3590. $this->deleteRecord($table, $uid, $noRecordCheck, $forceHardDelete);
  3591. }
  3592. }
  3593. /**
  3594. * Delete versions for element from any table
  3595. *
  3596. * @param string Table name
  3597. * @param integer Record UID
  3598. * @param boolean If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
  3599. * @return void
  3600. */
  3601. function deleteVersionsForRecord($table, $uid, $forceHardDelete) {
  3602. $versions = t3lib_BEfunc::selectVersionsOfRecord($table, $uid, 'uid,pid');
  3603. if (is_array($versions)) {
  3604. foreach($versions as $verRec) {
  3605. if (!$verRec['_CURRENT_VERSION']) {
  3606. if ($table == 'pages') {
  3607. $this->deletePages($verRec['uid'], TRUE, $forceHardDelete);
  3608. } else {
  3609. $this->deleteRecord($table, $verRec['uid'], TRUE, $forceHardDelete);
  3610. }
  3611. }
  3612. }
  3613. }
  3614. }
  3615. /**
  3616. * Undelete a single record
  3617. *
  3618. * @param string Table name
  3619. * @param integer Record UID
  3620. * @return void
  3621. */
  3622. function undeleteRecord($table,$uid) {
  3623. if ($this->isRecordUndeletable($table, $uid)) {
  3624. $this->deleteRecord($table, $uid, true, false, true);
  3625. }
  3626. }
  3627. /**
  3628. * Deleting/Undeleting a record
  3629. * This function may not be used to delete pages-records unless the underlying records are already deleted
  3630. * Deletes a record regardless of versioning state (live or offline, doesn't matter, the uid decides)
  3631. * If both $noRecordCheck and $forceHardDelete are set it could even delete a "deleted"-flagged record!
  3632. *
  3633. * @param string Table name
  3634. * @param integer Record UID
  3635. * @param boolean Flag: If $noRecordCheck is set, then the function does not check permission to delete record
  3636. * @param boolean If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
  3637. * @param boolean If TRUE, the "deleted" flag is set to 0 again and thus, the item is undeleted.
  3638. * @return void
  3639. */
  3640. function deleteRecord($table,$uid, $noRecordCheck = FALSE, $forceHardDelete = FALSE, $undeleteRecord = FALSE) {
  3641. global $TCA;
  3642. // Checking if there is anything else disallowing deleting the record by checking if editing is allowed
  3643. $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table, $uid, FALSE, $undeleteRecord, TRUE);
  3644. $uid = intval($uid);
  3645. if ($TCA[$table] && $uid) {
  3646. if ($mayEditAccess) {
  3647. if ($noRecordCheck || $this->doesRecordExist($table,$uid,'delete')) {
  3648. $this->clear_cache($table,$uid); // clear cache before deleting the record, else the correct page cannot be identified by clear_cache
  3649. $propArr = $this->getRecordProperties($table, $uid);
  3650. $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
  3651. $deleteRow = $TCA[$table]['ctrl']['delete'];
  3652. if ($deleteRow && !$forceHardDelete) {
  3653. $value = $undeleteRecord ? 0 : 1;
  3654. $updateFields = array(
  3655. $deleteRow => $value
  3656. );
  3657. if ($TCA[$table]['ctrl']['tstamp']) {
  3658. $updateFields[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
  3659. }
  3660. // If the table is sorted, then the sorting number is set very high
  3661. if ($TCA[$table]['ctrl']['sortby'] && !$undeleteRecord) {
  3662. $updateFields[$TCA[$table]['ctrl']['sortby']] = 1000000000;
  3663. }
  3664. // before (un-)deleting this record, check for child records or references
  3665. $this->deleteRecord_procFields($table, $uid, $undeleteRecord);
  3666. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
  3667. // delete all l10n records aswell, impossible during undelete because it might bring too many records back to life
  3668. if (!$undeleteRecord) {
  3669. $this->deleteL10nOverlayRecords($table, $uid);
  3670. }
  3671. } else {
  3672. // Fetches all fields with flexforms and look for files to delete:
  3673. t3lib_div::loadTCA($table);
  3674. foreach($TCA[$table]['columns'] as $fieldName => $cfg) {
  3675. $conf = $cfg['config'];
  3676. switch($conf['type']) {
  3677. case 'flex':
  3678. $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
  3679. $flexObj->traverseFlexFormXMLData($table,$fieldName,t3lib_BEfunc::getRecordRaw($table,'uid='.intval($uid)),$this,'deleteRecord_flexFormCallBack');
  3680. break;
  3681. }
  3682. }
  3683. // Fetches all fields that holds references to files
  3684. $fileFieldArr = $this->extFileFields($table);
  3685. if (count($fileFieldArr)) {
  3686. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',$fileFieldArr), $table, 'uid='.intval($uid));
  3687. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  3688. $fArray = $fileFieldArr;
  3689. foreach($fArray as $theField) { // MISSING: Support for MM file relations!
  3690. $this->extFileFunctions($table,$theField,$row[$theField],'deleteAll'); // This deletes files that belonged to this record.
  3691. }
  3692. } else {
  3693. $this->log($table,$uid,3,0,100,'Delete: Zero rows in result when trying to read filenames from record which should be deleted');
  3694. }
  3695. }
  3696. // Delete the hard way...:
  3697. $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($uid));
  3698. $this->deleteL10nOverlayRecords($table, $uid);
  3699. }
  3700. $state = $undeleteRecord ? 1 : 3; // 1 means insert, 3 means delete
  3701. if (!$GLOBALS['TYPO3_DB']->sql_error()) {
  3702. if ($forceHardDelete) {
  3703. $message = "Record '%s' (%s) was deleted unrecoverable from page '%s' (%s)";
  3704. }
  3705. else {
  3706. $message = $state == 1 ?
  3707. "Record '%s' (%s) was restored on page '%s' (%s)" :
  3708. "Record '%s' (%s) was deleted from page '%s' (%s)";
  3709. }
  3710. $this->log($table, $uid, $state, 0, 0,
  3711. $message, 0,
  3712. array(
  3713. $propArr['header'],
  3714. $table.':'.$uid,
  3715. $pagePropArr['header'],
  3716. $propArr['pid']
  3717. ),
  3718. $propArr['event_pid']);
  3719. } else {
  3720. $this->log($table,$uid,$state,0,100,$GLOBALS['TYPO3_DB']->sql_error());
  3721. }
  3722. // Update reference index:
  3723. $this->updateRefIndex($table,$uid);
  3724. // if there are entries in the updateRefIndexStack
  3725. if (is_array($this->updateRefIndexStack[$table]) && is_array($this->updateRefIndexStack[$table][$uid])) {
  3726. while ($args = array_pop($this->updateRefIndexStack[$table][$uid])) {
  3727. // $args[0]: table, $args[1]: uid
  3728. $this->updateRefIndex($args[0], $args[1]);
  3729. }
  3730. unset($this->updateRefIndexStack[$table][$uid]);
  3731. }
  3732. } else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions');
  3733. } else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions. ['.$this->BE_USER->errorMsg.']');
  3734. }
  3735. }
  3736. /**
  3737. * Call back function for deleting file relations for flexform fields in records which are being completely deleted.
  3738. *
  3739. * @param [type] $dsArr: ...
  3740. * @param [type] $dataValue: ...
  3741. * @param [type] $PA: ...
  3742. * @param [type] $structurePath: ...
  3743. * @param [type] $pObj: ...
  3744. * @return [type] ...
  3745. */
  3746. function deleteRecord_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, $pObj) {
  3747. // Use reference index object to find files in fields:
  3748. $refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
  3749. $files = $refIndexObj->getRelations_procFiles($dataValue, $dsArr['TCEforms']['config'], $PA['uid']);
  3750. // Traverse files and delete them:
  3751. if (is_array($files)) {
  3752. foreach($files as $dat) {
  3753. if (@is_file($dat['ID_absFile'])) {
  3754. unlink ($dat['ID_absFile']);
  3755. #echo 'DELETE FlexFormFile:'.$dat['ID_absFile'].LF;
  3756. } else {
  3757. $this->log($table,0,3,0,100,"Delete: Referenced file '".$dat['ID_absFile']."' that was supposed to be deleted together with it's record didn't exist");
  3758. }
  3759. }
  3760. }
  3761. }
  3762. /**
  3763. * Used to delete page because it will check for branch below pages and unallowed tables on the page as well.
  3764. *
  3765. * @param integer Page id
  3766. * @param boolean If TRUE, pages are not checked for permission.
  3767. * @param boolean If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
  3768. * @return void
  3769. */
  3770. function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE) {
  3771. // Getting list of pages to delete:
  3772. if ($force) {
  3773. $brExist = $this->doesBranchExist('',$uid,0,1); // returns the branch WITHOUT permission checks (0 secures that)
  3774. $res = t3lib_div::trimExplode(',',$brExist.$uid,1);
  3775. } else {
  3776. $res = $this->canDeletePage($uid);
  3777. }
  3778. // Perform deletion if not error:
  3779. if (is_array($res)) {
  3780. foreach($res as $deleteId) {
  3781. $this->deleteSpecificPage($deleteId,$forceHardDelete);
  3782. }
  3783. } else {
  3784. $this->newlog($res,1);
  3785. }
  3786. }
  3787. /**
  3788. * Delete a page and all records on it.
  3789. *
  3790. * @param integer Page id
  3791. * @param boolean If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
  3792. * @return void
  3793. * @access private
  3794. * @see deletePages()
  3795. */
  3796. function deleteSpecificPage($uid,$forceHardDelete=FALSE) {
  3797. $uid = intval($uid);
  3798. if ($uid) {
  3799. foreach (array_keys($GLOBALS['TCA']) as $table) {
  3800. if ($table!='pages') {
  3801. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table));
  3802. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  3803. $this->deleteVersionsForRecord($table,$row['uid'],$forceHardDelete);
  3804. $this->deleteRecord($table,$row['uid'], TRUE, $forceHardDelete);
  3805. }
  3806. $GLOBALS['TYPO3_DB']->sql_free_result($mres);
  3807. }
  3808. }
  3809. $this->deleteVersionsForRecord('pages',$uid,$forceHardDelete);
  3810. $this->deleteRecord('pages',$uid, TRUE, $forceHardDelete);
  3811. }
  3812. }
  3813. /**
  3814. * Used to evaluate if a page can be deleted
  3815. *
  3816. * @param integer Page id
  3817. * @return mixed If array: List of page uids to traverse and delete (means OK), if string: error code.
  3818. */
  3819. function canDeletePage($uid) {
  3820. if ($this->doesRecordExist('pages',$uid,'delete')) { // If we may at all delete this page
  3821. if ($this->deleteTree) {
  3822. $brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1); // returns the branch
  3823. if ($brExist != -1) { // Checks if we had permissions
  3824. if ($this->noRecordsFromUnallowedTables($brExist.$uid)) {
  3825. $pagesInBranch = t3lib_div::trimExplode(',', $brExist . $uid, 1);
  3826. foreach ($pagesInBranch as $pageInBranch) {
  3827. if (!$this->BE_USER->recordEditAccessInternals('pages', $pageInBranch, FALSE, FALSE, TRUE)) {
  3828. return 'Attempt to delete page which has prohibited localizations.';
  3829. }
  3830. }
  3831. return $pagesInBranch;
  3832. } else return 'Attempt to delete records from disallowed tables';
  3833. } else return 'Attempt to delete pages in branch without permissions';
  3834. } else {
  3835. $brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1); // returns the branch
  3836. if ($brExist == '') { // Checks if branch exists
  3837. if ($this->noRecordsFromUnallowedTables($uid)) {
  3838. if ($this->BE_USER->recordEditAccessInternals('pages', $uid, FALSE, FALSE, TRUE)) {
  3839. return array($uid);
  3840. } else return 'Attempt to delete page which has prohibited localizations.';
  3841. } else return 'Attempt to delete records from disallowed tables';
  3842. } else return 'Attempt to delete page which has subpages';
  3843. }
  3844. } else return 'Attempt to delete page without permissions';
  3845. }
  3846. /**
  3847. * Returns true if record CANNOT be deleted, otherwise false. Used to check before the versioning API allows a record to be marked for deletion.
  3848. *
  3849. * @param string Record Table
  3850. * @param integer Record UID
  3851. * @return string Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
  3852. */
  3853. function cannotDeleteRecord($table,$id) {
  3854. if ($table==='pages') {
  3855. $res = $this->canDeletePage($id);
  3856. return is_array($res) ? FALSE : $res;
  3857. } else {
  3858. return $this->doesRecordExist($table,$id,'delete') ? FALSE : 'No permission to delete record';
  3859. }
  3860. }
  3861. /**
  3862. * Determines whether a record can be undeleted.
  3863. *
  3864. * @param string $table: Table name of the record
  3865. * @param integer $uid: uid of the record
  3866. * @return boolean Whether the record can be undeleted
  3867. */
  3868. public function isRecordUndeletable($table, $uid) {
  3869. $result = FALSE;
  3870. $record = t3lib_BEfunc::getRecord($table, $uid, 'pid', '', FALSE);
  3871. if ($record['pid']) {
  3872. $page = t3lib_BEfunc::getRecord('pages', $record['pid'], 'deleted, title, uid', '', FALSE);
  3873. // The page containing the record is not deleted, thus the record can be undeleted:
  3874. if (!$page['deleted']) {
  3875. $result = TRUE;
  3876. // The page containing the record is deleted and has to be undeleted first:
  3877. } else {
  3878. $this->log(
  3879. $table, $uid, 'isRecordUndeletable', '', 1,
  3880. 'Record cannot be undeleted since the page containing it is deleted! Undelete page "' .
  3881. $page['title'] . ' (UID: ' . $page['uid'] . ')" first'
  3882. );
  3883. }
  3884. } else {
  3885. // The page containing the record is on rootlevel, so there is no parent record to check, and the record can be undeleted:
  3886. $result = TRUE;
  3887. }
  3888. return $result;
  3889. }
  3890. /**
  3891. * Before a record is deleted, check if it has references such as inline type or MM references.
  3892. * If so, set these child records also to be deleted.
  3893. *
  3894. * @param string $table: Record Table
  3895. * @param string $uid: Record UID
  3896. * @param boolean $undeleteRecord: If a record should be undeleted (e.g. from history/undo)
  3897. * @return void
  3898. * @see deleteRecord()
  3899. */
  3900. function deleteRecord_procFields($table, $uid, $undeleteRecord = false) {
  3901. t3lib_div::loadTCA($table);
  3902. $conf = $GLOBALS['TCA'][$table]['columns'];
  3903. $row = t3lib_BEfunc::getRecord($table, $uid, '*', '', false);
  3904. foreach ($row as $field => $value) {
  3905. $this->deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf[$field]['config'], $undeleteRecord);
  3906. }
  3907. }
  3908. /**
  3909. * Process fields of a record to be deleted and search for special handling, like
  3910. * inline type, MM records, etc.
  3911. *
  3912. * @param string $table: Record Table
  3913. * @param string $uid: Record UID
  3914. * @param string $field: Record field
  3915. * @param string $value: Record field value
  3916. * @param array $conf: TCA configuration of current field
  3917. * @param boolean $undeleteRecord: If a record should be undeleted (e.g. from history/undo)
  3918. * @return void
  3919. * @see deleteRecord()
  3920. */
  3921. function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false) {
  3922. if ($conf['type'] == 'inline') {
  3923. $foreign_table = $conf['foreign_table'];
  3924. if ($foreign_table) {
  3925. $inlineType = $this->getInlineFieldType($conf);
  3926. if ($inlineType == 'list' || $inlineType == 'field') {
  3927. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  3928. $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
  3929. $dbAnalysis->undeleteRecord = true;
  3930. // walk through the items and remove them
  3931. foreach ($dbAnalysis->itemArray as $v) {
  3932. if (!$undeleteRecord) {
  3933. $this->deleteAction($v['table'], $v['id']);
  3934. } else {
  3935. $this->undeleteRecord($v['table'], $v['id']);
  3936. }
  3937. }
  3938. }
  3939. }
  3940. // no delete action but calls to updateRefIndex *AFTER* this record was deleted
  3941. } elseif ($this->isReferenceField($conf)) {
  3942. $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
  3943. $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
  3944. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  3945. $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
  3946. foreach ($dbAnalysis->itemArray as $v) {
  3947. $this->updateRefIndexStack[$table][$uid][] = array($v['table'], $v['id']);
  3948. }
  3949. }
  3950. }
  3951. /**
  3952. * Find l10n-overlay records and perform the requested delete action for these records.
  3953. *
  3954. * @param string $table: Record Table
  3955. * @param string $uid: Record UID
  3956. * @return void
  3957. */
  3958. function deleteL10nOverlayRecords($table, $uid) {
  3959. // Check whether table can be localized or has a different table defined to store localizations:
  3960. if (!t3lib_BEfunc::isTableLocalizable($table) || !empty($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) || !empty($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'])) {
  3961. return;
  3962. }
  3963. $where = '';
  3964. if (isset($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
  3965. $where = ' AND t3ver_oid=0';
  3966. }
  3967. $l10nRecords = t3lib_BEfunc::getRecordsByField($table, $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'], $uid, $where);
  3968. if (is_array($l10nRecords)) {
  3969. foreach($l10nRecords as $record) {
  3970. $this->deleteAction($table, intval($record['t3ver_oid']) > 0 ? intval($record['t3ver_oid']) : intval($record['uid']));
  3971. }
  3972. }
  3973. }
  3974. /*********************************************
  3975. *
  3976. * Cmd: Versioning
  3977. *
  3978. ********************************************/
  3979. /**
  3980. * Creates a new version of a record
  3981. * (Requires support in the table)
  3982. *
  3983. * @param string Table name
  3984. * @param integer Record uid to versionize
  3985. * @param string Version label
  3986. * @param boolean If true, the version is created to delete the record.
  3987. * @param integer Indicating "treeLevel" - or versioning type - "element" (-1), "page" (0) or "branch" (>=1)
  3988. * @return integer Returns the id of the new version (if any)
  3989. * @see copyRecord()
  3990. */
  3991. function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1) {
  3992. global $TCA;
  3993. $id = intval($id);
  3994. if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS'] && $id>0) {
  3995. if ($this->doesRecordExist($table,$id,'show')) {
  3996. if ($this->BE_USER->workspaceVersioningTypeAccess($versionizeTree)) {
  3997. // Select main record:
  3998. $row = $this->recordInfo($table,$id,'pid,t3ver_id,t3ver_state');
  3999. if (is_array($row)) {
  4000. if ($row['pid']>=0) { // record must be online record
  4001. if ($row['t3ver_state']!=3) { // record must not be placeholder for moving.
  4002. if (!$delete || !$this->cannotDeleteRecord($table,$id)) {
  4003. // Look for next version number:
  4004. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  4005. 't3ver_id',
  4006. $table,
  4007. '((pid=-1 && t3ver_oid='.$id.') OR uid='.$id.')'.$this->deleteClause($table),
  4008. '',
  4009. 't3ver_id DESC',
  4010. '1'
  4011. );
  4012. list($highestVerNumber) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
  4013. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  4014. // Look for version number of the current:
  4015. $subVer = $row['t3ver_id'].'.'.($highestVerNumber+1);
  4016. // Set up the values to override when making a raw-copy:
  4017. $overrideArray = array(
  4018. 't3ver_id' => $highestVerNumber+1,
  4019. 't3ver_oid' => $id,
  4020. 't3ver_label' => ($label ? $label : $subVer.' / '.date('d-m-Y H:m:s')),
  4021. 't3ver_wsid' => $this->BE_USER->workspace,
  4022. 't3ver_state' => $delete ? 2 : 0,
  4023. 't3ver_count' => 0,
  4024. 't3ver_stage' => 0,
  4025. 't3ver_tstamp' => 0
  4026. );
  4027. if ($TCA[$table]['ctrl']['editlock']) {
  4028. $overrideArray[$TCA[$table]['ctrl']['editlock']] = 0;
  4029. }
  4030. if ($table==='pages') {
  4031. $overrideArray['t3ver_swapmode'] = $versionizeTree;
  4032. }
  4033. // Checking if the record already has a version in the current workspace of the backend user
  4034. $workspaceCheck = TRUE;
  4035. if ($this->BE_USER->workspace!==0) {
  4036. // Look for version already in workspace:
  4037. $workspaceCheck = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace,$table,$id,'uid') ? FALSE : TRUE;
  4038. }
  4039. if ($workspaceCheck) {
  4040. // Create raw-copy and return result:
  4041. return $this->copyRecord_raw($table,$id,-1,$overrideArray);
  4042. } else $this->newlog('Record "'.$table.':'.$id.'" you wanted to versionize was already a version in the workspace (wsid='.$this->BE_USER->workspace.')!',1);
  4043. } else $this->newlog('Record cannot be deleted: '.$this->cannotDeleteRecord($table,$id),1);
  4044. } else $this->newlog('Record cannot be versioned because it is a placeholder for a moving operation',1);
  4045. } else $this->newlog('Record "'.$table.':'.$id.'" you wanted to versionize was already a version in archive (pid=-1)!',1);
  4046. } else $this->newlog('Record "'.$table.':'.$id.'" you wanted to versionize did not exist!',1);
  4047. } else $this->newlog('The versioning type '.$versionizeTree.' mode you requested was not allowed',1);
  4048. } else $this->newlog('You didnt have correct permissions to make a new version (copy) of this record "'.$table.'" / '.$id,1);
  4049. } else $this->newlog('Versioning is not supported for this table "'.$table.'" / '.$id,1);
  4050. }
  4051. /**
  4052. * Creates a new version of a page including content and possible subpages.
  4053. *
  4054. * @param integer Page uid to create new version of.
  4055. * @param string Version label
  4056. * @param integer Indicating "treeLevel" - "page" (0) or "branch" (>=1) ["element" type must call versionizeRecord() directly]
  4057. * @return void
  4058. * @see copyPages()
  4059. */
  4060. function versionizePages($uid,$label,$versionizeTree) {
  4061. global $TCA;
  4062. $uid = intval($uid);
  4063. $brExist = $this->doesBranchExist('',$uid,$this->pMap['show'],1); // returns the branch
  4064. if ($brExist != -1) { // Checks if we had permissions
  4065. // Finding list of tables ALLOWED to be copied
  4066. $allowedTablesArray = $this->admin ? $this->compileAdminTables() : explode(',',$this->BE_USER->groupData['tables_modify']); // These are the tables, the user may modify
  4067. $allowedTablesArray = $this->compileAdminTables(); // These are ALL tables because a new version should be ALL of them regardless of permission of the user executing the request.
  4068. // Make list of tables that should come along with a new version of the page:
  4069. $verTablesArray = array();
  4070. $allTables = array_keys($TCA);
  4071. foreach($allTables as $tN) {
  4072. if ($tN!='pages' && ($versionizeTree>0 || $TCA[$tN]['ctrl']['versioning_followPages']) && ($this->admin || in_array($tN, $allowedTablesArray))) {
  4073. $verTablesArray[] = $tN;
  4074. }
  4075. }
  4076. // Begin to copy pages if we're allowed to:
  4077. if ($this->admin || in_array('pages',$allowedTablesArray)) {
  4078. if ($this->BE_USER->workspaceVersioningTypeAccess($versionizeTree)) {
  4079. // Versionize this page:
  4080. $theNewRootID = $this->versionizeRecord('pages',$uid,$label,FALSE,$versionizeTree);
  4081. if ($theNewRootID) {
  4082. $this->rawCopyPageContent($uid,$theNewRootID,$verTablesArray);
  4083. // If we're going to copy recursively...:
  4084. if ($versionizeTree>0) {
  4085. // Get ALL subpages to copy (read permissions respected - they should NOT be...):
  4086. $CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($versionizeTree), $theNewRootID);
  4087. // Now copying the subpages:
  4088. foreach($CPtable as $thePageUid => $thePagePid) {
  4089. $newPid = $this->copyMappingArray['pages'][$thePagePid];
  4090. if (isset($newPid)) {
  4091. $theNewRootID = $this->copyRecord_raw('pages',$thePageUid,$newPid);
  4092. $this->rawCopyPageContent($thePageUid,$theNewRootID,$verTablesArray);
  4093. } else {
  4094. $this->newlog('Something went wrong during copying branch (for versioning)',1);
  4095. break;
  4096. }
  4097. }
  4098. } // else the page was not copied. Too bad...
  4099. } else $this->newlog('The root version could not be created!',1);
  4100. } else $this->newlog('Versioning type "'.$versionizeTree.'" was not allowed in workspace',1);
  4101. } else $this->newlog('Attempt to versionize page without permission to this table',1);
  4102. } else $this->newlog('Could not read all subpages to versionize.',1);
  4103. }
  4104. /**
  4105. * Swapping versions of a record
  4106. * Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also
  4107. *
  4108. * @param string Table name
  4109. * @param integer UID of the online record to swap
  4110. * @param integer UID of the archived version to swap with!
  4111. * @param boolean If set, swaps online into workspace instead of publishing out of workspace.
  4112. * @return void
  4113. */
  4114. function version_swap($table,$id,$swapWith,$swapIntoWS=0) {
  4115. global $TCA;
  4116. // First, check if we may actually edit the online record
  4117. if ($this->checkRecordUpdateAccess($table,$id)) {
  4118. // Select the two versions:
  4119. $curVersion = t3lib_BEfunc::getRecord($table,$id,'*');
  4120. $swapVersion = t3lib_BEfunc::getRecord($table,$swapWith,'*');
  4121. $movePlh = array();
  4122. $movePlhID = 0;
  4123. if (is_array($curVersion) && is_array($swapVersion)) {
  4124. if ($this->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid'])) {
  4125. $wsAccess = $this->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']);
  4126. if ($swapVersion['t3ver_wsid']<=0 || !($wsAccess['publish_access']&1) || (int)$swapVersion['t3ver_stage']===10) {
  4127. if ($this->doesRecordExist($table,$swapWith,'show') && $this->checkRecordUpdateAccess($table,$swapWith)) {
  4128. if (!$swapIntoWS || $this->BE_USER->workspaceSwapAccess()) {
  4129. // Check if the swapWith record really IS a version of the original!
  4130. if ((int)$swapVersion['pid']==-1 && (int)$curVersion['pid']>=0 && !strcmp($swapVersion['t3ver_oid'],$id)) {
  4131. // Lock file name:
  4132. $lockFileName = PATH_site.'typo3temp/swap_locking/'.$table.':'.$id.'.ser';
  4133. if (!@is_file($lockFileName)) {
  4134. // Write lock-file:
  4135. t3lib_div::writeFileToTypo3tempDir($lockFileName,serialize(array(
  4136. 'tstamp' => $GLOBALS['EXEC_TIME'],
  4137. 'user' => $this->BE_USER->user['username'],
  4138. 'curVersion'=>$curVersion,
  4139. 'swapVersion'=>$swapVersion
  4140. )));
  4141. // Find fields to keep
  4142. $keepFields = $this->getUniqueFields($table);
  4143. if ($TCA[$table]['ctrl']['sortby']) {
  4144. $keepFields[] = $TCA[$table]['ctrl']['sortby'];
  4145. }
  4146. // l10n-fields must be kept otherwise the localization will be lost during the publishing
  4147. if (!isset($TCA[$table]['ctrl']['transOrigPointerTable']) && $TCA[$table]['ctrl']['transOrigPointerField']) {
  4148. $keepFields[] = $TCA[$table]['ctrl']['transOrigPointerField'];
  4149. }
  4150. // Swap "keepfields"
  4151. foreach($keepFields as $fN) {
  4152. $tmp = $swapVersion[$fN];
  4153. $swapVersion[$fN] = $curVersion[$fN];
  4154. $curVersion[$fN] = $tmp;
  4155. }
  4156. // Preserve states:
  4157. $t3ver_state = array();
  4158. $t3ver_state['swapVersion'] = $swapVersion['t3ver_state'];
  4159. $t3ver_state['curVersion'] = $curVersion['t3ver_state'];
  4160. // Modify offline version to become online:
  4161. $tmp_wsid = $swapVersion['t3ver_wsid'];
  4162. $swapVersion['pid'] = intval($curVersion['pid']); // Set pid for ONLINE
  4163. $swapVersion['t3ver_oid'] = 0; // We clear this because t3ver_oid only make sense for offline versions and we want to prevent unintentional misuse of this value for online records.
  4164. $swapVersion['t3ver_wsid'] = $swapIntoWS ? ($t3ver_state['swapVersion']>0 ? $this->BE_USER->workspace : intval($curVersion['t3ver_wsid'])) : 0; // In case of swapping and the offline record has a state (like 2 or 4 for deleting or move-pointer) we set the current workspace ID so the record is not deselected in the interface by t3lib_BEfunc::versioningPlaceholderClause()
  4165. $swapVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
  4166. $swapVersion['t3ver_stage'] = 0;
  4167. if (!$swapIntoWS) $swapVersion['t3ver_state'] = 0;
  4168. // Moving element.
  4169. if ((int)$TCA[$table]['ctrl']['versioningWS']>=2) { // && $t3ver_state['swapVersion']==4 // Maybe we don't need this?
  4170. if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table,$id,'t3ver_state,pid,uid'.($TCA[$table]['ctrl']['sortby']?','.$TCA[$table]['ctrl']['sortby']:''))) {
  4171. $movePlhID = $plhRec['uid'];
  4172. $movePlh['pid'] = $swapVersion['pid'];
  4173. $swapVersion['pid'] = intval($plhRec['pid']);
  4174. $curVersion['t3ver_state'] = intval($swapVersion['t3ver_state']);
  4175. $swapVersion['t3ver_state'] = 0;
  4176. if ($TCA[$table]['ctrl']['sortby']) {
  4177. $movePlh[$TCA[$table]['ctrl']['sortby']] = $swapVersion[$TCA[$table]['ctrl']['sortby']]; // sortby is a "keepFields" which is why this will work...
  4178. $swapVersion[$TCA[$table]['ctrl']['sortby']] = $plhRec[$TCA[$table]['ctrl']['sortby']];
  4179. }
  4180. }
  4181. }
  4182. // Take care of relations in each field (e.g. IRRE):
  4183. if (is_array($GLOBALS['TCA'][$table]['columns'])) {
  4184. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf) {
  4185. $this->version_swap_procBasedOnFieldType(
  4186. $table, $field, $fieldConf['config'], $curVersion, $swapVersion
  4187. );
  4188. }
  4189. }
  4190. unset($swapVersion['uid']);
  4191. // Modify online version to become offline:
  4192. unset($curVersion['uid']);
  4193. $curVersion['pid'] = -1; // Set pid for OFFLINE
  4194. $curVersion['t3ver_oid'] = intval($id);
  4195. $curVersion['t3ver_wsid'] = $swapIntoWS ? intval($tmp_wsid) : 0;
  4196. $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
  4197. $curVersion['t3ver_count'] = $curVersion['t3ver_count']+1; // Increment lifecycle counter
  4198. $curVersion['t3ver_stage'] = 0;
  4199. if (!$swapIntoWS) $curVersion['t3ver_state'] = 0;
  4200. if ($table==='pages') { // Keeping the swapmode state
  4201. $curVersion['t3ver_swapmode'] = $swapVersion['t3ver_swapmode'];
  4202. }
  4203. // Registering and swapping MM relations in current and swap records:
  4204. $this->version_remapMMForVersionSwap($table,$id,$swapWith);
  4205. // Generating proper history data to prepare logging
  4206. $this->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion);
  4207. $this->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion);
  4208. // Execute swapping:
  4209. $sqlErrors = array();
  4210. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($id),$swapVersion);
  4211. if ($GLOBALS['TYPO3_DB']->sql_error()) {
  4212. $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
  4213. } else {
  4214. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($swapWith),$curVersion);
  4215. if ($GLOBALS['TYPO3_DB']->sql_error()) {
  4216. $sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();
  4217. } else {
  4218. unlink($lockFileName);
  4219. }
  4220. }
  4221. if (!count($sqlErrors)) {
  4222. // If a moving operation took place...:
  4223. if ($movePlhID) {
  4224. if (!$swapIntoWS) { // Remove, if normal publishing:
  4225. $this->deleteEl($table, $movePlhID, TRUE, TRUE); // For delete + completely delete!
  4226. } else { // Otherwise update the movePlaceholder:
  4227. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($movePlhID),$movePlh);
  4228. $this->updateRefIndex($table,$movePlhID);
  4229. }
  4230. }
  4231. // Checking for delete:
  4232. if (!$swapIntoWS && ((int)$t3ver_state['swapVersion']===1 || (int)$t3ver_state['swapVersion']===2)) { // Delete only if new/deleted placeholders are there.
  4233. $this->deleteEl($table,$id,TRUE); // Force delete
  4234. }
  4235. $this->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing').' successful for table "'.$table.'" uid '.$id.'=>'.$swapWith, $table, $id, $swapVersion['pid']);
  4236. // Update reference index of the live record:
  4237. $this->updateRefIndex($table,$id);
  4238. // Set log entry for live record:
  4239. $propArr = $this->getRecordPropertiesFromRow($table, $swapVersion);
  4240. if ( $propArr['_ORIG_pid'] == -1) {
  4241. $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.offline_record_updated');
  4242. } else {
  4243. $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.online_record_updated');
  4244. }
  4245. $theLogId = $this->log($table, $id, 2, $propArr['pid'], 0, $label , 10, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']);
  4246. $this->setHistory($table, $id, $theLogId);
  4247. // Update reference index of the offline record:
  4248. $this->updateRefIndex($table,$swapWith);
  4249. // Set log entry for offline record:
  4250. $propArr = $this->getRecordPropertiesFromRow($table, $curVersion);
  4251. if ( $propArr['_ORIG_pid'] == -1) {
  4252. $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.offline_record_updated');
  4253. } else {
  4254. $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.online_record_updated');
  4255. }
  4256. $theLogId = $this->log($table, $swapWith, 2, $propArr['pid'], 0, $label , 10, array($propArr['header'], $table . ':'. $swapWith), $propArr['event_pid']);
  4257. $this->setHistory($table, $swapWith, $theLogId);
  4258. // SWAPPING pids for subrecords:
  4259. if ($table=='pages' && $swapVersion['t3ver_swapmode']>=0) {
  4260. // Collect table names that should be copied along with the tables:
  4261. foreach($TCA as $tN => $tCfg) {
  4262. if ($swapVersion['t3ver_swapmode']>0 || $TCA[$tN]['ctrl']['versioning_followPages']) { // For "Branch" publishing swap ALL, otherwise for "page" publishing, swap only "versioning_followPages" tables
  4263. $temporaryPid = -($id+1000000);
  4264. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($id),array('pid'=>$temporaryPid));
  4265. if ($GLOBALS['TYPO3_DB']->sql_error()) $sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();
  4266. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($swapWith),array('pid'=>$id));
  4267. if ($GLOBALS['TYPO3_DB']->sql_error()) $sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();
  4268. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($temporaryPid),array('pid'=>$swapWith));
  4269. if ($GLOBALS['TYPO3_DB']->sql_error()) $sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();
  4270. if (count($sqlErrors)) {
  4271. $this->newlog('During Swapping: SQL errors happened: '.implode('; ',$sqlErrors),2);
  4272. }
  4273. }
  4274. }
  4275. }
  4276. // Clear cache:
  4277. $this->clear_cache($table,$id);
  4278. // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
  4279. if (!$swapIntoWS && $t3ver_state['curVersion']>0) {
  4280. $this->deleteEl($table, $swapWith, TRUE, TRUE); // For delete + completely delete!
  4281. }
  4282. } else $this->newlog('During Swapping: SQL errors happened: '.implode('; ',$sqlErrors),2);
  4283. } else $this->newlog('A swapping lock file was present. Either another swap process is already running or a previous swap process failed. Ask your administrator to handle the situation.',2);
  4284. } else $this->newlog('In swap version, either pid was not -1 or the t3ver_oid didn\'t match the id of the online version as it must!',2);
  4285. } else $this->newlog('Workspace #'.$swapVersion['t3ver_wsid'].' does not support swapping.',1);
  4286. } else $this->newlog('You cannot publish a record you do not have edit and show permissions for',1);
  4287. } else $this->newlog('Records in workspace #'.$swapVersion['t3ver_wsid'].' can only be published when in "Publish" stage.',1);
  4288. } else $this->newlog('User could not publish records from workspace #'.$swapVersion['t3ver_wsid'],1);
  4289. } else $this->newlog('Error: Either online or swap version could not be selected!',2);
  4290. } else $this->newlog('Error: You cannot swap versions for a record you do not have access to edit!',1);
  4291. }
  4292. /**
  4293. * Release version from this workspace (and into "Live" workspace but as an offline version).
  4294. *
  4295. * @param string Table name
  4296. * @param integer Record UID
  4297. * @param boolean If set, will completely delete element
  4298. * @return void
  4299. */
  4300. function version_clearWSID($table,$id,$flush=FALSE) {
  4301. global $TCA;
  4302. if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
  4303. $this->newlog('Attempt to reset workspace for record failed: '.$errorCode,1);
  4304. } elseif ($this->checkRecordUpdateAccess($table,$id)) {
  4305. if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'uid,t3ver_state')) {
  4306. // Clear workspace ID:
  4307. $sArray = array();
  4308. $sArray['t3ver_wsid'] = 0;
  4309. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($id),$sArray);
  4310. // Clear workspace ID for live version AND DELETE IT as well because it is a new record!
  4311. if ((int)$liveRec['t3ver_state']==1 || (int)$liveRec['t3ver_state']==2) {
  4312. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($liveRec['uid']),$sArray);
  4313. $this->deleteEl($table, $liveRec['uid'], TRUE); // THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
  4314. }
  4315. // If "deleted" flag is set for the version that got released it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
  4316. $wsRec = t3lib_BEfunc::getRecord($table,$id);
  4317. if ($flush || ((int)$wsRec['t3ver_state']==1 || (int)$wsRec['t3ver_state']==2)) {
  4318. $this->deleteEl($table, $id, TRUE, TRUE);
  4319. }
  4320. // Remove the move-placeholder if found for live record.
  4321. if ((int)$TCA[$table]['ctrl']['versioningWS']>=2) {
  4322. if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table,$liveRec['uid'],'uid')) {
  4323. $this->deleteEl($table, $plhRec['uid'], TRUE, TRUE);
  4324. }
  4325. }
  4326. }
  4327. } else $this->newlog('Attempt to reset workspace for record failed because you do not have edit access',1);
  4328. }
  4329. /**
  4330. * Setting stage of record
  4331. *
  4332. * @param string Table name
  4333. * @param integer Record UID
  4334. * @param integer Stage ID to set
  4335. * @param string Comment that goes into log
  4336. * @param boolean Accumulate state changes in memory for compiled notification email?
  4337. * @return void
  4338. */
  4339. function version_setStage($table,$id,$stageId,$comment='',$accumulateForNotifEmail=FALSE) {
  4340. if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
  4341. $this->newlog('Attempt to set stage for record failed: '.$errorCode,1);
  4342. } elseif ($this->checkRecordUpdateAccess($table,$id)) {
  4343. $record = t3lib_BEfunc::getRecord($table, $id);
  4344. $stat = $this->BE_USER->checkWorkspace($record['t3ver_wsid']);
  4345. if (t3lib_div::inList('admin,online,offline,reviewer,owner', $stat['_ACCESS']) || ($stageId<=1 && $stat['_ACCESS']==='member')) {
  4346. // Set stage of record:
  4347. $sArray = array();
  4348. $sArray['t3ver_stage'] = $stageId;
  4349. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $sArray);
  4350. $this->newlog2('Stage for record was changed to '.$stageId.'. Comment was: "'.substr($comment,0,100).'"',$table,$id);
  4351. // TEMPORARY, except 6-30 as action/detail number which is observed elsewhere!
  4352. $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stage'=>$stageId));
  4353. if ((int)$stat['stagechg_notification']>0) {
  4354. if ($accumulateForNotifEmail) {
  4355. $this->accumulateForNotifEmail[$stat['uid'].':'.$stageId.':'.$comment]['shared'] = array($stat,$stageId,$comment);
  4356. $this->accumulateForNotifEmail[$stat['uid'].':'.$stageId.':'.$comment]['elements'][] = $table.':'.$id;
  4357. } else {
  4358. $this->notifyStageChange($stat,$stageId,$table,$id,$comment);
  4359. }
  4360. }
  4361. } else $this->newlog('The member user tried to set a stage value "'.$stageId.'" that was not allowed',1);
  4362. } else $this->newlog('Attempt to set stage for record failed because you do not have edit access',1);
  4363. }
  4364. /**
  4365. * Update relations on version/workspace swapping.
  4366. *
  4367. * @param string $table: Record Table
  4368. * @param string $field: Record field
  4369. * @param array $conf: TCA configuration of current field
  4370. * @param string $curVersion: Reference to the current (original) record
  4371. * @param string $swapVersion: Reference to the record (workspace/versionized) to publish in or swap with
  4372. * @return void
  4373. */
  4374. function version_swap_procBasedOnFieldType($table,$field,$conf,&$curVersion,&$swapVersion) {
  4375. $inlineType = $this->getInlineFieldType($conf);
  4376. // Process pointer fields on normalized database:
  4377. if ($inlineType == 'field') {
  4378. // Read relations that point to the current record (e.g. live record):
  4379. $dbAnalysisCur = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4380. $dbAnalysisCur->start('', $conf['foreign_table'], '', $curVersion['uid'], $table, $conf);
  4381. // Read relations that point to the record to be swapped with e.g. draft record):
  4382. $dbAnalysisSwap = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4383. $dbAnalysisSwap->start('', $conf['foreign_table'], '', $swapVersion['uid'], $table, $conf);
  4384. // Update relations for both (workspace/versioning) sites:
  4385. $dbAnalysisCur->writeForeignField($conf,$curVersion['uid'],$swapVersion['uid']);
  4386. $dbAnalysisSwap->writeForeignField($conf,$swapVersion['uid'],$curVersion['uid']);
  4387. // Swap field values (CSV):
  4388. // BUT: These values will be swapped back in the next steps, when the *CHILD RECORD ITSELF* is swapped!
  4389. } elseif ($inlineType == 'list') {
  4390. $tempValue = $curVersion[$field];
  4391. $curVersion[$field] = $swapVersion[$field];
  4392. $swapVersion[$field] = $tempValue;
  4393. }
  4394. }
  4395. /**
  4396. * Swaps MM-relations for current/swap record, see version_swap()
  4397. *
  4398. * @param string Table for the two input records
  4399. * @param integer Current record (about to go offline)
  4400. * @param integer Swap record (about to go online)
  4401. * @return void
  4402. * @see version_swap()
  4403. */
  4404. function version_remapMMForVersionSwap($table,$id,$swapWith) {
  4405. global $TCA;
  4406. // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
  4407. $currentRec = t3lib_BEfunc::getRecord($table,$id);
  4408. $swapRec = t3lib_BEfunc::getRecord($table,$swapWith);
  4409. $this->version_remapMMForVersionSwap_reg = array();
  4410. foreach($TCA[$table]['columns'] as $field => $fConf) {
  4411. $conf = $fConf['config'];
  4412. if ($this->isReferenceField($conf)) {
  4413. $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
  4414. $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
  4415. if ($conf['MM']) {
  4416. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4417. /* @var $dbAnalysis t3lib_loadDBGroup */
  4418. $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
  4419. if (count($dbAnalysis->getValueArray($prependName))) {
  4420. $this->version_remapMMForVersionSwap_reg[$id][$field] = array($dbAnalysis, $conf['MM'], $prependName);
  4421. }
  4422. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4423. /* @var $dbAnalysis t3lib_loadDBGroup */
  4424. $dbAnalysis->start('', $allowedTables, $conf['MM'], $swapWith, $table, $conf);
  4425. if (count($dbAnalysis->getValueArray($prependName))) {
  4426. $this->version_remapMMForVersionSwap_reg[$swapWith][$field] = array($dbAnalysis, $conf['MM'], $prependName);
  4427. }
  4428. }
  4429. } elseif($conf['type']=='flex') {
  4430. // Current record
  4431. $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $currentRec, $table);
  4432. $currentValueArray = t3lib_div::xml2array($currentRec[$field]);
  4433. if (is_array($currentValueArray)) {
  4434. $this->checkValue_flex_procInData(
  4435. $currentValueArray['data'],
  4436. array(), // Not used.
  4437. array(), // Not used.
  4438. $dataStructArray,
  4439. array($table,$id,$field), // Parameters.
  4440. 'version_remapMMForVersionSwap_flexFormCallBack'
  4441. );
  4442. }
  4443. // Swap record
  4444. $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $swapRec, $table);
  4445. $currentValueArray = t3lib_div::xml2array($swapRec[$field]);
  4446. if (is_array($currentValueArray)) {
  4447. $this->checkValue_flex_procInData(
  4448. $currentValueArray['data'],
  4449. array(), // Not used.
  4450. array(), // Not used.
  4451. $dataStructArray,
  4452. array($table,$swapWith,$field), // Parameters.
  4453. 'version_remapMMForVersionSwap_flexFormCallBack'
  4454. );
  4455. }
  4456. }
  4457. }
  4458. // Execute:
  4459. $this->version_remapMMForVersionSwap_execSwap($table,$id,$swapWith);
  4460. }
  4461. /**
  4462. * Callback function for traversing the FlexForm structure in relation to ...
  4463. *
  4464. * @param array Array of parameters in num-indexes: table, uid, field
  4465. * @param array TCA field configuration (from Data Structure XML)
  4466. * @param string The value of the flexForm field
  4467. * @param string Not used.
  4468. * @param string Not used.
  4469. * @param string Path in flexforms
  4470. * @return array Result array with key "value" containing the value of the processing.
  4471. * @see version_remapMMForVersionSwap(), checkValue_flex_procInData_travDS()
  4472. */
  4473. function version_remapMMForVersionSwap_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path) {
  4474. // Extract parameters:
  4475. list($table, $uid, $field) = $pParams;
  4476. if ($this->isReferenceField($dsConf)) {
  4477. $allowedTables = $dsConf['type']=='group' ? $dsConf['allowed'] : $dsConf['foreign_table'].','.$dsConf['neg_foreign_table'];
  4478. $prependName = $dsConf['type']=='group' ? $dsConf['prepend_tname'] : $dsConf['neg_foreign_table'];
  4479. if ($dsConf['MM']) {
  4480. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4481. /* @var $dbAnalysis t3lib_loadDBGroup */
  4482. $dbAnalysis->start('', $allowedTables, $dsConf['MM'], $uid, $table, $dsConf);
  4483. $this->version_remapMMForVersionSwap_reg[$uid][$field.'/'.$path] = array($dbAnalysis, $dsConf['MM'], $prependName);
  4484. }
  4485. }
  4486. }
  4487. /**
  4488. * Performing the remapping operations found necessary in version_remapMMForVersionSwap()
  4489. * It must be done in three steps with an intermediate "fake" uid. The UID can be something else than -$id (fx. 9999999+$id if you dare... :-)- as long as it is unique.
  4490. *
  4491. * @param string Table for the two input records
  4492. * @param integer Current record (about to go offline)
  4493. * @param integer Swap record (about to go online)
  4494. * @return void
  4495. * @see version_remapMMForVersionSwap()
  4496. */
  4497. function version_remapMMForVersionSwap_execSwap($table,$id,$swapWith) {
  4498. if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
  4499. foreach($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
  4500. $str[0]->remapMM($str[1],$id,-$id,$str[2]);
  4501. }
  4502. }
  4503. if (is_array($this->version_remapMMForVersionSwap_reg[$swapWith])) {
  4504. foreach($this->version_remapMMForVersionSwap_reg[$swapWith] as $field => $str) {
  4505. $str[0]->remapMM($str[1],$swapWith,$id,$str[2]);
  4506. }
  4507. }
  4508. if (is_array($this->version_remapMMForVersionSwap_reg[$id])) {
  4509. foreach($this->version_remapMMForVersionSwap_reg[$id] as $field => $str) {
  4510. $str[0]->remapMM($str[1],-$id,$swapWith,$str[2]);
  4511. }
  4512. }
  4513. }
  4514. /*********************************************
  4515. *
  4516. * Cmd: Helper functions
  4517. *
  4518. ********************************************/
  4519. /**
  4520. * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
  4521. *
  4522. * @return void
  4523. */
  4524. function remapListedDBRecords() {
  4525. global $TCA;
  4526. if (count($this->registerDBList)) {
  4527. foreach ($this->registerDBList as $table => $records) {
  4528. t3lib_div::loadTCA($table);
  4529. foreach ($records as $uid => $fields) {
  4530. $newData = array();
  4531. $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
  4532. $theUidToUpdate_saveTo = t3lib_BEfunc::wsMapId($table,$theUidToUpdate);
  4533. foreach($fields as $fieldName => $value) {
  4534. $conf = $TCA[$table]['columns'][$fieldName]['config'];
  4535. switch($conf['type']) {
  4536. case 'group':
  4537. case 'select':
  4538. $vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
  4539. if (is_array($vArray)) {
  4540. $newData[$fieldName] = implode(',',$vArray);
  4541. }
  4542. break;
  4543. case 'flex':
  4544. if ($value=='FlexForm_reference') {
  4545. $origRecordRow = $this->recordInfo($table,$theUidToUpdate,'*'); // This will fetch the new row for the element
  4546. if (is_array($origRecordRow)) {
  4547. t3lib_BEfunc::workspaceOL($table,$origRecordRow);
  4548. // Get current data structure and value array:
  4549. $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $origRecordRow, $table);
  4550. $currentValueArray = t3lib_div::xml2array($origRecordRow[$fieldName]);
  4551. // Do recursive processing of the XML data:
  4552. $currentValueArray['data'] = $this->checkValue_flex_procInData(
  4553. $currentValueArray['data'],
  4554. array(), // Not used.
  4555. array(), // Not used.
  4556. $dataStructArray,
  4557. array($table,$theUidToUpdate,$fieldName), // Parameters.
  4558. 'remapListedDBRecords_flexFormCallBack'
  4559. );
  4560. // The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
  4561. if (is_array($currentValueArray['data'])) {
  4562. $newData[$fieldName] =
  4563. $this->checkValue_flexArray2Xml($currentValueArray,TRUE);
  4564. }
  4565. }
  4566. }
  4567. break;
  4568. case 'inline':
  4569. $this->remapListedDBRecords_procInline($conf, $value, $uid, $table);
  4570. break;
  4571. default:
  4572. debug('Field type should not appear here: '. $conf['type']);
  4573. break;
  4574. }
  4575. }
  4576. if (count($newData)) { // If any fields were changed, those fields are updated!
  4577. $this->updateDB($table,$theUidToUpdate_saveTo,$newData);
  4578. }
  4579. }
  4580. }
  4581. }
  4582. }
  4583. /**
  4584. * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
  4585. *
  4586. * @param array Set of parameters in numeric array: table, uid, field
  4587. * @param array TCA config for field (from Data Structure of course)
  4588. * @param string Field value (from FlexForm XML)
  4589. * @param string Not used
  4590. * @param string Not used
  4591. * @return array Array where the "value" key carries the value.
  4592. * @see checkValue_flex_procInData_travDS(), remapListedDBRecords()
  4593. */
  4594. function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2) {
  4595. // Extract parameters:
  4596. list($table,$uid,$field) = $pParams;
  4597. // If references are set for this field, set flag so they can be corrected later:
  4598. if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
  4599. $vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid, $table);
  4600. if (is_array($vArray)) {
  4601. $dataValue = implode(',',$vArray);
  4602. }
  4603. }
  4604. // Return
  4605. return array('value' => $dataValue);
  4606. }
  4607. /**
  4608. * Performs remapping of old UID values to NEW uid values for a DB reference field.
  4609. *
  4610. * @param array TCA field config
  4611. * @param string Field value
  4612. * @param integer UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
  4613. * @param string Table name
  4614. * @return array Returns array of items ready to implode for field content.
  4615. * @see remapListedDBRecords()
  4616. */
  4617. function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table) {
  4618. // Initialize variables
  4619. $set = FALSE; // Will be set true if an upgrade should be done...
  4620. $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table']; // Allowed tables for references.
  4621. $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : ''; // Table name to prepend the UID
  4622. $dontRemapTables = t3lib_div::trimExplode(',',$conf['dontRemapTablesOnCopy'],1); // Which tables that should possibly not be remapped
  4623. // Convert value to list of references:
  4624. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4625. $dbAnalysis->registerNonTableValues = ($conf['type']=='select' && $conf['allowNonIdValues']) ? 1 : 0;
  4626. $dbAnalysis->start($value, $allowedTables, $conf['MM'], $MM_localUid, $table, $conf);
  4627. // Traverse those references and map IDs:
  4628. foreach($dbAnalysis->itemArray as $k => $v) {
  4629. $mapID = $this->copyMappingArray_merged[$v['table']][$v['id']];
  4630. if ($mapID && !in_array($v['table'],$dontRemapTables)) {
  4631. $dbAnalysis->itemArray[$k]['id'] = $mapID;
  4632. $set = TRUE;
  4633. }
  4634. }
  4635. // If a change has been done, set the new value(s)
  4636. if ($set) {
  4637. if ($conf['MM']) {
  4638. $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
  4639. } else {
  4640. $vArray = $dbAnalysis->getValueArray($prependName);
  4641. if ($conf['type']=='select') {
  4642. $vArray = $dbAnalysis->convertPosNeg($vArray, $conf['foreign_table'], $conf['neg_foreign_table']);
  4643. }
  4644. return $vArray;
  4645. }
  4646. }
  4647. }
  4648. /**
  4649. * Performs remapping of old UID values to NEW uid values for a inline field.
  4650. *
  4651. * @param array $conf: TCA field config
  4652. * @param string $value: Field value
  4653. * @param integer $uid: The uid of the ORIGINAL record
  4654. * @param string $table: Table name
  4655. * @return void
  4656. */
  4657. function remapListedDBRecords_procInline($conf, $value, $uid, $table) {
  4658. $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
  4659. if ($conf['foreign_table']) {
  4660. $inlineType = $this->getInlineFieldType($conf);
  4661. if ($inlineType == 'mm') {
  4662. $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate, $table);
  4663. } elseif ($inlineType !== false) {
  4664. $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
  4665. $dbAnalysis->start($value, $conf['foreign_table'], '', 0, $table, $conf);
  4666. // If the current field is set on a page record, update the pid of related child records:
  4667. if ($table == 'pages') {
  4668. $thePidToUpdate = $theUidToUpdate;
  4669. // If the current field has ancestors that have a field on a page record, update the pid of related child records:
  4670. } elseif (isset($this->registerDBPids[$table][$uid])) {
  4671. $thePidToUpdate = $this->registerDBPids[$table][$uid];
  4672. $thePidToUpdate = $this->copyMappingArray_merged['pages'][$thePidToUpdate];
  4673. }
  4674. // Update child records if using pointer fields ('foreign_field'):
  4675. if ($inlineType == 'field') {
  4676. $dbAnalysis->writeForeignField($conf, $uid, $theUidToUpdate);
  4677. }
  4678. // Update child records if change to pid is required:
  4679. if ($thePidToUpdate) {
  4680. $updateValues = array('pid' => $thePidToUpdate);
  4681. foreach ($dbAnalysis->itemArray as $v) {
  4682. if ($v['id'] && $v['table']) {
  4683. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($v['table'], 'uid='.intval($v['id']), $updateValues);
  4684. }
  4685. }
  4686. }
  4687. }
  4688. }
  4689. }
  4690. /**
  4691. * Processes the $this->remapStack at the end of copying, inserting, etc. actions.
  4692. * The remapStack takes care about the correct mapping of new and old uids in case of relational data.
  4693. *
  4694. * @return void
  4695. */
  4696. function processRemapStack() {
  4697. if(is_array($this->remapStack)) {
  4698. foreach($this->remapStack as $remapAction) {
  4699. // If no position index for the arguments was set, skip this remap action:
  4700. if (!is_array($remapAction['pos'])) continue;
  4701. // Load values from the argument array in remapAction:
  4702. $field = $remapAction['field'];
  4703. $id = $remapAction['args'][$remapAction['pos']['id']];
  4704. $rawId = $id;
  4705. $table = $remapAction['args'][$remapAction['pos']['table']];
  4706. $valueArray = $remapAction['args'][$remapAction['pos']['valueArray']];
  4707. $tcaFieldConf = $remapAction['args'][$remapAction['pos']['tcaFieldConf']];
  4708. // The record is new and has one or more new ids (in case of versioning/workspaces):
  4709. if(strpos($id, 'NEW') !== false) {
  4710. // Replace NEW...-ID with real uid:
  4711. $id = $this->substNEWwithIDs[$id];
  4712. // If the new parent record is on a non-live workspace or versionized, it has another new id:
  4713. if (isset($this->autoVersionIdMap[$table][$id])) {
  4714. $id = $this->autoVersionIdMap[$table][$id];
  4715. }
  4716. $remapAction['args'][$remapAction['pos']['id']] = $id;
  4717. }
  4718. // Replace relations to NEW...-IDs in field value (uids of child records):
  4719. if(is_array($valueArray)) {
  4720. $foreign_table = $tcaFieldConf['foreign_table'];
  4721. foreach($valueArray as $key => $value) {
  4722. if(strpos($value, 'NEW') !== false) {
  4723. $value = $this->substNEWwithIDs[$value];
  4724. // The record is new, but was also auto-versionized and has another new id:
  4725. if (isset($this->autoVersionIdMap[$foreign_table][$value])) {
  4726. $value = $this->autoVersionIdMap[$foreign_table][$value];
  4727. }
  4728. // Set a hint that this was a new child record:
  4729. $this->newRelatedIDs[$foreign_table][] = $value;
  4730. $valueArray[$key] = $value;
  4731. }
  4732. }
  4733. $remapAction['args'][$remapAction['pos']['valueArray']] = $valueArray;
  4734. }
  4735. // Process the arguments with the defined function:
  4736. $newValue = call_user_func_array(
  4737. array($this, $remapAction['func']),
  4738. $remapAction['args']
  4739. );
  4740. // If array is returned, check for maxitems condition, if string is returned this was already done:
  4741. if (is_array($newValue)) {
  4742. $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
  4743. }
  4744. // Update in database (list of children (csv) or number of relations (foreign_field)):
  4745. $this->updateDB($table, $id, array($field => $newValue));
  4746. // Process waiting Hook: processDatamap_afterDatabaseOperations:
  4747. if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
  4748. $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
  4749. // Update field with remapped data:
  4750. $hookArgs['fieldArray'][$field] = $newValue;
  4751. // Process waiting hook objects:
  4752. $hookObjectsArr = $hookArgs['hookObjectsArr'];
  4753. foreach($hookObjectsArr as $hookObj) {
  4754. if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
  4755. $hookObj->processDatamap_afterDatabaseOperations($hookArgs['status'], $table, $rawId, $hookArgs['fieldArray'], $this);
  4756. }
  4757. }
  4758. }
  4759. }
  4760. }
  4761. // Reset:
  4762. $this->remapStack = array();
  4763. $this->remapStackRecords = array();
  4764. }
  4765. /**
  4766. * If a parent record was versionized on a workspace in $this->process_datamap,
  4767. * it might be possible, that child records (e.g. on using IRRE) were affected.
  4768. * This function finds these relations and updates their uids in the $incomingFieldArray.
  4769. * The $incomingFieldArray is updated by reference!
  4770. *
  4771. * @param string $table: Table name of the parent record
  4772. * @param integer $id: Uid of the parent record
  4773. * @param array $incomingFieldArray: Reference to the incominfFieldArray of process_datamap
  4774. * @param array $registerDBList: Reference to the $registerDBList array that was created/updated by versionizing calls to TCEmain in process_datamap.
  4775. * @return void
  4776. */
  4777. function getVersionizedIncomingFieldArray($table, $id, &$incomingFieldArray, &$registerDBList) {
  4778. if (is_array($registerDBList[$table][$id])) {
  4779. foreach ($incomingFieldArray as $field => $value) {
  4780. $fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
  4781. if ($registerDBList[$table][$id][$field] && $foreignTable = $fieldConf['foreign_table']) {
  4782. $newValueArray = array();
  4783. $origValueArray = explode(',', $value);
  4784. // Update the uids of the copied records, but also take care about new records:
  4785. foreach ($origValueArray as $childId) {
  4786. $newValueArray[] = $this->autoVersionIdMap[$foreignTable][$childId]
  4787. ? $this->autoVersionIdMap[$foreignTable][$childId]
  4788. : $childId;
  4789. }
  4790. // Set the changed value to the $incomingFieldArray
  4791. $incomingFieldArray[$field] = implode(',', $newValueArray);
  4792. }
  4793. }
  4794. // Clean up the $registerDBList array:
  4795. unset($registerDBList[$table][$id]);
  4796. if (!count($registerDBList[$table])) unset($registerDBList[$table]);
  4797. }
  4798. }
  4799. /*****************************
  4800. *
  4801. * Access control / Checking functions
  4802. *
  4803. *****************************/
  4804. /**
  4805. * Checking group modify_table access list
  4806. *
  4807. * @param string Table name
  4808. * @return boolean Returns true if the user has general access to modify the $table
  4809. */
  4810. function checkModifyAccessList($table) {
  4811. $res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData['tables_modify'],$table)));
  4812. // Hook 'checkModifyAccessList': Post-processing of the state of access
  4813. foreach($this->getCheckModifyAccessListHookObjects() as $hookObject) {
  4814. /* @var $hookObject t3lib_TCEmain_checkModifyAccessListHook */
  4815. $hookObject->checkModifyAccessList($res, $table, $this);
  4816. }
  4817. return $res;
  4818. }
  4819. /**
  4820. * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
  4821. *
  4822. * @param string Table name
  4823. * @param integer UID of record
  4824. * @return boolean Returns true if OK. Cached results.
  4825. */
  4826. function isRecordInWebMount($table,$id) {
  4827. if (!isset($this->isRecordInWebMount_Cache[$table.':'.$id])) {
  4828. $recP=$this->getRecordProperties($table,$id);
  4829. $this->isRecordInWebMount_Cache[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
  4830. }
  4831. return $this->isRecordInWebMount_Cache[$table.':'.$id];
  4832. }
  4833. /**
  4834. * Checks if the input page ID is in the BE_USER webmounts
  4835. *
  4836. * @param integer Page ID to check
  4837. * @return boolean True if OK. Cached results.
  4838. */
  4839. function isInWebMount($pid) {
  4840. if (!isset($this->isInWebMount_Cache[$pid])) {
  4841. $this->isInWebMount_Cache[$pid]=$this->BE_USER->isInWebMount($pid);
  4842. }
  4843. return $this->isInWebMount_Cache[$pid];
  4844. }
  4845. /**
  4846. * Checks if user may update a record with uid=$id from $table
  4847. *
  4848. * @param string Record table
  4849. * @param integer Record UID
  4850. * @param array Record data
  4851. * @param array Hook objects
  4852. * @return boolean Returns true if the user may update the record given by $table and $id
  4853. */
  4854. function checkRecordUpdateAccess($table, $id, $data=false, &$hookObjectsArr = false) {
  4855. global $TCA;
  4856. $res = NULL;
  4857. if (is_array($hookObjectsArr)) {
  4858. foreach($hookObjectsArr as $hookObj) {
  4859. if (method_exists($hookObj, 'checkRecordUpdateAccess')) {
  4860. $res = $hookObj->checkRecordUpdateAccess($table, $id, $data, $res, $this);
  4861. }
  4862. }
  4863. }
  4864. if($res === 1 || $res === 0) {
  4865. return $res;
  4866. } else {
  4867. $res = 0;
  4868. }
  4869. if ($TCA[$table] && intval($id)>0) {
  4870. if (isset($this->recUpdateAccessCache[$table][$id])) { // If information is cached, return it
  4871. return $this->recUpdateAccessCache[$table][$id];
  4872. // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
  4873. } elseif ($this->doesRecordExist($table,$id,'edit')) {
  4874. $res = 1;
  4875. }
  4876. $this->recUpdateAccessCache[$table][$id]=$res; // Cache the result
  4877. }
  4878. return $res;
  4879. }
  4880. /**
  4881. * Checks if user may insert a record from $insertTable on $pid
  4882. * Does not check for workspace, use BE_USER->workspaceAllowLiveRecordsInPID for this in addition to this function call.
  4883. *
  4884. * @param string Tablename to check
  4885. * @param integer Integer PID
  4886. * @param integer For logging: Action number.
  4887. * @return boolean Returns true if the user may insert a record from table $insertTable on page $pid
  4888. */
  4889. function checkRecordInsertAccess($insertTable,$pid,$action=1) {
  4890. global $TCA;
  4891. $res = 0;
  4892. $pid = intval($pid);
  4893. if ($pid>=0) {
  4894. if (isset($this->recInsertAccessCache[$insertTable][$pid])) { // If information is cached, return it
  4895. return $this->recInsertAccessCache[$insertTable][$pid];
  4896. } else {
  4897. // If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
  4898. if ( (!$pid && $this->admin) || $this->doesRecordExist('pages',$pid,($insertTable=='pages'?$this->pMap['new']:$this->pMap['editcontent'])) ) { // Check permissions
  4899. if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
  4900. $res = 1;
  4901. $this->recInsertAccessCache[$insertTable][$pid]=$res; // Cache the result
  4902. } else {
  4903. $propArr = $this->getRecordProperties('pages',$pid);
  4904. $this->log($insertTable,$pid,$action,0,1,"Attempt to insert record on page '%s' (%s) where this table, %s, is not allowed",11,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
  4905. }
  4906. } else {
  4907. $propArr = $this->getRecordProperties('pages',$pid);
  4908. $this->log($insertTable,$pid,$action,0,1,"Attempt to insert a record on page '%s' (%s) from table '%s' without permissions. Or non-existing page.",12,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
  4909. }
  4910. }
  4911. }
  4912. return $res;
  4913. }
  4914. /**
  4915. * Checks if a table is allowed on a certain page id according to allowed tables set for the page "doktype" and its [ctrl][rootLevel]-settings if any.
  4916. *
  4917. * @param integer Page id for which to check, including 0 (zero) if checking for page tree root.
  4918. * @param string Table name to check
  4919. * @return boolean True if OK
  4920. */
  4921. function isTableAllowedForThisPage($page_uid, $checkTable) {
  4922. global $TCA, $PAGES_TYPES;
  4923. $page_uid = intval($page_uid);
  4924. // Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
  4925. if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages') {
  4926. return false;
  4927. }
  4928. // Check root-level
  4929. if (!$page_uid) {
  4930. if ($this->admin) {
  4931. return true;
  4932. }
  4933. } else {
  4934. // Check non-root-level
  4935. $doktype = $this->pageInfo($page_uid,'doktype');
  4936. $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
  4937. $allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
  4938. if (strstr($allowedTableList,'*') || in_array($checkTable,$allowedArray)) { // If all tables or the table is listed as a allowed type, return true
  4939. return true;
  4940. }
  4941. }
  4942. }
  4943. /**
  4944. * Checks if record can be selected based on given permission criteria
  4945. *
  4946. * @param string Record table name
  4947. * @param integer Record UID
  4948. * @param mixed Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array
  4949. * @return boolean Returns true if the record given by $table, $id and $perms can be selected
  4950. */
  4951. function doesRecordExist($table,$id,$perms) {
  4952. global $TCA;
  4953. if ($this->bypassAccessCheckForRecords) {
  4954. return is_array(t3lib_BEfunc::getRecordRaw($table,'uid='.intval($id),'uid'));
  4955. }
  4956. $res = 0;
  4957. $id = intval($id);
  4958. // Processing the incoming $perms (from possible string to integer that can be AND'ed)
  4959. if (!t3lib_div::testInt($perms)) {
  4960. if ($table!='pages') {
  4961. switch($perms) {
  4962. case 'edit':
  4963. case 'delete':
  4964. case 'new':
  4965. $perms = 'editcontent'; // This holds it all in case the record is not page!!
  4966. break;
  4967. }
  4968. }
  4969. $perms = intval($this->pMap[$perms]);
  4970. } else {
  4971. $perms = intval($perms);
  4972. }
  4973. if (!$perms) {
  4974. throw new RuntimeException(
  4975. 'Internal ERROR: no permissions to check for non-admin user',
  4976. 1270853920
  4977. );
  4978. }
  4979. // For all tables: Check if record exists:
  4980. if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) || $this->admin)) {
  4981. if ($table != 'pages') {
  4982. // Find record without checking page:
  4983. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid', $table, 'uid='.intval($id).$this->deleteClause($table)); // THIS SHOULD CHECK FOR editlock I think!
  4984. $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
  4985. t3lib_BEfunc::fixVersioningPid($table,$output,TRUE);
  4986. // If record found, check page as well:
  4987. if (is_array($output)) {
  4988. // Looking up the page for record:
  4989. $mres = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
  4990. $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
  4991. // Return true if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
  4992. if (is_array($pageRec) || (!$output['pid'] && $this->admin)) {
  4993. return TRUE;
  4994. }
  4995. }
  4996. return FALSE;
  4997. } else {
  4998. $mres = $this->doesRecordExist_pageLookUp($id, $perms);
  4999. return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
  5000. }
  5001. }
  5002. }
  5003. /**
  5004. * Looks up a page based on permissions.
  5005. *
  5006. * @param integer Page id
  5007. * @param integer Permission integer
  5008. * @return pointer MySQL result pointer (from exec_SELECTquery())
  5009. * @access private
  5010. * @see doesRecordExist()
  5011. */
  5012. function doesRecordExist_pageLookUp($id, $perms) {
  5013. global $TCA;
  5014. return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  5015. 'uid',
  5016. 'pages',
  5017. 'uid='.intval($id).
  5018. $this->deleteClause('pages').
  5019. ($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '').
  5020. (!$this->admin && $TCA['pages']['ctrl']['editlock'] && ($perms & (2+4+16)) ? ' AND '.$TCA['pages']['ctrl']['editlock'].'=0':'') // admin users don't need check
  5021. );
  5022. }
  5023. /**
  5024. * Checks if a whole branch of pages exists
  5025. *
  5026. * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
  5027. * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
  5028. * if $recurse is set, then the function will follow subpages. This MUST be set, if we need the idlist for deleting pages or else we get an incomplete list
  5029. *
  5030. * @param string List of page uids, this is added to and outputted in the end
  5031. * @param integer Page ID to select subpages from.
  5032. * @param integer Perms integer to check each page record for.
  5033. * @param boolean Recursion flag: If set, it will go out through the branch.
  5034. * @return string List of integers in branch
  5035. */
  5036. function doesBranchExist($inList,$pid,$perms,$recurse) {
  5037. global $TCA;
  5038. $pid = intval($pid);
  5039. $perms = intval($perms);
  5040. if ($pid>=0) {
  5041. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  5042. 'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
  5043. 'pages',
  5044. 'pid='.intval($pid).$this->deleteClause('pages'),
  5045. '',
  5046. 'sorting'
  5047. );
  5048. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  5049. if ($this->admin || $this->BE_USER->doesUserHaveAccess($row,$perms)) { // IF admin, then it's OK
  5050. $inList.=$row['uid'].',';
  5051. if ($recurse) { // Follow the subpages recursively...
  5052. $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
  5053. if ($inList == -1) {return -1;} // No permissions somewhere in the branch
  5054. }
  5055. } else {
  5056. return -1; // No permissions
  5057. }
  5058. }
  5059. $GLOBALS['TYPO3_DB']->sql_free_result($mres);
  5060. }
  5061. return $inList;
  5062. }
  5063. /**
  5064. * Checks if the $table is readOnly
  5065. *
  5066. * @param string Table name
  5067. * @return boolean True, if readonly
  5068. */
  5069. function tableReadOnly($table) {
  5070. // returns true if table is readonly
  5071. global $TCA;
  5072. return ($TCA[$table]['ctrl']['readOnly'] ? 1 : 0);
  5073. }
  5074. /**
  5075. * Checks if the $table is only editable by admin-users
  5076. *
  5077. * @param string Table name
  5078. * @return boolean True, if readonly
  5079. */
  5080. function tableAdminOnly($table) {
  5081. // returns true if table is admin-only
  5082. global $TCA;
  5083. return ($TCA[$table]['ctrl']['adminOnly'] ? 1 : 0);
  5084. }
  5085. /**
  5086. * Checks if piage $id is a uid in the rootline from page id, $dest
  5087. * Used when moving a page
  5088. *
  5089. * @param integer Destination Page ID to test
  5090. * @param integer Page ID to test for presence inside Destination
  5091. * @return boolean Returns false if ID is inside destination (including equal to)
  5092. */
  5093. function destNotInsideSelf($dest,$id) {
  5094. $loopCheck = 100;
  5095. $dest = intval($dest);
  5096. $id = intval($id);
  5097. if ($dest==$id) {
  5098. return FALSE;
  5099. }
  5100. while ($dest!=0 && $loopCheck>0) {
  5101. $loopCheck--;
  5102. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid, uid, t3ver_oid,t3ver_wsid', 'pages', 'uid='.intval($dest).$this->deleteClause('pages'));
  5103. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  5104. t3lib_BEfunc::fixVersioningPid('pages',$row);
  5105. if ($row['pid']==$id) {
  5106. return FALSE;
  5107. } else {
  5108. $dest = $row['pid'];
  5109. }
  5110. } else {
  5111. return FALSE;
  5112. }
  5113. }
  5114. return TRUE;
  5115. }
  5116. /**
  5117. * Generate an array of fields to be excluded from editing for the user. Based on "exclude"-field in TCA and a look up in non_exclude_fields
  5118. * Will also generate this list for admin-users so they must be check for before calling the function
  5119. *
  5120. * @return array Array of [table]-[field] pairs to exclude from editing.
  5121. */
  5122. function getExcludeListArray() {
  5123. $list = array();
  5124. foreach (array_keys($GLOBALS['TCA']) as $table) {
  5125. t3lib_div::loadTCA($table);
  5126. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $config) {
  5127. if ($config['exclude'] && !t3lib_div::inList($this->BE_USER->groupData['non_exclude_fields'],$table.':'.$field)) {
  5128. $list[]=$table.'-'.$field;
  5129. }
  5130. }
  5131. }
  5132. return $list;
  5133. }
  5134. /**
  5135. * Checks if there are records on a page from tables that are not allowed
  5136. *
  5137. * @param integer Page ID
  5138. * @param integer Page doktype
  5139. * @return array Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
  5140. */
  5141. function doesPageHaveUnallowedTables($page_uid,$doktype) {
  5142. global $PAGES_TYPES;
  5143. $page_uid = intval($page_uid);
  5144. if (!$page_uid) {
  5145. return FALSE; // Not a number. Probably a new page
  5146. }
  5147. $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
  5148. $allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
  5149. if (strstr($allowedTableList,'*')) { // If all tables is OK the return true
  5150. return FALSE; // OK...
  5151. }
  5152. $tableList = array();
  5153. foreach (array_keys($GLOBALS['TCA']) as $table) {
  5154. if (!in_array($table,$allowedArray)) { // If the table is not in the allowed list, check if there are records...
  5155. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', $table, 'pid=' . intval($page_uid));
  5156. if ($count) {
  5157. $tableList[]=$table;
  5158. }
  5159. }
  5160. }
  5161. return implode(',',$tableList);
  5162. }
  5163. /*****************************
  5164. *
  5165. * Information lookup
  5166. *
  5167. *****************************/
  5168. /**
  5169. * Returns the value of the $field from page $id
  5170. * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performanceloss since it doesn't look up the same record twice!
  5171. *
  5172. * @param integer Page uid
  5173. * @param string Field name for which to return value
  5174. * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
  5175. */
  5176. function pageInfo($id,$field) {
  5177. if (!isset($this->pageCache[$id])) {
  5178. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
  5179. if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
  5180. $this->pageCache[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  5181. }
  5182. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  5183. }
  5184. return $this->pageCache[$id][$field];
  5185. }
  5186. /**
  5187. * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
  5188. * NOTICE: No check for deleted or access!
  5189. *
  5190. * @param string Table name
  5191. * @param integer UID of the record from $table
  5192. * @param string Field list for the SELECT query, eg. "*" or "uid,pid,..."
  5193. * @return mixed Returns the selected record on success, otherwise false.
  5194. */
  5195. function recordInfo($table,$id,$fieldList) {
  5196. global $TCA;
  5197. if (is_array($TCA[$table])) {
  5198. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
  5199. if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
  5200. $result = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  5201. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  5202. return $result;
  5203. }
  5204. }
  5205. }
  5206. /**
  5207. * Returns an array with record properties, like header and pid
  5208. * No check for deleted or access is done!
  5209. * For versionized records, pid is resolved to its live versions pid.
  5210. * Used for loggin
  5211. *
  5212. * @param string Table name
  5213. * @param integer Uid of record
  5214. * @param boolean If set, no workspace overlay is performed
  5215. * @return array Properties of record
  5216. */
  5217. function getRecordProperties($table,$id,$noWSOL=FALSE) {
  5218. $row = ($table=='pages' && !$id) ? array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
  5219. if (!$noWSOL) {
  5220. t3lib_BEfunc::workspaceOL($table,$row);
  5221. }
  5222. return $this->getRecordPropertiesFromRow($table,$row);
  5223. }
  5224. /**
  5225. * Returns an array with record properties, like header and pid, based on the row
  5226. *
  5227. * @param string Table name
  5228. * @param array Input row
  5229. * @return array Output array
  5230. */
  5231. function getRecordPropertiesFromRow($table,$row) {
  5232. global $TCA;
  5233. if ($TCA[$table]) {
  5234. t3lib_BEfunc::fixVersioningPid($table,$row);
  5235. $out = array(
  5236. 'header' => $row[$TCA[$table]['ctrl']['label']],
  5237. 'pid' => $row['pid'],
  5238. 'event_pid' => $this->eventPid($table,isset($row['_ORIG_pid'])?$row['t3ver_oid']:$row['uid'],$row['pid']),
  5239. 't3ver_state' => $TCA[$table]['ctrl']['versioningWS'] ? $row['t3ver_state'] : '',
  5240. '_ORIG_pid' => $row['_ORIG_pid']
  5241. );
  5242. return $out;
  5243. }
  5244. }
  5245. function eventPid($table,$uid,$pid) {
  5246. return $table=='pages' ? $uid : $pid;
  5247. }
  5248. /*********************************************
  5249. *
  5250. * Storing data to Database Layer
  5251. *
  5252. ********************************************/
  5253. /**
  5254. * Update database record
  5255. * Does not check permissions but expects them to be verified on beforehand
  5256. *
  5257. * @param string Record table name
  5258. * @param integer Record uid
  5259. * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
  5260. * @return void
  5261. */
  5262. function updateDB($table,$id,$fieldArray) {
  5263. global $TCA;
  5264. if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id)) {
  5265. unset($fieldArray['uid']); // Do NOT update the UID field, ever!
  5266. if (count($fieldArray)) {
  5267. $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
  5268. // Execute the UPDATE query:
  5269. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
  5270. // If succees, do...:
  5271. if (!$GLOBALS['TYPO3_DB']->sql_error()) {
  5272. if ($this->checkStoredRecords) {
  5273. $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
  5274. }
  5275. // Update reference index:
  5276. $this->updateRefIndex($table,$id);
  5277. // Set log entry:
  5278. $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
  5279. $theLogId = $this->log($table,$id,2,$propArr['pid'],0,"Record '%s' (%s) was updated.".($propArr['_ORIG_pid']==-1?' (Offline version).':' (Online).'),10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
  5280. // Set History data:
  5281. $this->setHistory($table,$id,$theLogId);
  5282. // Clear cache for relevant pages:
  5283. $this->clear_cache($table,$id);
  5284. // Unset the pageCache for the id if table was page.
  5285. if ($table=='pages') unset($this->pageCache[$id]);
  5286. } else {
  5287. $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
  5288. }
  5289. }
  5290. }
  5291. }
  5292. /**
  5293. * Insert into database
  5294. * Does not check permissions but expects them to be verified on beforehand
  5295. *
  5296. * @param string Record table name
  5297. * @param string "NEW...." uid string
  5298. * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done. "pid" must point to the destination of the record!
  5299. * @param boolean Set to true if new version is created.
  5300. * @param integer Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
  5301. * @param boolean If true, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
  5302. * @return integer Returns ID on success.
  5303. */
  5304. function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE) {
  5305. global $TCA;
  5306. if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid'])) {
  5307. unset($fieldArray['uid']); // Do NOT insert the UID field, ever!
  5308. if (count($fieldArray)) {
  5309. // Check for "suggestedUid".
  5310. // This feature is used by the import functionality to force a new record to have a certain UID value.
  5311. // This is only recommended for use when the destination server is a passive mirrow of another server.
  5312. // As a security measure this feature is available only for Admin Users (for now)
  5313. $suggestedUid = intval($suggestedUid);
  5314. if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table.':'.$suggestedUid]) {
  5315. // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
  5316. if ($this->suggestedInsertUids[$table.':'.$suggestedUid]==='DELETE') {
  5317. // DELETE:
  5318. $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($suggestedUid));
  5319. }
  5320. $fieldArray['uid'] = $suggestedUid;
  5321. }
  5322. $fieldArray = $this->insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray);
  5323. // Execute the INSERT query:
  5324. $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
  5325. // If succees, do...:
  5326. if (!$GLOBALS['TYPO3_DB']->sql_error()) {
  5327. // Set mapping for NEW... -> real uid:
  5328. $NEW_id = $id; // the NEW_id now holds the 'NEW....' -id
  5329. $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
  5330. if (!$dontSetNewIdIndex) {
  5331. $this->substNEWwithIDs[$NEW_id] = $id;
  5332. $this->substNEWwithIDs_table[$NEW_id] = $table;
  5333. }
  5334. // Checking the record is properly saved and writing to log
  5335. if ($this->checkStoredRecords) {
  5336. $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
  5337. }
  5338. // Update reference index:
  5339. $this->updateRefIndex($table,$id);
  5340. if ($newVersion) {
  5341. $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
  5342. $this->log($table,$id,1,0,0,"New version created of table '%s', uid '%s'. UID of new version is '%s'",10,array($table,$fieldArray['t3ver_oid'],$id),$propArr['event_pid'],$NEW_id);
  5343. } else {
  5344. $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
  5345. $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
  5346. $this->log($table,$id,1,0,0,"Record '%s' (%s) was inserted on page '%s' (%s)",10,array($propArr['header'],$table.':'.$id,$page_propArr['header'],$newRow['pid']),$newRow['pid'],$NEW_id);
  5347. // Clear cache for relavant pages:
  5348. $this->clear_cache($table,$id);
  5349. }
  5350. return $id;
  5351. } else {
  5352. $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
  5353. }
  5354. }
  5355. }
  5356. }
  5357. /**
  5358. * Checking stored record to see if the written values are properly updated.
  5359. *
  5360. * @param string Record table name
  5361. * @param integer Record uid
  5362. * @param array Array of field=>value pairs to insert/update
  5363. * @param string Action, for logging only.
  5364. * @return array Selected row
  5365. * @see insertDB(), updateDB()
  5366. */
  5367. function checkStoredRecord($table,$id,$fieldArray,$action) {
  5368. global $TCA;
  5369. $id = intval($id);
  5370. if (is_array($TCA[$table]) && $id) {
  5371. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
  5372. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  5373. // Traverse array of values that was inserted into the database and compare with the actually stored value:
  5374. $errorString = array();
  5375. foreach($fieldArray as $key => $value) {
  5376. if ($this->checkStoredRecords_loose && !$value && !$row[$key]) {
  5377. // Nothing...
  5378. } elseif (strcmp($value,$row[$key])) {
  5379. $errorString[] = $key;
  5380. }
  5381. }
  5382. // Set log message if there were fields with unmatching values:
  5383. if (count($errorString)) {
  5384. $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
  5385. }
  5386. // Return selected rows:
  5387. return $row;
  5388. }
  5389. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  5390. }
  5391. }
  5392. /**
  5393. * Setting sys_history record, based on content previously set in $this->historyRecords[$table.':'.$id] (by compareFieldArrayWithCurrentAndUnset())
  5394. *
  5395. * @param string Table name
  5396. * @param integer Record ID
  5397. * @param integer Log entry ID, important for linking between log and history views
  5398. * @return void
  5399. */
  5400. function setHistory($table,$id,$logId) {
  5401. if (isset($this->historyRecords[$table.':'.$id])) {
  5402. // Initialize settings:
  5403. list($tscPID) = t3lib_BEfunc::getTSCpid($table,$id,'');
  5404. $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
  5405. $tE = $this->getTableEntries($table,$TSConfig);
  5406. $maxAgeSeconds = 60*60*24*(strcmp($tE['history.']['maxAgeDays'],'') ? t3lib_div::intInRange($tE['history.']['maxAgeDays'],0,365) : 30); // one month
  5407. // Garbage collect old entries:
  5408. $this->clearHistory($maxAgeSeconds, $table);
  5409. // Set history data:
  5410. $fields_values = array();
  5411. $fields_values['history_data'] = serialize($this->historyRecords[$table.':'.$id]);
  5412. $fields_values['fieldlist'] = implode(',',array_keys($this->historyRecords[$table.':'.$id]['newRecord']));
  5413. $fields_values['tstamp'] = $GLOBALS['EXEC_TIME'];
  5414. $fields_values['tablename'] = $table;
  5415. $fields_values['recuid'] = $id;
  5416. $fields_values['sys_log_uid'] = $logId;
  5417. $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_history', $fields_values);
  5418. }
  5419. }
  5420. /**
  5421. * Clearing sys_history table from older entries that are expired.
  5422. *
  5423. * @param integer $maxAgeSeconds (int+) however will set a max age in seconds so that any entry older than current time minus the age removed no matter what. If zero, this is not effective.
  5424. * @param string table where the history should be cleared
  5425. * @return void
  5426. */
  5427. function clearHistory($maxAgeSeconds=604800,$table) {
  5428. $tstampLimit = $maxAgeSeconds ? $GLOBALS['EXEC_TIME'] - $maxAgeSeconds : 0;
  5429. $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_history', 'tstamp<'.intval($tstampLimit).' AND tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_history'));
  5430. }
  5431. /**
  5432. * Update Reference Index (sys_refindex) for a record
  5433. * Should be called any almost any update to a record which could affect references inside the record.
  5434. *
  5435. * @param string Table name
  5436. * @param integer Record UID
  5437. * @return void
  5438. */
  5439. function updateRefIndex($table,$id) {
  5440. $refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
  5441. /* @var $refIndexObj t3lib_refindex */
  5442. $result = $refIndexObj->updateRefIndexTable($table,$id);
  5443. }
  5444. /*********************************************
  5445. *
  5446. * Misc functions
  5447. *
  5448. ********************************************/
  5449. /**
  5450. * Returning sorting number for tables with a "sortby" column
  5451. * Using when new records are created and existing records are moved around.
  5452. *
  5453. * @param string Table name
  5454. * @param integer Uid of record to find sorting number for. May be zero in case of new.
  5455. * @param integer Positioning PID, either >=0 (pointing to page in which case we find sorting number for first record in page) or <0 (pointing to record in which case to find next sorting number after this record)
  5456. * @return mixed Returns integer if PID is >=0, otherwise an array with PID and sorting number. Possibly false in case of error.
  5457. */
  5458. function getSortNumber($table,$uid,$pid) {
  5459. global $TCA;
  5460. if ($TCA[$table] && $TCA[$table]['ctrl']['sortby']) {
  5461. $sortRow = $TCA[$table]['ctrl']['sortby'];
  5462. if ($pid>=0) { // Sorting number is in the top
  5463. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'pid='.intval($pid).$this->deleteClause($table), '', $sortRow.' ASC', '1'); // Fetches the first record under this pid
  5464. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // There was an element
  5465. if ($row['uid']==$uid) { // The top record was the record it self, so we return its current sortnumber
  5466. return $row[$sortRow];
  5467. }
  5468. if ($row[$sortRow] < 1) { // If the pages sortingnumber < 1 we must resort the records under this pid
  5469. $this->resorting($table,$pid,$sortRow,0);
  5470. return $this->sortIntervals; // First sorting number after resorting
  5471. } else {
  5472. return floor($row[$sortRow]/2); // Sorting number between current top element and zero
  5473. }
  5474. } else { // No pages, so we choose the default value as sorting-number
  5475. return $this->sortIntervals; // First sorting number if no elements.
  5476. }
  5477. } else { // Sorting number is inside the list
  5478. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'uid='.abs($pid).$this->deleteClause($table)); // Fetches the record which is supposed to be the prev record
  5479. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // There was a record
  5480. // Look, if the record UID happens to be an offline record. If so, find its live version. Offline uids will be used when a page is versionized as "branch" so this is when we must correct - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
  5481. if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$row['uid'],$sortRow.',pid,uid')) {
  5482. $row = $lookForLiveVersion;
  5483. }
  5484. // If the record should be inserted after itself, keep the current sorting information:
  5485. if ($row['uid']==$uid) {
  5486. $sortNumber = $row[$sortRow];
  5487. } else {
  5488. $subres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  5489. $sortRow.',pid,uid',
  5490. $table,
  5491. 'pid='.intval($row['pid']).' AND '.$sortRow.'>='.intval($row[$sortRow]).$this->deleteClause($table),
  5492. '',
  5493. $sortRow.' ASC',
  5494. '2'
  5495. ); // Fetches the next record in order to calculate the in-between sortNumber
  5496. if ($GLOBALS['TYPO3_DB']->sql_num_rows($subres)==2) { // There was a record afterwards
  5497. $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres); // Forward to the second result...
  5498. $subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres); // There was a record afterwards
  5499. $sortNumber = $row[$sortRow]+ floor(($subrow[$sortRow]-$row[$sortRow])/2); // The sortNumber is found in between these values
  5500. if ($sortNumber<=$row[$sortRow] || $sortNumber>=$subrow[$sortRow]) { // The sortNumber happend NOT to be between the two surrounding numbers, so we'll have to resort the list
  5501. $sortNumber = $this->resorting($table,$row['pid'],$sortRow, $row['uid']); // By this special param, resorting reserves and returns the sortnumber after the uid
  5502. }
  5503. } else { // If after the last record in the list, we just add the sortInterval to the last sortvalue
  5504. $sortNumber = $row[$sortRow]+$this->sortIntervals;
  5505. }
  5506. $GLOBALS['TYPO3_DB']->sql_free_result($subres);
  5507. }
  5508. return Array('pid' => $row['pid'], 'sortNumber' => $sortNumber);
  5509. } else {
  5510. $propArr = $this->getRecordProperties($table,$uid);
  5511. $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after a non-existing record (uid=%s)",1,array($propArr['header'],$table.':'.$uid,abs($pid)),$propArr['pid']); // OK, dont insert $propArr['event_pid'] here...
  5512. return false; // There MUST be a page or else this cannot work
  5513. }
  5514. }
  5515. }
  5516. }
  5517. /**
  5518. * Resorts a table.
  5519. * Used internally by getSortNumber()
  5520. *
  5521. * @param string Table name
  5522. * @param integer Pid in which to resort records.
  5523. * @param string Sorting row
  5524. * @param integer Uid of record from $table in this $pid and for which the return value will be set to a free sorting number after that record. This is used to return a sortingValue if the list is resorted because of inserting records inside the list and not in the top
  5525. * @return integer If $return_SortNumber_After_This_Uid is set, will contain usable sorting number after that record if found (otherwise 0)
  5526. * @access private
  5527. * @see getSortNumber()
  5528. */
  5529. function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid) {
  5530. global $TCA;
  5531. if ($TCA[$table] && $sortRow && $TCA[$table]['ctrl']['sortby']==$sortRow) {
  5532. $returnVal = 0;
  5533. $intervals = $this->sortIntervals;
  5534. $i = $intervals*2;
  5535. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($pid).$this->deleteClause($table), '', $sortRow.' ASC');
  5536. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  5537. $uid=intval($row['uid']);
  5538. if ($uid) {
  5539. $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), array($sortRow=>$i));
  5540. if ($uid==$return_SortNumber_After_This_Uid) { // This is used to return a sortingValue if the list is resorted because of inserting records inside the list and not in the top
  5541. $i = $i+$intervals;
  5542. $returnVal=$i;
  5543. }
  5544. } else {die ('Fatal ERROR!! No Uid at resorting.');}
  5545. $i = $i+$intervals;
  5546. }
  5547. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  5548. return $returnVal;
  5549. }
  5550. }
  5551. /**
  5552. * Setting up perms_* fields in $fieldArray based on TSconfig input
  5553. * Used for new pages
  5554. *
  5555. * @param array Field Array, returned with modifications
  5556. * @param array TSconfig properties
  5557. * @return array Modified Field Array
  5558. */
  5559. function setTSconfigPermissions($fieldArray,$TSConfig_p) {
  5560. if (strcmp($TSConfig_p['userid'],'')) $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
  5561. if (strcmp($TSConfig_p['groupid'],'')) $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
  5562. if (strcmp($TSConfig_p['user'],'')) $fieldArray['perms_user']=t3lib_div::testInt($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
  5563. if (strcmp($TSConfig_p['group'],'')) $fieldArray['perms_group']=t3lib_div::testInt($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
  5564. if (strcmp($TSConfig_p['everybody'],'')) $fieldArray['perms_everybody']=t3lib_div::testInt($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
  5565. return $fieldArray;
  5566. }
  5567. /**
  5568. * Returns a fieldArray with default values. Values will be picked up from the TCA array looking at the config key "default" for each column. If values are set in ->defaultValues they will overrule though.
  5569. * Used for new records and during copy operations for defaults
  5570. *
  5571. * @param string Table name for which to set default values.
  5572. * @return array Array with default values.
  5573. */
  5574. function newFieldArray($table) {
  5575. t3lib_div::loadTCA($table);
  5576. $fieldArray=Array();
  5577. if (is_array($GLOBALS['TCA'][$table]['columns'])) {
  5578. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $content) {
  5579. if (isset($this->defaultValues[$table][$field])) {
  5580. $fieldArray[$field] = $this->defaultValues[$table][$field];
  5581. } elseif (isset($content['config']['default'])) {
  5582. $fieldArray[$field] = $content['config']['default'];
  5583. }
  5584. }
  5585. }
  5586. if ($table==='pages') { // Set default permissions for a page.
  5587. $fieldArray['perms_userid'] = $this->userid;
  5588. $fieldArray['perms_groupid'] = intval($this->BE_USER->firstMainGroup);
  5589. $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions['user']);
  5590. $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions['group']);
  5591. $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions['everybody']);
  5592. }
  5593. return $fieldArray;
  5594. }
  5595. /**
  5596. * If a "languageField" is specified for $table this function will add a possible value to the incoming array if none is found in there already.
  5597. *
  5598. * @param string Table name
  5599. * @param array Incoming array (passed by reference)
  5600. * @return void
  5601. */
  5602. function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray) {
  5603. global $TCA;
  5604. // Checking languages:
  5605. if ($TCA[$table]['ctrl']['languageField']) {
  5606. if (!isset($incomingFieldArray[$TCA[$table]['ctrl']['languageField']])) { // Language field must be found in input row - otherwise it does not make sense.
  5607. $rows = array_merge(array(array('uid'=>0)),$GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid','sys_language','pid=0'.t3lib_BEfunc::deleteClause('sys_language')),array(array('uid'=>-1)));
  5608. foreach($rows as $r) {
  5609. if ($this->BE_USER->checkLanguageAccess($r['uid'])) {
  5610. $incomingFieldArray[$TCA[$table]['ctrl']['languageField']] = $r['uid'];
  5611. break;
  5612. }
  5613. }
  5614. }
  5615. }
  5616. }
  5617. /**
  5618. * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
  5619. *
  5620. * @param string Table name
  5621. * @param array Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
  5622. * @return array Data array, processed.
  5623. */
  5624. function overrideFieldArray($table,$data) {
  5625. if (is_array($this->overrideValues[$table])) {
  5626. $data = array_merge($data,$this->overrideValues[$table]);
  5627. }
  5628. return $data;
  5629. }
  5630. /**
  5631. * Compares the incoming field array with the current record and unsets all fields which are the same.
  5632. * Used for existing records being updated
  5633. *
  5634. * @param string Record table name
  5635. * @param integer Record uid
  5636. * @param array Array of field=>value pairs intended to be inserted into the database. All keys with values matching exactly the current value will be unset!
  5637. * @return array Returns $fieldArray. If the returned array is empty, then the record should not be updated!
  5638. */
  5639. function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray) {
  5640. // Fetch the original record:
  5641. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
  5642. $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  5643. // If the current record exists (which it should...), begin comparison:
  5644. if (is_array($currentRecord)) {
  5645. // Read all field types:
  5646. $c = 0;
  5647. $cRecTypes = array();
  5648. foreach($currentRecord as $col => $val) {
  5649. $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
  5650. $c++;
  5651. }
  5652. // Free result:
  5653. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  5654. // Unset the fields which are similar:
  5655. foreach($fieldArray as $col => $val) {
  5656. if (
  5657. !$GLOBALS['TCA'][$table]['columns'][$col]['config']['MM'] && // Do not unset MM relation fields, since equality of the MM count doesn't always mean that relations haven't changed.
  5658. ( !strcmp($val,$currentRecord[$col]) || // Unset fields which matched exactly.
  5659. ($cRecTypes[$col]=='int' && $currentRecord[$col]==0 && !strcmp($val,'')) // Now, a situation where TYPO3 tries to put an empty string into an integer field, we should not strcmp the integer-zero and '', but rather accept them to be similar.
  5660. )
  5661. ) {
  5662. unset($fieldArray[$col]);
  5663. } else {
  5664. if (!isset($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col])) {
  5665. $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $currentRecord[$col];
  5666. } elseif ($this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col]) {
  5667. $this->historyRecords[$table . ':' . $id]['oldRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col];
  5668. }
  5669. if (!isset($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col])) {
  5670. $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $fieldArray[$col];
  5671. } elseif ($this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col] != $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$col]) {
  5672. $this->historyRecords[$table . ':' . $id]['newRecord'][$col] = $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$col];
  5673. }
  5674. }
  5675. }
  5676. } else { // If the current record does not exist this is an error anyways and we just return an empty array here.
  5677. $fieldArray = array();
  5678. }
  5679. return $fieldArray;
  5680. }
  5681. /**
  5682. * Calculates the bitvalue of the permissions given in a string, comma-sep
  5683. *
  5684. * @param string List of pMap strings
  5685. * @return integer Integer mask
  5686. * @see setTSconfigPermissions(), newFieldArray()
  5687. */
  5688. function assemblePermissions($string) {
  5689. $keyArr = t3lib_div::trimExplode(',',$string,1);
  5690. $value=0;
  5691. foreach ($keyArr as $key) {
  5692. if ($key && isset($this->pMap[$key])) {
  5693. $value |= $this->pMap[$key];
  5694. }
  5695. }
  5696. return $value;
  5697. }
  5698. /**
  5699. * Returns the $input string without a comma in the end
  5700. *
  5701. * @param string Input string
  5702. * @return string Output string with any comma in the end removed, if any.
  5703. */
  5704. function rmComma($input) {
  5705. return rtrim($input, ',');
  5706. }
  5707. /**
  5708. * Converts a HTML entity (like &#123;) to the character '123'
  5709. *
  5710. * @param string Input string
  5711. * @return string Output string
  5712. */
  5713. function convNumEntityToByteValue($input) {
  5714. $token = md5(microtime());
  5715. $parts = explode($token,preg_replace('/(&#([0-9]+);)/',$token.'\2'.$token,$input));
  5716. foreach($parts as $k => $v) {
  5717. if ($k%2) {
  5718. $v = intval($v);
  5719. if ($v > 32) { // Just to make sure that control bytes are not converted.
  5720. $parts[$k] =chr(intval($v));
  5721. }
  5722. }
  5723. }
  5724. return implode('',$parts);
  5725. }
  5726. /**
  5727. * Returns absolute destination path for the uploadfolder, $folder
  5728. *
  5729. * @param string Upload folder name, relative to PATH_site
  5730. * @return string Input string prefixed with PATH_site
  5731. */
  5732. function destPathFromUploadFolder($folder) {
  5733. return PATH_site.$folder;
  5734. }
  5735. /**
  5736. * Disables the delete clause for fetching records.
  5737. * In general only undeleted records will be used. If the delete
  5738. * clause is disabled, also deleted records are taken into account.
  5739. *
  5740. * @return void
  5741. */
  5742. public function disableDeleteClause() {
  5743. $this->disableDeleteClause = true;
  5744. }
  5745. /**
  5746. * Returns delete-clause for the $table
  5747. *
  5748. * @param string Table name
  5749. * @return string Delete clause
  5750. */
  5751. function deleteClause($table) {
  5752. // Returns the proper delete-clause if any for a table from TCA
  5753. global $TCA;
  5754. if (!$this->disableDeleteClause && $TCA[$table]['ctrl']['delete']) {
  5755. return ' AND '.$table.'.'.$TCA[$table]['ctrl']['delete'].'=0';
  5756. } else {
  5757. return '';
  5758. }
  5759. }
  5760. /**
  5761. * Return TSconfig for a page id
  5762. *
  5763. * @param integer Page id (PID) from which to get configuration.
  5764. * @return array TSconfig array, if any
  5765. */
  5766. function getTCEMAIN_TSconfig($tscPID) {
  5767. if (!isset($this->cachedTSconfig[$tscPID])) {
  5768. $this->cachedTSconfig[$tscPID] = $this->BE_USER->getTSConfig('TCEMAIN',t3lib_BEfunc::getPagesTSconfig($tscPID));
  5769. }
  5770. return $this->cachedTSconfig[$tscPID]['properties'];
  5771. }
  5772. /**
  5773. * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
  5774. *
  5775. * @param string Table name
  5776. * @param array TSconfig for page
  5777. * @return array TSconfig merged
  5778. * @see getTCEMAIN_TSconfig()
  5779. */
  5780. function getTableEntries($table,$TSconfig) {
  5781. $tA = is_array($TSconfig['table.'][$table.'.']) ? $TSconfig['table.'][$table.'.'] : array();;
  5782. $dA = is_array($TSconfig['default.']) ? $TSconfig['default.'] : array();
  5783. return t3lib_div::array_merge_recursive_overrule($dA,$tA);
  5784. }
  5785. /**
  5786. * Returns the pid of a record from $table with $uid
  5787. *
  5788. * @param string Table name
  5789. * @param integer Record uid
  5790. * @return integer PID value (unless the record did not exist in which case FALSE)
  5791. */
  5792. function getPID($table,$uid) {
  5793. $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
  5794. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
  5795. return $row['pid'];
  5796. }
  5797. }
  5798. /**
  5799. * Executing dbAnalysisStore
  5800. * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
  5801. *
  5802. * @return void
  5803. */
  5804. function dbAnalysisStoreExec() {
  5805. foreach ($this->dbAnalysisStore as $action) {
  5806. $id = t3lib_BEfunc::wsMapId(
  5807. $action[4],
  5808. (t3lib_div::testInt($action[2]) ? $action[2] : $this->substNEWwithIDs[$action[2]])
  5809. );
  5810. if ($id) {
  5811. $action[0]->writeMM($action[1], $id, $action[3]);
  5812. }
  5813. }
  5814. }
  5815. /**
  5816. * Removing files registered for removal before exit
  5817. *
  5818. * @return void
  5819. */
  5820. function removeRegisteredFiles() {
  5821. foreach ($this->removeFilesStore as $file) {
  5822. unlink($file);
  5823. }
  5824. }
  5825. /**
  5826. * Unlink (delete) typo3conf/temp_CACHED_*.php cache files
  5827. *
  5828. * @return integer The number of files deleted
  5829. */
  5830. function removeCacheFiles() {
  5831. return t3lib_extMgm::removeCacheFiles();
  5832. }
  5833. /**
  5834. * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
  5835. * Selecting ONLY pages which the user has read-access to!
  5836. *
  5837. * @param array Accumulation of page uid=>pid pairs in branch of $pid
  5838. * @param integer Page ID for which to find subpages
  5839. * @param integer Number of levels to go down.
  5840. * @param integer ID of root point for new copied branch: The idea seems to be that a copy is not made of the already new page!
  5841. * @return array Return array.
  5842. */
  5843. function int_pageTreeInfo($CPtable,$pid,$counter, $rootID) {
  5844. if ($counter) {
  5845. $addW = !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($this->pMap['show']) : '';
  5846. $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'pid='.intval($pid).$this->deleteClause('pages').$addW, '', 'sorting DESC');
  5847. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
  5848. if ($row['uid']!=$rootID) {
  5849. $CPtable[$row['uid']] = $pid;
  5850. if ($counter-1) { // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
  5851. $CPtable = $this->int_pageTreeInfo($CPtable,$row['uid'],$counter-1, $rootID);
  5852. }
  5853. }
  5854. }
  5855. $GLOBALS['TYPO3_DB']->sql_free_result($mres);
  5856. }
  5857. return $CPtable;
  5858. }
  5859. /**
  5860. * List of all tables (those administrators has access to = array_keys of $TCA)
  5861. *
  5862. * @return array Array of all TCA table names
  5863. */
  5864. function compileAdminTables() {
  5865. return array_keys($GLOBALS['TCA']);
  5866. }
  5867. /**
  5868. * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
  5869. *
  5870. * @param string Table name
  5871. * @param integer Record UID
  5872. * @return void
  5873. */
  5874. function fixUniqueInPid($table,$uid) {
  5875. if ($GLOBALS['TCA'][$table]) {
  5876. t3lib_div::loadTCA($table);
  5877. $curData=$this->recordInfo($table,$uid,'*');
  5878. $newData=array();
  5879. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
  5880. if ($conf['config']['type']=='input') {
  5881. $evalCodesArray = t3lib_div::trimExplode(',',$conf['config']['eval'],1);
  5882. if (in_array('uniqueInPid',$evalCodesArray)) {
  5883. $newV = $this->getUnique($table,$field,$curData[$field],$uid,$curData['pid']);
  5884. if (strcmp($newV,$curData[$field])) {
  5885. $newData[$field]=$newV;
  5886. }
  5887. }
  5888. }
  5889. }
  5890. // IF there are changed fields, then update the database
  5891. if (count($newData)) {
  5892. $this->updateDB($table,$uid,$newData);
  5893. }
  5894. }
  5895. }
  5896. /**
  5897. * When er record is copied you can specify fields from the previous record which should be copied into the new one
  5898. * This function is also called with new elements. But then $update must be set to zero and $newData containing the data array. In that case data in the incoming array is NOT overridden. (250202)
  5899. *
  5900. * @param string Table name
  5901. * @param integer Record UID
  5902. * @param integer UID of previous record
  5903. * @param boolean If set, updates the record
  5904. * @param array Input array. If fields are already specified AND $update is not set, values are not set in output array.
  5905. * @return array Output array (For when the copying operation needs to get the information instead of updating the info)
  5906. */
  5907. function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array()) {
  5908. global $TCA;
  5909. if ($TCA[$table] && $TCA[$table]['ctrl']['copyAfterDuplFields']) {
  5910. t3lib_div::loadTCA($table);
  5911. $prevData=$this->recordInfo($table,$prevUid,'*');
  5912. $theFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['copyAfterDuplFields'],1);
  5913. foreach ($theFields as $field) {
  5914. if ($TCA[$table]['columns'][$field] && ($update || !isset($newData[$field]))) {
  5915. $newData[$field]=$prevData[$field];
  5916. }
  5917. }
  5918. if ($update && count($newData)) {
  5919. $this->updateDB($table,$uid,$newData);
  5920. }
  5921. }
  5922. return $newData;
  5923. }
  5924. /**
  5925. * Returns all fieldnames from a table which are a list of files
  5926. *
  5927. * @param string Table name
  5928. * @return array Array of fieldnames that are either "group" or "file" types.
  5929. */
  5930. function extFileFields($table) {
  5931. $listArr=array();
  5932. t3lib_div::loadTCA($table);
  5933. if (isset($GLOBALS['TCA'][$table]['columns'])) {
  5934. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $configArr) {
  5935. if ($configArr['config']['type'] == 'group' &&
  5936. ($configArr['config']['internal_type'] == 'file' ||
  5937. $configArr['config']['internal_type'] == 'file_reference')) {
  5938. $listArr[] = $field;
  5939. }
  5940. }
  5941. }
  5942. return $listArr;
  5943. }
  5944. /**
  5945. * Returns all fieldnames from a table which have the unique evaluation type set.
  5946. *
  5947. * @param string Table name
  5948. * @return array Array of fieldnames
  5949. */
  5950. function getUniqueFields($table) {
  5951. $listArr=array();
  5952. t3lib_div::loadTCA($table);
  5953. if ($GLOBALS['TCA'][$table]['columns']) {
  5954. foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $configArr) {
  5955. if ($configArr['config']['type']==='input') {
  5956. $evalCodesArray = t3lib_div::trimExplode(',',$configArr['config']['eval'],1);
  5957. if (in_array('uniqueInPid',$evalCodesArray) || in_array('unique',$evalCodesArray)) {
  5958. $listArr[]=$field;
  5959. }
  5960. }
  5961. }
  5962. }
  5963. return $listArr;
  5964. }
  5965. /**
  5966. * Returns true if the TCA/columns field type is a DB reference field
  5967. *
  5968. * @param array config array for TCA/columns field
  5969. * @return boolean True if DB reference field (group/db or select with foreign-table)
  5970. */
  5971. function isReferenceField($conf) {
  5972. return ($conf['type']=='group' && $conf['internal_type']=='db' || $conf['type']=='select' && $conf['foreign_table']);
  5973. }
  5974. /**
  5975. * Returns the subtype as a string of an inline field.
  5976. * If it's not a inline field at all, it returns false.
  5977. *
  5978. * @param array config array for TCA/columns field
  5979. * @return mixed string: inline subtype (field|mm|list), boolean: false
  5980. */
  5981. function getInlineFieldType($conf) {
  5982. if ($conf['type'] == 'inline' && $conf['foreign_table']) {
  5983. if ($conf['foreign_field'])
  5984. return 'field'; // the reference to the parent is stored in a pointer field in the child record
  5985. elseif ($conf['MM'])
  5986. return 'mm'; // regular MM intermediate table is used to store data
  5987. else
  5988. return 'list'; // an item list (separated by comma) is stored (like select type is doing)
  5989. }
  5990. return false;
  5991. }
  5992. /**
  5993. * Get modified header for a copied record
  5994. *
  5995. * @param string Table name
  5996. * @param integer PID value in which other records to test might be
  5997. * @param string Field name to get header value for.
  5998. * @param string Current field value
  5999. * @param integer Counter (number of recursions)
  6000. * @param string Previous title we checked for (in previous recursion)
  6001. * @return string The field value, possibly appended with a "copy label"
  6002. */
  6003. function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='') {
  6004. global $TCA;
  6005. // Set title value to check for:
  6006. if ($count) {
  6007. $checkTitle = $value.rtrim(' '.sprintf($this->prependLabel($table),$count));
  6008. } else {
  6009. $checkTitle = $value;
  6010. }
  6011. // Do check:
  6012. if ($prevTitle != $checkTitle || $count<100) {
  6013. $rowCount = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  6014. 'uid',
  6015. $table,
  6016. 'pid=' . intval($pid) .
  6017. ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($checkTitle, $table) .
  6018. $this->deleteClause($table)
  6019. );
  6020. if ($rowCount) {
  6021. return $this->getCopyHeader($table,$pid,$field,$value,$count+1,$checkTitle);
  6022. }
  6023. }
  6024. // Default is to just return the current input title if no other was returned before:
  6025. return $checkTitle;
  6026. }
  6027. /**
  6028. * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
  6029. *
  6030. * @param string Table name
  6031. * @return string Label to append, containing "%s" for the number
  6032. * @see getCopyHeader()
  6033. */
  6034. function prependLabel($table) {
  6035. global $TCA;
  6036. if (is_object($GLOBALS['LANG'])) {
  6037. $label = $GLOBALS['LANG']->sL($TCA[$table]['ctrl']['prependAtCopy']);
  6038. } else {
  6039. list($label) = explode('|',$TCA[$table]['ctrl']['prependAtCopy']);
  6040. }
  6041. return $label;
  6042. }
  6043. /**
  6044. * Get the final pid based on $table and $pid ($destPid type... pos/neg)
  6045. *
  6046. * @param string Table name
  6047. * @param integer "Destination pid" : If the value is >= 0 it's just returned directly (through intval() though) but if the value is <0 then the method looks up the record with the uid equal to abs($pid) (positive number) and returns the PID of that record! The idea is that negative numbers point to the record AFTER WHICH the position is supposed to be!
  6048. * @return integer
  6049. */
  6050. function resolvePid($table,$pid) {
  6051. global $TCA;
  6052. $pid = intval($pid);
  6053. if ($pid < 0) {
  6054. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.abs($pid));
  6055. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  6056. // Look, if the record UID happens to be an offline record. If so, find its live version. Offline uids will be used when a page is versionized as "branch" so this is when we must correct - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
  6057. if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,abs($pid),'pid')) {
  6058. $row = $lookForLiveVersion;
  6059. }
  6060. $pid = intval($row['pid']);
  6061. } elseif ($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.
  6062. if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid, 'uid,t3ver_swapmode')) { // Looks for workspace version of page.
  6063. if ($WSdestPage['t3ver_swapmode']==0) { // if swapmode is zero, then change pid value.
  6064. $pid = $WSdestPage['uid'];
  6065. }
  6066. }
  6067. }
  6068. return $pid;
  6069. }
  6070. /**
  6071. * Removes the prependAtCopy prefix on values
  6072. *
  6073. * @param string Table name
  6074. * @param string The value to fix
  6075. * @return string Clean name
  6076. */
  6077. function clearPrefixFromValue($table,$value) {
  6078. global $TCA;
  6079. $regex = '/'.sprintf(quotemeta($this->prependLabel($table)),'[0-9]*').'$/';
  6080. return @preg_replace($regex,'',$value);
  6081. }
  6082. /**
  6083. * File functions on external file references. eg. deleting files when deleting record
  6084. *
  6085. * @param string Table name
  6086. * @param string Field name
  6087. * @param string List of files to work on from field
  6088. * @param string Function, eg. "deleteAll" which will delete all files listed.
  6089. * @return void
  6090. */
  6091. function extFileFunctions($table,$field,$filelist,$func) {
  6092. global $TCA;
  6093. t3lib_div::loadTCA($table);
  6094. $uploadFolder = $TCA[$table]['columns'][$field]['config']['uploadfolder'];
  6095. if ($uploadFolder && trim($filelist) && $TCA[$table]['columns'][$field]['config']['internal_type'] == 'file') {
  6096. $uploadPath = $this->destPathFromUploadFolder($uploadFolder);
  6097. $fileArray = explode(',',$filelist);
  6098. foreach ($fileArray as $theFile) {
  6099. $theFile=trim($theFile);
  6100. if ($theFile) {
  6101. switch($func) {
  6102. case 'deleteAll':
  6103. if (@is_file($uploadPath.'/'.$theFile)) {
  6104. unlink ($uploadPath.'/'.$theFile);
  6105. } else {
  6106. $this->log($table,0,3,0,100,"Delete: Referenced file that was supposed to be deleted together with it's record didn't exist");
  6107. }
  6108. break;
  6109. }
  6110. }
  6111. }
  6112. }
  6113. }
  6114. /**
  6115. * Used by the deleteFunctions to check if there are records from disallowed tables under the pages to be deleted.
  6116. *
  6117. * @param string List of page integers
  6118. * @return boolean Return true, if permission granted
  6119. */
  6120. function noRecordsFromUnallowedTables($inList) {
  6121. $inList = trim($this->rmComma(trim($inList)));
  6122. if ($inList && !$this->admin) {
  6123. foreach (array_keys($GLOBALS['TCA']) as $table) {
  6124. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  6125. 'uid',
  6126. $table,
  6127. 'pid IN (' . $inList . ')' . t3lib_BEfunc::deleteClause($table)
  6128. );
  6129. if ($count && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table))) {
  6130. return FALSE;
  6131. }
  6132. }
  6133. }
  6134. return TRUE;
  6135. }
  6136. /**
  6137. * Send an email notification to users in workspace
  6138. *
  6139. * @param array Workspace access array (from t3lib_userauthgroup::checkWorkspace())
  6140. * @param integer New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
  6141. * @param string Table name of element (or list of element names if $id is zero)
  6142. * @param integer Record uid of element (if zero, then $table is used as reference to element(s) alone)
  6143. * @param string User comment sent along with action
  6144. * @return void
  6145. */
  6146. function notifyStageChange($stat,$stageId,$table,$id,$comment) {
  6147. $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
  6148. $elementName = $id ? $table.':'.$id : $table; // So, if $id is not set, then $table is taken to be the complete element name!
  6149. if (is_array($workspaceRec)) {
  6150. // Compile label:
  6151. switch((int)$stageId) {
  6152. case 1:
  6153. $newStage = 'Ready for review';
  6154. break;
  6155. case 10:
  6156. $newStage = 'Ready for publishing';
  6157. break;
  6158. case -1:
  6159. $newStage = 'Element was rejected!';
  6160. break;
  6161. case 0:
  6162. $newStage = 'Rejected element was noticed and edited';
  6163. break;
  6164. default:
  6165. $newStage = 'Unknown state change!?';
  6166. break;
  6167. }
  6168. // Compile list of recipients:
  6169. $emails = array();
  6170. switch((int)$stat['stagechg_notification']) {
  6171. case 1:
  6172. switch((int)$stageId) {
  6173. case 1:
  6174. $emails = $this->notifyStageChange_getEmails($workspaceRec['reviewers']);
  6175. break;
  6176. case 10:
  6177. $emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
  6178. break;
  6179. case -1:
  6180. # $emails = $this->notifyStageChange_getEmails($workspaceRec['reviewers']);
  6181. # $emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['members']));
  6182. // List of elements to reject:
  6183. $allElements = explode(',',$elementName);
  6184. // Traverse them, and find the history of each
  6185. foreach($allElements as $elRef) {
  6186. list($eTable,$eUid) = explode(':',$elRef);
  6187. $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
  6188. 'log_data,tstamp,userid',
  6189. 'sys_log',
  6190. 'action=6 and details_nr=30
  6191. AND tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($eTable,'sys_log').'
  6192. AND recuid='.intval($eUid),
  6193. '',
  6194. 'uid DESC'
  6195. );
  6196. // Find all implicated since the last stage-raise from editing to review:
  6197. foreach($rows as $dat) {
  6198. $data = unserialize($dat['log_data']);
  6199. //debug($dat['userid'],'Adds user at stage: '.$data['stage']);
  6200. $emails = array_merge($emails,$this->notifyStageChange_getEmails($dat['userid'],TRUE));
  6201. if ($data['stage']==1) {
  6202. break;
  6203. }
  6204. }
  6205. }
  6206. break;
  6207. case 0:
  6208. $emails = $this->notifyStageChange_getEmails($workspaceRec['members']);
  6209. break;
  6210. default:
  6211. $emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
  6212. break;
  6213. }
  6214. break;
  6215. case 10:
  6216. $emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
  6217. $emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['reviewers']));
  6218. $emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['members']));
  6219. break;
  6220. }
  6221. $emails = array_unique($emails);
  6222. // Path to record is found:
  6223. list($eTable,$eUid) = explode(':',$elementName);
  6224. $eUid = intval($eUid);
  6225. $rr = t3lib_BEfunc::getRecord($eTable,$eUid);
  6226. $recTitle = t3lib_BEfunc::getRecordTitle($eTable,$rr);
  6227. if ($eTable!='pages') {
  6228. t3lib_BEfunc::fixVersioningPid($eTable,$rr);
  6229. $eUid=$rr['pid'];
  6230. }
  6231. $path = t3lib_BEfunc::getRecordPath($eUid,'',20);
  6232. // ALternative messages:
  6233. $TSConfig = $this->getTCEMAIN_TSconfig($eUid);
  6234. $body = trim($TSConfig['notificationEmail_body']) ? trim($TSConfig['notificationEmail_body']) : '
  6235. At the TYPO3 site "%s" (%s)
  6236. in workspace "%s" (#%s)
  6237. the stage has changed for the element(s) "%11$s" (%s) at location "%10$s" in the page tree:
  6238. ==> %s
  6239. User Comment:
  6240. "%s"
  6241. State was change by %s (username: %s)
  6242. ';
  6243. $subject = trim($TSConfig['notificationEmail_subject']) ? trim($TSConfig['notificationEmail_subject']) : 'TYPO3 Workspace Note: Stage Change for %s';
  6244. // Send email:
  6245. if (count($emails)) {
  6246. $message = sprintf($body,
  6247. $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
  6248. t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir,
  6249. $workspaceRec['title'],
  6250. $workspaceRec['uid'],
  6251. $elementName,
  6252. $newStage,
  6253. $comment,
  6254. $this->BE_USER->user['realName'],
  6255. $this->BE_USER->user['username'],
  6256. $path,
  6257. $recTitle);
  6258. t3lib_div::plainMailEncoded(
  6259. implode(',',$emails),
  6260. sprintf($subject,$elementName),
  6261. trim($message)
  6262. );
  6263. $this->newlog2('Notification email for stage change was sent to "'.implode(', ',$emails).'"',$table,$id);
  6264. }
  6265. }
  6266. }
  6267. /**
  6268. * Return emails addresses of be_users from input list.
  6269. *
  6270. * @param string List of backend users, on the form "be_users_10,be_users_2" or "10,2" in case noTablePrefix is set.
  6271. * @param boolean If set, the input list are integers and not strings.
  6272. * @return array Array of emails
  6273. */
  6274. function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE) {
  6275. $users = t3lib_div::trimExplode(',',$listOfUsers,1);
  6276. $emails = array();
  6277. foreach($users as $userIdent) {
  6278. if ($noTablePrefix) {
  6279. $id = intval($userIdent);
  6280. } else {
  6281. list($table,$id) = t3lib_div::revExplode('_',$userIdent,2);
  6282. }
  6283. if ($table==='be_users' || $noTablePrefix) {
  6284. if ($userRecord = t3lib_BEfunc::getRecord('be_users', $id, 'email')) {
  6285. if (strlen(trim($userRecord['email']))) {
  6286. $emails[$id] = $userRecord['email'];
  6287. }
  6288. }
  6289. }
  6290. }
  6291. return $emails;
  6292. }
  6293. /**
  6294. * Determine if a record was copied or if a record is the result of a copy action.
  6295. *
  6296. * @param string $table: The tablename of the record
  6297. * @param integer $uid: The uid of the record
  6298. * @return boolean Returns true if the record is copied or is the result of a copy action
  6299. */
  6300. function isRecordCopied($table, $uid) {
  6301. // If the record was copied:
  6302. if (isset($this->copyMappingArray[$table][$uid])) {
  6303. return true;
  6304. // If the record is the result of a copy action:
  6305. } elseif (isset($this->copyMappingArray[$table]) && in_array($uid, array_values($this->copyMappingArray[$table]))) {
  6306. return true;
  6307. }
  6308. return false;
  6309. }
  6310. /******************************
  6311. *
  6312. * Clearing cache
  6313. *
  6314. ******************************/
  6315. /**
  6316. * Clearing the cache based on a page being updated
  6317. * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
  6318. * Else just clear the cache for the parent page of the record.
  6319. *
  6320. * @param string Table name of record that was just updated.
  6321. * @param integer UID of updated / inserted record
  6322. * @return void
  6323. */
  6324. function clear_cache($table,$uid) {
  6325. global $TCA, $TYPO3_CONF_VARS;
  6326. $uid = intval($uid);
  6327. $pageUid = 0;
  6328. if (is_array($TCA[$table]) && $uid > 0) {
  6329. // Get Page TSconfig relavant:
  6330. list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
  6331. $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
  6332. if (!$TSConfig['clearCache_disable']) {
  6333. // If table is "pages":
  6334. if (t3lib_extMgm::isLoaded('cms')) {
  6335. $list_cache = array();
  6336. if ($table === 'pages' || $table === 'pages_language_overlay') {
  6337. if($table === 'pages_language_overlay') {
  6338. $pageUid = $this->getPID($table,$uid);
  6339. } else {
  6340. $pageUid = $uid;
  6341. }
  6342. // Builds list of pages on the SAME level as this page (siblings)
  6343. $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  6344. 'A.pid AS pid, B.uid AS uid',
  6345. 'pages A, pages B',
  6346. 'A.uid='.intval($pageUid).' AND B.pid=A.pid AND B.deleted=0'
  6347. );
  6348. $pid_tmp = 0;
  6349. while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
  6350. $list_cache[] = $row_tmp['uid'];
  6351. $pid_tmp = $row_tmp['pid'];
  6352. // Add children as well:
  6353. if ($TSConfig['clearCache_pageSiblingChildren']) {
  6354. $res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  6355. 'uid',
  6356. 'pages',
  6357. 'pid='.intval($row_tmp['uid']).' AND deleted=0'
  6358. );
  6359. while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2)) {
  6360. $list_cache[] = $row_tmp2['uid'];
  6361. }
  6362. $GLOBALS['TYPO3_DB']->sql_free_result($res_tmp2);
  6363. }
  6364. }
  6365. $GLOBALS['TYPO3_DB']->sql_free_result($res_tmp);
  6366. // Finally, add the parent page as well:
  6367. $list_cache[] = $pid_tmp;
  6368. // Add grand-parent as well:
  6369. if ($TSConfig['clearCache_pageGrandParent']) {
  6370. $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  6371. 'pid',
  6372. 'pages',
  6373. 'uid='.intval($pid_tmp)
  6374. );
  6375. if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
  6376. $list_cache[] = $row_tmp['pid'];
  6377. }
  6378. }
  6379. } else { // For other tables than "pages", delete cache for the records "parent page".
  6380. $list_cache[] = $pageUid = intval($this->getPID($table,$uid));
  6381. }
  6382. // Call pre-processing function for clearing of cache for page ids:
  6383. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'])) {
  6384. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName) {
  6385. $_params = array('pageIdArray' => &$list_cache, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()');
  6386. // Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
  6387. t3lib_div::callUserFunction($funcName,$_params,$this);
  6388. }
  6389. }
  6390. // Delete cache for selected pages:
  6391. if (is_array($list_cache)) {
  6392. if (TYPO3_UseCachingFramework) {
  6393. $pageCache = $GLOBALS['typo3CacheManager']->getCache(
  6394. 'cache_pages'
  6395. );
  6396. $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache(
  6397. 'cache_pagesection'
  6398. );
  6399. $pageIds = $GLOBALS['TYPO3_DB']->cleanIntArray($list_cache);
  6400. foreach ($pageIds as $pageId) {
  6401. $pageCache->flushByTag('pageId_' . $pageId);
  6402. $pageSectionCache->flushByTag('pageId_' . $pageId);
  6403. }
  6404. } else {
  6405. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
  6406. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
  6407. }
  6408. }
  6409. }
  6410. }
  6411. // Clear cache for pages entered in TSconfig:
  6412. if ($TSConfig['clearCacheCmd']) {
  6413. $Commands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
  6414. $Commands = array_unique($Commands);
  6415. foreach($Commands as $cmdPart) {
  6416. $this->clear_cacheCmd($cmdPart);
  6417. }
  6418. }
  6419. // Call post processing function for clear-cache:
  6420. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
  6421. $_params = array('table' => $table,'uid' => $uid,'uid_page' => $pageUid,'TSConfig' => $TSConfig);
  6422. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
  6423. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  6424. }
  6425. }
  6426. }
  6427. }
  6428. /**
  6429. * Clears the cache based on the command $cacheCmd.
  6430. *
  6431. * $cacheCmd='pages': Clears cache for all pages. Requires admin-flag to
  6432. * be set for BE_USER.
  6433. *
  6434. * $cacheCmd='all': Clears all cache_tables. This is necessary if
  6435. * templates are updated. Requires admin-flag to be set for BE_USER.
  6436. *
  6437. * $cacheCmd=[integer]: Clears cache for the page pointed to by $cacheCmd
  6438. * (an integer).
  6439. *
  6440. * Can call a list of post processing functions as defined in
  6441. * $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']
  6442. * (numeric array with values being the function references, called by
  6443. * t3lib_div::callUserFunction()).
  6444. *
  6445. * Note: The following cache_* are intentionally not cleared by
  6446. * $cacheCmd='all':
  6447. *
  6448. * - cache_md5params: Clearing this table would destroy all simulateStatic
  6449. * URLs, simulates file name and RDCT redirects.
  6450. * - cache_imagesizes: Clearing this table would cause a lot of unneeded
  6451. * Imagemagick calls because the size informations have
  6452. * to be fetched again after clearing.
  6453. * - cache_extensions: Clearing this table would make the extension manager
  6454. * unusable until a new extension list is fetched from
  6455. * the TER.
  6456. *
  6457. * @param string the cache command, see above description
  6458. * @return void
  6459. */
  6460. public function clear_cacheCmd($cacheCmd) {
  6461. global $TYPO3_CONF_VARS;
  6462. // Clear cache for either ALL pages or ALL tables!
  6463. switch($cacheCmd) {
  6464. case 'pages':
  6465. if ($this->admin || $this->BE_USER->getTSConfigVal('options.clearCache.pages')) {
  6466. $this->internal_clearPageCache();
  6467. }
  6468. break;
  6469. case 'all':
  6470. if ($this->admin || $this->BE_USER->getTSConfigVal('options.clearCache.all')) {
  6471. // Clear all caching framework caches if it is initialized:
  6472. // (it could be disabled by initialized by an extension)
  6473. if (t3lib_cache::isCachingFrameworkInitialized()) {
  6474. $GLOBALS['typo3CacheManager']->flushCaches();
  6475. }
  6476. if (TYPO3_UseCachingFramework) {
  6477. if (t3lib_extMgm::isLoaded('cms')) {
  6478. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('cache_treelist');
  6479. }
  6480. } else {
  6481. if (t3lib_extMgm::isLoaded('cms')) {
  6482. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('cache_treelist');
  6483. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('cache_pagesection');
  6484. }
  6485. $this->internal_clearPageCache();
  6486. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('cache_hash');
  6487. }
  6488. // Clearing additional cache tables:
  6489. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearAllCache_additionalTables'])) {
  6490. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearAllCache_additionalTables'] as $tableName) {
  6491. if (!preg_match('/[^[:alnum:]_]/',$tableName) && substr($tableName,-5)=='cache') {
  6492. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery($tableName);
  6493. } else {
  6494. throw new RuntimeException(
  6495. 'TYPO3 Fatal Error: Trying to flush table "' . $tableName . '" with "Clear All Cache"',
  6496. 1270853922
  6497. );
  6498. }
  6499. }
  6500. }
  6501. }
  6502. if ($this->admin && $TYPO3_CONF_VARS['EXT']['extCache']) {
  6503. $this->removeCacheFiles();
  6504. }
  6505. break;
  6506. case 'temp_CACHED':
  6507. if ($this->admin && $TYPO3_CONF_VARS['EXT']['extCache']) {
  6508. $this->removeCacheFiles();
  6509. }
  6510. break;
  6511. }
  6512. // Clear cache for a page ID!
  6513. if (t3lib_div::testInt($cacheCmd)) {
  6514. if (t3lib_extMgm::isLoaded('cms')) {
  6515. $list_cache = array($cacheCmd);
  6516. // Call pre-processing function for clearing of cache for page ids:
  6517. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'])) {
  6518. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName) {
  6519. $_params = array('pageIdArray' => &$list_cache, 'cacheCmd' => $cacheCmd, 'functionID' => 'clear_cacheCmd()');
  6520. // Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
  6521. t3lib_div::callUserFunction($funcName,$_params,$this);
  6522. }
  6523. }
  6524. // Delete cache for selected pages:
  6525. if (is_array($list_cache)) {
  6526. if (TYPO3_UseCachingFramework) {
  6527. $pageCache = $GLOBALS['typo3CacheManager']->getCache(
  6528. 'cache_pages'
  6529. );
  6530. $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache(
  6531. 'cache_pagesection'
  6532. );
  6533. foreach ($list_cache as $pageId) {
  6534. $pageCache->flushByTag('pageId_' . (int) $pageId);
  6535. $pageSectionCache->flushByTag('pageId_' . (int) $pageId);
  6536. }
  6537. } else {
  6538. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
  6539. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')'); // Originally, cache_pagesection was not cleared with cache_pages!
  6540. }
  6541. }
  6542. }
  6543. }
  6544. // Call post processing function for clear-cache:
  6545. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
  6546. $_params = array('cacheCmd'=>$cacheCmd);
  6547. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
  6548. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  6549. }
  6550. }
  6551. }
  6552. /*****************************
  6553. *
  6554. * Logging
  6555. *
  6556. *****************************/
  6557. /**
  6558. * Logging actions from TCEmain
  6559. *
  6560. * @param string Table name the log entry is concerned with. Blank if NA
  6561. * @param integer Record UID. Zero if NA
  6562. * @param integer Action number: 0=No category, 1=new record, 2=update record, 3= delete record, 4= move record, 5= Check/evaluate
  6563. * @param integer Normally 0 (zero). If set, it indicates that this log-entry is used to notify the backend of a record which is moved to another location
  6564. * @param integer The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin)
  6565. * @param string Default error message in english
  6566. * @param integer This number is unique for every combination of $type and $action. This is the error-message number, which can later be used to translate error messages. 0 if not categorized, -1 if temporary
  6567. * @param array Array with special information that may go into $details by '%s' marks / sprintf() when the log is shown
  6568. * @param integer The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
  6569. * @param string NEW id for new records
  6570. * @return integer Log entry UID
  6571. * @see class.t3lib_userauthgroup.php
  6572. */
  6573. function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='') {
  6574. if ($this->enableLogging) {
  6575. $type=1; // Type value for tce_db.php
  6576. if (!$this->storeLogMessages) {$details='';}
  6577. if ($error>0) $this->errorLog[] = '['.$type.'.'.$action.'.'.$details_nr.']: '.$details;
  6578. return $this->BE_USER->writelog($type,$action,$error,$details_nr,$details,$data,$table,$recuid,$recpid,$event_pid,$NEWid);
  6579. }
  6580. }
  6581. /**
  6582. * Simple logging function meant to be used when logging messages is not yet fixed.
  6583. *
  6584. * @param string Message string
  6585. * @param integer Error code, see log()
  6586. * @return integer Log entry UID
  6587. * @see log()
  6588. */
  6589. function newlog($message, $error=0) {
  6590. return $this->log('',0,0,0,$error,'[newlog()] '.$message,-1);
  6591. }
  6592. /**
  6593. * Simple logging function meant to bridge the gap between newlog() and log() with a littme more info, in particular the record table/uid and event_pid so we can filter messages pr page.
  6594. *
  6595. * @param string Message string
  6596. * @param string Table name
  6597. * @param integer Record uid
  6598. * @param integer Record PID (from page tree). Will be turned into an event_pid internally in function: Meaning that the PID for a page will be its own UID, not its page tree PID.
  6599. * @param integer Error code, see log()
  6600. * @return integer Log entry UID
  6601. * @see log()
  6602. */
  6603. function newlog2($message,$table,$uid,$pid=FALSE,$error=0) {
  6604. if ($pid===FALSE) {
  6605. $propArr = $this->getRecordProperties($table, $uid);
  6606. $pid = $propArr['pid'];
  6607. }
  6608. return $this->log($table,$uid,0,0,$error,$message,-1,array(),$this->eventPid($table,$uid,$pid));
  6609. }
  6610. /**
  6611. * Print log error messages from the operations of this script instance
  6612. *
  6613. * @param string Redirect URL (for creating link in message)
  6614. * @return void (Will exit on error)
  6615. */
  6616. function printLogErrorMessages($redirect) {
  6617. $res_log = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  6618. '*',
  6619. 'sys_log',
  6620. 'type=1 AND userid='.intval($this->BE_USER->user['uid']).' AND tstamp='.intval($GLOBALS['EXEC_TIME']).' AND error!=0'
  6621. );
  6622. while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_log)) {
  6623. $log_data = unserialize($row['log_data']);
  6624. $msg = $row['error'] . ': ' . sprintf($row['details'], $log_data[0], $log_data[1], $log_data[2], $log_data[3], $log_data[4]);
  6625. $flashMessage = t3lib_div::makeInstance(
  6626. 't3lib_FlashMessage',
  6627. $msg,
  6628. '',
  6629. t3lib_FlashMessage::ERROR,
  6630. TRUE
  6631. );
  6632. t3lib_FlashMessageQueue::addMessage($flashMessage);
  6633. }
  6634. $GLOBALS['TYPO3_DB']->sql_free_result($res_log);
  6635. }
  6636. /*****************************
  6637. *
  6638. * Internal (do not use outside Core!)
  6639. *
  6640. *****************************/
  6641. /**
  6642. * Clears page cache. Takes into account file cache.
  6643. *
  6644. * @return void
  6645. */
  6646. function internal_clearPageCache() {
  6647. if (TYPO3_UseCachingFramework) {
  6648. if (t3lib_extMgm::isLoaded('cms')) {
  6649. $GLOBALS['typo3CacheManager']->getCache('cache_pages')->flush();
  6650. }
  6651. } else {
  6652. if (t3lib_extMgm::isLoaded('cms')) {
  6653. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageCacheToExternalFiles']) {
  6654. $cacheDir = PATH_site.'typo3temp/cache_pages';
  6655. $retVal = t3lib_div::rmdir($cacheDir,true);
  6656. if (!$retVal) {
  6657. t3lib_div::sysLog('Could not remove page cache files in "'.$cacheDir.'"','Core/t3lib_tcemain',2);
  6658. }
  6659. }
  6660. $GLOBALS['TYPO3_DB']->exec_TRUNCATEquery('cache_pages');
  6661. }
  6662. }
  6663. }
  6664. /**
  6665. * Finds page UIDs for the element from table <code>$table</code> with UIDs from <code>$idList</code>
  6666. *
  6667. * @param array $table Table to search
  6668. * @param array $idList List of records' UIDs
  6669. * @param int $workspaceId Workspace ID. We need this parameter because user can be in LIVE but he still can publisg DRAFT from ws module!
  6670. * @param array $pageIdList List of found page UIDs
  6671. * @param array $elementList List of found element UIDs. Key is table name, value is list of UIDs
  6672. * @return void
  6673. */
  6674. function findPageIdsForVersionStateChange($table, $idList, $workspaceId, &$pageIdList, &$elementList) {
  6675. if ($workspaceId != 0) {
  6676. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('DISTINCT B.pid',
  6677. $table . ' A,' . $table . ' B',
  6678. 'A.pid=-1' . // Offline version
  6679. ' AND A.t3ver_wsid=' . $workspaceId .
  6680. ' AND A.uid IN (' . implode(',', $idList) . ') AND A.t3ver_oid=B.uid' .
  6681. t3lib_BEfunc::deleteClause($table,'A').
  6682. t3lib_BEfunc::deleteClause($table,'B')
  6683. );
  6684. while (false !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
  6685. $pageIdList[] = $row[0];
  6686. // Find ws version
  6687. $rec = t3lib_BEfunc::getRecord('pages', $row[0]);
  6688. t3lib_BEfunc::workspaceOL('pages', $rec, $workspaceId); // Note: cannot use t3lib_BEfunc::getRecordWSOL() here because it does not accept workspace id!
  6689. if ($rec['_ORIG_uid']) {
  6690. $elementList['pages'][$row[0]] = $rec['_ORIG_uid'];
  6691. }
  6692. }
  6693. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  6694. // The line below is necessary even with DISTINCT because several elements can be passed by caller
  6695. $pageIdList = array_unique($pageIdList);
  6696. }
  6697. }
  6698. /**
  6699. * Searches for all elements from all tables on the given pages in the same workspace.
  6700. *
  6701. * @param array $pageIdList List of PIDs to search
  6702. * @param int $workspaceId Workspace ID
  6703. * @param array $elementList List of found elements. Key is table name, value is array of element UIDs
  6704. * @return void
  6705. */
  6706. function findPageElementsForVersionStageChange($pageIdList, $workspaceId, &$elementList) {
  6707. global $TCA;
  6708. if ($workspaceId != 0) {
  6709. // Traversing all tables supporting versioning:
  6710. foreach($TCA as $table => $cfg) {
  6711. if ($TCA[$table]['ctrl']['versioningWS'] && $table != 'pages') {
  6712. // Using SELECTquery for better debugging
  6713. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('DISTINCT A.uid',
  6714. $table . ' A,' . $table . ' B',
  6715. 'A.pid=-1' . // Offline version
  6716. ' AND A.t3ver_wsid=' . $workspaceId .
  6717. ' AND B.pid IN (' . implode(',', $pageIdList) . ') AND A.t3ver_oid=B.uid' .
  6718. t3lib_BEfunc::deleteClause($table,'A').
  6719. t3lib_BEfunc::deleteClause($table,'B')
  6720. );
  6721. while (false !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
  6722. $elementList[$table][] = $row[0];
  6723. }
  6724. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  6725. if (is_array($elementList[$table])) {
  6726. // Yes, it is possible to get non-unique array even with DISTINCT above! It happens because several UIDs are passed in the array already.
  6727. $elementList[$table] = array_unique($elementList[$table]);
  6728. }
  6729. }
  6730. }
  6731. }
  6732. }
  6733. /**
  6734. * Finds real page IDs for state change.
  6735. *
  6736. * @param array $idList List of page UIDs, possibly versioned
  6737. * @return void
  6738. */
  6739. function findRealPageIds(&$idList) {
  6740. foreach ($idList as $key => $id) {
  6741. $rec = t3lib_BEfunc::getRecord('pages', $id, 't3ver_oid');
  6742. if ($rec['t3ver_oid'] > 0) {
  6743. $idList[$key] = $rec['t3ver_oid'];
  6744. }
  6745. }
  6746. }
  6747. /**
  6748. * Finds all elements for swapping versions in workspace
  6749. *
  6750. * @param string $table Table name of the original element to swap
  6751. * @param int $id UID of the original element to swap (online)
  6752. * @param int $offlineId As above but offline
  6753. * @return array Element data. Key is table name, values are array with first element as online UID, second - offline UID
  6754. */
  6755. function findPageElementsForVersionSwap($table, $id, $offlineId) {
  6756. global $TCA;
  6757. $rec = t3lib_BEfunc::getRecord($table, $offlineId, 't3ver_wsid');
  6758. $workspaceId = $rec['t3ver_wsid'];
  6759. $elementData = array();
  6760. if ($workspaceId != 0) {
  6761. // Get page UID for LIVE and workspace
  6762. if ($table != 'pages') {
  6763. $rec = t3lib_BEfunc::getRecord($table, $id, 'pid');
  6764. $pageId = $rec['pid'];
  6765. $rec = t3lib_BEfunc::getRecord('pages', $pageId);
  6766. t3lib_BEfunc::workspaceOL('pages', $rec, $workspaceId);
  6767. $offlinePageId = $rec['_ORIG_uid'];
  6768. }
  6769. else {
  6770. $pageId = $id;
  6771. $offlinePageId = $offlineId;
  6772. }
  6773. // Traversing all tables supporting versioning:
  6774. foreach($TCA as $table => $cfg) {
  6775. if ($TCA[$table]['ctrl']['versioningWS'] && $table != 'pages') {
  6776. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('A.uid AS offlineUid, B.uid AS uid',
  6777. $table . ' A,' . $table . ' B',
  6778. 'A.pid=-1 AND B.pid=' . $pageId . ' AND A.t3ver_wsid=' . $workspaceId .
  6779. ' AND B.uid=A.t3ver_oid' .
  6780. t3lib_BEfunc::deleteClause($table, 'A') . t3lib_BEfunc::deleteClause($table, 'B'));
  6781. while (false != ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
  6782. $elementData[$table][] = array($row[1], $row[0]);
  6783. }
  6784. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  6785. }
  6786. }
  6787. if ($offlinePageId && $offlinePageId != $pageId) {
  6788. $elementData['pages'][] = array($pageId, $offlinePageId);
  6789. }
  6790. }
  6791. return $elementData;
  6792. }
  6793. /**
  6794. * Proprocesses field array based on field type. Some fields must be adjusted
  6795. * before going to database. This is done on the copy of the field array because
  6796. * original values are used in remap action later.
  6797. *
  6798. * @param string $table Table name
  6799. * @param array $fieldArray Field array to check
  6800. * @return array Updated field array
  6801. */
  6802. function insertUpdateDB_preprocessBasedOnFieldType($table, $fieldArray) {
  6803. global $TCA;
  6804. $result = $fieldArray;
  6805. foreach ($fieldArray as $field => $value) {
  6806. switch ($TCA[$table]['columns'][$field]['config']['type']) {
  6807. case 'inline':
  6808. if ($TCA[$table]['columns'][$field]['config']['foreign_field']) {
  6809. if (!t3lib_div::testInt($value)) {
  6810. $result[$field] = count(t3lib_div::trimExplode(',', $value, TRUE));
  6811. }
  6812. }
  6813. break;
  6814. }
  6815. }
  6816. return $result;
  6817. }
  6818. }
  6819. if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tcemain.php']) {
  6820. include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tcemain.php']);
  6821. }
  6822. ?>