[BUGFIX] Warning in list module
[Packages/TYPO3.CMS.git] / typo3 / class.db_list.inc
1 <?php
2 /***************************************************************
3 *  Copyright notice
4 *
5 *  (c) 1999-2009 Kasper Skårhøj (kasperYYYY@typo3.com)
6 *  All rights reserved
7 *
8 *  This script is part of the TYPO3 project. The TYPO3 project is
9 *  free software; you can redistribute it and/or modify
10 *  it under the terms of the GNU General Public License as published by
11 *  the Free Software Foundation; either version 2 of the License, or
12 *  (at your option) any later version.
13 *
14 *  The GNU General Public License can be found at
15 *  http://www.gnu.org/copyleft/gpl.html.
16 *  A copy is found in the textfile GPL.txt and important notices to the license
17 *  from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 *  This script is distributed in the hope that it will be useful,
21 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 *  GNU General Public License for more details.
24 *
25 *  This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28  * 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 Skårhøj
33  * XHTML compliant
34  *
35  * @author      Kasper Skårhøj <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 Skårhøj <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 = 'index.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']['list']) ? $GLOBALS['BE_USER']->uc['moduleData']['list'] : 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']['list'] = $this->tablesCollapsed;
212                         $GLOBALS['BE_USER']->writeUC($GLOBALS['BE_USER']->uc);
213                         if (t3lib_div::sanitizeLocalUrl(t3lib_div::_GP('returnUrl'))) {
214                                 $location = t3lib_div::sanitizeLocalUrl(t3lib_div::_GP('returnUrl'));
215                                 t3lib_utility_Http::redirect($location);
216                         }
217                 }
218
219                 if ($sL>0)      {
220                         $tree = $this->getTreeObject($this->id, $sL, $this->perms_clause);
221                         $pidList = implode(',', $GLOBALS['TYPO3_DB']->cleanIntArray($tree->ids));
222                         $this->pidSelect = 'pid IN (' . $pidList . ')';
223                 } else {
224                         $this->pidSelect = 'pid='.intval($id);
225                 }
226
227                         // Initialize languages:
228                 if ($this->localizationView)    {
229                         $this->initializeLanguages();
230                 }
231         }
232
233         /**
234          * Traverses the table(s) to be listed and renders the output code for each:
235          * The HTML is accumulated in $this->HTMLcode
236          * Finishes off with a stopper-gif
237          *
238          * @return      void
239          */
240         function generateList() {
241                 global $TCA;
242
243                         // Set page record in header
244                 $this->pageRecord = t3lib_BEfunc::getRecordWSOL('pages',$this->id);
245
246                         // Traverse the TCA table array:
247                 foreach ($TCA as $tableName => $value) {
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                                         // Don't show table if hidden by TCA ctrl section
256                                 $hideTable = $GLOBALS['TCA'][$tableName]['ctrl']['hideTable'] ? TRUE : FALSE;
257                                         // Don't show table if hidden by pageTSconfig mod.web_list.hideTables
258                                 if (in_array($tableName, t3lib_div::trimExplode(',', $this->hideTables))) {
259                                         $hideTable = TRUE;
260                                 }
261                                         // Override previous selection if table is enabled or hidden by TSconfig TCA override mod.web_list.table
262                                 if (isset($this->tableTSconfigOverTCA[$tableName.'.']['hideTable'])) {
263                                         $hideTable = $this->tableTSconfigOverTCA[$tableName.'.']['hideTable'] ? TRUE : FALSE;
264                                 }
265                                 if ($hideTable) {
266                                         continue;
267                                 }
268
269                                         // iLimit is set depending on whether we're in single- or multi-table mode
270                                 if ($this->table)       {
271                                         $this->iLimit=(isset($TCA[$tableName]['interface']['maxSingleDBListItems'])?intval($TCA[$tableName]['interface']['maxSingleDBListItems']):$this->itemsLimitSingleTable);
272                                 } else {
273                                         $this->iLimit=(isset($TCA[$tableName]['interface']['maxDBListItems'])?intval($TCA[$tableName]['interface']['maxDBListItems']):$this->itemsLimitPerTable);
274                                 }
275                                 if ($this->showLimit)   $this->iLimit = $this->showLimit;
276
277                                         // Setting fields to select:
278                                 if ($this->allFields)   {
279                                         $fields = $this->makeFieldList($tableName);
280                                         $fields[]='tstamp';
281                                         $fields[]='crdate';
282                                         $fields[]='_PATH_';
283                                         $fields[]='_CONTROL_';
284                                         if (is_array($this->setFields[$tableName]))     {
285                                                 $fields = array_intersect($fields,$this->setFields[$tableName]);
286                                         } else {
287                                                 $fields = array();
288                                         }
289                                 } else {
290                                         $fields = array();
291                                 }
292
293                                         // Find ID to use (might be different for "versioning_followPages" tables)
294                                 if (intval($this->searchLevels)==0)     {
295                                         if ($TCA[$tableName]['ctrl']['versioning_followPages'] && $this->pageRecord['_ORIG_pid']==-1 && $this->pageRecord['t3ver_swapmode']==0) {
296                                                 $this->pidSelect = 'pid='.intval($this->pageRecord['_ORIG_uid']);
297                                         } else {
298                                                 $this->pidSelect = 'pid='.intval($this->id);
299                                         }
300                                 }
301 #debug($this->pidSelect,$tableName);
302                                         // Finally, render the list:
303                                 $this->HTMLcode.=$this->getTable($tableName, $this->id, implode(',',$fields));
304                         }
305                 }
306         }
307
308         /**
309          * Creates the search box
310          *
311          * @param       boolean         If true, the search box is wrapped in its own form-tags
312          * @return      string          HTML for the search box
313          */
314         function getSearchBox($formFields=1)    {
315
316                         // Setting form-elements, if applicable:
317                 $formElements=array('','');
318                 if ($formFields)        {
319                         $formElements = array('<form action="' . htmlspecialchars($this->listURL('', -1, 'firstElementNumber')) . '" method="post">', '</form>');
320                 }
321
322                         // Make level selector:
323                 $opt=array();
324                 $parts = explode('|',$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.enterSearchLevels'));
325                 foreach ($parts as $kv => $label) {
326                         $opt[] = '<option value="'.$kv.'"'.($kv==intval($this->searchLevels)?' selected="selected"':'').'>'.htmlspecialchars($label).'</option>';
327                 }
328                 $lMenu = '<select name="search_levels">'.implode('',$opt).'</select>';
329
330                         // Table with the search box:
331                 $content.= '
332                         '.$formElements[0].'
333
334                                 <!--
335                                         Search box:
336                                 -->
337                                 <table border="0" cellpadding="0" cellspacing="0" id="typo3-dblist-search">
338                                         <tr>
339                                                 <td><label for="search_field">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.enterSearchString', 1) . '</label><input type="text" name="search_field" id="search_field" value="' . htmlspecialchars($this->searchString) . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(10) . ' /></td>
340                                                 <td>' . $lMenu . '</td>
341                                                 <td><input type="submit" name="search" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.search', 1) . '" /></td>
342                                         </tr>
343                                         <tr>
344                                                 <td colspan="3"><label for="showLimit">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showRecords', 1) . '</label>:<input type="text" name="showLimit" id="showLimit" value="' . htmlspecialchars($this->showLimit ? $this->showLimit : '') . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(4) . ' /></td>
345                                         </tr>
346                                 </table>
347                         '.$formElements[1];
348                 return $content;
349         }
350
351         /**
352          * Creates the display of sys_notes for the page.
353          * Relies on the "sys_note" extension to be loaded.
354          *
355          * @return      string          HTML for the sys-notes (if any)
356          */
357         function showSysNotesForPage()  {
358                 global $TCA;
359
360                 $out='';
361
362                         // Checking if extension is loaded:
363                 if (!t3lib_extMgm::isLoaded('sys_note'))        return '';
364
365                         // Create query for selecting the notes:
366                 $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'));
367
368                         // Executing query:
369                 $dbCount = $GLOBALS['TYPO3_DB']->sql_num_rows($result);
370
371                         // If some notes were found, render them:
372                 if ($dbCount)   {
373                         $cat = array();
374
375                                 // Load full table description:
376                         t3lib_div::loadTCA('sys_note');
377
378                                 // Traverse note-types and get labels:
379                         if ($TCA['sys_note'] && $TCA['sys_note']['columns']['category'] && is_array($TCA['sys_note']['columns']['category']['config']['items']))        {
380                                 foreach($TCA['sys_note']['columns']['category']['config']['items'] as $el)      {
381                                         $cat[$el[1]]=$GLOBALS['LANG']->sL($el[0]);
382                                 }
383                         }
384
385                                 // For each note found, make rendering:
386                         while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))    {
387
388                                         // Create content:
389                                 $iconImg = t3lib_iconWorks::getSpriteIconForRecord('sys_note', $row);
390                                 $subject = htmlspecialchars($row['subject']);
391                                 $fields = array();
392                                 $fields['Author:'] = htmlspecialchars($row['author'].($row['email'] && $row['author'] ? ', ':'').$row['email']);
393                                 $fields['Category:'] = htmlspecialchars($cat[$row['category']]);
394                                 $fields['Note:'] = nl2br(htmlspecialchars($row['message']));
395
396                                         // Compile content:
397                                 $out.='
398
399
400                                 <!--
401                                         Sys-notes for list module:
402                                 -->
403                                         <table border="0" cellpadding="1" cellspacing="1" id="typo3-dblist-sysnotes">
404                                                 <tr><td colspan="2" class="bgColor2">'.$iconImg.'<strong>'.$subject.'</strong></td></tr>
405                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.category',1).'</td><td class="bgColor4">'.$fields['Category:'].'</td></tr>
406                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.author',1).'</td><td class="bgColor4">'.$fields['Author:'].'</td></tr>
407                                                 <tr><td class="bgColor4">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.note',1).'</td><td class="bgColor4">'.$fields['Note:'].'</td></tr>
408                                         </table>
409                                 ';
410                         }
411                 }
412                 return $out;
413         }
414
415
416
417
418
419
420
421
422         /******************************
423          *
424          * Various helper functions
425          *
426          ******************************/
427
428         /**
429          * Setting the field names to display in extended list.
430          * Sets the internal variable $this->setFields
431          *
432          * @return      void
433          */
434         function setDispFields()        {
435
436                         // Getting from session:
437                 $dispFields = $GLOBALS['BE_USER']->getModuleData('list/displayFields');
438
439                         // If fields has been inputted, then set those as the value and push it to session variable:
440                 if (is_array($this->displayFields))     {
441                         reset($this->displayFields);
442                         $tKey = key($this->displayFields);
443                         $dispFields[$tKey]=$this->displayFields[$tKey];
444                         $GLOBALS['BE_USER']->pushModuleData('list/displayFields',$dispFields);
445                 }
446
447                         // Setting result:
448                 $this->setFields=$dispFields;
449         }
450
451         /**
452          * Create thumbnail code for record/field
453          *
454          * @param       array           Record array
455          * @param       string          Table (record is from)
456          * @param       string          Field name for which thumbsnail are to be rendered.
457          * @return      string          HTML for thumbnails, if any.
458          */
459         function thumbCode($row,$table,$field)  {
460                 return t3lib_BEfunc::thumbCode($row,$table,$field,$this->backPath,$this->thumbScript);
461         }
462
463         /**
464          * Returns the SQL-query array to select the records from a table $table with pid = $id
465          *
466          * @param       string          Table name
467          * @param       integer         Page id (NOT USED! $this->pidSelect is used instead)
468          * @param       string          Additional part for where clause
469          * @param       string          Field list to select, * for all (for "SELECT [fieldlist] FROM ...")
470          * @return      array           Returns query array
471          */
472         function makeQueryArray($table, $id, $addWhere='', $fieldList='*')      {
473                 global $TCA, $TYPO3_CONF_VARS;
474
475                 $hookObjectsArr = array();
476                 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['typo3/class.db_list.inc']['makeQueryArray'])) {
477                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['typo3/class.db_list.inc']['makeQueryArray'] as $classRef) {
478                                 $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
479                         }
480                 }
481
482                         // Set ORDER BY:
483                 $orderBy = ($TCA[$table]['ctrl']['sortby']) ? 'ORDER BY '.$TCA[$table]['ctrl']['sortby'] : $TCA[$table]['ctrl']['default_sortby'];
484                 if ($this->sortField)   {
485                         if (in_array($this->sortField,$this->makeFieldList($table,1)))  {
486                                 $orderBy = 'ORDER BY '.$this->sortField;
487                                 if ($this->sortRev)     $orderBy.=' DESC';
488                         }
489                 }
490
491                         // Set LIMIT:
492                 $limit = $this->iLimit ? ($this->firstElementNumber ? $this->firstElementNumber.',' : '').($this->iLimit+1) : '';
493
494                         // Filtering on displayable pages (permissions):
495                 $pC = ($table=='pages' && $this->perms_clause)?' AND '.$this->perms_clause:'';
496
497                         // Adding search constraints:
498                 $search = $this->makeSearchString($table);
499
500                         // Compiling query array:
501                 $queryParts = array(
502                         'SELECT' => $fieldList,
503                         'FROM' => $table,
504                         'WHERE' => $this->pidSelect.
505                                                 ' '.$pC.
506                                                 t3lib_BEfunc::deleteClause($table).
507                                                 t3lib_BEfunc::versioningPlaceholderClause($table).
508                                                 ' '.$addWhere.
509                                                 ' '.$search,
510                         'GROUPBY' => '',
511                         'ORDERBY' => $GLOBALS['TYPO3_DB']->stripOrderBy($orderBy),
512                         'LIMIT' => $limit
513                 );
514
515                         // Apply hook as requested in http://bugs.typo3.org/view.php?id=4361
516                 foreach ($hookObjectsArr as $hookObj) {
517                         if (method_exists($hookObj, 'makeQueryArray_post')) {
518                                 $_params = array(
519                                         'orderBy' => $orderBy,
520                                         'limit' => $limit,
521                                         'pC' => $pC,
522                                         'search' => $search,
523                                 );
524                                 $hookObj->makeQueryArray_post($queryParts, $this, $table, $id, $addWhere, $fieldList, $_params);
525                         }
526                 }
527
528                         // Return query:
529                 return $queryParts;
530         }
531
532         /**
533          * 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
534          *
535          * @param       array           Query array
536          * @return      void
537          * @see makeQueryArray()
538          */
539         function setTotalItems($queryParts)     {
540                 $this->totalItems = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
541                         '*',
542                         $queryParts['FROM'],
543                         $queryParts['WHERE']
544                 );
545         }
546
547         /**
548          * Creates part of query for searching after a word ($this->searchString) fields in input table
549          *
550          * @param       string          Table, in which the fields are being searched.
551          * @return      string          Returns part of WHERE-clause for searching, if applicable.
552          */
553         function makeSearchString($table)       {
554                 global $TCA;
555
556                         // Make query, only if table is valid and a search string is actually defined:
557                 if ($TCA[$table] && $this->searchString)        {
558
559                                 // Loading full table description - we need to traverse fields:
560                         t3lib_div::loadTCA($table);
561
562                                 // Initialize field array:
563                         $sfields=array();
564                         $sfields[]='uid';       // Adding "uid" by default.
565
566                                 // Traverse the configured columns and add all columns that can be searched:
567                         foreach($TCA[$table]['columns'] as $fieldName => $info) {
568                                 if ($info['config']['type']=='text' || ($info['config']['type']=='input' && !preg_match('/date|time|int/',$info['config']['eval'])))    {
569                                         $sfields[]=$fieldName;
570                                 }
571                         }
572
573                                 // If search-fields were defined (and there always are) we create the query:
574                         if (count($sfields))    {
575                                 $like = ' LIKE \'%'.$GLOBALS['TYPO3_DB']->quoteStr($this->searchString, $table).'%\'';          // Free-text searching...
576                                 $queryPart = ' AND ('.implode($like.' OR ',$sfields).$like.')';
577
578                                         // Return query:
579                                 return $queryPart;
580                         }
581                 }
582         }
583
584         /**
585          * Returns the title (based on $code) of a table ($table) with the proper link around. For headers over tables.
586          * The link will cause the display of all extended mode or not for the table.
587          *
588          * @param       string          Table name
589          * @param       string          Table label
590          * @return      string          The linked table label
591          */
592         function linkWrapTable($table,$code)    {
593                 if ($this->table!=$table)       {
594                         return '<a href="' . htmlspecialchars($this->listURL('', $table, 'firstElementNumber')) . '">' . $code . '</a>';
595                 } else {
596                         return '<a href="' . htmlspecialchars($this->listURL('', '', 'sortField,sortRev,table,firstElementNumber')) . '">' . $code . '</a>';
597                 }
598         }
599
600         /**
601          * 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...)
602          *
603          * @param       string          Table name
604          * @param       integer         Item uid
605          * @param       string          Item title (not htmlspecialchars()'ed yet)
606          * @param       array           Item row
607          * @return      string          The item title. Ready for HTML output (is htmlspecialchars()'ed)
608          */
609         function linkWrapItems($table,$uid,$code,$row)  {
610                 global $TCA, $LANG;
611
612                 $origCode = $code;
613
614                         // If the title is blank, make a "no title" label:
615                 if (!strcmp($code,'')) {
616                         $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']));
617                 } else {
618                         $code = htmlspecialchars(t3lib_div::fixed_lgd_cs($code, $this->fixedL));
619                         if ($code != htmlspecialchars($origCode)) {
620                                 $code = '<span title="'.htmlspecialchars($origCode).'">'.$code.'</span>';
621                         }
622                 }
623
624                 switch((string)$this->clickTitleMode)   {
625                         case 'edit':
626                                         // If the listed table is 'pages' we have to request the permission settings for each page:
627                                 if ($table=='pages')    {
628                                         $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$row['uid']));
629                                         $permsEdit = $localCalcPerms&2;
630                                 } else {
631                                         $permsEdit = $this->calcPerms&16;
632                                 }
633
634                                         // "Edit" link: ( Only if permissions to edit the page-record of the content of the parent page ($this->id)
635                                 if ($permsEdit) {
636                                         $params='&edit['.$table.']['.$row['uid'].']=edit';
637                                         $code = '<a href="#" onclick="'.htmlspecialchars(t3lib_BEfunc::editOnClick($params,$this->backPath,-1)).'" title="'.$LANG->getLL('edit',1).'">'.
638                                                         $code.
639                                                         '</a>';
640                                 }
641                         break;
642                         case 'show':
643                                         // "Show" link (only pages and tt_content elements)
644                                 if ($table=='pages' || $table=='tt_content')    {
645                                         $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).'">'.
646                                                         $code.
647                                                         '</a>';
648                                 }
649                         break;
650                         case 'info':
651                                 // "Info": (All records)
652                                 $code = '<a href="#" onclick="'.htmlspecialchars('top.launchView(\''.$table.'\', \''.$row['uid'].'\'); return false;').'" title="'.$LANG->getLL('showInfo',1).'">'.
653                                         $code.
654                                         '</a>';
655                         break;
656                         default:
657                                         // Output the label now:
658                                 if ($table=='pages')    {
659                                         $code = '<a href="' . htmlspecialchars($this->listURL($uid, '', 'firstElementNumber')) . '" onclick="setHighlight(' . $uid . ')">' . $code . '</a>';
660                                 } else {
661                                         $code = $this->linkUrlMail($code,$origCode);
662                                 }
663                         break;
664                 }
665
666                 return $code;
667         }
668
669         /**
670          * Wrapping input code in link to URL or email if $testString is either.
671          *
672          * @param       string          code to wrap
673          * @param       string          String which is tested for being a URL or email and which will be used for the link if so.
674          * @return      string          Link-Wrapped $code value, if $testString was URL or email.
675          */
676         function linkUrlMail($code,$testString) {
677
678                         // Check for URL:
679                 $schema = parse_url($testString);
680                 if ($schema['scheme'] && t3lib_div::inList('http,https,ftp',$schema['scheme'])) {
681                         return '<a href="'.htmlspecialchars($testString).'" target="_blank">'.$code.'</a>';
682                 }
683
684                         // Check for email:
685                 if (t3lib_div::validEmail($testString)) {
686                         return '<a href="mailto:'.htmlspecialchars($testString).'" target="_blank">'.$code.'</a>';
687                 }
688
689                         // Return if nothing else...
690                 return $code;
691         }
692
693         /**
694          * Creates the URL to this script, including all relevant GPvars
695          * Fixed GPvars are id, table, imagemode, returlUrl, search_field, search_levels and showLimit
696          * The GPvars "sortField" and "sortRev" are also included UNLESS they are found in the $exclList variable.
697          *
698          * @param       string          Alternative id value. Enter blank string for the current id ($this->id)
699          * @param       string          Tablename to display. Enter "-1" for the current table.
700          * @param       string          Commalist of fields NOT to include ("sortField", "sortRev" or "firstElementNumber")
701          * @return      string          URL
702          */
703         function listURL($altId='',$table=-1,$exclList='')      {
704                 $urlParameters = array();
705                 if (strcmp($altId, '')) {
706                         $urlParameters['id'] = $altId;
707                 } else {
708                         $urlParameters['id'] = $this->id;
709                 }
710                 if ($table === -1) {
711                         $urlParameters['table'] = $this->table;
712                 } else {
713                         $urlParameters['table'] = $table;
714                 }
715                 if ($this->thumbs) {
716                         $urlParameters['imagemode'] = $this->thumbs;
717                 }
718                 if ($this->returnUrl) {
719                         $urlParameters['returnUrl'] = $this->returnUrl;
720                 }
721                 if ($this->searchString) {
722                         $urlParameters['search_field'] = $this->searchString;
723                 }
724                 if ($this->searchLevels) {
725                         $urlParameters['search_levels'] = $this->searchLevels;
726                 }
727                 if ($this->showLimit) {
728                         $urlParameters['showLimit'] = $this->showLimit;
729                 }
730                 if ((!$exclList || !t3lib_div::inList($exclList, 'firstElementNumber')) && $this->firstElementNumber) {
731                         $urlParameters['pointer'] = $this->firstElementNumber;
732                 }
733                 if ((!$exclList || !t3lib_div::inList($exclList, 'sortField')) && $this->sortField) {
734                         $urlParameters['sortField'] = $this->sortField;
735                 }
736                 if ((!$exclList || !t3lib_div::inList($exclList, 'sortRev')) && $this->sortRev) {
737                         $urlParameters['sortRev'] = $this->sortRev;
738                 }
739
740                 return t3lib_BEfunc::getModuleUrl('web_list', $urlParameters);
741         }
742
743         /**
744          * Returns "requestUri" - which is basically listURL
745          *
746          * @return      string          Content of ->listURL()
747          */
748         function requestUri()   {
749                 return $this->listURL();
750         }
751
752         /**
753          * Makes the list of fields to select for a table
754          *
755          * @param       string          Table name
756          * @param       boolean         If set, users access to the field (non-exclude-fields) is NOT checked.
757          * @param       boolean         If set, also adds crdate and tstamp fields (note: they will also be added if user is admin or dontCheckUser is set)
758          * @return      array           Array, where values are fieldnames to include in query
759          */
760         function makeFieldList($table,$dontCheckUser=0,$addDateFields=0)        {
761                 global $TCA,$BE_USER;
762
763                         // Init fieldlist array:
764                 $fieldListArr = array();
765
766                         // Check table:
767                 if (is_array($TCA[$table]))     {
768                         t3lib_div::loadTCA($table);
769
770                         if (isset($GLOBALS['TCA'][$table]['columns']) && is_array($GLOBALS['TCA'][$table]['columns'])) {
771                                         // Traverse configured columns and add them to field array, if available for user.
772                                 foreach ($GLOBALS['TCA'][$table]['columns'] as $fN => $fieldValue) {
773                                         if ($dontCheckUser ||
774                                                         ((!$fieldValue['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields', $table . ':' . $fN))
775                                                                         && $fieldValue['config']['type']!='passthrough')) {
776                                                 $fieldListArr[]=$fN;
777                                         }
778                                 }
779
780                                         // Add special fields:
781                                 if ($dontCheckUser || $GLOBALS['BE_USER']->isAdmin()) {
782                                         $fieldListArr[]='uid';
783                                         $fieldListArr[]='pid';
784                                 }
785
786                                         // Add date fields
787                                 if ($dontCheckUser || $GLOBALS['BE_USER']->isAdmin() || $addDateFields) {
788                                         if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
789                                                 $fieldListArr[]=$GLOBALS['TCA'][$table]['ctrl']['tstamp'];
790                                         }
791                                         if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
792                                                 $fieldListArr[]=$GLOBALS['TCA'][$table]['ctrl']['crdate'];
793                                         }
794                                 }
795
796                                         // Add more special fields:
797                                 if ($dontCheckUser || $GLOBALS['BE_USER']->isAdmin()) {
798                                         if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
799                                                 $fieldListArr[]=$GLOBALS['TCA'][$table]['ctrl']['cruser_id'];
800                                         }
801                                         if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
802                                                 $fieldListArr[]=$GLOBALS['TCA'][$table]['ctrl']['sortby'];
803                                         }
804                                         if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
805                                                 $fieldListArr[]='t3ver_id';
806                                                 $fieldListArr[]='t3ver_state';
807                                                 $fieldListArr[]='t3ver_wsid';
808                                                 if ($table==='pages') {
809                                                         $fieldListArr[]='t3ver_swapmode';
810                                                 }
811                                         }
812                                 }
813                         } else {
814                                 t3lib_div::sysLog(
815                                         sprintf('$TCA is broken for the table "%s": no required "columns" entry in $TCA.', $table),
816                                         'core',
817                                         t3lib_div::SYSLOG_SEVERITY_ERROR
818                                 );
819                         }
820                 }
821                 return $fieldListArr;
822         }
823
824         /**
825          * 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.
826          *
827          * @param       integer         Page id.
828          * @param       integer         Depth to go down.
829          * @param       string          Select clause
830          * @return      object          t3lib_pageTree instance with created list of ids.
831          */
832         function getTreeObject($id,$depth,$perms_clause)        {
833                 $tree = t3lib_div::makeInstance('t3lib_pageTree');
834                 $tree->init('AND '.$perms_clause);
835                 $tree->makeHTML=0;
836                 $tree->fieldArray = Array('uid','php_tree_stop');
837                 if ($depth)     {
838                         $tree->getTree($id, $depth, '');
839                 }
840                 $tree->ids[]=$id;
841                 return $tree;
842         }
843
844         /**
845          * Redirects to TCEforms (alt_doc) if a record is just localized.
846          *
847          * @param       string          string with table, orig uid and language separated by ":"
848          * @return      void
849          */
850         function localizationRedirect($justLocalized)   {
851                 global $TCA;
852
853                 list($table,$orig_uid,$language) = explode(':',$justLocalized);
854
855                 if ($TCA[$table] && $TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField'])     {
856                         $localizedRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
857                                         'uid',
858                                         $table,
859                                         $TCA[$table]['ctrl']['languageField'].'='.intval($language).' AND '.
860                                                 $TCA[$table]['ctrl']['transOrigPointerField'].'='.intval($orig_uid).
861                                                 t3lib_BEfunc::deleteClause($table).
862                                                 t3lib_BEfunc::versioningPlaceholderClause($table)
863                                 );
864
865                         if (is_array($localizedRecord)) {
866                                         // Create parameters and finally run the classic page module for creating a new page translation
867                                 $url = substr($this->listURL(), strlen($this->backPath));
868                                 $params = '&edit['.$table.']['.$localizedRecord['uid'].']=edit';
869                                 $returnUrl = '&returnUrl='.rawurlencode($url);
870                                 $location = $GLOBALS['BACK_PATH'].'alt_doc.php?'.$params.$returnUrl;
871
872                                 t3lib_utility_Http::redirect($location);
873                         }
874                 }
875         }
876 }
877
878
879 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc'])) {
880         include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc']);
881 }
882
883 ?>