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