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