PageRenderTime 50ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/t3lib/class.t3lib_befunc.php

https://bitbucket.org/linxpinx/mercurial
PHP | 4447 lines | 2453 code | 476 blank | 1518 comment | 563 complexity | 3c9c968c5339b22b1bbd0b09e7a917f7 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. * Standard functions available for the TYPO3 backend.
  29. * You are encouraged to use this class in your own applications (Backend Modules)
  30. *
  31. * Call ALL methods without making an object!
  32. * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
  33. *
  34. * $Id: class.t3lib_befunc.php 8415 2010-07-28 09:15:10Z ohader $
  35. * Usage counts are based on search 22/2 2003 through whole backend source of typo3/
  36. * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  37. * XHTML compliant
  38. *
  39. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  40. */
  41. /**
  42. * [CLASS/FUNCTION INDEX of SCRIPT]
  43. *
  44. *
  45. *
  46. * 185: class t3lib_BEfunc
  47. *
  48. * SECTION: SQL-related, selecting records, searching
  49. * 206: function deleteClause($table,$tableAlias='')
  50. * 230: function getRecord($table,$uid,$fields='*',$where='',$useDeleteClause=true)
  51. * 253: function getRecordWSOL($table,$uid,$fields='*',$where='',$useDeleteClause=true)
  52. * 286: function getRecordRaw($table,$where='',$fields='*')
  53. * 309: function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='',$useDeleteClause=true)
  54. * 342: function searchQuery($searchWords,$fields,$table='')
  55. * 357: function listQuery($field,$value)
  56. * 369: function splitTable_Uid($str)
  57. * 384: function getSQLselectableList($in_list,$tablename,$default_tablename)
  58. * 412: function BEenableFields($table,$inv=0)
  59. *
  60. * SECTION: SQL-related, DEPRECATED functions
  61. * 476: function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
  62. * 498: function DBcompileInsert($table,$fields_values)
  63. * 512: function DBcompileUpdate($table,$where,$fields_values)
  64. *
  65. * SECTION: Page tree, TCA related
  66. * 542: function BEgetRootLine($uid,$clause='',$workspaceOL=FALSE)
  67. * 598: function openPageTree($pid,$clearExpansion)
  68. * 643: function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)
  69. * 686: function getExcludeFields()
  70. * 716: function getExplicitAuthFieldValues()
  71. * 787: function getSystemLanguages()
  72. * 812: function readPageAccess($id,$perms_clause)
  73. * 843: function getTCAtypes($table,$rec,$useFieldNameAsKey=0)
  74. * 896: function getTCAtypeValue($table,$rec)
  75. * 919: function getSpecConfParts($str, $defaultExtras)
  76. * 950: function getSpecConfParametersFromArray($pArr)
  77. * 978: function getFlexFormDS($conf,$row,$table,$fieldName='',$WSOL=TRUE)
  78. *
  79. * SECTION: Caching related
  80. * 1105: function storeHash($hash,$data,$ident)
  81. * 1125: function getHash($hash)
  82. *
  83. * SECTION: TypoScript related
  84. * 1161: function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)
  85. * 1217: function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')
  86. * 1272: function implodeTSParams($p,$k='')
  87. *
  88. * SECTION: Users / Groups related
  89. * 1309: function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='')
  90. * 1327: function getGroupNames($fields='title,uid', $where='')
  91. * 1344: function getListGroupNames($fields='title,uid')
  92. * 1363: function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)
  93. * 1396: function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)
  94. *
  95. * SECTION: Output related
  96. * 1437: function daysUntil($tstamp)
  97. * 1449: function date($tstamp)
  98. * 1460: function datetime($value)
  99. * 1472: function time($value)
  100. * 1488: function calcAge($seconds,$labels = 'min|hrs|days|yrs')
  101. * 1514: function dateTimeAge($tstamp,$prefix=1,$date='')
  102. * 1532: function titleAttrib($content='',$hsc=0)
  103. * 1545: function titleAltAttrib($content)
  104. * 1569: function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='')
  105. * 1637: function getThumbNail($thumbScript,$theFile,$tparams='',$size='')
  106. * 1654: function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)
  107. * 1716: function getRecordIconAltText($row,$table='pages')
  108. * 1758: function getLabelFromItemlist($table,$col,$key)
  109. * 1784: function getItemLabel($table,$col,$printAllWrap='')
  110. * 1809: function getRecordTitle($table,$row,$prep=0)
  111. * 1847: function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0)
  112. * 2009: function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0)
  113. * 2033: function getFileIcon($ext)
  114. * 2047: function getCommonSelectFields($table,$prefix='')
  115. * 2090: function makeConfigForm($configArray,$defaults,$dataPrefix)
  116. *
  117. * SECTION: Backend Modules API functions
  118. * 2165: function helpTextIcon($table,$field,$BACK_PATH,$force=0)
  119. * 2187: function helpText($table,$field,$BACK_PATH,$styleAttrib='')
  120. * 2239: function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='')
  121. * 2277: function editOnClick($params,$backPath='',$requestUri='')
  122. * 2296: function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE)
  123. * 2328: function getModTSconfig($id,$TSref)
  124. * 2349: function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')
  125. * 2392: function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='')
  126. * 2417: function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="")
  127. * 2438: function unsetMenuItems($modTSconfig,$itemArray,$TSref)
  128. * 2461: function getSetUpdateSignal($set='')
  129. * 2512: function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')
  130. *
  131. * SECTION: Core
  132. * 2585: function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl=172800)
  133. * 2613: function lockRecords($table='',$uid=0,$pid=0)
  134. * 2642: function isRecordLocked($table,$uid)
  135. * 2682: function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')
  136. * 2763: function getTCEFORM_TSconfig($table,$row)
  137. * 2814: function getTSconfig_pidValue($table,$uid,$pid)
  138. * 2844: function getPidForModTSconfig($table,$uid,$pid)
  139. * 2860: function getTSCpid($table,$uid,$pid)
  140. * 2876: function firstDomainRecord($rootLine)
  141. * 2898: function getDomainStartPage($domain, $path='')
  142. * 2928: function RTEsetup($RTEprop,$table,$field,$type='')
  143. * 2947: function &RTEgetObj()
  144. * 2986: function &softRefParserObj($spKey)
  145. * 3018: function explodeSoftRefParserList($parserList)
  146. * 3050: function isModuleSetInTBE_MODULES($modName)
  147. * 3073: function referenceCount($table,$ref,$msg='')
  148. *
  149. * SECTION: Workspaces / Versioning
  150. * 3132: function selectVersionsOfRecord($table, $uid, $fields='*', $workspace=0)
  151. * 3180: function fixVersioningPid($table,&$rr,$ignoreWorkspaceMatch=FALSE)
  152. * 3220: function workspaceOL($table,&$row,$wsid=-99)
  153. * 3268: function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*')
  154. * 3297: function getLiveVersionOfRecord($table,$uid,$fields='*')
  155. * 3319: function isPidInVersionizedBranch($pid, $table='',$returnStage=FALSE)
  156. * 3342: function versioningPlaceholderClause($table)
  157. * 3356: function countVersionsOfRecordsOnPage($workspace,$pageId, $allTables=FALSE)
  158. * 3391: function wsMapId($table,$uid)
  159. *
  160. * SECTION: Miscellaneous
  161. * 3421: function typo3PrintError($header,$text,$js='',$head=1)
  162. * 3465: function TYPO3_copyRightNotice()
  163. * 3489: function displayWarningMessages()
  164. * 3546: function getPathType_web_nonweb($path)
  165. * 3558: function ADMCMD_previewCmds($pageinfo)
  166. * 3580: function processParams($params)
  167. * 3606: function getListOfBackendModules($name,$perms_clause,$backPath='',$script='index.php')
  168. *
  169. * TOTAL FUNCTIONS: 99
  170. * (This index is automatically created/updated by the extension "extdeveval")
  171. *
  172. */
  173. /**
  174. * Standard functions available for the TYPO3 backend.
  175. * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
  176. *
  177. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  178. * @package TYPO3
  179. * @subpackage t3lib
  180. */
  181. final class t3lib_BEfunc {
  182. /*******************************************
  183. *
  184. * SQL-related, selecting records, searching
  185. *
  186. *******************************************/
  187. /**
  188. * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field is configured in $TCA for the tablename, $table
  189. * This function should ALWAYS be called in the backend for selection on tables which are configured in TCA since it will ensure consistent selection of records, even if they are marked deleted (in which case the system must always treat them as non-existent!)
  190. * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering on those fields as well in the backend you can use ->BEenableFields() though.
  191. * Usage: 71
  192. *
  193. * @param string Table name present in $TCA
  194. * @param string Table alias if any
  195. * @return string WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
  196. */
  197. public static function deleteClause($table,$tableAlias = '') {
  198. global $TCA;
  199. if ($TCA[$table]['ctrl']['delete']) {
  200. return ' AND '.($tableAlias ? $tableAlias : $table).'.'.$TCA[$table]['ctrl']['delete'].'=0';
  201. } else {
  202. return '';
  203. }
  204. }
  205. /**
  206. * Gets record with uid = $uid from $table
  207. * You can set $field to a list of fields (default is '*')
  208. * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
  209. * Will automatically check if records has been deleted and if so, not return anything.
  210. * $table must be found in $TCA
  211. * Usage: 99
  212. *
  213. * @param string Table name present in $TCA
  214. * @param integer UID of record
  215. * @param string List of fields to select
  216. * @param string Additional WHERE clause, eg. " AND blablabla = 0"
  217. * @param boolean Use the deleteClause to check if a record is deleted (default true)
  218. * @return array Returns the row if found, otherwise nothing
  219. */
  220. public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
  221. if ($GLOBALS['TCA'][$table]) {
  222. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  223. $fields,
  224. $table,
  225. 'uid=' . intval($uid) . ($useDeleteClause ? self::deleteClause($table) : '') . $where
  226. );
  227. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  228. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  229. if ($row) {
  230. return $row;
  231. }
  232. }
  233. }
  234. /**
  235. * Like getRecord(), but overlays workspace version if any.
  236. *
  237. * @param string Table name present in $TCA
  238. * @param integer UID of record
  239. * @param string List of fields to select
  240. * @param string Additional WHERE clause, eg. " AND blablabla = 0"
  241. * @param boolean Use the deleteClause to check if a record is deleted (default true)
  242. * @return array Returns the row if found, otherwise nothing
  243. */
  244. public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
  245. if ($fields !== '*') {
  246. $internalFields = t3lib_div::uniqueList($fields.',uid,pid'.($table == 'pages' ? ',t3ver_swapmode' : ''));
  247. $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
  248. self::workspaceOL($table, $row);
  249. if (is_array ($row)) {
  250. foreach (array_keys($row) as $key) {
  251. if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
  252. unset ($row[$key]);
  253. }
  254. }
  255. }
  256. } else {
  257. $row = self::getRecord($table, $uid, $fields, $where);
  258. self::workspaceOL($table, $row);
  259. }
  260. return $row;
  261. }
  262. /**
  263. * Returns the first record found from $table with $where as WHERE clause
  264. * This function does NOT check if a record has the deleted flag set.
  265. * $table does NOT need to be configured in $TCA
  266. * The query used is simply this:
  267. * $query = 'SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
  268. * Usage: 5 (ext: sys_todos)
  269. *
  270. * @param string Table name (not necessarily in TCA)
  271. * @param string WHERE clause
  272. * @param string $fields is a list of fields to select, default is '*'
  273. * @return array First row found, if any, FALSE otherwise
  274. */
  275. public static function getRecordRaw($table, $where = '', $fields = '*') {
  276. $row = FALSE;
  277. if (FALSE !== ($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
  278. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  279. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  280. }
  281. return $row;
  282. }
  283. /**
  284. * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
  285. * The records are returned in an array
  286. * If no records were selected, the function returns nothing
  287. * Usage: 8
  288. *
  289. * @param string Table name present in $TCA
  290. * @param string Field to select on
  291. * @param string Value that $theField must match
  292. * @param string Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
  293. * @param string Optional GROUP BY field(s), if none, supply blank string.
  294. * @param string Optional ORDER BY field(s), if none, supply blank string.
  295. * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
  296. * @param boolean Use the deleteClause to check if a record is deleted (default true)
  297. * @return mixed Multidimensional array with selected records (if any is selected)
  298. */
  299. public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true) {
  300. global $TCA;
  301. if (is_array($TCA[$theTable])) {
  302. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  303. '*',
  304. $theTable,
  305. $theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
  306. ($useDeleteClause ? self::deleteClause($theTable).' ' : '').
  307. self::versioningPlaceholderClause($theTable) . ' ' .
  308. $whereClause, // whereClauseMightContainGroupOrderBy
  309. $groupBy,
  310. $orderBy,
  311. $limit
  312. );
  313. $rows = array();
  314. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  315. $rows[] = $row;
  316. }
  317. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  318. if (count($rows)) return $rows;
  319. }
  320. }
  321. /**
  322. * Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
  323. * Usage: 0
  324. *
  325. * @param array Array of search words
  326. * @param array Array of fields
  327. * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
  328. * @return string WHERE clause for search
  329. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5, use $GLOBALS['TYPO3_DB']->searchQuery() directly!
  330. */
  331. public static function searchQuery($searchWords, $fields, $table = '') {
  332. t3lib_div::logDeprecatedFunction();
  333. return $GLOBALS['TYPO3_DB']->searchQuery($searchWords, $fields, $table);
  334. }
  335. /**
  336. * Returns a WHERE clause that can find a value ($value) in a list field ($field)
  337. * For instance a record in the database might contain a list of numbers, "34,234,5" (with no spaces between). This query would be able to select that record based on the value "34", "234" or "5" regardless of their positioni in the list (left, middle or right).
  338. * Is nice to look up list-relations to records or files in TYPO3 database tables.
  339. * Usage: 0
  340. *
  341. * @param string Table field name
  342. * @param string Value to find in list
  343. * @return string WHERE clause for a query
  344. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5, use $GLOBALS['TYPO3_DB']->listQuery() directly!
  345. */
  346. public static function listQuery($field, $value) {
  347. t3lib_div::logDeprecatedFunction();
  348. return $GLOBALS['TYPO3_DB']->listQuery($field, $value, '');
  349. }
  350. /**
  351. * Makes an backwards explode on the $str and returns an array with ($table, $uid).
  352. * Example: tt_content_45 => array('tt_content', 45)
  353. * Usage: 1
  354. *
  355. * @param string [tablename]_[uid] string to explode
  356. * @return array
  357. */
  358. public static function splitTable_Uid($str) {
  359. list($uid, $table) = explode('_', strrev($str), 2);
  360. return array(strrev($table), strrev($uid));
  361. }
  362. /**
  363. * Returns a list of pure integers based on $in_list being a list of records with table-names prepended.
  364. * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
  365. * Usage: 1 (t3lib_userauthgroup)
  366. *
  367. * @param string Input list
  368. * @param string Table name from which ids is returned
  369. * @param string $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
  370. * @return string List of ids
  371. */
  372. public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
  373. $list = Array();
  374. if ((string)trim($in_list)!='') {
  375. $tempItemArray = explode(',', trim($in_list));
  376. foreach ($tempItemArray as $key => $val) {
  377. $val = strrev($val);
  378. $parts = explode('_', $val, 2);
  379. if ((string)trim($parts[0])!='') {
  380. $theID = intval(strrev($parts[0]));
  381. $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
  382. if ($theTable==$tablename) {$list[] = $theID;}
  383. }
  384. }
  385. }
  386. return implode(',', $list);
  387. }
  388. /**
  389. * Backend implementation of enableFields()
  390. * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
  391. * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
  392. * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
  393. * Usage: 5
  394. *
  395. * @param string $table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $TCA.
  396. * @param boolean $inv means that the query will select all records NOT VISIBLE records (inverted selection)
  397. * @return string WHERE clause part
  398. */
  399. public static function BEenableFields($table, $inv = 0) {
  400. $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
  401. $query = array();
  402. $invQuery = array();
  403. if (is_array($ctrl)) {
  404. if (is_array($ctrl['enablecolumns'])) {
  405. if ($ctrl['enablecolumns']['disabled']) {
  406. $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
  407. $query[] = $field.'=0';
  408. $invQuery[] = $field.'!=0';
  409. }
  410. if ($ctrl['enablecolumns']['starttime']) {
  411. $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
  412. $query[] = '('.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
  413. $invQuery[] = '('.$field.'!=0 AND '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
  414. }
  415. if ($ctrl['enablecolumns']['endtime']) {
  416. $field = $table.'.'.$ctrl['enablecolumns']['endtime'];
  417. $query[] = '('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
  418. $invQuery[] = '('.$field.'!=0 AND '.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
  419. }
  420. }
  421. }
  422. $outQ = ($inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query));
  423. return $outQ ? ' AND ' . $outQ : '';
  424. }
  425. /**
  426. * Fetches the localization for a given record.
  427. *
  428. * @param string $table: Table name present in $TCA
  429. * @param integer $uid: The uid of the record
  430. * @param integer $language: The uid of the language record in sys_language
  431. * @param string $andWhereClause: Optional additional WHERE clause (default: '')
  432. * @return mixed Multidimensional array with selected records; if none exist, false is returned
  433. */
  434. public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
  435. $recordLocalization = false;
  436. if (self::isTableLocalizable($table)) {
  437. $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
  438. $recordLocalization = self::getRecordsByField(
  439. $table,
  440. $tcaCtrl['transOrigPointerField'],
  441. $uid,
  442. 'AND '.$tcaCtrl['languageField'].'='.intval($language).($andWhereClause ? ' '.$andWhereClause : ''),
  443. '',
  444. '',
  445. '1'
  446. );
  447. }
  448. return $recordLocalization;
  449. }
  450. /*******************************************
  451. *
  452. * SQL-related, DEPRECATED functions
  453. * (use t3lib_DB functions instead)
  454. *
  455. *******************************************/
  456. /**
  457. * Returns a SELECT query, selecting fields ($select) from two/three tables joined
  458. * $local_table and $mm_table is mandatory. $foreign_table is optional.
  459. * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
  460. * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
  461. *
  462. * @param string Field list for SELECT
  463. * @param string Tablename, local table
  464. * @param string Tablename, relation table
  465. * @param string Tablename, foreign table
  466. * @param string Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
  467. * @param string Optional GROUP BY field(s), if none, supply blank string.
  468. * @param string Optional ORDER BY field(s), if none, supply blank string.
  469. * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
  470. * @return string Full SQL query
  471. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5, use $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query() instead since that will return the result pointer while this returns the query. Using this function may make your application less fitted for DBAL later.
  472. * @see t3lib_DB::exec_SELECT_mm_query()
  473. */
  474. public static function mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
  475. t3lib_div::logDeprecatedFunction();
  476. $query = $GLOBALS['TYPO3_DB']->SELECTquery(
  477. $select,
  478. $local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
  479. $local_table.'.uid='.$mm_table.'.uid_local'.($foreign_table?' AND '.$foreign_table.'.uid='.$mm_table.'.uid_foreign':'').' '.
  480. $whereClause, // whereClauseMightContainGroupOrderBy
  481. $groupBy,
  482. $orderBy,
  483. $limit
  484. );
  485. return $query;
  486. }
  487. /**
  488. * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
  489. * DEPRECATED - $GLOBALS['TYPO3_DB']->INSERTquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_INSERTquery()
  490. *
  491. * @param string Table name
  492. * @param array Field values as key=>value pairs.
  493. * @return string Full SQL query for INSERT
  494. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5, use $GLOBALS['TYPO3_DB']->exec_INSERTquery() directly!
  495. */
  496. public static function DBcompileInsert($table, $fields_values) {
  497. t3lib_div::logDeprecatedFunction();
  498. return $GLOBALS['TYPO3_DB']->INSERTquery($table, $fields_values);
  499. }
  500. /**
  501. * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
  502. * DEPRECATED - $GLOBALS['TYPO3_DB']->UPDATEquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery()
  503. *
  504. * @param string Database tablename
  505. * @param string WHERE clause, eg. "uid=1"
  506. * @param array Field values as key=>value pairs.
  507. * @return string Full SQL query for UPDATE
  508. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery() directly!
  509. */
  510. public static function DBcompileUpdate($table, $where, $fields_values) {
  511. t3lib_div::logDeprecatedFunction();
  512. return $GLOBALS['TYPO3_DB']->UPDATEquery($table, $where, $fields_values);
  513. }
  514. /*******************************************
  515. *
  516. * Page tree, TCA related
  517. *
  518. *******************************************/
  519. /**
  520. * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
  521. * By default deleted pages are filtered.
  522. * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
  523. * Usage: 1
  524. *
  525. * @param integer Page id for which to create the root line.
  526. * @param string $clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
  527. * @param boolean If true, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
  528. * @return array Root line array, all the way to the page tree root (or as far as $clause allows!)
  529. */
  530. public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
  531. static $BEgetRootLine_cache = array();
  532. $output = array();
  533. $pid = $uid;
  534. $ident = $pid . '-' . $clause . '-' . $workspaceOL;
  535. if (is_array($BEgetRootLine_cache[$ident])) {
  536. $output = $BEgetRootLine_cache[$ident];
  537. } else {
  538. $loopCheck = 100;
  539. $theRowArray = array();
  540. while ($uid != 0 && $loopCheck) {
  541. $loopCheck--;
  542. $row = self::getPageForRootline($uid, $clause, $workspaceOL);
  543. if (is_array($row)) {
  544. $uid = $row['pid'];
  545. $theRowArray[] = $row;
  546. } else {
  547. break;
  548. }
  549. }
  550. if ($uid == 0) {
  551. $theRowArray[] = array('uid' => 0, 'title' => '');
  552. }
  553. $c = count($theRowArray);
  554. foreach ($theRowArray as $val) {
  555. $c--;
  556. $output[$c] = array(
  557. 'uid' => $val['uid'],
  558. 'pid' => $val['pid'],
  559. 'title' => $val['title'],
  560. 'TSconfig' => $val['TSconfig'],
  561. 'is_siteroot' => $val['is_siteroot'],
  562. 'storage_pid' => $val['storage_pid'],
  563. 't3ver_oid' => $val['t3ver_oid'],
  564. 't3ver_wsid' => $val['t3ver_wsid'],
  565. 't3ver_state' => $val['t3ver_state'],
  566. 't3ver_swapmode' => $val['t3ver_swapmode'],
  567. 't3ver_stage' => $val['t3ver_stage']
  568. );
  569. if (isset($val['_ORIG_pid'])) {
  570. $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
  571. }
  572. }
  573. $BEgetRootLine_cache[$ident] = $output;
  574. }
  575. return $output;
  576. }
  577. /**
  578. * Gets the cached page record for the rootline
  579. *
  580. * @param integer $uid: Page id for which to create the root line.
  581. * @param string $clause: can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
  582. * @param boolean $workspaceOL: If true, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
  583. * @return array Cached page record for the rootline
  584. * @see BEgetRootLine
  585. */
  586. protected static function getPageForRootline($uid, $clause, $workspaceOL) {
  587. static $getPageForRootline_cache = array();
  588. $ident = $uid . '-' . $clause . '-' . $workspaceOL;
  589. if (is_array($getPageForRootline_cache[$ident])) {
  590. $row = $getPageForRootline_cache[$ident];
  591. } else {
  592. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  593. 'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,t3ver_stage',
  594. 'pages',
  595. 'uid=' . intval($uid) . ' ' .
  596. self::deleteClause('pages') . ' ' .
  597. $clause // whereClauseMightContainGroupOrderBy
  598. );
  599. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  600. if ($row) {
  601. if ($workspaceOL) {
  602. self::workspaceOL('pages', $row);
  603. }
  604. if (is_array($row)) {
  605. self::fixVersioningPid('pages', $row);
  606. $getPageForRootline_cache[$ident] = $row;
  607. }
  608. }
  609. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  610. }
  611. return $row;
  612. }
  613. /**
  614. * Opens the page tree to the specified page id
  615. *
  616. * @param integer Page id.
  617. * @param boolean If set, then other open branches are closed.
  618. * @return void
  619. */
  620. public static function openPageTree($pid, $clearExpansion) {
  621. global $BE_USER;
  622. // Get current expansion data:
  623. if ($clearExpansion) {
  624. $expandedPages = array();
  625. } else {
  626. $expandedPages = unserialize($BE_USER->uc['browseTrees']['browsePages']);
  627. }
  628. // Get rootline:
  629. $rL = self::BEgetRootLine($pid);
  630. // First, find out what mount index to use (if more than one DB mount exists):
  631. $mountIndex = 0;
  632. $mountKeys = array_flip($BE_USER->returnWebmounts());
  633. foreach($rL as $rLDat) {
  634. if (isset($mountKeys[$rLDat['uid']])) {
  635. $mountIndex = $mountKeys[$rLDat['uid']];
  636. break;
  637. }
  638. }
  639. // Traverse rootline and open paths:
  640. foreach($rL as $rLDat) {
  641. $expandedPages[$mountIndex][$rLDat['uid']] = 1;
  642. }
  643. // Write back:
  644. $BE_USER->uc['browseTrees']['browsePages'] = serialize($expandedPages);
  645. $BE_USER->writeUC();
  646. }
  647. /**
  648. * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
  649. * Each part of the path will be limited to $titleLimit characters
  650. * Deleted pages are filtered out.
  651. * Usage: 15
  652. *
  653. * @param integer Page uid for which to create record path
  654. * @param string $clause is additional where clauses, eg. "
  655. * @param integer Title limit
  656. * @param integer Title limit of Full title (typ. set to 1000 or so)
  657. * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
  658. */
  659. public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
  660. if (!$titleLimit) { $titleLimit = 1000; }
  661. $loopCheck = 100;
  662. $output = $fullOutput = '/';
  663. $clause = trim($clause);
  664. if ($clause !== '' && substr($clause, 0, 3) !== 'AND') {
  665. $clause = 'AND ' . $clause;
  666. }
  667. $data = self::BEgetRootLine($uid, $clause);
  668. foreach ($data as $record) {
  669. if ($record['uid'] === 0) {
  670. continue;
  671. }
  672. if ($record['_ORIG_pid'] && $record['t3ver_swapmode'] > 0) { // Branch points
  673. $output = ' [#VEP#]' . $output; // Adding visual token - Versioning Entry Point - that tells that THIS position was where the versionized branch got connected to the main tree. I will have to find a better name or something...
  674. }
  675. $output = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
  676. if ($fullTitleLimit) {
  677. $fullOutput = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
  678. }
  679. }
  680. if ($fullTitleLimit) {
  681. return array($output, $fullOutput);
  682. } else {
  683. return $output;
  684. }
  685. }
  686. /**
  687. * Returns an array with the exclude-fields as defined in TCA
  688. * Used for listing the exclude-fields in be_groups forms
  689. * Usage: 2 (t3lib_tceforms + t3lib_transferdata)
  690. *
  691. * @return array Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries
  692. */
  693. public static function getExcludeFields() {
  694. global $TCA;
  695. // All TCA keys:
  696. $theExcludeArray = Array();
  697. $tc_keys = array_keys($TCA);
  698. foreach($tc_keys as $table) {
  699. // Load table
  700. t3lib_div::loadTCA($table);
  701. // All field names configured:
  702. if (is_array($TCA[$table]['columns'])) {
  703. $f_keys = array_keys($TCA[$table]['columns']);
  704. foreach($f_keys as $field) {
  705. if ($TCA[$table]['columns'][$field]['exclude']) {
  706. // Get Human Readable names of fields and table:
  707. $Fname = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
  708. // add entry:
  709. $theExcludeArray[] = Array($Fname, $table.':'.$field);
  710. }
  711. }
  712. }
  713. }
  714. return $theExcludeArray;
  715. }
  716. /**
  717. * Returns an array with explicit Allow/Deny fields.
  718. * Used for listing these field/value pairs in be_groups forms
  719. *
  720. * @return array Array with information from all of $TCA
  721. */
  722. public static function getExplicitAuthFieldValues() {
  723. global $TCA;
  724. // Initialize:
  725. $adLabel = array(
  726. 'ALLOW' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.allow'),
  727. 'DENY' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.deny'),
  728. );
  729. // All TCA keys:
  730. $allowDenyOptions = Array();
  731. $tc_keys = array_keys($TCA);
  732. foreach($tc_keys as $table) {
  733. // Load table
  734. t3lib_div::loadTCA($table);
  735. // All field names configured:
  736. if (is_array($TCA[$table]['columns'])) {
  737. $f_keys = array_keys($TCA[$table]['columns']);
  738. foreach($f_keys as $field) {
  739. $fCfg = $TCA[$table]['columns'][$field]['config'];
  740. if ($fCfg['type']=='select' && $fCfg['authMode']) {
  741. // Check for items:
  742. if (is_array($fCfg['items'])) {
  743. // Get Human Readable names of fields and table:
  744. $allowDenyOptions[$table.':'.$field]['tableFieldLabel'] = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
  745. // Check for items:
  746. foreach($fCfg['items'] as $iVal) {
  747. if (strcmp($iVal[1], '')) { // Values '' is not controlled by this setting.
  748. // Find iMode:
  749. $iMode = '';
  750. switch((string)$fCfg['authMode']) {
  751. case 'explicitAllow':
  752. $iMode = 'ALLOW';
  753. break;
  754. case 'explicitDeny':
  755. $iMode = 'DENY';
  756. break;
  757. case 'individual':
  758. if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
  759. $iMode = 'ALLOW';
  760. } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
  761. $iMode = 'DENY';
  762. }
  763. break;
  764. }
  765. // Set iMode:
  766. if ($iMode) {
  767. $allowDenyOptions[$table.':'.$field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
  768. }
  769. }
  770. }
  771. }
  772. }
  773. }
  774. }
  775. }
  776. return $allowDenyOptions;
  777. }
  778. /**
  779. * Returns an array with system languages:
  780. *
  781. * @return array Array with languages
  782. */
  783. public static function getSystemLanguages() {
  784. // Initialize, add default language:
  785. $sysLanguages = array();
  786. $sysLanguages[] = array('Default language', 0);
  787. // Traverse languages
  788. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,flag', 'sys_language', 'pid=0' . self::deleteClause('sys_language'));
  789. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  790. $sysLanguages[] = array(
  791. htmlspecialchars($row['title']) . ' [' . $row['uid'] . ']',
  792. $row['uid'],
  793. ($row['flag'] ? 'flags/' . $row['flag'] : '')
  794. );
  795. }
  796. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  797. return $sysLanguages;
  798. }
  799. /**
  800. * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $TCA.
  801. *
  802. * @param string $table: The table to check
  803. * @return boolean Whether a table is localizable
  804. */
  805. public static function isTableLocalizable($table) {
  806. $isLocalizable = false;
  807. if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
  808. $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
  809. $isLocalizable = (isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField']);
  810. }
  811. return $isLocalizable;
  812. }
  813. /**
  814. * Returns the value of the property localizationMode in the given $config array ($TCA[<table>]['columns'][<field>]['config']).
  815. * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
  816. * If the table is not prepared for localization or not defined at all in $TCA, false is returned.
  817. *
  818. * @param string $table: The name of the table to lookup in TCA
  819. * @param mixed $fieldOrConfig: The fieldname (string) or the configuration of the field to check (array)
  820. * @return mixed If table is localizable, the set localizationMode is returned (if property is not set, 'select' is returned by default); if table is not localizable, false is returned
  821. */
  822. public static function getInlineLocalizationMode($table, $fieldOrConfig) {
  823. $localizationMode = false;
  824. if (is_array($fieldOrConfig) && count($fieldOrConfig)) {
  825. $config = $fieldOrConfig;
  826. } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
  827. $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
  828. }
  829. if (is_array($config) && isset($config['type']) && $config['type']=='inline' && self::isTableLocalizable($table)) {
  830. $localizationMode = (isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode'] ? $config['behaviour']['localizationMode'] : 'select');
  831. // The mode 'select' is not possible when child table is not localizable at all:
  832. if ($localizationMode=='select' && !self::isTableLocalizable($config['foreign_table'])) {
  833. $localizationMode = false;
  834. }
  835. }
  836. return $localizationMode;
  837. }
  838. /**
  839. * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
  840. * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
  841. * In any case ->isInWebMount must return true for the user (regardless of $perms_clause)
  842. * Usage: 21
  843. *
  844. * @param integer Page uid for which to check read-access
  845. * @param string $perms_clause is typically a value generated with $BE_USER->getPagePermsClause(1);
  846. * @return array Returns page record if OK, otherwise false.
  847. */
  848. public static function readPageAccess($id, $perms_clause) {
  849. if ((string)$id!='') {
  850. $id = intval($id);
  851. if (!$id) {
  852. if ($GLOBALS['BE_USER']->isAdmin()) {
  853. $path = '/';
  854. $pageinfo['_thePath'] = $path;
  855. return $pageinfo;
  856. }
  857. } else {
  858. $pageinfo = self::getRecord('pages', $id, '*', ($perms_clause ? ' AND ' . $perms_clause : ''));
  859. if ($pageinfo['uid'] && $GLOBALS['BE_USER']->isInWebMount($id, $perms_clause)) {
  860. self::workspaceOL('pages', $pageinfo);
  861. if (is_array($pageinfo)) {
  862. self::fixVersioningPid('pages', $pageinfo);
  863. list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
  864. return $pageinfo;
  865. }
  866. }
  867. }
  868. }
  869. return false;
  870. }
  871. /**
  872. * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
  873. * Usage: 6
  874. *
  875. * @param string Table name (present in TCA)
  876. * @param array Record from $table
  877. * @param boolean If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
  878. * @return array
  879. */
  880. public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
  881. global $TCA;
  882. t3lib_div::loadTCA($table);
  883. if ($TCA[$table]) {
  884. // Get type value:
  885. $fieldValue = self::getTCAtypeValue($table, $rec);
  886. // Get typesConf
  887. $typesConf = $TCA[$table]['types'][$fieldValue];
  888. // Get fields list and traverse it
  889. $fieldList = explode(',', $typesConf['showitem']);
  890. $altFieldList = array();
  891. // Traverse fields in types config and parse the configuration into a nice array:
  892. foreach($fieldList as $k => $v) {
  893. list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
  894. $defaultExtras = is_array($TCA[$table]['columns'][$pFieldName]) ? $TCA[$table]['columns'][$pFieldName]['defaultExtras'] : '';
  895. $specConfParts = self::getSpecConfParts($pSpec, $defaultExtras);
  896. $fieldList[$k] = array(
  897. 'field' => $pFieldName,
  898. 'title' => $pAltTitle,
  899. 'palette' => $pPalette,
  900. 'spec' => $specConfParts,
  901. 'origString' => $v
  902. );
  903. if ($useFieldNameAsKey) {
  904. $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
  905. }
  906. }
  907. if ($useFieldNameAsKey) {
  908. $fieldList = $altFieldList;
  909. }
  910. // Return array:
  911. return $fieldList;
  912. }
  913. }
  914. /**
  915. * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $TCA
  916. * If no "type" field is configured in the "ctrl"-section of the $TCA for the table, zero is used.
  917. * If zero is not an index in the "types" section of $TCA for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
  918. * Usage: 7
  919. *
  920. * @param string Table name present in TCA
  921. * @param array Record from $table
  922. * @return string Field value
  923. * @see getTCAtypes()
  924. */
  925. public static function getTCAtypeValue($table, $rec) {
  926. global $TCA;
  927. // If no field-value, set it to zero. If there is no type matching the field-value (which now may be zero...) test field-value '1' as default.
  928. t3lib_div::loadTCA($table);
  929. if ($TCA[$table]) {
  930. $field = $TCA[$table]['ctrl']['type'];
  931. $fieldValue = $field ? ($rec[$field] ? $rec[$field] : 0) : 0;
  932. if (!is_array($TCA[$table]['types'][$fieldValue])) $fieldValue = 1;
  933. return $fieldValue;
  934. }
  935. }
  936. /**
  937. * Parses a part of the field lists in the "types"-section of $TCA arrays, namely the "special configuration" at index 3 (position 4)
  938. * Elements are splitted by ":" and within those parts, parameters are splitted by "|".
  939. * Everything is returned in an array and you should rather see it visually than listen to me anymore now... Check out example in Inside TYPO3
  940. * Usage: 5
  941. *
  942. * @param string Content from the "types" configuration of TCA (the special configuration) - see description of function
  943. * @param string The ['defaultExtras'] value from field configuration
  944. * @return array
  945. */
  946. public static function getSpecConfParts($str, $defaultExtras) {
  947. // Add defaultExtras:
  948. $specConfParts = t3lib_div::trimExplode(':', $defaultExtras.':'.$str, 1);
  949. $reg = array();
  950. if (count($specConfParts)) {
  951. foreach($specConfParts as $k2 => $v2) {
  952. unset($specConfParts[$k2]);
  953. if (preg_match('/(.*)\[(.*)\]/', $v2, $reg)) {
  954. $specConfParts[trim($reg[1])] = array(
  955. 'parameters' => t3lib_div::trimExplode('|', $reg[2], 1)
  956. );
  957. } else {
  958. $specConfParts[trim($v2)] = 1;
  959. }
  960. }
  961. } else {
  962. $specConfParts = array();
  963. }
  964. return $specConfParts;
  965. }
  966. /**
  967. * Takes an array of "[key] = [value]" strings and returns an array with the keys set as keys pointing to the value.
  968. * Better see it in action! Find example in Inside TYPO3
  969. * Usage: 6
  970. *
  971. * @param array Array of "[key] = [value]" strings to convert.
  972. * @return array
  973. */
  974. public static function getSpecConfParametersFromArray($pArr) {
  975. $out = array();
  976. if (is_array($pArr)) {
  977. foreach ($pArr as $k => $v) {
  978. $parts = explode('=', $v, 2);
  979. if (count($parts)==2) {
  980. $out[trim($parts[0])] = trim($parts[1]);
  981. } else {
  982. $out[$k] = $v;
  983. }
  984. }
  985. }
  986. return $out;
  987. }
  988. /**
  989. * Finds the Data Structure for a FlexForm field
  990. * NOTE ON data structures for deleted records: This function may fail to deliver the data structure for a record for a few reasons: a) The data structure could be deleted (either with deleted-flagged or hard-deleted), b) the data structure is fetched using the ds_pointerField_searchParent in which case any deleted record on the route to the final location of the DS will make it fail. In theory, we can solve the problem in the case where records that are deleted-flagged keeps us from finding the DS - this is done at the markers ###NOTE_A### where we make sure to also select deleted records. However, we generally want the DS lookup to fail for deleted records since for the working website we expect a deleted-flagged record to be as inaccessible as one that is completely deleted from the DB. Any way we look at it, this may lead to integrity problems of the reference index and even lost files if attached. However, that is not really important considering that a single change to a data structure can instantly invalidate large amounts of the reference index which we do accept as a cost for the flexform features. Other than requiring a reference index update, deletion of/changes in data structure or the failure to look them up when completely deleting records may lead to lost files in the uploads/ folders since those are now without a proper reference.
  991. * Usage: 5
  992. *
  993. * @param array Field config array
  994. * @param array Record data
  995. * @param string The table name
  996. * @param string Optional fieldname passed to hook object
  997. * @param boolean Boolean; If set, workspace overlay is applied to records. This is correct behaviour for all presentation and export, but NOT if you want a true reflection of how things are in the live workspace.
  998. * @param integer SPECIAL CASES: Use this, if the DataStructure may come from a parent record and the INPUT row doesn't have a uid yet (hence, the pid cannot be looked up). Then it is necessary to supply a PID value to search recursively in for the DS (used from TCEmain)
  999. * @return mixed If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
  1000. * @see t3lib_TCEforms::getSingleField_typeFlex()
  1001. */
  1002. public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
  1003. global $TYPO3_CONF_VARS;
  1004. // Get pointer field etc from TCA-config:
  1005. $ds_pointerField = $conf['ds_pointerField'];
  1006. $ds_array = $conf['ds'];
  1007. $ds_tableField = $conf['ds_tableField'];
  1008. $ds_searchParentField = $conf['ds_pointerField_searchParent'];
  1009. // Find source value:
  1010. $dataStructArray = '';
  1011. if (is_array($ds_array)) { // If there is a data source array, that takes precedence
  1012. // If a pointer field is set, take the value from that field in the $row array and use as key.
  1013. if ($ds_pointerField) {
  1014. // Up to two pointer fields can be specified in a comma separated list.
  1015. $pointerFields = t3lib_div::trimExplode(',', $ds_pointerField);
  1016. if(count($pointerFields) == 2) { // If we have two pointer fields, the array keys should contain both field values separated by comma. The asterisk "*" catches all values. For backwards compatibility, it's also possible to specify only the value of the first defined ds_pointerField.
  1017. if($ds_array[$row[$pointerFields[0]].','.$row[$pointerFields[1]]]) { // Check if we have a DS for the combination of both pointer fields values
  1018. $srcPointer = $row[$pointerFields[0]].','.$row[$pointerFields[1]];
  1019. } elseif($ds_array[$row[$pointerFields[1]].',*']) { // Check if we have a DS for the value of the first pointer field suffixed with ",*"
  1020. $srcPointer = $row[$pointerFields[1]].',*';
  1021. } elseif($ds_array['*,'.$row[$pointerFields[1]]]) { // Check if we have a DS for the value of the second pointer field prefixed with "*,"
  1022. $srcPointer = '*,'.$row[$pointerFields[1]];
  1023. } elseif($ds_array[$row[$pointerFields[0]]]) { // Check if we have a DS for just the value of the first pointer field (mainly for backwards compatibility)
  1024. $srcPointer = $row[$pointerFields[0]];
  1025. }
  1026. } else {
  1027. $srcPointer = $row[$pointerFields[0]];
  1028. }
  1029. $srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
  1030. } else $srcPointer = 'default';
  1031. // Get Data Source: Detect if it's a file reference and in that case read the file and parse as XML. Otherwise the value is expected to be XML.
  1032. if (substr($ds_array[$srcPointer], 0, 5)=='FILE:') {
  1033. $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
  1034. if ($file && @is_file($file)) {
  1035. $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
  1036. } else $dataStructArray = 'The file "'.substr($ds_array[$srcPointer], 5).'" in ds-array key "'.$srcPointer.'" was not found ("'.$file.'")'; // Error message.
  1037. } else {
  1038. $dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
  1039. }
  1040. } elseif ($ds_pointerField) { // If pointer field AND possibly a table/field is set:
  1041. // Value of field pointed to:
  1042. $srcPointer = $row[$ds_pointerField];
  1043. // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
  1044. if ($ds_searchParentField && !$srcPointer) {
  1045. $rr = self::getRecord($table, $row['uid'], 'uid,' . $ds_searchParentField); // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
  1046. if ($WSOL) {
  1047. self::workspaceOL($table, $rr);
  1048. self::fixVersioningPid($table, $rr, TRUE); // Added "TRUE" 23/03/06 before 4.0. (Also to similar call below!). Reason: When t3lib_refindex is scanning the system in Live workspace all Pages with FlexForms will not find their inherited datastructure. Thus all references from workspaces are removed! Setting TRUE means that versioning PID doesn't check workspace of the record. I can't see that this should give problems anywhere. See more information inside t3lib_refindex!
  1049. }
  1050. $uidAcc = array(); // Used to avoid looping, if any should happen.
  1051. $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
  1052. while(!$srcPointer) {
  1053. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  1054. 'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
  1055. $table,
  1056. 'uid=' . intval($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField]) . self::deleteClause($table) ###NOTE_A###
  1057. );
  1058. $newRecordPidValue = 0;
  1059. $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  1060. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  1061. // break if no result from SQL db or if looping...
  1062. if (!is_array($rr) || isset($uidAcc[$rr['uid']])) break;
  1063. $uidAcc[$rr['uid']] = 1;
  1064. if ($WSOL) {
  1065. self::workspaceOL($table, $rr);
  1066. self::fixVersioningPid($table, $rr, TRUE);
  1067. }
  1068. $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
  1069. }
  1070. }
  1071. // If there is a srcPointer value:
  1072. if ($srcPointer) {
  1073. if (t3lib_div::testInt($srcPointer)) { // If integer, then its a record we will look up:
  1074. list($tName, $fName) = explode(':', $ds_tableField, 2);
  1075. if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
  1076. $dataStructRec = self::getRecord($tName, $srcPointer);
  1077. if ($WSOL) {
  1078. self::workspaceOL($tName, $dataStructRec);
  1079. }
  1080. $dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
  1081. } else $dataStructArray = 'No tablename ('.$tName.') or fieldname ('.$fName.') was found an valid!';
  1082. } else { // Otherwise expect it to be a file:
  1083. $file = t3lib_div::getFileAbsFileName($srcPointer);
  1084. if ($file && @is_file($file)) {
  1085. $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
  1086. } else $dataStructArray = 'The file "'.$srcPointer.'" was not found ("'.$file.'")'; // Error message.
  1087. }
  1088. } else $dataStructArray = 'No source value in fieldname "'.$ds_pointerField.'"'; // Error message.
  1089. } else $dataStructArray = 'No proper configuration!';
  1090. // Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
  1091. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
  1092. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
  1093. $hookObj = t3lib_div::getUserObj($classRef);
  1094. if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
  1095. $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
  1096. }
  1097. }
  1098. }
  1099. return $dataStructArray;
  1100. }
  1101. /*******************************************
  1102. *
  1103. * Caching related
  1104. *
  1105. *******************************************/
  1106. /**
  1107. * Stores the string value $data in the 'cache_hash' cache with the
  1108. * hash key, $hash, and visual/symbolic identification, $ident
  1109. * IDENTICAL to the function by same name found in t3lib_page:
  1110. * Usage: 2
  1111. *
  1112. * @param string 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
  1113. * @param string The data string. If you want to store an array, then just serialize it first.
  1114. * @param string $ident is just a textual identification in order to inform about the content!
  1115. * @return void
  1116. */
  1117. public static function storeHash($hash, $data, $ident) {
  1118. if (TYPO3_UseCachingFramework) {
  1119. $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
  1120. $hash,
  1121. $data,
  1122. array('ident_' . $ident),
  1123. 0 // unlimited lifetime
  1124. );
  1125. } else {
  1126. $insertFields = array(
  1127. 'hash' => $hash,
  1128. 'content' => $data,
  1129. 'ident' => $ident,
  1130. 'tstamp' => $GLOBALS['EXEC_TIME']
  1131. );
  1132. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
  1133. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
  1134. }
  1135. }
  1136. /**
  1137. * Returns string value stored for the hash string in the cache "cache_hash"
  1138. * Can be used to retrieved a cached value
  1139. *
  1140. * IDENTICAL to the function by same name found in t3lib_page
  1141. *
  1142. * @param string The hash-string which was used to store the data value
  1143. * @return string
  1144. */
  1145. public static function getHash($hash, $expTime = 0) {
  1146. $hashContent = null;
  1147. if (TYPO3_UseCachingFramework) {
  1148. $contentHashCache = $GLOBALS['typo3CacheManager']->getCache('cache_hash');
  1149. $cacheEntry = $contentHashCache->get($hash);
  1150. if ($cacheEntry) {
  1151. $hashContent = $cacheEntry;
  1152. }
  1153. } else {
  1154. $expTime = intval($expTime);
  1155. if ($expTime) {
  1156. $whereAdd = ' AND tstamp > '.(time()-$expTime);
  1157. }
  1158. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
  1159. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  1160. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  1161. $hashContent = (is_array($row) ? $row['content'] : null);
  1162. }
  1163. return $hashContent;
  1164. }
  1165. /*******************************************
  1166. *
  1167. * TypoScript related
  1168. *
  1169. *******************************************/
  1170. /**
  1171. * Returns the Page TSconfig for page with id, $id
  1172. * Requires class "t3lib_TSparser"
  1173. * Usage: 26 (spec. in ext info_pagetsconfig)
  1174. *
  1175. * @param integer Page uid for which to create Page TSconfig
  1176. * @param array If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
  1177. * @param boolean If $returnPartArray is set, then the array with accumulated Page TSconfig is returned non-parsed. Otherwise the output will be parsed by the TypoScript parser.
  1178. * @return array Page TSconfig
  1179. * @see t3lib_TSparser
  1180. */
  1181. public static function getPagesTSconfig($id, $rootLine = '', $returnPartArray = 0) {
  1182. $id = intval($id);
  1183. if (!is_array($rootLine)) {
  1184. $rootLine = self::BEgetRootLine($id, '', TRUE);
  1185. }
  1186. ksort($rootLine); // Order correctly
  1187. $TSdataArray = array();
  1188. $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
  1189. foreach($rootLine as $k => $v) {
  1190. $TSdataArray['uid_'.$v['uid']] = $v['TSconfig'];
  1191. }
  1192. $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
  1193. if ($returnPartArray) {
  1194. return $TSdataArray;
  1195. }
  1196. // Parsing the page TS-Config (or getting from cache)
  1197. $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
  1198. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions']) {
  1199. /* @var $parseObj t3lib_TSparser_TSconfig */
  1200. $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
  1201. $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
  1202. if ($res) {
  1203. $TSconfig = $res['TSconfig'];
  1204. }
  1205. } else {
  1206. $hash = md5('pageTS:' . $pageTS);
  1207. $cachedContent = self::getHash($hash);
  1208. $TSconfig = array();
  1209. if (isset($cachedContent)) {
  1210. $TSconfig = unserialize($cachedContent);
  1211. } else {
  1212. $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
  1213. $parseObj->parse($pageTS);
  1214. $TSconfig = $parseObj->setup;
  1215. self::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
  1216. }
  1217. }
  1218. // get User TSconfig overlay
  1219. $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
  1220. if (is_array($userTSconfig)) {
  1221. $TSconfig = t3lib_div::array_merge_recursive_overrule($TSconfig, $userTSconfig);
  1222. }
  1223. return $TSconfig;
  1224. }
  1225. /**
  1226. * Updates Page TSconfig for a page with $id
  1227. * The function seems to take $pageTS as an array with properties and compare the values with those that already exists for the "object string", $TSconfPrefix, for the page, then sets those values which were not present.
  1228. * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
  1229. *
  1230. * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
  1231. * More documentation is needed.
  1232. *
  1233. * Usage: 1 (ext. direct_mail)
  1234. *
  1235. * @param integer Page id
  1236. * @param array Page TS array to write
  1237. * @param string Prefix for object paths
  1238. * @param array [Description needed.]
  1239. * @return void
  1240. * @internal
  1241. * @see implodeTSParams(), getPagesTSconfig()
  1242. */
  1243. public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
  1244. $id = intval($id);
  1245. if (is_array($pageTS) && $id>0) {
  1246. if (!is_array($impParams)) {
  1247. $impParams = self::implodeTSParams(self::getPagesTSconfig($id));
  1248. }
  1249. $set = array();
  1250. foreach ($pageTS as $f => $v) {
  1251. $f = $TSconfPrefix.$f;
  1252. if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
  1253. $set[$f] = trim($v);
  1254. }
  1255. }
  1256. if (count($set)) {
  1257. // Get page record and TS config lines
  1258. $pRec = self::getRecord('pages', $id);
  1259. $TSlines = explode(LF, $pRec['TSconfig']);
  1260. $TSlines = array_reverse($TSlines);
  1261. // Reset the set of changes.
  1262. foreach ($set as $f => $v) {
  1263. $inserted = 0;
  1264. foreach ($TSlines as $ki => $kv) {
  1265. if (substr($kv, 0, strlen($f)+1)==$f.'=') {
  1266. $TSlines[$ki] = $f.'='.$v;
  1267. $inserted = 1;
  1268. break;
  1269. }
  1270. }
  1271. if (!$inserted) {
  1272. $TSlines = array_reverse($TSlines);
  1273. $TSlines[] = $f.'='.$v;
  1274. $TSlines = array_reverse($TSlines);
  1275. }
  1276. }
  1277. $TSlines = array_reverse($TSlines);
  1278. // store those changes
  1279. $TSconf = implode(LF, $TSlines);
  1280. $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
  1281. }
  1282. }
  1283. }
  1284. /**
  1285. * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
  1286. * Usage: 3
  1287. *
  1288. * @param array TypoScript structure
  1289. * @param string Prefix string
  1290. * @return array Imploded TypoScript objectstring/values
  1291. */
  1292. public static function implodeTSParams($p, $k = '') {
  1293. $implodeParams = array();
  1294. if (is_array($p)) {
  1295. foreach ($p as $kb => $val) {
  1296. if (is_array($val)) {
  1297. $implodeParams = array_merge($implodeParams, self::implodeTSParams($val, $k . $kb));
  1298. } else {
  1299. $implodeParams[$k.$kb] = $val;
  1300. }
  1301. }
  1302. }
  1303. return $implodeParams;
  1304. }
  1305. /*******************************************
  1306. *
  1307. * Users / Groups related
  1308. *
  1309. *******************************************/
  1310. /**
  1311. * Returns an array with be_users records of all user NOT DELETED sorted by their username
  1312. * Keys in the array is the be_users uid
  1313. * Usage: 14 (spec. ext. "beuser" and module "web_perm")
  1314. *
  1315. * @param string Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
  1316. * @param string Optional $where clause (fx. "AND username='pete'") can be used to limit query
  1317. * @return array
  1318. */
  1319. public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
  1320. $be_user_Array = Array();
  1321. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 ' . $where . self::deleteClause('be_users'), '', 'username');
  1322. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  1323. $be_user_Array[$row['uid']] = $row;
  1324. }
  1325. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  1326. return $be_user_Array;
  1327. }
  1328. /**
  1329. * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
  1330. * Usage: 8 (spec. ext. "beuser" and module "web_perm")
  1331. *
  1332. * @param string Field list
  1333. * @param string WHERE clause
  1334. * @return array
  1335. */
  1336. public static function getGroupNames($fields = 'title,uid', $where = '') {
  1337. $be_group_Array = Array();
  1338. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 ' . $where . self::deleteClause('be_groups'), '', 'title');
  1339. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  1340. $be_group_Array[$row['uid']] = $row;
  1341. }
  1342. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  1343. return $be_group_Array;
  1344. }
  1345. /**
  1346. * Returns an array with be_groups records (like ->getGroupNames) but:
  1347. * - if the current BE_USER is admin, then all groups are returned, otherwise only groups that the current user is member of (usergroup_cached_list) will be returned.
  1348. * Usage: 2 (module "web_perm" and ext. taskcenter)
  1349. *
  1350. * @param string Field list; $fields specify the fields selected (default: title,uid)
  1351. * @return array
  1352. */
  1353. public static function getListGroupNames($fields = 'title, uid') {
  1354. $exQ = ' AND hide_in_lists=0';
  1355. if (!$GLOBALS['BE_USER']->isAdmin()) {
  1356. $exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
  1357. }
  1358. return self::getGroupNames($fields, $exQ);
  1359. }
  1360. /**
  1361. * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
  1362. * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
  1363. * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
  1364. * Usage: 8
  1365. *
  1366. * @param array User names
  1367. * @param array Group names
  1368. * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
  1369. * @return array User names, blinded
  1370. */
  1371. public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = 0) {
  1372. if (is_array($usernames) && is_array($groupArray)) {
  1373. foreach ($usernames as $uid => $row) {
  1374. $userN = $uid;
  1375. $set = 0;
  1376. if ($row['uid']!=$GLOBALS['BE_USER']->user['uid']) {
  1377. foreach ($groupArray as $v) {
  1378. if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
  1379. $userN = $row['username'];
  1380. $set = 1;
  1381. }
  1382. }
  1383. } else {
  1384. $userN = $row['username'];
  1385. $set = 1;
  1386. }
  1387. $usernames[$uid]['username'] = $userN;
  1388. if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
  1389. }
  1390. }
  1391. return $usernames;
  1392. }
  1393. /**
  1394. * Corresponds to blindUserNames but works for groups instead
  1395. * Usage: 2 (module web_perm)
  1396. *
  1397. * @param array Group names
  1398. * @param array Group names (reference)
  1399. * @param boolean If $excludeBlindedFlag is set, then these records are unset from the array $usernames
  1400. * @return array
  1401. */
  1402. public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = 0) {
  1403. if (is_array($groups) && is_array($groupArray)) {
  1404. foreach ($groups as $uid => $row) {
  1405. $groupN = $uid;
  1406. $set = 0;
  1407. if (t3lib_div::inArray($groupArray, $uid)) {
  1408. $groupN = $row['title'];
  1409. $set = 1;
  1410. }
  1411. $groups[$uid]['title'] = $groupN;
  1412. if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
  1413. }
  1414. }
  1415. return $groups;
  1416. }
  1417. /*******************************************
  1418. *
  1419. * Output related
  1420. *
  1421. *******************************************/
  1422. /**
  1423. * Returns the difference in days between input $tstamp and $EXEC_TIME
  1424. * Usage: 2 (class t3lib_BEfunc)
  1425. *
  1426. * @param integer Time stamp, seconds
  1427. * @return integer
  1428. */
  1429. public static function daysUntil($tstamp) {
  1430. $delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
  1431. return ceil($delta_t/(3600*24));
  1432. }
  1433. /**
  1434. * Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])
  1435. * Usage: 11
  1436. *
  1437. * @param integer Time stamp, seconds
  1438. * @return string Formatted time
  1439. */
  1440. public static function date($tstamp) {
  1441. return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
  1442. }
  1443. /**
  1444. * Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])
  1445. * Usage: 28
  1446. *
  1447. * @param integer Time stamp, seconds
  1448. * @return string Formatted time
  1449. */
  1450. public static function datetime($value) {
  1451. return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
  1452. }
  1453. /**
  1454. * Returns $value (in seconds) formatted as hh:mm:ss
  1455. * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
  1456. * Usage: 1 (class t3lib_BEfunc)
  1457. *
  1458. * @param integer Time stamp, seconds
  1459. * @param boolean Output hh:mm:ss. If false: hh:mm
  1460. * @return string Formatted time
  1461. */
  1462. public static function time($value, $withSeconds = TRUE) {
  1463. $hh = floor($value/3600);
  1464. $min = floor(($value-$hh*3600)/60);
  1465. $sec = $value-$hh*3600-$min*60;
  1466. $l = sprintf('%02d', $hh).':'.sprintf('%02d', $min);
  1467. if ($withSeconds) {
  1468. $l .= ':'.sprintf('%02d', $sec);
  1469. }
  1470. return $l;
  1471. }
  1472. /**
  1473. * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
  1474. * Usage: 15
  1475. *
  1476. * @param integer $seconds could be the difference of a certain timestamp and time()
  1477. * @param string $labels should be something like ' min| hrs| days| yrs'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
  1478. * @return string Formatted time
  1479. */
  1480. public static function calcAge($seconds, $labels = 'min|hrs|days|yrs') {
  1481. $labelArr = explode('|', $labels);
  1482. $prefix = '';
  1483. if ($seconds<0) {$prefix = '-'; $seconds = abs($seconds);}
  1484. if ($seconds<3600) {
  1485. $seconds = round ($seconds/60).' '.trim($labelArr[0]);
  1486. } elseif ($seconds<24*3600) {
  1487. $seconds = round ($seconds/3600).' '.trim($labelArr[1]);
  1488. } elseif ($seconds<365*24*3600) {
  1489. $seconds = round ($seconds/(24*3600)).' '.trim($labelArr[2]);
  1490. } else {
  1491. $seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
  1492. }
  1493. return $prefix.$seconds;
  1494. }
  1495. /**
  1496. * Returns a formatted timestamp if $tstamp is set.
  1497. * The date/datetime will be followed by the age in parenthesis.
  1498. * Usage: 3
  1499. *
  1500. * @param integer Time stamp, seconds
  1501. * @param integer 1/-1 depending on polarity of age.
  1502. * @param string $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
  1503. * @return string
  1504. */
  1505. public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
  1506. return $tstamp ?
  1507. ($date=='date' ? self::date($tstamp) : self::datetime($tstamp)) .
  1508. ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) . ')'
  1509. : '';
  1510. }
  1511. /**
  1512. * Returns either title = '' or alt = '' attribute. This depends on the client browser and whether it supports title = '' or not (which is the default)
  1513. * If no $content is given only the attribute name is returned.
  1514. * The returned attribute with content will have a leading space char.
  1515. * Warning: Be careful to submit empty $content var - that will return just the attribute name!
  1516. * Usage: 0
  1517. *
  1518. * @param string String to set as title-attribute. If no $content is given only the attribute name is returned.
  1519. * @param boolean If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
  1520. * @return string
  1521. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5 - The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
  1522. */
  1523. public static function titleAttrib($content = '', $hsc = 0) {
  1524. t3lib_div::logDeprecatedFunction();
  1525. global $CLIENT;
  1526. $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
  1527. return strcmp($content, '')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
  1528. }
  1529. /**
  1530. * Returns alt="" and title="" attributes with the value of $content.
  1531. * Usage: 7
  1532. *
  1533. * @param string Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
  1534. * @return string
  1535. */
  1536. public static function titleAltAttrib($content) {
  1537. $out = '';
  1538. $out.=' alt="'.htmlspecialchars($content).'"';
  1539. $out.=' title="'.htmlspecialchars($content).'"';
  1540. return $out;
  1541. }
  1542. /**
  1543. * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field
  1544. * All $TYPO3_CONF_VARS['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
  1545. * Thumbsnails are linked to the show_item.php script which will display further details.
  1546. * Usage: 7
  1547. *
  1548. * @param array $row is the database row from the table, $table.
  1549. * @param string Table name for $row (present in TCA)
  1550. * @param string $field is pointing to the field with the list of image files
  1551. * @param string Back path prefix for image tag src="" field
  1552. * @param string Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
  1553. * @param string Optional: $uploaddir is the directory relative to PATH_site where the image files from the $field value is found (Is by default set to the entry in $TCA for that field! so you don't have to!)
  1554. * @param boolean If set, uploaddir is NOT prepended with "../"
  1555. * @param string Optional: $tparams is additional attributes for the image tags
  1556. * @param integer Optional: $size is [w]x[h] of the thumbnail. 56 is default.
  1557. * @return string Thumbnail image tag.
  1558. */
  1559. public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '') {
  1560. global $TCA;
  1561. // Load table.
  1562. t3lib_div::loadTCA($table);
  1563. // Find uploaddir automatically
  1564. $uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
  1565. $uploaddir = preg_replace('#/$#','', $uploaddir);
  1566. // Set thumbs-script:
  1567. if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
  1568. $thumbScript = 'gfx/notfound_thumb.gif';
  1569. } elseif(!$thumbScript) {
  1570. $thumbScript = 'thumbs.php';
  1571. }
  1572. // Check and parse the size parameter
  1573. $sizeParts = array();
  1574. if ($size = trim($size)) {
  1575. $sizeParts = explode('x', $size.'x'.$size);
  1576. if(!intval($sizeParts[0])) $size = '';
  1577. }
  1578. // Traverse files:
  1579. $thumbs = explode(',', $row[$field]);
  1580. $thumbData = '';
  1581. foreach ($thumbs as $theFile) {
  1582. if (trim($theFile)) {
  1583. $fI = t3lib_div::split_fileref($theFile);
  1584. $ext = $fI['fileext'];
  1585. // New 190201 start
  1586. $max = 0;
  1587. if (t3lib_div::inList('gif,jpg,png', $ext)) {
  1588. $imgInfo = @getimagesize(PATH_site.$uploaddir.'/'.$theFile);
  1589. if (is_array($imgInfo)) {$max = max($imgInfo[0], $imgInfo[1]);}
  1590. }
  1591. // use the original image if it's size fits to the thumbnail size
  1592. if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56)) {
  1593. $theFile = $url = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
  1594. $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
  1595. $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
  1596. // New 190201 stop
  1597. } elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $ext)) {
  1598. $theFile_abs = PATH_site.($uploaddir?$uploaddir.'/':'').trim($theFile);
  1599. $theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
  1600. if (!is_readable($theFile_abs)) {
  1601. $flashMessage = t3lib_div::makeInstance(
  1602. 't3lib_FlashMessage',
  1603. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing_text') . ' <abbr title="' . $theFile_abs . '">' . $theFile . '</abbr>',
  1604. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing'),
  1605. t3lib_FlashMessage::ERROR
  1606. );
  1607. $thumbData .= $flashMessage->render();
  1608. continue;
  1609. }
  1610. $check = basename($theFile_abs).':'.filemtime($theFile_abs).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  1611. $params = '&file='.rawurlencode($theFile);
  1612. $params.= $size?'&size='.$size:'';
  1613. $params.= '&md5sum='.t3lib_div::shortMD5($check);
  1614. $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
  1615. $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
  1616. $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
  1617. } else {
  1618. $icon = self::getFileIcon($ext);
  1619. $url = 'gfx/fileicons/'.$icon;
  1620. $thumbData.= '<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
  1621. }
  1622. }
  1623. }
  1624. return $thumbData;
  1625. }
  1626. /**
  1627. * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
  1628. * Usage: 3
  1629. *
  1630. * @param string $thumbScript must point to "thumbs.php" relative to the script position
  1631. * @param string $theFile must be the proper reference to the file thumbs.php should show
  1632. * @param string $tparams are additional attributes for the image tag
  1633. * @param integer $size is the size of the thumbnail send along to "thumbs.php"
  1634. * @return string Image tag
  1635. */
  1636. public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
  1637. $check = basename($theFile).':'.filemtime($theFile).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  1638. $params = '&file='.rawurlencode($theFile);
  1639. $params.= trim($size)?'&size='.trim($size):'';
  1640. $params.= '&md5sum='.t3lib_div::shortMD5($check);
  1641. $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
  1642. $th = '<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
  1643. return $th;
  1644. }
  1645. /**
  1646. * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
  1647. * Usage: 8
  1648. *
  1649. * @param array Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
  1650. * @param string $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
  1651. * @param boolean If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
  1652. * @return string
  1653. */
  1654. public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
  1655. global $TCA, $LANG;
  1656. $parts = array();
  1657. $parts[] = 'id='.$row['uid'];
  1658. if ($row['alias']) $parts[] = $LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
  1659. if ($row['pid']<0) $parts[] = 'v#1.'.$row['t3ver_id'];
  1660. switch($row['t3ver_state']) {
  1661. case 1:
  1662. $parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
  1663. break;
  1664. case 2:
  1665. $parts[] = 'Deleted element!';
  1666. break;
  1667. case 3:
  1668. $parts[] = 'NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
  1669. break;
  1670. case 4:
  1671. $parts[] = 'OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
  1672. break;
  1673. case -1:
  1674. $parts[] = 'New element!';
  1675. break;
  1676. }
  1677. if ($row['doktype']=='3') {
  1678. $parts[] = $LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
  1679. } elseif ($row['doktype']=='4') {
  1680. if ($perms_clause) {
  1681. $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
  1682. } else {
  1683. $lRec = self::getRecordWSOL('pages', intval($row['shortcut']), 'title');
  1684. $label = $lRec['title'];
  1685. }
  1686. if ($row['shortcut_mode']>0) {
  1687. $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
  1688. $LANG->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
  1689. }
  1690. $parts[] = $LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
  1691. } elseif ($row['doktype']=='7') {
  1692. if ($perms_clause) {
  1693. $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
  1694. } else {
  1695. $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
  1696. $label = $lRec['title'];
  1697. }
  1698. $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
  1699. if ($row['mount_pid_ol']) {
  1700. $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
  1701. }
  1702. }
  1703. if ($row['nav_hide']) $parts[] = rtrim($LANG->sL($TCA['pages']['columns']['nav_hide']['label']), ':');
  1704. if ($row['hidden']) $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
  1705. if ($row['starttime']) $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
  1706. if ($row['endtime']) $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
  1707. if ($row['fe_group']) {
  1708. $fe_groups = array();
  1709. foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
  1710. if ($fe_group<0) {
  1711. $fe_groups[] = $LANG->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
  1712. } else {
  1713. $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
  1714. $fe_groups[] = $lRec['title'];
  1715. }
  1716. }
  1717. $label = implode(', ', $fe_groups);
  1718. $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
  1719. }
  1720. $out = htmlspecialchars(implode(' - ', $parts));
  1721. return $includeAttrib ? 'title="'.$out.'"' : $out;
  1722. }
  1723. /**
  1724. * Returns title-attribute information for ANY record (from a table defined in TCA of course)
  1725. * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
  1726. * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
  1727. * Usage: 10
  1728. *
  1729. * @param array Table row; $row is a row from the table, $table
  1730. * @param string Table name
  1731. * @return string
  1732. */
  1733. public static function getRecordIconAltText($row, $table = 'pages') {
  1734. if ($table=='pages') {
  1735. $out = self::titleAttribForPages($row, '', 0);
  1736. } else {
  1737. $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
  1738. $out = 'id='.$row['uid']; // Uid is added
  1739. if ($table=='pages' && $row['alias']) {
  1740. $out.=' / '.$row['alias'];
  1741. }
  1742. if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0) {
  1743. $out.=' - v#1.'.$row['t3ver_id'];
  1744. }
  1745. if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
  1746. switch($row['t3ver_state']) {
  1747. case 1:
  1748. $out.= ' - PLH WSID#'.$row['t3ver_wsid'];
  1749. break;
  1750. case 2:
  1751. $out.= ' - Deleted element!';
  1752. break;
  1753. case 3:
  1754. $out.= ' - NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
  1755. break;
  1756. case 4:
  1757. $out.= ' - OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
  1758. break;
  1759. case -1:
  1760. $out.= ' - New element!';
  1761. break;
  1762. }
  1763. }
  1764. if ($ctrl['disabled']) { // Hidden ...
  1765. $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
  1766. }
  1767. if ($ctrl['starttime']) {
  1768. if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
  1769. $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime') . ':' .
  1770. self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' .
  1771. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
  1772. }
  1773. }
  1774. if ($row[$ctrl['endtime']]) {
  1775. $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime') . ': ' .
  1776. self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' .
  1777. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
  1778. }
  1779. }
  1780. return htmlspecialchars($out);
  1781. }
  1782. /**
  1783. * Returns the label of the first found entry in an "items" array from $TCA (tablename = $table/fieldname = $col) where the value is $key
  1784. * Usage: 9
  1785. *
  1786. * @param string Table name, present in $TCA
  1787. * @param string Field name, present in $TCA
  1788. * @param string items-array value to match
  1789. * @return string Label for item entry
  1790. */
  1791. public static function getLabelFromItemlist($table, $col, $key) {
  1792. global $TCA;
  1793. // Load full TCA for $table
  1794. t3lib_div::loadTCA($table);
  1795. // Check, if there is an "items" array:
  1796. if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
  1797. // Traverse the items-array...
  1798. foreach ($TCA[$table]['columns'][$col]['config']['items'] as $k => $v) {
  1799. // ... and return the first found label where the value was equal to $key
  1800. if (!strcmp($v[1], $key)) return $v[0];
  1801. }
  1802. }
  1803. }
  1804. /**
  1805. * Returns the label-value for fieldname $col in table, $table
  1806. * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap = '<strong>|</strong>' and the fieldname was 'not_found_field' then the return value would be '<strong>not_found_field</strong>'
  1807. * Usage: 17
  1808. *
  1809. * @param string Table name, present in $TCA
  1810. * @param string Field name
  1811. * @param string Wrap value - set function description
  1812. * @return string
  1813. */
  1814. public static function getItemLabel($table, $col, $printAllWrap = '') {
  1815. global $TCA;
  1816. // Load full TCA for $table
  1817. t3lib_div::loadTCA($table);
  1818. // Check if column exists
  1819. if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
  1820. // Re
  1821. return $TCA[$table]['columns'][$col]['label'];
  1822. }
  1823. if ($printAllWrap) {
  1824. $parts = explode('|', $printAllWrap);
  1825. return $parts[0].$col.$parts[1];
  1826. }
  1827. }
  1828. /**
  1829. * Returns the "title"-value in record, $row, from table, $table
  1830. * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
  1831. * Usage: 26
  1832. *
  1833. * @param string Table name, present in TCA
  1834. * @param array Row from table
  1835. * @param boolean If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
  1836. * @param boolean If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
  1837. * @return string
  1838. */
  1839. public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
  1840. global $TCA;
  1841. if (is_array($TCA[$table])) {
  1842. // If configured, call userFunc
  1843. if ($TCA[$table]['ctrl']['label_userFunc']) {
  1844. $params['table'] = $table;
  1845. $params['row'] = $row;
  1846. $params['title'] = '';
  1847. t3lib_div::callUserFunction($TCA[$table]['ctrl']['label_userFunc'], $params, $this);
  1848. $t = $params['title'];
  1849. } else {
  1850. // No userFunc: Build label
  1851. $t = self::getProcessedValue($table, $TCA[$table]['ctrl']['label'], $row[$TCA[$table]['ctrl']['label']], 0, 0, false, $row['uid'], $forceResult);
  1852. if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
  1853. $altFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
  1854. $tA = array();
  1855. if (!empty($t)) $tA[] = $t;
  1856. foreach ($altFields as $fN) {
  1857. $t = trim(strip_tags($row[$fN]));
  1858. if (strcmp($t, '')) {
  1859. $t = self::getProcessedValue($table, $fN, $t, 0, 0, false, $row['uid']);
  1860. if (!$TCA[$table]['ctrl']['label_alt_force']) {
  1861. break;
  1862. }
  1863. $tA[] = $t;
  1864. }
  1865. }
  1866. if ($TCA[$table]['ctrl']['label_alt_force']) {
  1867. $t = implode(', ', $tA);
  1868. }
  1869. }
  1870. }
  1871. // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
  1872. if ($prep || $forceResult) {
  1873. if ($prep) {
  1874. $t = self::getRecordTitlePrep($t);
  1875. }
  1876. if (!strcmp(trim($t), '')) {
  1877. $t = self::getNoRecordTitle($prep);
  1878. }
  1879. }
  1880. return $t;
  1881. }
  1882. }
  1883. /**
  1884. * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
  1885. * which offers a tooltip with the original title when moving mouse over it.
  1886. *
  1887. * @param string $title: The title string to be cropped
  1888. * @param integer $titleLength: Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
  1889. * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
  1890. */
  1891. public static function getRecordTitlePrep($title, $titleLength = 0) {
  1892. // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
  1893. if (!$titleLength || !t3lib_div::testInt($titleLength) || $titleLength < 0) {
  1894. $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
  1895. }
  1896. $titleOrig = htmlspecialchars($title);
  1897. $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($title, $titleLength));
  1898. // If title was cropped, offer a tooltip:
  1899. if ($titleOrig != $title) {
  1900. $title = '<span title="'.$titleOrig.'">'.$title.'</span>';
  1901. }
  1902. return $title;
  1903. }
  1904. /**
  1905. * Get a localized [No title] string, wrapped in <em>|</em> if $prep is true.
  1906. *
  1907. * @param boolean $prep: Wrap result in <em>|</em>
  1908. * @return string Localized [No title] string
  1909. */
  1910. public static function getNoRecordTitle($prep = FALSE) {
  1911. $noTitle = '['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1).']';
  1912. if ($prep) $noTitle = '<em>'.$noTitle.'</em>';
  1913. return $noTitle;
  1914. }
  1915. /**
  1916. * Returns a human readable output of a value from a record
  1917. * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
  1918. * $table/$col is tablename and fieldname
  1919. * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
  1920. * Usage: 24
  1921. *
  1922. * @param string Table name, present in TCA
  1923. * @param string Field name, present in TCA
  1924. * @param string $value is the value of that field from a selected record
  1925. * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
  1926. * @param boolean $defaultPassthrough flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
  1927. * @param boolean If set, no records will be looked up, UIDs are just shown.
  1928. * @param integer uid of the current record
  1929. * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
  1930. * @return string
  1931. */
  1932. public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
  1933. global $TCA;
  1934. global $TYPO3_CONF_VARS;
  1935. if ($col == 'uid') {
  1936. // no need to load TCA as uid is not in TCA-array
  1937. return $value;
  1938. }
  1939. // Load full TCA for $table
  1940. t3lib_div::loadTCA($table);
  1941. // Check if table and field is configured:
  1942. if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
  1943. // Depending on the fields configuration, make a meaningful output value.
  1944. $theColConf = $TCA[$table]['columns'][$col]['config'];
  1945. /*****************
  1946. *HOOK: pre-processing the human readable output from a record
  1947. ****************/
  1948. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
  1949. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
  1950. t3lib_div::callUserFunction($_funcRef,$theColConf,$this);
  1951. }
  1952. }
  1953. $l = '';
  1954. switch((string)$theColConf['type']) {
  1955. case 'radio':
  1956. $l = self::getLabelFromItemlist($table, $col, $value);
  1957. $l = $GLOBALS['LANG']->sL($l);
  1958. break;
  1959. case 'select':
  1960. if ($theColConf['MM']) {
  1961. // Display the title of MM related records in lists
  1962. if ($noRecordLookup) {
  1963. $MMfield = $theColConf['foreign_table'].'.uid';
  1964. } else {
  1965. $MMfields = array($theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label']);
  1966. foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
  1967. $MMfields[] = $theColConf['foreign_table'].'.'.$f;
  1968. }
  1969. $MMfield = join(',',$MMfields);
  1970. }
  1971. $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
  1972. $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
  1973. $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
  1974. if (is_array($selectUids) && count($selectUids)>0) {
  1975. $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  1976. 'uid, '.$MMfield,
  1977. $theColConf['foreign_table'],
  1978. 'uid IN ('.implode(',', $selectUids).')'
  1979. );
  1980. while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
  1981. $mmlA[] = ($noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
  1982. }
  1983. $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
  1984. if (is_array($mmlA)) {
  1985. $l = implode('; ', $mmlA);
  1986. } else {
  1987. $l = '';
  1988. }
  1989. } else {
  1990. $l = 'N/A';
  1991. }
  1992. } else {
  1993. $l = self::getLabelFromItemlist($table, $col, $value);
  1994. $l = $GLOBALS['LANG']->sL($l);
  1995. if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
  1996. if ($noRecordLookup) {
  1997. $l = $value;
  1998. } else {
  1999. $rParts = t3lib_div::trimExplode(',', $value, 1);
  2000. $lA = array();
  2001. foreach ($rParts as $rVal) {
  2002. $rVal = intval($rVal);
  2003. if ($rVal>0) {
  2004. $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
  2005. } else {
  2006. $r = self::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
  2007. }
  2008. if (is_array($r)) {
  2009. $lA[] = $GLOBALS['LANG']->sL($rVal>0?$theColConf['foreign_table_prefix']:$theColConf['neg_foreign_table_prefix']) . self::getRecordTitle($rVal>0?$theColConf['foreign_table']:$theColConf['neg_foreign_table'], $r, FALSE, $forceResult);
  2010. } else {
  2011. $lA[] = $rVal?'['.$rVal.'!]':'';
  2012. }
  2013. }
  2014. $l = implode(', ', $lA);
  2015. }
  2016. }
  2017. }
  2018. break;
  2019. case 'group':
  2020. $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
  2021. break;
  2022. case 'check':
  2023. if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
  2024. $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
  2025. } else {
  2026. $lA = Array();
  2027. foreach ($theColConf['items'] as $key => $val) {
  2028. if ($value & pow(2, $key)) {$lA[] = $GLOBALS['LANG']->sL($val[0]);}
  2029. }
  2030. $l = implode(', ', $lA);
  2031. }
  2032. break;
  2033. case 'input':
  2034. if (isset($value)) {
  2035. if (t3lib_div::inList($theColConf['eval'], 'date')) {
  2036. $l = self::date($value) .
  2037. ' (' .
  2038. ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
  2039. self::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
  2040. ')';
  2041. } elseif (t3lib_div::inList($theColConf['eval'], 'time')) {
  2042. $l = self::time($value, FALSE);
  2043. } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
  2044. $l = self::time($value);
  2045. } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
  2046. $l = self::datetime($value);
  2047. } else {
  2048. $l = $value;
  2049. }
  2050. }
  2051. break;
  2052. case 'flex':
  2053. $l = strip_tags($value);
  2054. break;
  2055. default:
  2056. if ($defaultPassthrough) {
  2057. $l = $value;
  2058. } elseif ($theColConf['MM']) {
  2059. $l = 'N/A';
  2060. } elseif ($value) {
  2061. $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
  2062. }
  2063. break;
  2064. }
  2065. // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
  2066. if (stristr($theColConf['eval'], 'password')) {
  2067. unset($l);
  2068. $randomNumber = rand(5, 12);
  2069. for ($i=0; $i < $randomNumber; $i++) {
  2070. $l .= '*';
  2071. }
  2072. }
  2073. /*****************
  2074. *HOOK: post-processing the human readable output from a record
  2075. ****************/
  2076. if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
  2077. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
  2078. $params = array(
  2079. 'value' => $l,
  2080. 'colConf' => $theColConf
  2081. );
  2082. $l = t3lib_div::callUserFunction($_funcRef, $params, $this);
  2083. }
  2084. }
  2085. if ($fixed_lgd_chars) {
  2086. return t3lib_div::fixed_lgd_cs($l, $fixed_lgd_chars);
  2087. } else {
  2088. return $l;
  2089. }
  2090. }
  2091. }
  2092. /**
  2093. * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
  2094. * Usage: 2
  2095. *
  2096. * @param string Table name, present in TCA
  2097. * @param string Field name
  2098. * @param string Field value
  2099. * @param integer $fixed_lgd_chars is the max amount of characters the value may occupy
  2100. * @param integer uid of the current record
  2101. * @param boolean If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
  2102. * @return string
  2103. * @see getProcessedValue()
  2104. */
  2105. public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
  2106. global $TCA;
  2107. $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 0, 0, $uid, $forceResult);
  2108. if (!isset($fVnew)) {
  2109. if (is_array($TCA[$table])) {
  2110. if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
  2111. $fVnew = self::datetime($fV);
  2112. } elseif ($fN=='pid'){
  2113. $fVnew = self::getRecordPath($fV, '1=1', 20); // Fetches the path with no regard to the users permissions to select pages.
  2114. } else {
  2115. $fVnew = $fV;
  2116. }
  2117. }
  2118. }
  2119. return $fVnew;
  2120. }
  2121. /**
  2122. * Returns file icon name (from $FILEICONS) for the fileextension $ext
  2123. * Usage: 10
  2124. *
  2125. * @param string File extension, lowercase
  2126. * @return string File icon filename
  2127. */
  2128. public static function getFileIcon($ext) {
  2129. return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
  2130. }
  2131. /**
  2132. * Returns fields for a table, $table, which would typically be interesting to select
  2133. * This includes uid, the fields defined for title, icon-field.
  2134. * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
  2135. * Usage: 3
  2136. *
  2137. * @param string Table name, present in TCA
  2138. * @param string Table prefix
  2139. * @param array Preset fields (must include prefix if that is used)
  2140. * @return string List of fields.
  2141. */
  2142. public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
  2143. global $TCA;
  2144. $fields[] = $prefix.'uid';
  2145. $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
  2146. if ($TCA[$table]['ctrl']['label_alt']) {
  2147. $secondFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
  2148. foreach($secondFields as $fieldN) {
  2149. $fields[] = $prefix.$fieldN;
  2150. }
  2151. }
  2152. if ($TCA[$table]['ctrl']['versioningWS']) {
  2153. $fields[] = $prefix.'t3ver_id';
  2154. $fields[] = $prefix.'t3ver_state';
  2155. $fields[] = $prefix.'t3ver_wsid';
  2156. $fields[] = $prefix.'t3ver_count';
  2157. }
  2158. if ($TCA[$table]['ctrl']['selicon_field']) $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
  2159. if ($TCA[$table]['ctrl']['typeicon_column']) $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
  2160. if (is_array($TCA[$table]['ctrl']['enablecolumns'])) {
  2161. if ($TCA[$table]['ctrl']['enablecolumns']['disabled']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
  2162. if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
  2163. if ($TCA[$table]['ctrl']['enablecolumns']['endtime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
  2164. if ($TCA[$table]['ctrl']['enablecolumns']['fe_group']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
  2165. }
  2166. return implode(',', array_unique($fields));
  2167. }
  2168. /**
  2169. * Makes a form for configuration of some values based on configuration found in the array $configArray, with default values from $defaults and a data-prefix $dataPrefix
  2170. * <form>-tags must be supplied separately
  2171. * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3. That's were you can expect to find example, if anywhere.
  2172. * Usage: 1 (ext. direct_mail)
  2173. *
  2174. * @param array Field configuration code.
  2175. * @param array Defaults
  2176. * @param string Prefix for formfields
  2177. * @return string HTML for a form.
  2178. */
  2179. public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
  2180. $params = $defaults;
  2181. if (is_array($configArray)) {
  2182. $lines = array();
  2183. foreach ($configArray as $fname => $config) {
  2184. if (is_array($config)) {
  2185. $lines[$fname] = '<strong>'.htmlspecialchars($config[1]).'</strong><br />';
  2186. $lines[$fname].=$config[2].'<br />';
  2187. switch($config[0]) {
  2188. case 'string':
  2189. case 'short':
  2190. $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
  2191. break;
  2192. case 'check':
  2193. $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
  2194. break;
  2195. case 'comment':
  2196. $formEl = '';
  2197. break;
  2198. case 'select':
  2199. $opt = array();
  2200. foreach ($config[3] as $k => $v) {
  2201. $opt[] = '<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
  2202. }
  2203. $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('', $opt).'</select>';
  2204. break;
  2205. default:
  2206. debug($config);
  2207. break;
  2208. }
  2209. $lines[$fname].=$formEl;
  2210. $lines[$fname].='<br /><br />';
  2211. } else {
  2212. $lines[$fname] = '<hr />';
  2213. if ($config) $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
  2214. if ($config) $lines[$fname].='<br />';
  2215. }
  2216. }
  2217. }
  2218. $out = implode('', $lines);
  2219. $out.='<input type="submit" name="submit" value="Update configuration" />';
  2220. return $out;
  2221. }
  2222. /*******************************************
  2223. *
  2224. * Backend Modules API functions
  2225. *
  2226. *******************************************/
  2227. /**
  2228. * Returns help-text icon if configured for.
  2229. * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
  2230. * Usage: 6
  2231. *
  2232. * @param string Table name
  2233. * @param string Field name
  2234. * @param string Back path
  2235. * @param boolean Force display of icon nomatter BE_USER setting for help
  2236. * @return string HTML content for a help icon/text
  2237. */
  2238. public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
  2239. global $TCA_DESCR, $BE_USER;
  2240. $onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
  2241. if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && (isset($BE_USER->uc['edit_showFieldHelp']) || $force)) {
  2242. if ($BE_USER->uc['edit_showFieldHelp'] == 'icon') {
  2243. $text = self::helpText($table, $field, $BACK_PATH, '');
  2244. $text = '<div class="typo3-csh-inline">' . $GLOBALS['LANG']->hscAndCharConv($text, false) . '</div>';
  2245. }
  2246. return '<a class="typo3-csh-link" href="#" onclick="'.htmlspecialchars($onClick).'">' . t3lib_iconWorks::getSpriteIcon('actions-system-help-open', array('class' => 'typo3-csh-icon')) . $text.'</a>';
  2247. }
  2248. }
  2249. /**
  2250. * Returns CSH help text (description), if configured for.
  2251. * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text",
  2252. * otherwise nothing is returned
  2253. * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
  2254. * Usage: 4
  2255. *
  2256. * @param string Table name
  2257. * @param string Field name
  2258. * @param string Back path
  2259. * @param string DEPRECATED: Additional style-attribute content for wrapping table (now: only in function cshItem needed)
  2260. * @return string HTML content for help text
  2261. */
  2262. public static function helpText($table, $field, $BACK_PATH, $styleAttrib = '') {
  2263. global $TCA_DESCR, $BE_USER;
  2264. $output = '';
  2265. if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field])) {
  2266. $data = $TCA_DESCR[$table]['columns'][$field];
  2267. // add see also arrow
  2268. if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
  2269. $arrow = t3lib_iconWorks::getSpriteIcon('actions-view-go-forward');
  2270. }
  2271. // add description text
  2272. if ($data['description'] || $arrow) {
  2273. $output = '<p class="t3-csh-short">' . nl2br(htmlspecialchars($data['description'])) . $arrow . '</p>';
  2274. }
  2275. // put header before the rest of the text
  2276. if ($data['alttitle']) {
  2277. $output = '<h2 class="t3-row-header">' . $data['alttitle'] . '</h2>' . $output;
  2278. }
  2279. }
  2280. return $output;
  2281. }
  2282. /**
  2283. * API for getting CSH icons/text for use in backend modules.
  2284. * TCA_DESCR will be loaded if it isn't already
  2285. * Usage: ?
  2286. *
  2287. * @param string Table name ('_MOD_'+module name)
  2288. * @param string Field name (CSH locallang main key)
  2289. * @param string Back path
  2290. * @param string Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
  2291. * @param boolean If set, the full text will never be shown (only icon).
  2292. * Useful for places where it will break the page if the table with full text is shown.
  2293. * @param string Additional style-attribute content for wrapping table (full text mode only)
  2294. * @return string HTML content for help text
  2295. * @see helpText(), helpTextIcon()
  2296. */
  2297. public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
  2298. global $TCA_DESCR, $LANG, $BE_USER;
  2299. if ($BE_USER->uc['edit_showFieldHelp']) {
  2300. $LANG->loadSingleTableDescription($table);
  2301. if (is_array($TCA_DESCR[$table])) {
  2302. // Creating CSH icon and short description:
  2303. $fullText = self::helpText($table, $field, $BACK_PATH, '');
  2304. $icon = self::helpTextIcon($table, $field, $BACK_PATH);
  2305. if ($fullText && !$onlyIconMode && $BE_USER->uc['edit_showFieldHelp'] == 'text') {
  2306. // Additional styles?
  2307. $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
  2308. // Compile table with CSH information:
  2309. $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"'.$params.'>
  2310. <tr>
  2311. <td valign="top" width="14"><div class="t3-row-header">' . $icon . '</div></td>
  2312. <td valign="top">'.$fullText.'</td>
  2313. </tr>
  2314. </table>';
  2315. $output = $LANG->hscAndCharConv($fullText, false);
  2316. } else {
  2317. $output = $icon;
  2318. if ($output && $wrap) {
  2319. $wrParts = explode('|', $wrap);
  2320. $output = $wrParts[0].$output.$wrParts[1];
  2321. }
  2322. }
  2323. return $output;
  2324. }
  2325. }
  2326. }
  2327. /**
  2328. * Returns a JavaScript string (for an onClick handler) which will load the alt_doc.php script that shows the form for editing of the record(s) you have send as params.
  2329. * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
  2330. * Usage: 35
  2331. *
  2332. * @param string $params is parameters sent along to alt_doc.php. This requires a much more details description which you must seek in Inside TYPO3s documentation of the alt_doc.php API. And example could be '&edit[pages][123] = edit' which will show edit form for page record 123.
  2333. * @param string $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
  2334. * @param string $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
  2335. * @return string
  2336. * @see template::issueCommand()
  2337. */
  2338. public static function editOnClick($params, $backPath = '', $requestUri = '') {
  2339. $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
  2340. return "window.location.href='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
  2341. }
  2342. /**
  2343. * Returns a JavaScript string for viewing the page id, $id
  2344. * It will detect the correct domain name if needed and provide the link with the right back path. Also it will re-use any window already open.
  2345. * Usage: 8
  2346. *
  2347. * @param integer $id is page id
  2348. * @param string $backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
  2349. * @param array If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
  2350. * @param string $anchor is optional anchor to the URL
  2351. * @param string $altUrl is an alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
  2352. * @param string Additional GET variables.
  2353. * @param boolean If true, then the preview window will gain the focus.
  2354. * @return string
  2355. */
  2356. public static function viewOnClick($id, $backPath = '', $rootLine = '', $anchor = '', $altUrl = '', $addGetVars = '', $switchFocus = TRUE) {
  2357. $viewScriptPreviewEnabled = '/' . TYPO3_mainDir . 'mod/user/ws/wsol_preview.php?id=';
  2358. $viewScriptPreviewDisabled = '/index.php?id=';
  2359. if ($altUrl) {
  2360. $viewScriptPreviewEnabled = $viewScriptPreviewDisabled = $altUrl;
  2361. }
  2362. // Look if a fixed preview language should be added:
  2363. $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
  2364. if (strlen($viewLanguageOrder)) {
  2365. $suffix = '';
  2366. // Find allowed languages (if none, all are allowed!)
  2367. if (!$GLOBALS['BE_USER']->user['admin'] &&
  2368. strlen($GLOBALS['BE_USER']->groupData['allowed_languages'])) {
  2369. $allowed_languages = array_flip(explode(',', $GLOBALS['BE_USER']->groupData['allowed_languages']));
  2370. }
  2371. // Traverse the view order, match first occurence:
  2372. $lOrder = t3lib_div::intExplode(',', $viewLanguageOrder);
  2373. foreach($lOrder as $langUid) {
  2374. if (is_array($allowed_languages) && count($allowed_languages)) {
  2375. if (isset($allowed_languages[$langUid])) { // Choose if set.
  2376. $suffix = '&L=' . $langUid;
  2377. break;
  2378. }
  2379. } else { // All allowed since no lang. are listed.
  2380. $suffix = '&L=' . $langUid;
  2381. break;
  2382. }
  2383. }
  2384. // Add it:
  2385. $addGetVars .= $suffix;
  2386. }
  2387. // check if we need to preview a mount point
  2388. $sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
  2389. $sys_page->init(FALSE);
  2390. $mountPointInfo = $sys_page->getMountPointInfo($id);
  2391. if ($mountPointInfo && $mountPointInfo['overlay']) {
  2392. $id = $mountPointInfo['mount_pid'];
  2393. $addGetVars .= '&MP=' . $mountPointInfo['MPvar'];
  2394. }
  2395. $viewDomain = self::getViewDomain($id, $rootLine);
  2396. $urlPreviewEnabled = $viewDomain . $viewScriptPreviewEnabled . $id . $addGetVars . $anchor;
  2397. $urlPreviewDisabled = $viewDomain . $viewScriptPreviewDisabled . $id . $addGetVars . $anchor;
  2398. return "var previewWin=window.open(top.TYPO3.configuration.inWorkspace !== 0 && top.TYPO3.configuration.workspaceFrontendPreviewEnabled ?'" .
  2399. $urlPreviewEnabled . "':'" . $urlPreviewDisabled .
  2400. "','newTYPO3frontendWindow');" . ( $switchFocus ? 'previewWin.focus();' : '');
  2401. }
  2402. /**
  2403. * Builds the frontend view domain for a given page ID with a given root
  2404. * line.
  2405. *
  2406. * @param integer $pageId the page ID to use, must be > 0
  2407. * @param array $rootLine the root line structure to use
  2408. *
  2409. * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
  2410. *
  2411. * @author Michael Klapper <michael.klapper@aoemedia.de>
  2412. */
  2413. public static function getViewDomain($pageId, $rootLine = null) {
  2414. $domain = rtrim(t3lib_div::getIndpEnv('TYPO3_SITE_URL'), '/');
  2415. if (!is_array($rootLine)) {
  2416. $rootLine = self::BEgetRootLine($pageId);
  2417. }
  2418. // checks alternate domains
  2419. if (count($rootLine) > 0) {
  2420. $urlParts = parse_url($domain);
  2421. if (self::getDomainStartPage($urlParts['host'], $urlParts['path'])) {
  2422. $protocol = t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://';
  2423. $domain = $protocol . self::firstDomainRecord($rootLine);
  2424. }
  2425. }
  2426. return $domain;
  2427. }
  2428. /**
  2429. * Returns the merged User/Page TSconfig for page id, $id.
  2430. * Please read details about module programming elsewhere!
  2431. * Usage: 15
  2432. *
  2433. * @param integer Page uid
  2434. * @param string $TSref is an object string which determines the path of the TSconfig to return.
  2435. * @return array
  2436. */
  2437. public static function getModTSconfig($id, $TSref) {
  2438. $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, self::getPagesTSconfig($id));
  2439. $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
  2440. $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
  2441. return $modTSconfig;
  2442. }
  2443. /**
  2444. * Returns a selector box "function menu" for a module
  2445. * Requires the JS function jumpToUrl() to be available
  2446. * See Inside TYPO3 for details about how to use / make Function menus
  2447. * Usage: 50
  2448. *
  2449. * @param mixed $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
  2450. * @param string $elementName it the form elements name, probably something like "SET[...]"
  2451. * @param string $currentValue is the value to be selected currently.
  2452. * @param array $menuItems is an array with the menu items for the selector box
  2453. * @param string $script is the script to send the &id to, if empty it's automatically found
  2454. * @param string $addParams is additional parameters to pass to the script.
  2455. * @return string HTML code for selector box
  2456. */
  2457. public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
  2458. if (is_array($menuItems)) {
  2459. if (!is_array($mainParams)) {
  2460. $mainParams = array('id' => $mainParams);
  2461. }
  2462. $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
  2463. if (!$script) {
  2464. $script = basename(PATH_thisScript);
  2465. $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
  2466. }
  2467. $options = array();
  2468. foreach($menuItems as $value => $label) {
  2469. $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue, $value)?' selected="selected"':'').'>'.
  2470. t3lib_div::deHSCentities(htmlspecialchars($label)).
  2471. '</option>';
  2472. }
  2473. if (count($options)) {
  2474. $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
  2475. return '
  2476. <!-- Function Menu of module -->
  2477. <select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
  2478. '.implode('
  2479. ',$options).'
  2480. </select>
  2481. ';
  2482. }
  2483. }
  2484. }
  2485. /**
  2486. * Checkbox function menu.
  2487. * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
  2488. * Usage: 34
  2489. *
  2490. * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
  2491. * @param string $elementName it the form elements name, probably something like "SET[...]"
  2492. * @param string $currentValue is the value to be selected currently.
  2493. * @param string $script is the script to send the &id to, if empty it's automatically found
  2494. * @param string $addParams is additional parameters to pass to the script.
  2495. * @param string Additional attributes for the checkbox input tag
  2496. * @return string HTML code for checkbox
  2497. * @see getFuncMenu()
  2498. */
  2499. public static function getFuncCheck($mainParams, $elementName, $currentValue, $script = '', $addparams = '', $tagParams = '') {
  2500. if (!is_array($mainParams)) {
  2501. $mainParams = array('id' => $mainParams);
  2502. }
  2503. $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
  2504. if (!$script) {
  2505. $script = basename(PATH_thisScript);
  2506. $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
  2507. }
  2508. $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
  2509. return '<input type="checkbox" class="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
  2510. }
  2511. /**
  2512. * Input field function menu
  2513. * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
  2514. * Usage: 1
  2515. *
  2516. * @param mixed $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
  2517. * @param string $elementName it the form elements name, probably something like "SET[...]"
  2518. * @param string $currentValue is the value to be selected currently.
  2519. * @param integer Relative size of input field, max is 48
  2520. * @param string $script is the script to send the &id to, if empty it's automatically found
  2521. * @param string $addParams is additional parameters to pass to the script.
  2522. * @return string HTML code for input text field.
  2523. * @see getFuncMenu()
  2524. */
  2525. public static function getFuncInput($mainParams, $elementName, $currentValue, $size = 10, $script = "", $addparams = "") {
  2526. if (!is_array($mainParams)) {
  2527. $mainParams = array('id' => $mainParams);
  2528. }
  2529. $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
  2530. if (!$script) {
  2531. $script = basename(PATH_thisScript);
  2532. $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
  2533. }
  2534. $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
  2535. return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
  2536. }
  2537. /**
  2538. * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
  2539. * See Inside TYPO3 about how to program modules and use this API.
  2540. * Usage: 4
  2541. *
  2542. * @param array Module TS config array
  2543. * @param array Array of items from which to remove items.
  2544. * @param string $TSref points to the "object string" in $modTSconfig
  2545. * @return array The modified $itemArray is returned.
  2546. */
  2547. public static function unsetMenuItems($modTSconfig, $itemArray, $TSref) {
  2548. // Getting TS-config options for this module for the Backend User:
  2549. $conf = $GLOBALS['BE_USER']->getTSConfig($TSref, $modTSconfig);
  2550. if (is_array($conf['properties'])) {
  2551. foreach ($conf['properties'] as $key => $val) {
  2552. if (!$val) {
  2553. unset($itemArray[$key]);
  2554. }
  2555. }
  2556. }
  2557. return $itemArray;
  2558. }
  2559. /**
  2560. * Call to update the page tree frame (or something else..?) after
  2561. * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
  2562. * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
  2563. * please use the setUpdateSignal function instead now, as it allows you to add more parameters
  2564. * Usage: 11
  2565. *
  2566. * @param string Whether to set or clear the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set.
  2567. * @return string HTML code (<script> section)
  2568. * @see t3lib_BEfunc::getUpdateSignalCode()
  2569. * @see t3lib_BEfunc::setUpdateSignal()
  2570. * @deprecated since TYPO3 4.2, this function will be removed in TYPO3 4.5, use the setUpdateSignal function instead, as it allows you to add more parameters
  2571. */
  2572. public static function getSetUpdateSignal($set = '') {
  2573. t3lib_div::logDeprecatedFunction();
  2574. // kept for backwards compatibility if $set is empty, use "getUpdateSignalCode()" instead
  2575. if ($set) {
  2576. return self::setUpdateSignal($set);
  2577. } else {
  2578. return self::getUpdateSignalCode();
  2579. }
  2580. }
  2581. /**
  2582. * Call to update the page tree frame (or something else..?) after
  2583. * use 'updatePageTree' as a first parameter will set the page tree to be updated.
  2584. * Usage: 10
  2585. *
  2586. * @param string Key to set the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set. If empty, all update signals will be removed.
  2587. * @param mixed Additional information for the update signal, used to only refresh a branch of the tree
  2588. * @return void
  2589. * @see t3lib_BEfunc::getUpdateSignalCode()
  2590. */
  2591. public static function setUpdateSignal($set = '', $params = '') {
  2592. global $BE_USER;
  2593. $modData = $BE_USER->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
  2594. if ($set) {
  2595. $modData[$set] = array(
  2596. 'set' => $set,
  2597. 'parameter' => $params);
  2598. } else { // clear the module data
  2599. $modData = array();
  2600. }
  2601. $BE_USER->pushModuleData('t3lib_BEfunc::getUpdateSignal', $modData);
  2602. }
  2603. /**
  2604. * Call to update the page tree frame (or something else..?) if this is set by the function
  2605. * setUpdateSignal(). It will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
  2606. * Usage: 1
  2607. *
  2608. * @return string HTML javascript code
  2609. * @see t3lib_BEfunc::setUpdateSignal()
  2610. */
  2611. public static function getUpdateSignalCode() {
  2612. $signals = array();
  2613. $modData = $GLOBALS['BE_USER']->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
  2614. if (!count($modData)) {
  2615. return '';
  2616. }
  2617. // Hook: Allows to let TYPO3 execute your JS code
  2618. if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'])) {
  2619. $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'];
  2620. } else {
  2621. $updateSignals = array();
  2622. }
  2623. // loop through all setUpdateSignals and get the JS code
  2624. foreach ($modData as $set => $val) {
  2625. if (isset($updateSignals[$set])) {
  2626. $params = array('set' => $set, 'parameter' => $val['parameter'], 'JScode' => '');
  2627. $ref = NULL;
  2628. t3lib_div::callUserFunction($updateSignals[$set], $params, $ref);
  2629. $signals[] = $params['JScode'];
  2630. } else if ($set == 'updatePageTree' || $set == 'updateFolderTree') {
  2631. $signals[] = '
  2632. if (top && top.content && top.content.nav_frame && top.content.nav_frame.Tree) {
  2633. top.content.nav_frame.Tree.refresh();
  2634. }';
  2635. }
  2636. }
  2637. $content = implode(LF, $signals);
  2638. self::setUpdateSignal(); // for backwards compatibility, should be replaced
  2639. return $content;
  2640. }
  2641. /**
  2642. * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
  2643. * This is kind of session variable management framework for the backend users.
  2644. * If a key from MOD_MENU is set in the CHANGED_SETTINGS array (eg. a value is passed to the script from the outside), this value is put into the settings-array
  2645. * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
  2646. * Usage: 23
  2647. *
  2648. * @param array MOD_MENU is an array that defines the options in menus.
  2649. * @param array CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
  2650. * @param string modName is the name of this module. Used to get the correct module data.
  2651. * @param string If type is 'ses' then the data is stored as session-lasting data. This means that it'll be wiped out the next time the user logs in.
  2652. * @param string dontValidateList can be used to list variables that should not be checked if their value is found in the MOD_MENU array. Used for dynamically generated menus.
  2653. * @param string List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
  2654. * @return array The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
  2655. */
  2656. public static function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type = '', $dontValidateList = '', $setDefaultList = '') {
  2657. if ($modName && is_string($modName)) {
  2658. // GETTING stored user-data from this module:
  2659. $settings = $GLOBALS['BE_USER']->getModuleData($modName, $type);
  2660. $changed = 0;
  2661. if (!is_array($settings)) {
  2662. $changed = 1;
  2663. $settings = array();
  2664. }
  2665. if (is_array($MOD_MENU)) {
  2666. foreach ($MOD_MENU as $key=>$var) {
  2667. // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
  2668. if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key])) {
  2669. if (is_array($CHANGED_SETTINGS[$key])) {
  2670. $serializedSettings = serialize($CHANGED_SETTINGS[$key]);
  2671. if (strcmp($settings[$key], $serializedSettings)) {
  2672. $settings[$key] = $serializedSettings;
  2673. $changed = 1;
  2674. }
  2675. } else {
  2676. if (strcmp($settings[$key], $CHANGED_SETTINGS[$key]) ) {
  2677. $settings[$key] = $CHANGED_SETTINGS[$key];
  2678. $changed = 1;
  2679. }
  2680. }
  2681. }
  2682. // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
  2683. if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList, $key))) {
  2684. // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
  2685. if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
  2686. $settings[$key] = (string)key($var);
  2687. $changed = 1;
  2688. }
  2689. }
  2690. if ($setDefaultList && !is_array($var)) { // Sets default values (only strings/checkboxes, not menus)
  2691. if (t3lib_div::inList($setDefaultList, $key) && !isset($settings[$key])) {
  2692. $settings[$key] = (string)$var;
  2693. }
  2694. }
  2695. }
  2696. } else {die ('No menu!');}
  2697. if ($changed) {
  2698. $GLOBALS['BE_USER']->pushModuleData($modName, $settings);
  2699. }
  2700. return $settings;
  2701. } else {die ('Wrong module name: "'.$modName.'"');}
  2702. }
  2703. /*******************************************
  2704. *
  2705. * Core
  2706. *
  2707. *******************************************/
  2708. /**
  2709. * Set preview keyword, eg:
  2710. * $previewUrl = t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.t3lib_BEfunc::compilePreviewKeyword('id='.$pageId.'&L='.$language.'&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS='.$this->workspace, $GLOBALS['BE_USER']->user['uid'], 120);
  2711. *
  2712. * todo for sys_preview:
  2713. * - Add a comment which can be shown to previewer in frontend in some way (plus maybe ability to write back, take other action?)
  2714. * - Add possibility for the preview keyword to work in the backend as well: So it becomes a quick way to a certain action of sorts?
  2715. *
  2716. * @param string Get variables to preview, eg. 'id=1150&L=0&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS=8'
  2717. * @param string 32 byte MD5 hash keyword for the URL: "?ADMCMD_prev=[keyword]"
  2718. * @param integer Time-To-Live for keyword
  2719. * @param integer Which workspace to preview. Workspace UID, -1 or >0. If set, the getVars is ignored in the frontend, so that string can be empty
  2720. * @return string Returns keyword to use in URL for ADMCMD_prev=
  2721. */
  2722. public static function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl = 172800, $fullWorkspace = NULL) {
  2723. $field_array = array(
  2724. 'keyword' => md5(uniqid(microtime())),
  2725. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2726. 'endtime' => $GLOBALS['EXEC_TIME'] + $ttl,
  2727. 'config' => serialize(array(
  2728. 'fullWorkspace' => $fullWorkspace,
  2729. 'getVars' => $getVarsStr,
  2730. 'BEUSER_uid' => $beUserUid
  2731. ))
  2732. );
  2733. $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_preview', $field_array);
  2734. return $field_array['keyword'];
  2735. }
  2736. /**
  2737. * Unlock or Lock a record from $table with $uid
  2738. * If $table and $uid is not set, then all locking for the current BE_USER is removed!
  2739. * Usage: 5
  2740. *
  2741. * @param string Table name
  2742. * @param integer Record uid
  2743. * @param integer Record pid
  2744. * @return void
  2745. * @internal
  2746. * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
  2747. */
  2748. public static function lockRecords($table = '', $uid = 0, $pid = 0) {
  2749. $user_id = intval($GLOBALS['BE_USER']->user['uid']);
  2750. if ($table && $uid) {
  2751. $fields_values = array(
  2752. 'userid' => $user_id,
  2753. 'feuserid' => 0,
  2754. 'tstamp' => $GLOBALS['EXEC_TIME'],
  2755. 'record_table' => $table,
  2756. 'record_uid' => $uid,
  2757. 'username' => $GLOBALS['BE_USER']->user['username'],
  2758. 'record_pid' => $pid
  2759. );
  2760. $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
  2761. } else {
  2762. $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid='.intval($user_id));
  2763. }
  2764. }
  2765. /**
  2766. * Returns information about whether the record from table, $table, with uid, $uid is currently locked (edited by another user - which should issue a warning).
  2767. * Notice: Locking is not strictly carried out since locking is abandoned when other backend scripts are activated - which means that a user CAN have a record "open" without having it locked. So this just serves as a warning that counts well in 90% of the cases, which should be sufficient.
  2768. * Usage: 5
  2769. *
  2770. * @param string Table name
  2771. * @param integer Record uid
  2772. * @return array
  2773. * @internal
  2774. * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
  2775. */
  2776. public static function isRecordLocked($table, $uid) {
  2777. global $LOCKED_RECORDS;
  2778. if (!is_array($LOCKED_RECORDS)) {
  2779. $LOCKED_RECORDS = array();
  2780. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  2781. '*',
  2782. 'sys_lockedrecords',
  2783. 'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
  2784. AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
  2785. );
  2786. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  2787. // Get the type of the user that locked this record:
  2788. if ($row['userid']) {
  2789. $userTypeLabel = 'beUser';
  2790. } elseif ($row['feuserid']) {
  2791. $userTypeLabel = 'feUser';
  2792. } else {
  2793. $userTypeLabel = 'user';
  2794. }
  2795. $userType = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.' . $userTypeLabel);
  2796. // Get the username (if available):
  2797. if ($row['username']) {
  2798. $userName = $row['username'];
  2799. } else {
  2800. $userName = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.unknownUser');
  2801. }
  2802. $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']] = $row;
  2803. $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg'] = sprintf(
  2804. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecordUser'),
  2805. $userType,
  2806. $userName,
  2807. self::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'], $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
  2808. );
  2809. if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
  2810. $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg'] = sprintf(
  2811. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecordUser_content'),
  2812. $userType,
  2813. $userName,
  2814. self::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'], $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
  2815. );
  2816. }
  2817. }
  2818. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  2819. }
  2820. return $LOCKED_RECORDS[$table.':'.$uid];
  2821. }
  2822. /**
  2823. * Returns select statement for MM relations (as used by TCEFORMs etc)
  2824. * Usage: 3
  2825. *
  2826. * @param array Configuration array for the field, taken from $TCA
  2827. * @param string Field name
  2828. * @param array TSconfig array from which to get further configuration settings for the field name
  2829. * @param string Prefix string for the key "*foreign_table_where" from $fieldValue array
  2830. * @return string Part of query
  2831. * @internal
  2832. * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
  2833. */
  2834. public static function exec_foreign_table_where_query($fieldValue, $field = '', $TSconfig = array(), $prefix = '') {
  2835. global $TCA;
  2836. t3lib_div::loadTCA($foreign_table);
  2837. $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
  2838. $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
  2839. $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
  2840. if (strstr($fTWHERE, '###REC_FIELD_')) {
  2841. $fTWHERE_parts = explode('###REC_FIELD_', $fTWHERE);
  2842. foreach ($fTWHERE_parts as $kk => $vv) {
  2843. if ($kk) {
  2844. $fTWHERE_subpart = explode('###', $vv, 2);
  2845. if (substr($fTWHERE_parts[0], -1) === '\'' && $fTWHERE_subpart[1]{0} === '\'') {
  2846. $fTWHERE_parts[$kk] = $GLOBALS['TYPO3_DB']->quoteStr($TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]], $foreign_table) . $fTWHERE_subpart[1];
  2847. } else {
  2848. $fTWHERE_parts[$kk] = $GLOBALS['TYPO3_DB']->fullQuoteStr($TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]], $foreign_table) . $fTWHERE_subpart[1];
  2849. }
  2850. }
  2851. }
  2852. $fTWHERE = implode('', $fTWHERE_parts);
  2853. }
  2854. $fTWHERE = str_replace('###CURRENT_PID###', intval($TSconfig['_CURRENT_PID']), $fTWHERE);
  2855. $fTWHERE = str_replace('###THIS_UID###', intval($TSconfig['_THIS_UID']), $fTWHERE);
  2856. $fTWHERE = str_replace('###THIS_CID###', intval($TSconfig['_THIS_CID']), $fTWHERE);
  2857. $fTWHERE = str_replace('###STORAGE_PID###', intval($TSconfig['_STORAGE_PID']), $fTWHERE);
  2858. $fTWHERE = str_replace('###SITEROOT###', intval($TSconfig['_SITEROOT']), $fTWHERE);
  2859. $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###', intval($TSconfig[$field]['PAGE_TSCONFIG_ID']), $fTWHERE);
  2860. $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###', $GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']), $fTWHERE);
  2861. $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###', $GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table), $fTWHERE);
  2862. // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
  2863. $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
  2864. if ($rootLevel) {
  2865. $queryParts = array(
  2866. 'SELECT' => self::getCommonSelectFields($foreign_table, $foreign_table . '.'),
  2867. 'FROM' => $foreign_table,
  2868. 'WHERE' => $foreign_table.'.pid=0 '.
  2869. self::deleteClause($foreign_table) . ' ' .
  2870. $wgolParts['WHERE'],
  2871. 'GROUPBY' => $wgolParts['GROUPBY'],
  2872. 'ORDERBY' => $wgolParts['ORDERBY'],
  2873. 'LIMIT' => $wgolParts['LIMIT']
  2874. );
  2875. } else {
  2876. $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
  2877. if ($foreign_table!='pages') {
  2878. $queryParts = array(
  2879. 'SELECT' => self::getCommonSelectFields($foreign_table, $foreign_table . '.'),
  2880. 'FROM' => $foreign_table.', pages',
  2881. 'WHERE' => 'pages.uid='.$foreign_table.'.pid
  2882. AND pages.deleted=0 '.
  2883. self::deleteClause($foreign_table) .
  2884. ' AND '.$pageClause.' '.
  2885. $wgolParts['WHERE'],
  2886. 'GROUPBY' => $wgolParts['GROUPBY'],
  2887. 'ORDERBY' => $wgolParts['ORDERBY'],
  2888. 'LIMIT' => $wgolParts['LIMIT']
  2889. );
  2890. } else {
  2891. $queryParts = array(
  2892. 'SELECT' => self::getCommonSelectFields($foreign_table, $foreign_table . '.'),
  2893. 'FROM' => 'pages',
  2894. 'WHERE' => 'pages.deleted=0
  2895. AND '.$pageClause.' '.
  2896. $wgolParts['WHERE'],
  2897. 'GROUPBY' => $wgolParts['GROUPBY'],
  2898. 'ORDERBY' => $wgolParts['ORDERBY'],
  2899. 'LIMIT' => $wgolParts['LIMIT']
  2900. );
  2901. }
  2902. }
  2903. return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
  2904. }
  2905. /**
  2906. * Returns TSConfig for the TCEFORM object in Page TSconfig.
  2907. * Used in TCEFORMs
  2908. * Usage: 4
  2909. *
  2910. * @param string Table name present in TCA
  2911. * @param array Row from table
  2912. * @return array
  2913. * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
  2914. */
  2915. public static function getTCEFORM_TSconfig($table, $row) {
  2916. self::fixVersioningPid($table, $row);
  2917. $res = array();
  2918. $typeVal = self::getTCAtypeValue($table, $row);
  2919. // Get main config for the table
  2920. list($TScID, $cPid) = self::getTSCpid($table, $row['uid'], $row['pid']);
  2921. $rootLine = self::BEgetRootLine($TScID, '', TRUE);
  2922. if ($TScID>=0) {
  2923. $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.' . $table, self::getPagesTSconfig($TScID, $rootLine));
  2924. if (is_array($tempConf['properties'])) {
  2925. foreach ($tempConf['properties'] as $key => $val) {
  2926. if (is_array($val)) {
  2927. $fieldN = substr($key, 0, -1);
  2928. $res[$fieldN] = $val;
  2929. unset($res[$fieldN]['types.']);
  2930. if (strcmp($typeVal, '') && is_array($val['types.'][$typeVal.'.'])) {
  2931. $res[$fieldN] = t3lib_div::array_merge_recursive_overrule($res[$fieldN], $val['types.'][$typeVal.'.']);
  2932. }
  2933. }
  2934. }
  2935. }
  2936. }
  2937. $res['_CURRENT_PID'] = $cPid;
  2938. $res['_THIS_UID'] = $row['uid'];
  2939. $res['_THIS_CID'] = $row['cid'];
  2940. $res['_THIS_ROW'] = $row; // So the row will be passed to foreign_table_where_query()
  2941. foreach ($rootLine as $rC) {
  2942. if (!$res['_STORAGE_PID']) $res['_STORAGE_PID'] = intval($rC['storage_pid']);
  2943. if (!$res['_SITEROOT']) $res['_SITEROOT'] = $rC['is_siteroot']?intval($rC['uid']):0;
  2944. }
  2945. return $res;
  2946. }
  2947. /**
  2948. * Find the real PID of the record (with $uid from $table). This MAY be impossible if the pid is set as a reference to the former record or a page (if two records are created at one time).
  2949. * NOTICE: Make sure that the input PID is never negative because the record was an offline version! Therefore, you should always use t3lib_BEfunc::fixVersioningPid($table,$row); on the data you input before calling this function!
  2950. * Usage: 2
  2951. *
  2952. * @param string Table name
  2953. * @param integer Record uid
  2954. * @param integer Record pid, could be negative then pointing to a record from same table whose pid to find and return.
  2955. * @return integer
  2956. * @internal
  2957. * @see t3lib_TCEmain::copyRecord(), getTSCpid()
  2958. */
  2959. public static function getTSconfig_pidValue($table, $uid, $pid) {
  2960. if (t3lib_div::testInt($pid)) { // If pid is an integer this takes precedence in our lookup.
  2961. $thePidValue = intval($pid);
  2962. if ($thePidValue<0) { // If ref to another record, look that record up.
  2963. $pidRec = self::getRecord($table, abs($thePidValue), 'pid');
  2964. $thePidValue = is_array($pidRec) ? $pidRec['pid'] : -2; // Returns -2 if the record did not exist.
  2965. }
  2966. // ... else the pos/zero pid is just returned here.
  2967. } else { // No integer pid and we are forced to look up the $pid
  2968. $rr = self::getRecord($table, $uid); // Try to fetch the record pid from uid. If the uid is 'NEW...' then this will of course return nothing...
  2969. if (is_array($rr)) {
  2970. // First check if the pid is -1 which means it is a workspaced element. Get the "real" record:
  2971. if ($rr['pid']=='-1') {
  2972. $rr = self::getRecord($table, $rr['t3ver_oid'], 'pid');
  2973. if (is_array($rr)) {
  2974. $thePidValue = $rr['pid'];
  2975. }
  2976. } else {
  2977. $thePidValue = $rr['pid']; // Returning the "pid" of the record
  2978. }
  2979. }
  2980. if (!$thePidValue) $thePidValue = -1; // Returns -1 if the record with this pid was not found.
  2981. }
  2982. return $thePidValue;
  2983. }
  2984. /**
  2985. * Return $uid if $table is pages and $uid is integer - otherwise the $pid
  2986. * Usage: 1
  2987. *
  2988. * @param string Table name
  2989. * @param integer Record uid
  2990. * @param integer Record pid
  2991. * @return integer
  2992. * @internal
  2993. * @see t3lib_TCEforms::getTSCpid()
  2994. */
  2995. public static function getPidForModTSconfig($table, $uid, $pid) {
  2996. $retVal = ($table=='pages' && t3lib_div::testInt($uid)) ? $uid : $pid;
  2997. return $retVal;
  2998. }
  2999. /**
  3000. * Returns the REAL pid of the record, if possible. If both $uid and $pid is strings, then pid=-1 is returned as an error indication.
  3001. * Usage: 8
  3002. *
  3003. * @param string Table name
  3004. * @param integer Record uid
  3005. * @param integer Record pid
  3006. * @return array Array of two integers; first is the REAL PID of a record and if its a new record negative values are resolved to the true PID, second value is the PID value for TSconfig (uid if table is pages, otherwise the pid)
  3007. * @internal
  3008. * @see t3lib_TCEmain::setHistory(), t3lib_TCEmain::process_datamap()
  3009. */
  3010. public static function getTSCpid($table, $uid, $pid) {
  3011. // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
  3012. $cPid = self::getTSconfig_pidValue($table, $uid, $pid);
  3013. // $TScID is the id of $table = pages, else it's the pid of the record.
  3014. $TScID = self::getPidForModTSconfig($table, $uid, $cPid);
  3015. return array($TScID, $cPid);
  3016. }
  3017. /**
  3018. * Returns first found domain record "domainName" (without trailing slash) if found in the input $rootLine
  3019. * Usage: 2
  3020. *
  3021. * @param array Root line array
  3022. * @return string Domain name, if found.
  3023. */
  3024. public static function firstDomainRecord($rootLine) {
  3025. if (t3lib_extMgm::isLoaded('cms')) {
  3026. foreach ($rootLine as $row) {
  3027. $dRec = self::getRecordsByField('sys_domain', 'pid', $row['uid'], ' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
  3028. if (is_array($dRec)) {
  3029. reset($dRec);
  3030. $dRecord = current($dRec);
  3031. return rtrim($dRecord['domainName'], '/');
  3032. }
  3033. }
  3034. }
  3035. }
  3036. /**
  3037. * Returns the sys_domain record for $domain, optionally with $path appended.
  3038. * Usage: 2
  3039. *
  3040. * @param string Domain name
  3041. * @param string Appended path
  3042. * @return array Domain record, if found
  3043. */
  3044. public static function getDomainStartPage($domain, $path = '') {
  3045. if (t3lib_extMgm::isLoaded('cms')) {
  3046. $domain = explode(':', $domain);
  3047. $domain = strtolower(preg_replace('/\.$/', '', $domain[0]));
  3048. // path is calculated.
  3049. $path = trim(preg_replace('/\/[^\/]*$/', '', $path));
  3050. // stuff:
  3051. $domain.=$path;
  3052. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
  3053. pages.uid=sys_domain.pid
  3054. AND sys_domain.hidden=0
  3055. AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' OR sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').')'.
  3056. self::deleteClause('pages'),
  3057. '', '', '1');
  3058. $result = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  3059. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  3060. return $result;
  3061. }
  3062. }
  3063. /**
  3064. * Returns overlayered RTE setup from an array with TSconfig. Used in TCEforms and TCEmain
  3065. * Usage: 8
  3066. *
  3067. * @param array The properties of Page TSconfig in the key "RTE."
  3068. * @param string Table name
  3069. * @param string Field name
  3070. * @param string Type value of the current record (like from CType of tt_content)
  3071. * @return array Array with the configuration for the RTE
  3072. * @internal
  3073. */
  3074. public static function RTEsetup($RTEprop, $table, $field, $type = '') {
  3075. $thisConfig = is_array($RTEprop['default.']) ? $RTEprop['default.'] : array();
  3076. $thisFieldConf = $RTEprop['config.'][$table.'.'][$field.'.'];
  3077. if (is_array($thisFieldConf)) {
  3078. unset($thisFieldConf['types.']);
  3079. $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig, $thisFieldConf);
  3080. }
  3081. if ($type && is_array($RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.'])) {
  3082. $thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig, $RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.']);
  3083. }
  3084. return $thisConfig;
  3085. }
  3086. /**
  3087. * Returns first possible RTE object if available.
  3088. * Usage: $RTEobj = &t3lib_BEfunc::RTEgetObj();
  3089. *
  3090. * @return mixed If available, returns RTE object, otherwise an array of messages from possible RTEs
  3091. */
  3092. public static function &RTEgetObj() {
  3093. // If no RTE object has been set previously, try to create it:
  3094. if (!isset($GLOBALS['T3_VAR']['RTEobj'])) {
  3095. // Set the object string to blank by default:
  3096. $GLOBALS['T3_VAR']['RTEobj'] = array();
  3097. // Traverse registered RTEs:
  3098. if (is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'])) {
  3099. foreach($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'] as $extKey => $rteObjCfg) {
  3100. $rteObj = t3lib_div::getUserObj($rteObjCfg['objRef']);
  3101. if (is_object($rteObj)) {
  3102. if ($rteObj->isAvailable()) {
  3103. $GLOBALS['T3_VAR']['RTEobj'] = $rteObj;
  3104. break;
  3105. } else {
  3106. $GLOBALS['T3_VAR']['RTEobj'] = array_merge($GLOBALS['T3_VAR']['RTEobj'], $rteObj->errorLog);
  3107. }
  3108. }
  3109. }
  3110. }
  3111. if (!count($GLOBALS['T3_VAR']['RTEobj'])) {
  3112. $GLOBALS['T3_VAR']['RTEobj'][] = 'No RTEs configured at all';
  3113. }
  3114. }
  3115. // Return RTE object (if any!)
  3116. return $GLOBALS['T3_VAR']['RTEobj'];
  3117. }
  3118. /**
  3119. * Returns soft-reference parser for the softRef processing type
  3120. * Usage: $softRefObj = &t3lib_BEfunc::softRefParserObj('[parser key]');
  3121. *
  3122. * @param string softRef parser key
  3123. * @return mixed If available, returns Soft link parser object.
  3124. */
  3125. public static function &softRefParserObj($spKey) {
  3126. // If no softRef parser object has been set previously, try to create it:
  3127. if (!isset($GLOBALS['T3_VAR']['softRefParser'][$spKey])) {
  3128. // Set the object string to blank by default:
  3129. $GLOBALS['T3_VAR']['softRefParser'][$spKey] = '';
  3130. // Now, try to create parser object:
  3131. $objRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?
  3132. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] :
  3133. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'][$spKey];
  3134. if ($objRef) {
  3135. $softRefParserObj = t3lib_div::getUserObj($objRef, '');
  3136. if (is_object($softRefParserObj)) {
  3137. $GLOBALS['T3_VAR']['softRefParser'][$spKey] = $softRefParserObj;
  3138. }
  3139. }
  3140. }
  3141. // Return RTE object (if any!)
  3142. return $GLOBALS['T3_VAR']['softRefParser'][$spKey];
  3143. }
  3144. /**
  3145. * Returns array of soft parser references
  3146. *
  3147. * @param string softRef parser list
  3148. * @param string Table name
  3149. * @param string Field name
  3150. * @return array Array where the parser key is the key and the value is the parameter string
  3151. */
  3152. public static function explodeSoftRefParserList($parserList) {
  3153. // Looking for global parsers:
  3154. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])) {
  3155. $parserList = implode(',', array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])).','.$parserList;
  3156. }
  3157. // Return immediately if list is blank:
  3158. if (!strlen($parserList)) return FALSE;
  3159. // Otherwise parse the list:
  3160. $keyList = t3lib_div::trimExplode(',', $parserList, 1);
  3161. $output = array();
  3162. foreach($keyList as $val) {
  3163. $reg = array();
  3164. if (preg_match('/^([[:alnum:]_-]+)\[(.*)\]$/', $val, $reg)) {
  3165. $output[$reg[1]] = t3lib_div::trimExplode(';', $reg[2], 1);
  3166. } else {
  3167. $output[$val] = '';
  3168. }
  3169. }
  3170. return $output;
  3171. }
  3172. /**
  3173. * Returns true if $modName is set and is found as a main- or submodule in $TBE_MODULES array
  3174. * Usage: 1
  3175. *
  3176. * @param string Module name
  3177. * @return boolean
  3178. */
  3179. public static function isModuleSetInTBE_MODULES($modName) {
  3180. $loaded = array();
  3181. foreach ($GLOBALS['TBE_MODULES'] as $mkey => $list) {
  3182. $loaded[$mkey] = 1;
  3183. if (!is_array($list) && trim($list)) {
  3184. $subList = t3lib_div::trimExplode(',', $list, 1);
  3185. foreach ($subList as $skey) {
  3186. $loaded[$mkey.'_'.$skey] = 1;
  3187. }
  3188. }
  3189. }
  3190. return $modName && isset($loaded[$modName]);
  3191. }
  3192. /**
  3193. * Counting references to a record/file
  3194. *
  3195. * @param string Table name (or "_FILE" if its a file)
  3196. * @param string Reference: If table, then integer-uid, if _FILE, then file reference (relative to PATH_site)
  3197. * @param string Message with %s, eg. "There were %s records pointing to this file!"
  3198. * @param string reference count
  3199. * @return string Output string (or integer count value if no msg string specified)
  3200. */
  3201. public static function referenceCount($table, $ref, $msg = '', $count = NULL) {
  3202. if ($count === NULL) {
  3203. // Look up the path:
  3204. if ($table=='_FILE') {
  3205. if (t3lib_div::isFirstPartOfStr($ref, PATH_site)) {
  3206. $ref = substr($ref, strlen(PATH_site));
  3207. $condition = 'ref_string='.$GLOBALS['TYPO3_DB']->fullQuoteStr($ref, 'sys_refindex');
  3208. } else {
  3209. return '';
  3210. }
  3211. } else {
  3212. $condition = 'ref_uid=' . intval($ref);
  3213. }
  3214. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  3215. '*',
  3216. 'sys_refindex',
  3217. 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_refindex') .
  3218. ' AND ' . $condition .
  3219. ' AND deleted=0'
  3220. );
  3221. }
  3222. return ($count ? ($msg ? sprintf($msg, $count) : $count) : '');
  3223. }
  3224. /**
  3225. * Counting translations of records
  3226. *
  3227. * @param string Table name
  3228. * @param string Reference: the record's uid
  3229. * @param string Message with %s, eg. "This record has %s translation(s) which will be deleted, too!"
  3230. * @return string Output string (or integer count value if no msg string specified)
  3231. */
  3232. public static function translationCount($table, $ref, $msg = '') {
  3233. if (empty($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) &&
  3234. $GLOBALS['TCA'][$table]['ctrl']['languageField'] &&
  3235. $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] &&
  3236. !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
  3237. $where = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . intval($ref) .
  3238. ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '!=0';
  3239. if (!empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
  3240. $where .= ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
  3241. }
  3242. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  3243. '*',
  3244. $table,
  3245. $where
  3246. );
  3247. }
  3248. return ($count ? ($msg ? sprintf($msg, $count) : $count) : '');
  3249. }
  3250. /*******************************************
  3251. *
  3252. * Workspaces / Versioning
  3253. *
  3254. *******************************************/
  3255. /**
  3256. * Select all versions of a record, ordered by version id (DESC)
  3257. *
  3258. * @param string Table name to select from
  3259. * @param integer Record uid for which to find versions.
  3260. * @param string Field list to select
  3261. * @param integer Workspace ID, if zero all versions regardless of workspace is found.
  3262. * @param boolean If set, deleted-flagged versions are included! (Only for clean-up script!)
  3263. * @param array The current record
  3264. * @return array Array of versions of table/uid
  3265. */
  3266. public static function selectVersionsOfRecord($table, $uid, $fields = '*', $workspace = 0, $includeDeletedRecords = FALSE, $row = NULL) {
  3267. global $TCA;
  3268. $realPid = 0;
  3269. $outputRows = array();
  3270. if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS']) {
  3271. if (is_array($row) && !$includeDeletedRecords) {
  3272. $row['_CURRENT_VERSION'] = TRUE;
  3273. $realPid = $row['pid'];
  3274. $outputRows[] = $row;
  3275. } else {
  3276. // Select UID version:
  3277. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  3278. $fields,
  3279. $table,
  3280. 'uid=' . intval($uid) .
  3281. ($includeDeletedRecords ? '' : self::deleteClause($table))
  3282. );
  3283. // Add rows to output array:
  3284. if ($res) {
  3285. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  3286. if ($row) {
  3287. $row['_CURRENT_VERSION'] = TRUE;
  3288. $realPid = $row['pid'];
  3289. $outputRows[] = $row;
  3290. }
  3291. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  3292. }
  3293. }
  3294. // Select all offline versions of record:
  3295. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  3296. $fields,
  3297. $table,
  3298. 'pid=-1 AND uid!='.intval($uid).' AND t3ver_oid='.intval($uid).($workspace!=0?' AND t3ver_wsid='.intval($workspace):'').
  3299. ($includeDeletedRecords ? '' : self::deleteClause($table)),
  3300. '',
  3301. 't3ver_id DESC'
  3302. );
  3303. // Add rows to output array:
  3304. while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
  3305. $outputRows[] = $row;
  3306. }
  3307. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  3308. // Set real-pid:
  3309. foreach ($outputRows as $idx => $oRow) {
  3310. $outputRows[$idx]['_REAL_PID'] = $realPid;
  3311. }
  3312. return $outputRows;
  3313. }
  3314. }
  3315. /**
  3316. * Find page-tree PID for versionized record
  3317. * Will look if the "pid" value of the input record is -1 and if the table supports versioning - if so, it will translate the -1 PID into the PID of the original record
  3318. * Used whenever you are tracking something back, like making the root line.
  3319. * Will only translate if the workspace of the input record matches that of the current user (unless flag set)
  3320. * Principle; Record offline! => Find online?
  3321. *
  3322. * @param string Table name
  3323. * @param array Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
  3324. * @param boolean Ignore workspace match
  3325. * @return void (Passed by ref). If the record had its pid corrected to the online versions pid, then "_ORIG_pid" is set to the original pid value (-1 of course). The field "_ORIG_pid" is used by various other functions to detect if a record was in fact in a versionized branch.
  3326. * @see t3lib_page::fixVersioningPid()
  3327. */
  3328. public static function fixVersioningPid($table, &$rr, $ignoreWorkspaceMatch = FALSE) {
  3329. global $TCA;
  3330. if (t3lib_extMgm::isLoaded('version')) {
  3331. // Check that the input record is an offline version from a table that supports versioning:
  3332. if (is_array($rr) && $rr['pid'] == -1 && $TCA[$table]['ctrl']['versioningWS']) {
  3333. // Check values for t3ver_oid and t3ver_wsid:
  3334. if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) { // If "t3ver_oid" is already a field, just set this:
  3335. $oid = $rr['t3ver_oid'];
  3336. $wsid = $rr['t3ver_wsid'];
  3337. } else { // Otherwise we have to expect "uid" to be in the record and look up based on this:
  3338. $newPidRec = self::getRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid');
  3339. if (is_array($newPidRec)) {
  3340. $oid = $newPidRec['t3ver_oid'];
  3341. $wsid = $newPidRec['t3ver_wsid'];
  3342. }
  3343. }
  3344. // If ID of current online version is found, look up the PID value of that:
  3345. if ($oid && ($ignoreWorkspaceMatch || !strcmp((int)$wsid, $GLOBALS['BE_USER']->workspace))) {
  3346. $oidRec = self::getRecord($table, $oid, 'pid');
  3347. if (is_array($oidRec)) {
  3348. $rr['_ORIG_pid'] = $rr['pid'];
  3349. $rr['pid'] = $oidRec['pid'];
  3350. }
  3351. }
  3352. }
  3353. }
  3354. }
  3355. /**
  3356. * Workspace Preview Overlay
  3357. * Generally ALWAYS used when records are selected based on uid or pid. If records are selected on other fields than uid or pid (eg. "email = ....") then usage might produce undesired results and that should be evaluated on individual basis.
  3358. * Principle; Record online! => Find offline?
  3359. * Recently, this function has been modified so it MAY set $row to FALSE. This happens if a version overlay with the move-id pointer is found in which case we would like a backend preview. In other words, you should check if the input record is still an array afterwards when using this function.
  3360. *
  3361. * @param string Table name
  3362. * @param array Record array passed by reference. As minimum, the "uid", "pid" and "t3ver_swapmode" (pages) fields must exist! Fake fields cannot exist since the fields in the array is used as field names in the SQL look up. It would be nice to have fields like "t3ver_state" and "t3ver_mode_id" as well to avoid a new lookup inside movePlhOL().
  3363. * @param integer Workspace ID, if not specified will use $GLOBALS['BE_USER']->workspace
  3364. * @return void (Passed by ref).
  3365. * @see fixVersioningPid()
  3366. */
  3367. public static function workspaceOL($table, &$row, $wsid = -99, $unsetMovePointers = FALSE) {
  3368. global $TCA;
  3369. if (t3lib_extMgm::isLoaded('version')) {
  3370. $previewMovePlaceholders = TRUE; // If this is false the placeholder is shown raw in the backend. I don't know if this move can be useful for users to toggle. Technically it can help debugging...
  3371. // Initialize workspace ID:
  3372. if ($wsid == -99) $wsid = $GLOBALS['BE_USER']->workspace;
  3373. // Check if workspace is different from zero and record is set:
  3374. if ($wsid !== 0 && is_array($row)) {
  3375. // Check if input record is a move-placeholder and if so, find the pointed-to live record:
  3376. if ($previewMovePlaceholders) {
  3377. $orig_uid = $row['uid'];
  3378. $orig_pid = $row['pid'];
  3379. $movePldSwap = self::movePlhOL($table, $row);
  3380. # if (!is_array($row)) return;
  3381. }
  3382. $wsAlt = self::getWorkspaceVersionOfRecord($wsid, $table, $row['uid'], implode(',', array_keys($row)));
  3383. // If version was found, swap the default record with that one.
  3384. if (is_array($wsAlt)) {
  3385. // Check if this is in move-state:
  3386. if ($previewMovePlaceholders && !$movePldSwap && ($table=='pages' || (int)$TCA[$table]['ctrl']['versioningWS']>=2) && $unsetMovePointers) { // Only for WS ver 2... (moving)
  3387. // If t3ver_state is not found, then find it... (but we like best if it is here...)
  3388. if (!isset($wsAlt['t3ver_state'])) {
  3389. $stateRec = self::getRecord($table, $wsAlt['uid'], 't3ver_state');
  3390. $state = $stateRec['t3ver_state'];
  3391. } else {
  3392. $state = $wsAlt['t3ver_state'];
  3393. }
  3394. if ((int)$state===4) {
  3395. // TODO: Same problem as frontend in versionOL(). See TODO point there.
  3396. $row = FALSE;
  3397. return;
  3398. }
  3399. }
  3400. // Always correct PID from -1 to what it should be:
  3401. if (isset($wsAlt['pid'])) {
  3402. $wsAlt['_ORIG_pid'] = $wsAlt['pid']; // Keep the old (-1) - indicates it was a version...
  3403. $wsAlt['pid'] = $row['pid']; // Set in the online versions PID.
  3404. }
  3405. // For versions of single elements or page+content, swap UID and PID:
  3406. if ($table!=='pages' || $wsAlt['t3ver_swapmode']<=0) {
  3407. $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
  3408. $wsAlt['uid'] = $row['uid'];
  3409. // Backend css class:
  3410. $wsAlt['_CSSCLASS'] = $table==='pages' && $wsAlt['t3ver_swapmode']==0 ? 'ver-page' : 'ver-element';
  3411. } else { // This is only for page-versions with BRANCH below!
  3412. $wsAlt['_ONLINE_uid'] = $row['uid'];
  3413. // Backend css class:
  3414. $wsAlt['_CSSCLASS'] = 'ver-branchpoint';
  3415. $wsAlt['_SUBCSSCLASS'] = 'ver-branch';
  3416. }
  3417. // Changing input record to the workspace version alternative:
  3418. $row = $wsAlt;
  3419. }
  3420. // If the original record was a move placeholder, the uid and pid of that is preserved here:
  3421. if ($movePldSwap) {
  3422. $row['_MOVE_PLH'] = TRUE;
  3423. $row['_MOVE_PLH_uid'] = $orig_uid;
  3424. $row['_MOVE_PLH_pid'] = $orig_pid;
  3425. $row['t3ver_state'] = 3; // For display; To make the icon right for the placeholder vs. the original
  3426. }
  3427. }
  3428. }
  3429. }
  3430. /**
  3431. * Checks if record is a move-placeholder (t3ver_state==3) and if so it will set $row to be the pointed-to live record (and return TRUE)
  3432. *
  3433. * @param string Table name
  3434. * @param array Row (passed by reference) - must be online record!
  3435. * @return boolean True if overlay is made.
  3436. * @see t3lib_page::movePlhOl()
  3437. */
  3438. public static function movePlhOL($table, &$row) {
  3439. global $TCA;
  3440. if ($table=='pages' || (int)$TCA[$table]['ctrl']['versioningWS']>=2) { // Only for WS ver 2... (moving)
  3441. // If t3ver_move_id or t3ver_state is not found, then find it... (but we like best if it is here...)
  3442. if (!isset($row['t3ver_move_id']) || !isset($row['t3ver_state'])) {
  3443. $moveIDRec = self::getRecord($table, $row['uid'], 't3ver_move_id, t3ver_state');
  3444. $moveID = $moveIDRec['t3ver_move_id'];
  3445. $state = $moveIDRec['t3ver_state'];
  3446. } else {
  3447. $moveID = $row['t3ver_move_id'];
  3448. $state = $row['t3ver_state'];
  3449. }
  3450. // Find pointed-to record.
  3451. if ((int)$state===3 && $moveID) {
  3452. if ($origRow = self::getRecord($table, $moveID, implode(',', array_keys($row)))) {
  3453. $row = $origRow;
  3454. return TRUE;
  3455. }
  3456. }
  3457. }
  3458. return FALSE;
  3459. }
  3460. /**
  3461. * Select the workspace version of a record, if exists
  3462. *
  3463. * @param integer Workspace ID
  3464. * @param string Table name to select from
  3465. * @param integer Record uid for which to find workspace version.
  3466. * @param string Field list to select
  3467. * @return array If found, return record, otherwise false
  3468. */
  3469. public static function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*') {
  3470. global $TCA;
  3471. if (t3lib_extMgm::isLoaded('version')) {
  3472. if ($workspace !== 0 && $TCA[$table] && $TCA[$table]['ctrl']['versioningWS']) {
  3473. // Select workspace version of record:
  3474. $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
  3475. $fields,
  3476. $table,
  3477. 'pid=-1 AND
  3478. t3ver_oid=' . intval($uid) . ' AND
  3479. t3ver_wsid=' . intval($workspace) .
  3480. self::deleteClause($table)
  3481. );
  3482. if (is_array($rows[0])) return $rows[0];
  3483. }
  3484. }
  3485. return FALSE;
  3486. }
  3487. /**
  3488. * Returns live version of record
  3489. *
  3490. * @param string Table name
  3491. * @param integer Record UID of draft, offline version
  3492. * @param string Field list, default is *
  3493. * @return array If found, the record, otherwise nothing.
  3494. */
  3495. public static function getLiveVersionOfRecord($table, $uid, $fields = '*') {
  3496. global $TCA;
  3497. // Check that table supports versioning:
  3498. if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS']) {
  3499. $rec = self::getRecord($table, $uid, 'pid,t3ver_oid');
  3500. if ($rec['pid']==-1) {
  3501. return self::getRecord($table, $rec['t3ver_oid'], $fields);
  3502. }
  3503. }
  3504. }
  3505. /**
  3506. * Will fetch the rootline for the pid, then check if anywhere in the rootline there is a branch point and if so everything is allowed of course.
  3507. * Alternatively; if the page of the PID itself is a version and swapmode is zero (page+content) then tables from versioning_followPages are allowed as well.
  3508. *
  3509. * @param integer Page id inside of which you want to edit/create/delete something.
  3510. * @param string Table name you are checking for. If you don't give the table name ONLY "branch" types are found and returned true. Specifying table you might also get a positive response if the pid is a "page" versioning type AND the table has "versioning_followPages" set.
  3511. * @param boolean If set, the keyword "branchpoint" or "first" is not returned by rather the "t3ver_stage" value of the branch-point.
  3512. * @return mixed Returns either "branchpoint" (if branch) or "first" (if page) or false if nothing. Alternatively, it returns the value of "t3ver_stage" for the branchpoint (if any)
  3513. */
  3514. public static function isPidInVersionizedBranch($pid, $table = '', $returnStage = FALSE) {
  3515. $rl = self::BEgetRootLine($pid);
  3516. $c = 0;
  3517. foreach($rl as $rec) {
  3518. if ($rec['_ORIG_pid']==-1) {
  3519. // In any case: is it a branchpoint, then OK...
  3520. if ($rec['t3ver_swapmode']>0) {
  3521. return $returnStage ? (int)$rec['t3ver_stage'] : 'branchpoint'; // OK, we are in a versionized branch
  3522. } elseif ($c==0 && $rec['t3ver_swapmode']==0 && $table && $GLOBALS['TCA'][$table]['ctrl']['versioning_followPages']) { // First level: So $table must be versioning_followPages
  3523. return $returnStage ? (int)$rec['t3ver_stage'] : 'first'; // OK, we are in a versionized branch
  3524. }
  3525. }
  3526. $c++;
  3527. }
  3528. }
  3529. /**
  3530. * Will return where clause de-selecting new(/deleted)-versions from other workspaces.
  3531. *
  3532. * @param string Table name
  3533. * @return string Where clause if applicable.
  3534. */
  3535. public static function versioningPlaceholderClause($table) {
  3536. if ($GLOBALS['BE_USER']->workspace!==0 && $GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
  3537. return ' AND ('.$table.'.t3ver_state<=0 OR '.$table.'.t3ver_wsid='.intval($GLOBALS['BE_USER']->workspace).')';
  3538. }
  3539. }
  3540. /**
  3541. * Count number of versions on a page
  3542. *
  3543. * @param integer Workspace ID
  3544. * @param integer Page ID
  3545. * @param boolean If set, then all tables and not only "versioning_followPages" are found (except other pages)
  3546. * @return array Overview of records
  3547. */
  3548. public static function countVersionsOfRecordsOnPage($workspace, $pageId, $allTables = FALSE) {
  3549. $output = array();
  3550. if ($workspace!=0) {
  3551. foreach($GLOBALS['TCA'] as $tableName => $cfg) {
  3552. if ($tableName!='pages' && $cfg['ctrl']['versioningWS'] && ($cfg['ctrl']['versioning_followPages'] || $allTables)) {
  3553. // Select all records from this table in the database from the workspace
  3554. // This joins the online version with the offline version as tables A and B
  3555. $output[$tableName] = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows (
  3556. 'B.uid as live_uid, A.uid as offline_uid',
  3557. $tableName.' A,'.$tableName.' B',
  3558. 'A.pid=-1'. // Table A is the offline version and pid=-1 defines offline
  3559. ' AND B.pid='.intval($pageId).
  3560. ' AND A.t3ver_wsid='.intval($workspace).
  3561. ' AND A.t3ver_oid=B.uid'. // ... and finally the join between the two tables.
  3562. self::deleteClause($tableName, 'A').
  3563. self::deleteClause($tableName, 'B')
  3564. );
  3565. if (!is_array($output[$tableName]) || !count($output[$tableName])) {
  3566. unset($output[$tableName]);
  3567. }
  3568. }
  3569. }
  3570. }
  3571. return $output;
  3572. }
  3573. /**
  3574. * Performs mapping of new uids to new versions UID in case of import inside a workspace.
  3575. *
  3576. * @param string Table name
  3577. * @param integer Record uid (of live record placeholder)
  3578. * @return integer Uid of offline version if any, otherwise live uid.
  3579. */
  3580. public static function wsMapId($table, $uid) {
  3581. if ($wsRec = self::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid')) {
  3582. return $wsRec['uid'];
  3583. } else {
  3584. return $uid;
  3585. }
  3586. }
  3587. /**
  3588. * Returns move placeholder of online (live) version
  3589. *
  3590. * @param string Table name
  3591. * @param integer Record UID of online version
  3592. * @param string Field list, default is *
  3593. * @return array If found, the record, otherwise nothing.
  3594. */
  3595. public static function getMovePlaceholder($table, $uid, $fields = '*') {
  3596. global $TCA;
  3597. $workspace = $GLOBALS['BE_USER']->workspace;
  3598. if ($workspace!==0 && $TCA[$table] && (int)$TCA[$table]['ctrl']['versioningWS']>=2) {
  3599. // Select workspace version of record:
  3600. $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
  3601. $fields,
  3602. $table,
  3603. 'pid!=-1 AND
  3604. t3ver_state=3 AND
  3605. t3ver_move_id='.intval($uid).' AND
  3606. t3ver_wsid='.intval($workspace).
  3607. self::deleteClause($table)
  3608. );
  3609. if (is_array($rows[0])) return $rows[0];
  3610. }
  3611. return FALSE;
  3612. }
  3613. /*******************************************
  3614. *
  3615. * Miscellaneous
  3616. *
  3617. *******************************************/
  3618. /**
  3619. * Print error message with header, text etc.
  3620. * Usage: 19
  3621. *
  3622. * @param string Header string
  3623. * @param string Content string
  3624. * @param boolean Will return an alert() with the content of header and text.
  3625. * @param boolean Print header.
  3626. * @return void
  3627. */
  3628. public static function typo3PrintError($header, $text, $js = '', $head = 1) {
  3629. // This prints out a TYPO3 error message.
  3630. // If $js is set the message will be output in JavaScript
  3631. if ($js) {
  3632. echo "alert('".t3lib_div::slashJS($header.'\n'.$text)."');";
  3633. } else {
  3634. echo $head?'<html>
  3635. <head>
  3636. <title>Error!</title>
  3637. </head>
  3638. <body bgcolor="white" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">':'';
  3639. echo '<div align="center">
  3640. <table border="0" cellspacing="0" cellpadding="0" width="333">
  3641. <tr>
  3642. <td align="center">'.
  3643. ($GLOBALS['TBE_STYLES']['logo_login']?'<img src="'.$GLOBALS['BACK_PATH'].$GLOBALS['TBE_STYLES']['logo_login'].'" alt="" />':'<img src="'.$GLOBALS['BACK_PATH'].'gfx/typo3logo.gif" width="123" height="34" vspace="10" />').
  3644. '</td>
  3645. </tr>
  3646. <tr>
  3647. <td bgcolor="black">
  3648. <table width="100%" border="0" cellspacing="1" cellpadding="10">
  3649. <tr>
  3650. <td bgcolor="#F4F0E8">
  3651. <font face="verdana,arial,helvetica" size="2">';
  3652. echo '<strong><center><font size="+1">'.$header.'</font></center></strong><br />'.$text;
  3653. echo ' </font>
  3654. </td>
  3655. </tr>
  3656. </table>
  3657. </td>
  3658. </tr>
  3659. </table>
  3660. </div>';
  3661. echo $head?'
  3662. </body>
  3663. </html>':'';
  3664. }
  3665. }
  3666. /**
  3667. * Prints TYPO3 Copyright notice for About Modules etc. modules.
  3668. *
  3669. * @return void
  3670. */
  3671. public static function TYPO3_copyRightNotice() {
  3672. global $TYPO3_CONF_VARS;
  3673. // COPYRIGHT NOTICE:
  3674. $loginCopyrightWarrantyProvider = strip_tags(trim($TYPO3_CONF_VARS['SYS']['loginCopyrightWarrantyProvider']));
  3675. $loginCopyrightWarrantyURL = strip_tags(trim($TYPO3_CONF_VARS['SYS']['loginCopyrightWarrantyURL']));
  3676. if (strlen($loginCopyrightWarrantyProvider)>=2 && strlen($loginCopyrightWarrantyURL)>=10) {
  3677. $warrantyNote = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:warranty.by'),
  3678. htmlspecialchars($loginCopyrightWarrantyProvider),
  3679. '<a href="' . htmlspecialchars($loginCopyrightWarrantyURL) . '" target="_blank">', '</a>'
  3680. );
  3681. } else {
  3682. $warrantyNote = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:no.warranty'),
  3683. '<a href="http://typo3.com/1316.0.html" target="_blank">', '</a>'
  3684. );
  3685. }
  3686. $cNotice = '<a href="http://typo3.com/" target="_blank">' .
  3687. '<img' . t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/loginlogo_transp.gif', 'width="75" height="19" vspace="2" hspace="4"') . ' alt="' .
  3688. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:typo3.logo') . '" align="left" />' .
  3689. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:typo3.cms') . ' ' .
  3690. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:version.short') . ' ' .
  3691. htmlspecialchars(TYPO3_version) . '</a>. ' .
  3692. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:copyright') . ' &copy; ' .
  3693. htmlspecialchars(TYPO3_copyright_year) . ' Kasper Sk&aring;rh&oslash;j. ' .
  3694. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:extension.copyright') . ' ' .
  3695. sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:details.link'),
  3696. '<a href="http://typo3.com/" target="_blank">http://typo3.com/</a>'
  3697. ) . ' ' .
  3698. strip_tags($warrantyNote, '<a>') . ' ' .
  3699. sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:free.software'),
  3700. '<a href="http://typo3.com/1316.0.html" target="_blank">', '</a> '
  3701. ) .
  3702. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_login.xml:keep.notice');
  3703. return $cNotice;
  3704. }
  3705. /**
  3706. * Display some warning messages if this installation is obviously insecure!!
  3707. * These warnings are only displayed to admin users
  3708. *
  3709. * @return void
  3710. */
  3711. public static function displayWarningMessages() {
  3712. if ($GLOBALS['BE_USER']->isAdmin()) {
  3713. $warnings = array(); // Array containing warnings that must be displayed
  3714. $enableInstallToolFile = PATH_site . 'typo3conf/ENABLE_INSTALL_TOOL'; // If this file exists and it isn't older than one hour, the Install Tool is enabled
  3715. $cmd = t3lib_div::_GET('adminWarning_cmd'); // Cleanup command, if set
  3716. switch($cmd) {
  3717. case 'remove_ENABLE_INSTALL_TOOL':
  3718. if (unlink($enableInstallToolFile)) {
  3719. unset($enableInstallToolFile);
  3720. }
  3721. break;
  3722. }
  3723. // Check if the Install Tool Password is still default: joh316
  3724. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['installToolPassword']==md5('joh316')) {
  3725. $url = 'install/index.php?redirect_url=index.php'.urlencode('?TYPO3_INSTALL[type]=about');
  3726. $warnings["install_password"] = sprintf(
  3727. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.install_password'),
  3728. '<a href="'.$url.'">',
  3729. '</a>');
  3730. }
  3731. // Check if there is still a default user 'admin' with password 'password' (MD5sum = 5f4dcc3b5aa765d61d8327deb882cf99)
  3732. $where_clause = 'username=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('admin', 'be_users') . ' AND password=' .
  3733. $GLOBALS['TYPO3_DB']->fullQuoteStr('5f4dcc3b5aa765d61d8327deb882cf99', 'be_users') . self::deleteClause('be_users');
  3734. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, username, password', 'be_users', $where_clause);
  3735. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  3736. $url = "alt_doc.php?returnUrl=index.php&edit[be_users][".$row['uid']."]=edit";
  3737. $warnings["backend_admin"] = sprintf(
  3738. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.backend_admin'),
  3739. '<a href="' . htmlspecialchars($url) . '">',
  3740. '</a>');
  3741. }
  3742. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  3743. // Check whether the file ENABLE_INSTALL_TOOL contains the string "KEEP_FILE" which permanently unlocks the install tool
  3744. if (is_file($enableInstallToolFile) && trim(file_get_contents($enableInstallToolFile)) === 'KEEP_FILE') {
  3745. $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT').'?adminWarning_cmd=remove_ENABLE_INSTALL_TOOL';
  3746. $warnings['install_enabled'] = sprintf(
  3747. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.install_enabled'),
  3748. '<span style="white-space:nowrap;">'.$enableInstallToolFile.'</span>');
  3749. $warnings['install_enabled'].= ' <a href="'.$url.'">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.install_enabled_cmd').'</a>';
  3750. }
  3751. // Check if the encryption key is empty
  3752. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] == '') {
  3753. $url = 'install/index.php?redirect_url=index.php'.urlencode('?TYPO3_INSTALL[type]=config#set_encryptionKey');
  3754. $warnings["install_encryption"] = sprintf(
  3755. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.install_encryption'),
  3756. '<a href="'.$url.'">',
  3757. '</a>');
  3758. }
  3759. // Check if fileDenyPattern was changed which is dangerous on Apache
  3760. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] != FILE_DENY_PATTERN_DEFAULT ) {
  3761. $warnings['file_deny_pattern'] = sprintf(
  3762. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_deny_pattern'),
  3763. '<br /><pre>'.htmlspecialchars(FILE_DENY_PATTERN_DEFAULT).'</pre><br />');
  3764. }
  3765. // Check if fileDenyPattern allows to upload .htaccess files which is dangerous on Apache
  3766. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] != FILE_DENY_PATTERN_DEFAULT && t3lib_div::verifyFilenameAgainstDenyPattern(".htaccess")) {
  3767. $warnings['file_deny_htaccess'] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_deny_htaccess');
  3768. }
  3769. // Check if there are still updates to perform
  3770. if (!t3lib_div::compat_version(TYPO3_branch)) {
  3771. $url = 'install/index.php?redirect_url=index.php'.urlencode('?TYPO3_INSTALL[type]=update');
  3772. $warnings["install_update"] = sprintf(
  3773. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.install_update'),
  3774. '<a href="'.$url.'">',
  3775. '</a>');
  3776. }
  3777. // Check if sys_refindex is empty
  3778. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', 'sys_refindex');
  3779. $registry = t3lib_div::makeInstance('t3lib_Registry');
  3780. $lastRefIndexUpdate = $registry->get('core', 'sys_refindex_lastUpdate');
  3781. if (!$count && $lastRefIndexUpdate) {
  3782. $url = 'sysext/lowlevel/dbint/index.php?&id=0&SET[function]=refindex';
  3783. $warnings["backend_reference"] = sprintf(
  3784. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.backend_reference_index'),
  3785. '<a href="'.$url.'">',
  3786. '</a>',
  3787. self::dateTime($lastRefIndexUpdate));
  3788. }
  3789. // Check for memcached if configured
  3790. $memCacheUse = false;
  3791. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'])) {
  3792. foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $table => $conf) {
  3793. if (is_array($conf)) {
  3794. foreach ($conf as $key => $value) {
  3795. if (!is_array($value) && $value === 't3lib_cache_backend_MemcachedBackend') {
  3796. $servers = $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'][$table]['options']['servers'];
  3797. $memCacheUse = true;
  3798. break;
  3799. }
  3800. }
  3801. }
  3802. }
  3803. if ($memCacheUse) {
  3804. $failed = array();
  3805. $defaultPort = ini_get('memcache.default_port');
  3806. if (function_exists('memcache_connect')) {
  3807. if (is_array($servers)) {
  3808. foreach ($servers as $testServer) {
  3809. $configuredServer = $testServer;
  3810. if (substr($testServer, 0, 7) == 'unix://') {
  3811. $host = $testServer;
  3812. $port = 0;
  3813. } else {
  3814. if (substr($testServer, 0, 6) === 'tcp://') {
  3815. $testServer = substr($testServer, 6);
  3816. }
  3817. if (strstr($testServer, ':') !== FALSE) {
  3818. list($host, $port) = explode(':', $testServer, 2);
  3819. } else {
  3820. $host = $testServer;
  3821. $port = $defaultPort;
  3822. }
  3823. }
  3824. $memcache_obj = @memcache_connect($host, $port);
  3825. if ($memcache_obj != null) {
  3826. memcache_close($memcache_obj);
  3827. } else {
  3828. $failed[] = $configuredServer;
  3829. }
  3830. }
  3831. }
  3832. }
  3833. if (count($failed) > 0) {
  3834. $warnings['memcached'] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.memcache_not_usable') . '<br/>' .
  3835. implode(', ', $failed);
  3836. }
  3837. }
  3838. }
  3839. // Hook for additional warnings
  3840. if (is_array ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['displayWarningMessages'])) {
  3841. foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['displayWarningMessages'] as $classRef) {
  3842. $hookObj = t3lib_div::getUserObj($classRef);
  3843. if (method_exists($hookObj, 'displayWarningMessages_postProcess')) {
  3844. $hookObj->displayWarningMessages_postProcess($warnings);
  3845. }
  3846. }
  3847. }
  3848. if (count($warnings)) {
  3849. $style = ' style="margin-bottom:10px;"';
  3850. $securityWarnings = '<ul><li' . $style . '>'
  3851. . implode('</li><li' . $style . '>', $warnings)
  3852. . '</li></ul>';
  3853. $securityMessage = t3lib_div::makeInstance(
  3854. 't3lib_FlashMessage',
  3855. $securityWarnings,
  3856. $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.header'),
  3857. t3lib_FlashMessage::ERROR
  3858. );
  3859. $content = '<div style="margin: 20px 0px;">'
  3860. . $securityMessage->render()
  3861. . '</div>';
  3862. unset($warnings);
  3863. return $content;
  3864. }
  3865. }
  3866. return '<p>&nbsp;</p>';
  3867. }
  3868. /**
  3869. * Returns "web" if the $path (absolute) is within the DOCUMENT ROOT - and thereby qualifies as a "web" folder.
  3870. * Usage: 4
  3871. *
  3872. * @param string Path to evaluate
  3873. * @return boolean
  3874. */
  3875. public static function getPathType_web_nonweb($path) {
  3876. return t3lib_div::isFirstPartOfStr($path, t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT')) ? 'web' : '';
  3877. }
  3878. /**
  3879. * Creates ADMCMD parameters for the "viewpage" extension / "cms" frontend
  3880. * Usage: 1
  3881. *
  3882. * @param array Page record
  3883. * @return string Query-parameters
  3884. * @internal
  3885. */
  3886. public static function ADMCMD_previewCmds($pageinfo) {
  3887. if ($pageinfo['fe_group']>0) {
  3888. $simUser = '&ADMCMD_simUser='.$pageinfo['fe_group'];
  3889. }
  3890. if ($pageinfo['starttime'] > $GLOBALS['EXEC_TIME']) {
  3891. $simTime = '&ADMCMD_simTime='.$pageinfo['starttime'];
  3892. }
  3893. if ($pageinfo['endtime'] < $GLOBALS['EXEC_TIME'] && $pageinfo['endtime'] != 0) {
  3894. $simTime = '&ADMCMD_simTime='.($pageinfo['endtime']-1);
  3895. }
  3896. return $simUser.$simTime;
  3897. }
  3898. /**
  3899. * Returns an array with key=>values based on input text $params
  3900. * $params is exploded by line-breaks and each line is supposed to be on the syntax [key] = [some value]
  3901. * These pairs will be parsed into an array an returned.
  3902. * Usage: 1
  3903. *
  3904. * @param string String of parameters on multiple lines to parse into key-value pairs (see function description)
  3905. * @return array
  3906. */
  3907. public static function processParams($params) {
  3908. $paramArr = array();
  3909. $lines = explode(LF, $params);
  3910. foreach ($lines as $val) {
  3911. $val = trim($val);
  3912. if ($val) {
  3913. $pair = explode('=', $val, 2);
  3914. $paramArr[trim($pair[0])] = trim($pair[1]);
  3915. }
  3916. }
  3917. return $paramArr;
  3918. }
  3919. /**
  3920. * Returns "list of backend modules". Most likely this will be obsolete soon / removed. Don't use.
  3921. * Usage: 0
  3922. *
  3923. * @param array Module names in array. Must be "addslashes()"ed
  3924. * @param string Perms clause for SQL query
  3925. * @param string Backpath
  3926. * @param string The URL/script to jump to (used in A tag)
  3927. * @return array Two keys, rows and list
  3928. * @internal
  3929. * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.5.
  3930. * @obsolete
  3931. */
  3932. public static function getListOfBackendModules($name, $perms_clause, $backPath = '', $script = 'index.php') {
  3933. t3lib_div::logDeprecatedFunction();
  3934. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'doktype!=255 AND module IN (\'' . implode('\',\'', $name) . '\') AND' . $perms_clause . self::deleteClause('pages'));
  3935. if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res)) return false;
  3936. $out = '';
  3937. $theRows = array();
  3938. while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  3939. $theRows[] = $row;
  3940. $out.='<span class="nobr"><a href="'.htmlspecialchars($script.'?id='.$row['uid']).'">'.
  3941. t3lib_iconWorks::getSpriteIconForRecord('pages', $row, array('title' => htmlspecialchars(self::getRecordPath($row['uid'], $perms_clause, 20)))) .
  3942. htmlspecialchars($row['title']).
  3943. '</a></span><br />';
  3944. }
  3945. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  3946. return array('rows'=>$theRows, 'list'=>$out);
  3947. }
  3948. /**
  3949. * Returns the name of the backend script relative to the TYPO3 main directory.
  3950. *
  3951. * @param string Name of the backend interface (backend, frontend) to look up the script name for. If no interface is given, the interface for the current backend user is used.
  3952. * @return string The name of the backend script relative to the TYPO3 main directory.
  3953. */
  3954. public static function getBackendScript($interface = '') {
  3955. if (!$interface) {
  3956. $interface = $GLOBALS['BE_USER']->uc['interfaceSetup'];
  3957. }
  3958. switch ($interface) {
  3959. case 'frontend':
  3960. $script = '../.';
  3961. break;
  3962. case 'backend':
  3963. default:
  3964. $script = 'backend.php';
  3965. break;
  3966. }
  3967. return $script;
  3968. }
  3969. }
  3970. ?>