Followup to #4361 / New Hook: removed the "&" when calling the hook method (Thanks...
[Packages/TYPO3.CMS.git] / typo3 / class.db_list.inc
1 <?php
2 /***************************************************************
3 *  Copyright notice
4 *
5 *  (c) 1999-2009 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  * Include file extending t3lib_recordList
29  * Shared between Web>List (db_list.php) and Web>Page (sysext/cms/layout/db_layout.php)
30  *
31  * $Id$
32  * Revised for TYPO3 3.6 December/2003 by Kasper Skaarhoj
33  * XHTML compliant
34  *
35  * @author      Kasper Skaarhoj <kasperYYYY@typo3.com>
36  */
37 /**
38  * [CLASS/FUNCTION INDEX of SCRIPT]
39  *
40  *
41  *
42  *   86: class recordList extends t3lib_recordList
43  *  148:     function start($id,$table,$pointer,$search="",$levels="",$showLimit=0)
44  *  211:     function generateList()
45  *  275:     function getSearchBox($formFields=1)
46  *  319:     function showSysNotesForPage()
47  *
48  *              SECTION: Various helper functions
49  *  396:     function setDispFields()
50  *  421:     function thumbCode($row,$table,$field)
51  *  434:     function makeQueryArray($table, $id, $addWhere="",$fieldList='*')
52  *  481:     function setTotalItems($queryParts)
53  *  497:     function makeSearchString($table)
54  *  536:     function linkWrapTable($table,$code)
55  *  553:     function linkWrapItems($table,$uid,$code,$row)
56  *  617:     function linkUrlMail($code,$testString)
57  *  644:     function listURL($altId='',$table=-1,$exclList='')
58  *  663:     function requestUri()
59  *  674:     function makeFieldList($table,$dontCheckUser=0)
60  *  721:     function getTreeObject($id,$depth,$perms_clause)
61  *  739:     function localizationRedirect($justLocalized)
62  *
63  * TOTAL FUNCTIONS: 17
64  * (This index is automatically created/updated by the extension "extdeveval")
65  *
66  */
67
68
69
70
71
72
73
74
75
76
77
78 /**
79  * Child class for rendering of Web > List (not the final class. see class.db_list_extra)
80  *
81  * @author      Kasper Skaarhoj <kasperYYYY@typo3.com>
82  * @package TYPO3
83  * @subpackage core
84  * @see localRecordList
85  */
86 class recordList extends t3lib_recordList {
87
88                 // External, static:
89         var $tableList='';                              // Specify a list of tables which are the only ones allowed to be displayed.
90         var $returnUrl='';                              // Return URL
91         var $thumbs = 0;                                // Boolean. Thumbnails on records containing files (pictures)
92         var $itemsLimitPerTable = 20;                   // default Max items shown per table in "multi-table mode", may be overridden by tables.php
93         var $itemsLimitSingleTable = 100;               // default Max items shown per table in "single-table mode", may be overridden by tables.php
94         var $widthGif = '<img src="clear.gif" width="1" height="4" hspace="160" alt="" />';
95         var $script = 'db_list.php';                    // Current script name
96         var $allFields=0;                               // Indicates if all available fields for a user should be selected or not.
97         var $localizationView=FALSE;                    // Whether to show localization view or not.
98
99                 // Internal, static: GPvar:
100         var $csvOutput=FALSE;                           // If set, csvList is outputted.
101         var $sortField;                                 // Field, to sort list by
102         var $sortRev;                                   // Field, indicating to sort in reverse order.
103         var $displayFields;                             // Array, containing which fields to display in extended mode
104         var $duplicateField;                            // String, can contain the field name from a table which must have duplicate values marked.
105
106                 // Internal, static:
107         var $id;                                        // Page id
108         var $table='';                                  // Tablename if single-table mode
109         var $listOnlyInSingleTableMode=FALSE;           // If true, records are listed only if a specific table is selected.
110         var $firstElementNumber=0;                      // Pointer for browsing list
111         var $searchString='';                           // Search string
112         var $searchLevels='';                           // Levels to search down.
113         var $showLimit=0;                               // Number of records to show
114         var $pidSelect='';                              // List of ids from which to select/search etc. (when search-levels are set high). See start()
115         var $perms_clause='';                           // Page select permissions
116         var $calcPerms=0;                               // Some permissions...
117         var $clickTitleMode = '';                       // Mode for what happens when a user clicks the title of a record.
118         var $modSharedTSconfig = array();               // Shared module configuration, used by localization features
119         var $pageRecord = array();              // Loaded with page record with version overlay if any.
120         var $hideTables = '';                   // Tables which should not get listed
121         var $tableTSconfigOverTCA = array(); //TSconfig which overwrites TCA-Settings
122         var $tablesCollapsed = array(); // Array of collapsed / uncollapsed tables in multi table view
123
124                 // Internal, dynamic:
125         var $JScode = '';                               // JavaScript code accumulation
126         var $HTMLcode = '';                             // HTML output
127         var $iLimit=0;                                  // "LIMIT " in SQL...
128         var $eCounter=0;                                // Counting the elements no matter what...
129         var $totalItems='';                             // Set to the total number of items for a table when selecting.
130         var $recPath_cache=array();                     // Cache for record path
131         var $setFields=array();                         // Fields to display for the current table
132         var $currentTable = array();                    // Used for tracking next/prev uids
133         var $duplicateStack=array();                    // Used for tracking duplicate values of fields
134
135         var $modTSconfig;                               // module configuratio
136
137
138
139         /**
140          * Initializes the list generation
141          *
142          * @param       integer         Page id for which the list is rendered. Must be >= 0
143          * @param       string          Tablename - if extended mode where only one table is listed at a time.
144          * @param       integer         Browsing pointer.
145          * @param       string          Search word, if any
146          * @param       integer         Number of levels to search down the page tree
147          * @param       integer         Limit of records to be listed.
148          * @return      void
149          */
150         function start($id,$table,$pointer,$search="",$levels="",$showLimit=0)  {
151                 global $TCA;
152
153                         // Setting internal variables:
154                 $this->id=intval($id);                                  // sets the parent id
155                 if ($TCA[$table])       $this->table=$table;            // Setting single table mode, if table exists:
156                 $this->firstElementNumber=$pointer;
157                 $this->searchString=trim($search);
158                 $this->searchLevels=trim($levels);
159                 $this->showLimit=t3lib_div::intInRange($showLimit,0,10000);
160
161                         // Setting GPvars:
162                 $this->csvOutput = t3lib_div::_GP('csv') ? TRUE : FALSE;
163                 $this->sortField = t3lib_div::_GP('sortField');
164                 $this->sortRev = t3lib_div::_GP('sortRev');
165                 $this->displayFields = t3lib_div::_GP('displayFields');
166                 $this->duplicateField = t3lib_div::_GP('duplicateField');
167
168                 if (t3lib_div::_GP('justLocalized'))    {
169                         $this->localizationRedirect(t3lib_div::_GP('justLocalized'));
170                 }
171
172                         // If thumbnails are disabled, set the "notfound" icon as default:
173                 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'])  {
174                         $this->thumbScript='gfx/notfound_thumb.gif';
175                 }
176
177                         // Init dynamic vars:
178                 $this->counter=0;
179                 $this->JScode='';
180                 $this->HTMLcode='';
181         
182                         // limits
183                 if(isset($this->modTSconfig['properties']['itemsLimitPerTable'])) {
184                         $this->itemsLimitPerTable = t3lib_div::intInRange(intval($this->modTSconfig['properties']['itemsLimitPerTable']), 1, 10000);
185                 }
186                 if(isset($this->modTSconfig['properties']['itemsLimitSingleTable'])) {
187                         $this->itemsLimitSingleTable = t3lib_div::intInRange(intval($this->modTSconfig['properties']['itemsLimitSingleTable']), 1, 10000);
188                 }
189                 
190                         // Set select levels:
191                 $sL=intval($this->searchLevels);
192                 $this->perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
193
194                         // this will hide records from display - it has nothing todo with user rights!!
195                 if ($pidList = $GLOBALS['BE_USER']->getTSConfigVal('options.hideRecords.pages')) {
196                         if ($pidList = $GLOBALS['TYPO3_DB']->cleanIntList($pidList)) {
197                                 $this->perms_clause .= ' AND pages.uid NOT IN ('.$pidList.')';
198                         }
199                 }
200
201                 // Get configuration of collapsed tables from user uc and merge with sanitized GP vars
202                 $this->tablesCollapsed = is_array($GLOBALS['BE_USER']->uc['moduleData']['db_list.php']) ? $GLOBALS['BE_USER']->uc['moduleData']['db_list.php'] : array();
203                 $collapseOverride = t3lib_div::_GP('collapse');
204                 if (is_array($collapseOverride)) {
205                         foreach($collapseOverride as $collapseTable => $collapseValue) {
206                                 if (is_array($GLOBALS['TCA'][$collapseTable]) && ($collapseValue == 0 || $collapseValue == 1)) {
207                                         $this->tablesCollapsed[$collapseTable] = $collapseValue;
208                                 }
209                         }
210                         // Save modified user uc
211                         $GLOBALS['BE_USER']->uc['moduleData']['db_list.php'] = $this->tablesCollapsed;
212                         $GLOBALS['BE_USER']->writeUC($GLOBALS['BE_USER']->uc);
213                         if (t3lib_div::_GP('returnUrl')) {
214                                 $location = t3lib_div::_GP('returnUrl');
215                                 t3lib_div::redirect($location);
216                         }
217                 }
218
219                 if ($sL>0)      {
220                         $tree = $this->getTreeObject($id,$sL,$this->perms_clause);
221                         $this->pidSelect = 'pid IN ('.implode(',',$tree->ids).')';
222                 } else {
223                         $this->pidSelect = 'pid='.intval($id);
224                 }
225
226                         // Initialize languages:
227                 if ($this->localizationView)    {
228                         $this->initializeLanguages();
229                 }
230         }
231
232         /**
233          * Traverses the table(s) to be listed and renders the output code for each:
234          * The HTML is accumulated in $this->HTMLcode
235          * Finishes off with a stopper-gif
236          *
237          * @return      void
238          */
239         function generateList() {
240                 global $TCA;
241
242                         // Set page record in header
243                 $this->pageRecord = t3lib_BEfunc::getRecordWSOL('pages',$this->id);
244
245                         // Traverse the TCA table array:
246                 reset($TCA);
247                 while (list($tableName)=each($TCA))     {
248
249                                 // Checking if the table should be rendered:
250                         if ((!$this->table || $tableName==$this->table) && (!$this->tableList || t3lib_div::inList($this->tableList,$tableName)) && $GLOBALS['BE_USER']->check('tables_select',$tableName))     {               // Checks that we see only permitted/requested tables:
251
252                                         // Load full table definitions:
253                                 t3lib_div::loadTCA($tableName);
254
255                                         // Hide tables which are configured via TSConfig not to be shown (also works for admins):
256                                 if (isset($this->tableTSconfigOverTCA[$tableName.'.']['hideTable']) ? $this->tableTSconfigOverTCA[$tableName.'.']['hideTable'] :
257                                                 (t3lib_div::inList($this->hideTables, $tableName) ? true : $GLOBALS['TCA'][$tableName]['ctrl']['hideTable'])) {
258                                         continue;
259                                 }
260
261                                         // iLimit is set depending on whether we're in single- or multi-table mode
262                                 if ($this->table)       {
263                                         $this->iLimit=(isset($TCA[$tableName]['interface']['maxSingleDBListItems'])?intval($TCA[$tableName]['interface']['maxSingleDBListItems']):$this->itemsLimitSingleTable);
264                                 } else {
265                                         $this->iLimit=(isset($TCA[$tableName]['interface']['maxDBListItems'])?intval($TCA[$tableName]['interface']['maxDBListItems']):$this->itemsLimitPerTable);
266                                 }
267                                 if ($this->showLimit)   $this->iLimit = $this->showLimit;
268
269                                         // Setting fields to select:
270                                 if ($this->allFields)   {
271                                         $fields = $this->makeFieldList($tableName);
272                                         $fields[]='tstamp';
273                                         $fields[]='crdate';
274                                         $fields[]='_PATH_';
275                                         $fields[]='_CONTROL_';
276                                         if (is_array($this->setFields[$tableName]))     {
277                                                 $fields = array_intersect($fields,$this->setFields[$tableName]);
278                                         } else {
279                                                 $fields = array();
280                                         }
281                                 } else {
282                                         $fields = array();
283                                 }
284
285                                         // Find ID to use (might be different for "versioning_followPages" tables)
286                                 if (intval($this->searchLevels)==0)     {
287                                         if ($TCA[$tableName]['ctrl']['versioning_followPages'] && $this->pageRecord['_ORIG_pid']==-1 && $this->pageRecord['t3ver_swapmode']==0) {
288                                                 $this->pidSelect = 'pid='.intval($this->pageRecord['_ORIG_uid']);
289                                         } else {
290                                                 $this->pidSelect = 'pid='.intval($this->id);
291                                         }
292                                 }
293 #debug($this->pidSelect,$tableName);
294                                         // Finally, render the list:
295                                 $this->HTMLcode.=$this->getTable($tableName, $this->id, implode(',',$fields));
296                         }
297                 }
298         }
299
300         /**
301          * Creates the search box
302          *
303          * @param       boolean         If true, the search box is wrapped in its own form-tags
304          * @return      string          HTML for the search box
305          */
306         function getSearchBox($formFields=1)    {
307
308                         // Setting form-elements, if applicable:
309                 $formElements=array('','');
310                 if ($formFields)        {
311                         $formElements=array('<form action="'.htmlspecialchars($this->listURL()).'" method="post">','</form>');
312                 }
313
314                         // Make level selector:
315                 $opt=array();
316                 $parts = explode('|',$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.enterSearchLevels'));
317                 while(list($kv,$label)=each($parts))    {
318                         $opt[] = '<option value="'.$kv.'"'.($kv==intval($this->searchLevels)?' selected="selected"':'').'>'.htmlspecialchars($label).'</option>';
319                 }
320                 $lMenu = '<select name="search_levels">'.implode('',$opt).'</select>';
321
322                         // Table with the search box:
323                 $content.= '
324                         '.$formElements[0].'
325
326                                 <!--
327                                         Search box:
328                                 -->
329                                 <table border="0" cellpadding="0" cellspacing="0" class="bgColor4" id="typo3-dblist-search">
330                                         <tr>
331                                                 <td>'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.enterSearchString',1).'<input type="text" name="search_field" value="'.htmlspecialchars($this->searchString).'"'.$GLOBALS['TBE_TEMPLATE']->formWidth(10).' /></td>
332                                                 <td>'.$lMenu.'</td>
333                                                 <td><input type="submit" name="search" value="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.search',1).'" /></td>
334                                         </tr>
335                                         <tr>
336                                                 <td colspan="3">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showRecords',1).':<input type="text" name="showLimit" value="'.htmlspecialchars($this->showLimit?$this->showLimit:'').'"'.$GLOBALS['TBE_TEMPLATE']->formWidth(4).' /></td>
337                                         </tr>
338                                 </table>
339                         '.$formElements[1];
340                 $content.=t3lib_BEfunc::cshItem('xMOD_csh_corebe', 'list_searchbox', $GLOBALS['BACK_PATH'],'|<br/>');
341                 return $content;
342         }
343
344         /**
345          * Creates the display of sys_notes for the page.
346          * Relies on the "sys_note" extension to be loaded.
347          *
348          * @return      string          HTML for the sys-notes (if any)
349          */
350         function showSysNotesForPage()  {
351                 global $TCA;
352
353                 $out='';
354
355                         // Checking if extension is loaded:
356                 if (!t3lib_extMgm::isLoaded('sys_note'))        return '';
357
358                         // Create query for selecting the notes:
359                 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*','sys_note','pid IN ('.$this->id.') AND (personal=0 OR cruser='.intval($GLOBALS['BE_USER']->user['uid']).')'.t3lib_BEfunc::deleteClause('sys_note').t3lib_BEfunc::versioningPlaceholderClause('sys_note'));
360
361                         // Executing query:
362                 $dbCount = $GLOBALS['TYPO3_DB']->sql_num_rows($result);
363
364                         // If some notes were found, render them:
365                 if ($dbCount)   {
366                         $cat = array();
367
368                                 // Load full table description:
369                         t3lib_div::loadTCA('sys_note');
370
371                                 // Traverse note-types and get labels:
372                         if ($TCA['sys_note'] && $TCA['sys_note']['columns']['category'] && is_array($TCA['sys_note']['columns']['category']['config']['items']))        {
373                                 foreach($TCA['sys_note']['columns']['category']['config']['items'] as $el)      {
374                                         $cat[$el[1]]=$GLOBALS['LANG']->sL($el[0]);
375                                 }
376                         }
377
378                                 // For each note found, make rendering:
379                         while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))    {
380
381                                         // Create content:
382                                 $iconImg = t3lib_iconWorks::getIconImage('sys_note',$row,$this->backPath,'');
383                                 $subject = htmlspecialchars($row['subject']);
384                                 $fields = array();
385                                 $fields['Author:'] = htmlspecialchars($row['author'].($row['email'] && $row['author'] ? ', ':'').$row['email']);
386                                 $fields['Category:'] = htmlspecialchars($cat[$row['category']]);
387                                 $fields['Note:'] = nl2br(htmlspecialchars($row['message']));
388
389                                         // Compile content:
390                                 $out.='
391
392
393                                 <!--
394                                         Sys-notes for the db_list.php:
395                                 -->
396                                         <table border="0" cellpadding="1" cellspacing="1" id="typo3-dblist-sysnotes">
397                                                 <tr><td colspan="2" class="bgColor2">'.$iconImg.'<strong>'.$subject.'</strong></td></tr>
398                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.category',1).'</td><td class="bgColor4">'.$fields['Category:'].'</td></tr>
399                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.author',1).'</td><td class="bgColor4">'.$fields['Author:'].'</td></tr>
400                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.note',1).'</td><td class="bgColor4">'.$fields['Note:'].'</td></tr>
401                                         </table>
402                                 ';
403                         }
404                 }
405                 return $out;
406         }
407
408
409
410
411
412
413
414
415         /******************************
416          *
417          * Various helper functions
418          *
419          ******************************/
420
421         /**
422          * Setting the field names to display in extended list.
423          * Sets the internal variable $this->setFields
424          *
425          * @return      void
426          */
427         function setDispFields()        {
428
429                         // Getting from session:
430                 $dispFields = $GLOBALS['BE_USER']->getModuleData('db_list.php/displayFields');
431
432                         // If fields has been inputted, then set those as the value and push it to session variable:
433                 if (is_array($this->displayFields))     {
434                         reset($this->displayFields);
435                         $tKey = key($this->displayFields);
436                         $dispFields[$tKey]=$this->displayFields[$tKey];
437                         $GLOBALS['BE_USER']->pushModuleData('db_list.php/displayFields',$dispFields);
438                 }
439
440                         // Setting result:
441                 $this->setFields=$dispFields;
442         }
443
444         /**
445          * Create thumbnail code for record/field
446          *
447          * @param       array           Record array
448          * @param       string          Table (record is from)
449          * @param       string          Field name for which thumbsnail are to be rendered.
450          * @return      string          HTML for thumbnails, if any.
451          */
452         function thumbCode($row,$table,$field)  {
453                 return t3lib_BEfunc::thumbCode($row,$table,$field,$this->backPath,$this->thumbScript);
454         }
455
456         /**
457          * Returns the SQL-query array to select the records from a table $table with pid = $id
458          *
459          * @param       string          Table name
460          * @param       integer         Page id (NOT USED! $this->pidSelect is used instead)
461          * @param       string          Additional part for where clause
462          * @param       string          Field list to select, * for all (for "SELECT [fieldlist] FROM ...")
463          * @return      array           Returns query array
464          */
465         function makeQueryArray($table, $id, $addWhere='', $fieldList='*')      {
466                 global $TCA, $TYPO3_CONF_VARS;
467
468                 $hookObjectsArr = array();
469                 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['typo3/class.db_list.inc']['makeQueryArray'])) {
470                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['typo3/class.db_list.inc']['makeQueryArray'] as $classRef) {
471                                 $hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
472                         }
473                 }
474
475                         // Set ORDER BY:
476                 $orderBy = ($TCA[$table]['ctrl']['sortby']) ? 'ORDER BY '.$TCA[$table]['ctrl']['sortby'] : $TCA[$table]['ctrl']['default_sortby'];
477                 if ($this->sortField)   {
478                         if (in_array($this->sortField,$this->makeFieldList($table,1)))  {
479                                 $orderBy = 'ORDER BY '.$this->sortField;
480                                 if ($this->sortRev)     $orderBy.=' DESC';
481                         }
482                 }
483
484                         // Set LIMIT:
485                 $limit = $this->iLimit ? ($this->firstElementNumber ? $this->firstElementNumber.',' : '').($this->iLimit+1) : '';
486
487                         // Filtering on displayable pages (permissions):
488                 $pC = ($table=='pages' && $this->perms_clause)?' AND '.$this->perms_clause:'';
489
490                         // Adding search constraints:
491                 $search = $this->makeSearchString($table);
492
493                         // Compiling query array:
494                 $queryParts = array(
495                         'SELECT' => $fieldList,
496                         'FROM' => $table,
497                         'WHERE' => $this->pidSelect.
498                                                 ' '.$pC.
499                                                 t3lib_BEfunc::deleteClause($table).
500                                                 t3lib_BEfunc::versioningPlaceholderClause($table).
501                                                 ' '.$addWhere.
502                                                 ' '.$search,
503                         'GROUPBY' => '',
504                         'ORDERBY' => $GLOBALS['TYPO3_DB']->stripOrderBy($orderBy),
505                         'LIMIT' => $limit
506                 );
507
508                         // Apply hook as requested in http://bugs.typo3.org/view.php?id=4361
509                 foreach ($hookObjectsArr as $hookObj) {
510                         if (method_exists($hookObj, 'makeQueryArray_post')) {
511                                 $_params = array(
512                                         'orderBy' => $orderBy,
513                                         'limit' => $limit,
514                                         'pC' => $pC,
515                                         'search' => $search,
516                                 );
517                                 $hookObj->makeQueryArray_post($queryParts, $this, $table, $id, $addWhere, $fieldList, $_params);
518                         }
519                 }
520
521                         // Return query:
522                 return $queryParts;
523         }
524
525         /**
526          * Based on input query array (query for selecting count(*) from a table) it will select the number of records and set the value in $this->totalItems
527          *
528          * @param       array           Query array
529          * @return      void
530          * @see makeQueryArray()
531          */
532         function setTotalItems($queryParts)     {
533                 $this->totalItems = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
534                         '*',
535                         $queryParts['FROM'],
536                         $queryParts['WHERE']
537                 );
538         }
539
540         /**
541          * Creates part of query for searching after a word ($this->searchString) fields in input table
542          *
543          * @param       string          Table, in which the fields are being searched.
544          * @return      string          Returns part of WHERE-clause for searching, if applicable.
545          */
546         function makeSearchString($table)       {
547                 global $TCA;
548
549                         // Make query, only if table is valid and a search string is actually defined:
550                 if ($TCA[$table] && $this->searchString)        {
551
552                                 // Loading full table description - we need to traverse fields:
553                         t3lib_div::loadTCA($table);
554
555                                 // Initialize field array:
556                         $sfields=array();
557                         $sfields[]='uid';       // Adding "uid" by default.
558
559                                 // Traverse the configured columns and add all columns that can be searched:
560                         foreach($TCA[$table]['columns'] as $fieldName => $info) {
561                                 if ($info['config']['type']=='text' || ($info['config']['type']=='input' && !preg_match('/date|time|int/',$info['config']['eval'])))    {
562                                         $sfields[]=$fieldName;
563                                 }
564                         }
565
566                                 // If search-fields were defined (and there always are) we create the query:
567                         if (count($sfields))    {
568                                 $like = ' LIKE \'%'.$GLOBALS['TYPO3_DB']->quoteStr($this->searchString, $table).'%\'';          // Free-text searching...
569                                 $queryPart = ' AND ('.implode($like.' OR ',$sfields).$like.')';
570
571                                         // Return query:
572                                 return $queryPart;
573                         }
574                 }
575         }
576
577         /**
578          * Returns the title (based on $code) of a table ($table) with the proper link around. For headers over tables.
579          * The link will cause the display of all extended mode or not for the table.
580          *
581          * @param       string          Table name
582          * @param       string          Table label
583          * @return      string          The linked table label
584          */
585         function linkWrapTable($table,$code)    {
586                 if ($this->table!=$table)       {
587                         return '<a href="'.htmlspecialchars($this->listURL('',$table)).'">'.$code.'</a>';
588                 } else {
589                         return '<a href="'.htmlspecialchars($this->listURL('','','sortField,sortRev,table')).'">'.$code.'</a>';
590                 }
591         }
592
593         /**
594          * Returns the title (based on $code) of a record (from table $table) with the proper link around (that is for 'pages'-records a link to the level of that record...)
595          *
596          * @param       string          Table name
597          * @param       integer         Item uid
598          * @param       string          Item title (not htmlspecialchars()'ed yet)
599          * @param       array           Item row
600          * @return      string          The item title. Ready for HTML output (is htmlspecialchars()'ed)
601          */
602         function linkWrapItems($table,$uid,$code,$row)  {
603                 global $TCA, $LANG;
604
605                 $origCode = $code;
606
607                         // If the title is blank, make a "no title" label:
608                 if (!strcmp($code,'')) {
609                         $code = '<i>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</i> - '.htmlspecialchars(t3lib_div::fixed_lgd_cs(t3lib_BEfunc::getRecordTitle($table,$row),$GLOBALS['BE_USER']->uc['titleLen']));
610                 } else {
611                         $code = htmlspecialchars(t3lib_div::fixed_lgd_cs($code, $this->fixedL));
612                         if ($code != htmlspecialchars($origCode)) {
613                                 $code = '<span title="'.htmlspecialchars($origCode).'">'.$code.'</span>';
614                         }
615                 }
616
617                 switch((string)$this->clickTitleMode)   {
618                         case 'edit':
619                                         // If the listed table is 'pages' we have to request the permission settings for each page:
620                                 if ($table=='pages')    {
621                                         $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$row['uid']));
622                                         $permsEdit = $localCalcPerms&2;
623                                 } else {
624                                         $permsEdit = $this->calcPerms&16;
625                                 }
626
627                                         // "Edit" link: ( Only if permissions to edit the page-record of the content of the parent page ($this->id)
628                                 if ($permsEdit) {
629                                         $params='&edit['.$table.']['.$row['uid'].']=edit';
630                                         $code = '<a href="#" onclick="'.htmlspecialchars(t3lib_BEfunc::editOnClick($params,$this->backPath,-1)).'" title="'.$LANG->getLL('edit',1).'">'.
631                                                         $code.
632                                                         '</a>';
633                                 }
634                         break;
635                         case 'show':
636                                         // "Show" link (only pages and tt_content elements)
637                                 if ($table=='pages' || $table=='tt_content')    {
638                                         $code = '<a href="#" onclick="'.htmlspecialchars(t3lib_BEfunc::viewOnClick($table=='tt_content'?$this->id.'#'.$row['uid']:$row['uid'])).'" title="'.$LANG->sL('LLL:EXT:lang/locallang_core.php:labels.showPage',1).'">'.
639                                                         $code.
640                                                         '</a>';
641                                 }
642                         break;
643                         case 'info':
644                                 // "Info": (All records)
645                                 $code = '<a href="#" onclick="'.htmlspecialchars('top.launchView(\''.$table.'\', \''.$row['uid'].'\'); return false;').'" title="'.$LANG->getLL('showInfo',1).'">'.
646                                         $code.
647                                         '</a>';
648                         break;
649                         default:
650                                         // Output the label now:
651                                 if ($table=='pages')    {
652                                         $code = '<a href="'.htmlspecialchars($this->listURL($uid,'')).'" onclick="setHighlight('.$uid.')">'.$code.'</a>';
653                                 } else {
654                                         $code = $this->linkUrlMail($code,$origCode);
655                                 }
656                         break;
657                 }
658
659                 return $code;
660         }
661
662         /**
663          * Wrapping input code in link to URL or email if $testString is either.
664          *
665          * @param       string          code to wrap
666          * @param       string          String which is tested for being a URL or email and which will be used for the link if so.
667          * @return      string          Link-Wrapped $code value, if $testString was URL or email.
668          */
669         function linkUrlMail($code,$testString) {
670
671                         // Check for URL:
672                 $schema = parse_url($testString);
673                 if ($schema['scheme'] && t3lib_div::inList('http,https,ftp',$schema['scheme'])) {
674                         return '<a href="'.htmlspecialchars($testString).'" target="_blank">'.$code.'</a>';
675                 }
676
677                         // Check for email:
678                 if (t3lib_div::validEmail($testString)) {
679                         return '<a href="mailto:'.htmlspecialchars($testString).'" target="_blank">'.$code.'</a>';
680                 }
681
682                         // Return if nothing else...
683                 return $code;
684         }
685
686         /**
687          * Creates the URL to this script, including all relevant GPvars
688          * Fixed GPvars are id, table, imagemode, returlUrl, search_field, search_levels and showLimit
689          * The GPvars "sortField" and "sortRev" are also included UNLESS they are found in the $exclList variable.
690          *
691          * @param       string          Alternative id value. Enter blank string for the current id ($this->id)
692          * @param       string          Tablename to display. Enter "-1" for the current table.
693          * @param       string          Commalist of fields NOT to include ("sortField" or "sortRev")
694          * @return      string          URL
695          */
696         function listURL($altId='',$table=-1,$exclList='')      {
697                 return $GLOBALS['BACK_PATH'] . $this->script.
698                         '?id='.(strcmp($altId,'')?$altId:$this->id).
699                         '&table='.rawurlencode($table==-1?$this->table:$table).
700                         ($this->thumbs?'&imagemode='.$this->thumbs:'').
701                         ($this->returnUrl?'&returnUrl='.rawurlencode($this->returnUrl):'').
702                         ($this->searchString?'&search_field='.rawurlencode($this->searchString):'').
703                         ($this->searchLevels?'&search_levels='.rawurlencode($this->searchLevels):'').
704                         ($this->showLimit?'&showLimit='.rawurlencode($this->showLimit):'').
705                         ($this->firstElementNumber?'&pointer='.rawurlencode($this->firstElementNumber):'').
706                         ((!$exclList || !t3lib_div::inList($exclList,'sortField')) && $this->sortField?'&sortField='.rawurlencode($this->sortField):'').
707                         ((!$exclList || !t3lib_div::inList($exclList,'sortRev')) && $this->sortRev?'&sortRev='.rawurlencode($this->sortRev):'')
708                         ;
709         }
710
711         /**
712          * Returns "requestUri" - which is basically listURL
713          *
714          * @return      string          Content of ->listURL()
715          */
716         function requestUri()   {
717                 return $this->listURL();
718         }
719
720         /**
721          * Makes the list of fields to select for a table
722          *
723          * @param       string          Table name
724          * @param       boolean         If set, users access to the field (non-exclude-fields) is NOT checked.
725          * @param       boolean         If set, also adds crdate and tstamp fields (note: they will also be added if user is admin or dontCheckUser is set)
726          * @return      array           Array, where values are fieldnames to include in query
727          */
728         function makeFieldList($table,$dontCheckUser=0,$addDateFields=0)        {
729                 global $TCA,$BE_USER;
730
731                         // Init fieldlist array:
732                 $fieldListArr = array();
733
734                         // Check table:
735                 if (is_array($TCA[$table]))     {
736                         t3lib_div::loadTCA($table);
737
738                                 // Traverse configured columns and add them to field array, if available for user.
739                         foreach($TCA[$table]['columns'] as $fN => $fieldValue)  {
740                                 if ($dontCheckUser ||
741                                         ((!$fieldValue['exclude'] || $BE_USER->check('non_exclude_fields',$table.':'.$fN)) && $fieldValue['config']['type']!='passthrough'))    {
742                                         $fieldListArr[]=$fN;
743                                 }
744                         }
745
746                                 // Add special fields:
747                         if ($dontCheckUser || $BE_USER->isAdmin())      {
748                                 $fieldListArr[]='uid';
749                                 $fieldListArr[]='pid';
750                         }
751
752                                 // Add date fields
753                         if ($dontCheckUser || $BE_USER->isAdmin() || $addDateFields)    {
754                                 if ($TCA[$table]['ctrl']['tstamp'])     $fieldListArr[]=$TCA[$table]['ctrl']['tstamp'];
755                                 if ($TCA[$table]['ctrl']['crdate'])     $fieldListArr[]=$TCA[$table]['ctrl']['crdate'];
756                         }
757
758                                 // Add more special fields:
759                         if ($dontCheckUser || $BE_USER->isAdmin())      {
760                                 if ($TCA[$table]['ctrl']['cruser_id'])  $fieldListArr[]=$TCA[$table]['ctrl']['cruser_id'];
761                                 if ($TCA[$table]['ctrl']['sortby'])     $fieldListArr[]=$TCA[$table]['ctrl']['sortby'];
762                                 if ($TCA[$table]['ctrl']['versioningWS'])       {
763                                         $fieldListArr[]='t3ver_id';
764                                         $fieldListArr[]='t3ver_state';
765                                         $fieldListArr[]='t3ver_wsid';
766                                         if ($table==='pages')   {
767                                                 $fieldListArr[]='t3ver_swapmode';
768                                         }
769                                 }
770                         }
771                 }
772                 return $fieldListArr;
773         }
774
775         /**
776          * Creates an instance of t3lib_pageTree which will select a page tree to $depth and return the object. In that object we will find the ids of the tree.
777          *
778          * @param       integer         Page id.
779          * @param       integer         Depth to go down.
780          * @param       string          Select clause
781          * @return      object          t3lib_pageTree instance with created list of ids.
782          */
783         function getTreeObject($id,$depth,$perms_clause)        {
784                 $tree = t3lib_div::makeInstance('t3lib_pageTree');
785                 $tree->init('AND '.$perms_clause);
786                 $tree->makeHTML=0;
787                 $tree->fieldArray = Array('uid','php_tree_stop');
788                 if ($depth)     {
789                         $tree->getTree($id, $depth, '');
790                 }
791                 $tree->ids[]=$id;
792                 return $tree;
793         }
794
795         /**
796          * Redirects to TCEforms (alt_doc) if a record is just localized.
797          *
798          * @param       string          string with table, orig uid and language separated by ":"
799          * @return      void
800          */
801         function localizationRedirect($justLocalized)   {
802                 global $TCA;
803
804                 list($table,$orig_uid,$language) = explode(':',$justLocalized);
805
806                 if ($TCA[$table] && $TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField'])     {
807                         list($localizedRecord) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
808                                         'uid',
809                                         $table,
810                                         $TCA[$table]['ctrl']['languageField'].'='.intval($language).' AND '.
811                                                 $TCA[$table]['ctrl']['transOrigPointerField'].'='.intval($orig_uid).
812                                                 t3lib_BEfunc::deleteClause($table).
813                                                 t3lib_BEfunc::versioningPlaceholderClause($table)
814                                 );
815
816                         if (is_array($localizedRecord)) {
817                                         // Create parameters and finally run the classic page module for creating a new page translation
818                                 $params = '&edit['.$table.']['.$localizedRecord['uid'].']=edit';
819                                 $returnUrl = '&returnUrl='.rawurlencode($this->listURL());
820                                 $location = $GLOBALS['BACK_PATH'].'alt_doc.php?'.$params.$returnUrl;
821
822                                 header('Location: '.t3lib_div::locationHeaderUrl($location));
823                                 exit;
824                         }
825                 }
826         }
827 }
828
829
830 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc']) {
831         include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc']);
832 }
833
834 ?>