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