Added more comments, $Id$ keywords etc for the whole core of TYPO3.
[Packages/TYPO3.CMS.git] / typo3 / class.db_list.inc
1 <?php
2 /***************************************************************
3 *  Copyright notice
4 *  
5 *  (c) 1999-2003 Kasper Skaarhoj (kasper@typo3.com)
6 *  All rights reserved
7 *
8 *  This script is part of the TYPO3 project. The TYPO3 project is 
9 *  free software; you can redistribute it and/or modify
10 *  it under the terms of the GNU General Public License as published by
11 *  the Free Software Foundation; either version 2 of the License, or
12 *  (at your option) any later version.
13
14 *  The GNU General Public License can be found at
15 *  http://www.gnu.org/copyleft/gpl.html.
16 *  A copy is found in the textfile GPL.txt and important notices to the license 
17 *  from the author is found in LICENSE.txt distributed with these scripts.
18 *
19
20 *  This script is distributed in the hope that it will be useful,
21 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 *  GNU General Public License for more details.
24 *
25 *  This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /** 
28  * Include file extending t3lib_recordList
29  *
30  * $Id$
31  *
32  * @author      Kasper Skaarhoj <kasper@typo3.com>
33  */
34 /**
35  * [CLASS/FUNCTION INDEX of SCRIPT]
36  *
37  *
38  *
39  *   79: class recordList extends t3lib_recordList 
40  *  124:     function start($id,$table,$pointer,$search="",$levels="",$showLimit=0)     
41  *  165:     function setDispFields()   
42  *  183:     function generateList()    
43  *  227:     function thumbCode($row,$table,$field)     
44  *  240:     function makeQuery($table, $id, $addWhere="",$fieldList="*")       
45  *  269:     function setTotalItems()   
46  *  288:     function makeSearchString($table)  
47  *  319:     function linkWrapTable($table,$code)       
48  *  337:     function linkWrapItems($table,$uid,$code,$row)     
49  *  356:     function listURL($altId="",$table=-1,$exclList="") 
50  *  375:     function requestUri()      
51  *  385:     function getSearchBox($formFields=1)       
52  *  432:     function makeFieldList($table,$dontCheckUser=0)    
53  *  464:     function getTreeObject($id,$depth,$perms_clause)   
54  *  482:     function showSysNotesForPage()     
55  *
56  * TOTAL FUNCTIONS: 15
57  * (This index is automatically created/updated by the extension "extdeveval")
58  *
59  */
60
61
62  
63  
64  
65  
66  
67
68
69
70
71 /**
72  * Child class for rendering of Web > List (not the final class. see class.db_list_extra)
73  * 
74  * @author      Kasper Skaarhoj <kasper@typo3.com>
75  * @package TYPO3
76  * @subpackage core
77  * @see localRecordList
78  */
79 class recordList extends t3lib_recordList {
80         var $thumbs = 0;                                                // Boolean. Thumbnails on records containing files (pictures)
81         var $itemsLimitPerTable = 20;                   // default Max items shown per table in "multi-table mode", may be overridden by tables.php
82         var $itemsLimitSingleTable = 100;               // default Max items shown per table in "single-table mode", may be overridden by tables.php
83         var $widthGif = '<img src="clear.gif" width=1 height=4 hspace=160>';
84         var $script = "db_list.php";
85         var $spaceSearchBoxFromLeft = 5;
86         var $allFields=0;
87         
88                 // internal
89         var $JScode = "";       
90         var $HTMLcode = "";
91         var $table="";          // set to the tablename if single-table mode
92         var $tableList="";      // Specify a list of tables which are the only ones allowed to be displayed.
93         var $searchString="";
94         var $searchLevels="";
95         var $returnUrl="";
96         var $showLimit=0;
97         var $pidSelect="";
98         var $iLimit=0;          // "LIMIT " in SQL...
99         var $firstElementNumber=0;
100
101         var $eCounter=0;                // Counting the elements no matter what...
102         var $totalItems="";
103         var $recPath_cache=array();
104         var $csvLines=array();
105         var $perms_clause="";
106         var $csvOutput=0;
107         var $setFields=array();
108         var $calcPerms=0;
109         var $currentTable = array();
110
111         var $temp_countQ="";
112         var $duplicateStack=array();
113         
114
115         /**
116          * @param       [type]          $id: ...
117          * @param       [type]          $table: ...
118          * @param       [type]          $pointer: ...
119          * @param       [type]          $search: ...
120          * @param       [type]          $levels: ...
121          * @param       [type]          $showLimit: ...
122          * @return      [type]          ...
123          */
124         function start($id,$table,$pointer,$search="",$levels="",$showLimit=0)  {
125                         // Starts the list-generation.
126                         // $id is the parent-id from which we generate the list
127                         // $table is the tablename - if single-table mode
128                 global $TCA;
129                 if ($TCA[$table])       {               // single-table mode
130                         $this->table=$table;    
131                 }
132                 $this->id=intval($id);  // sets the parent id
133
134                 $this->counter=0;       
135                 $this->JScode="";
136                 $this->HTMLcode="";
137                 $this->firstElementNumber=$pointer;
138                 $this->searchString=trim($search);
139                 $this->searchLevels=trim($levels);
140                 $this->showLimit=t3lib_div::intInRange($showLimit,0,10000);
141                 $this->csvOutput = t3lib_div::GPvar("csv") ? 1 : 0;
142                 $this->sortField = t3lib_div::GPvar("sortField");
143                 $this->sortRev = t3lib_div::GPvar("sortRev");
144                 
145                 if (!$GLOBALS["TYPO3_CONF_VARS"]["GFX"]["thumbnails"])  {
146                         $this->thumbScript='gfx/notfound_thumb.gif';
147                 }
148                 
149                         // Set select levels:
150                 $sL=intval($this->searchLevels);
151                 $this->perms_clause = $GLOBALS["BE_USER"]->getPagePermsClause(1);
152                 if ($sL>0)      {
153                         $tree = $this->getTreeObject($id,$sL,$this->perms_clause);
154                         $this->pidSelect = "pid IN (".implode($tree->ids,",").")";
155                 } else {
156                         $this->pidSelect = "pid=".intval($id);
157                 }
158         }
159
160         /**
161          * [Describe function...]
162          * 
163          * @return      [type]          ...
164          */
165         function setDispFields()        {
166                         // Display fields:
167                 $dispFields = $GLOBALS["BE_USER"]->getModuleData("db_list.php/displayFields");
168                 $dispFields_in = t3lib_div::GPvar("displayFields");
169                 if (is_array($dispFields_in))   {
170                         reset($dispFields_in);
171                         $tKey = key($dispFields_in);
172                         $dispFields[$tKey]=$dispFields_in[$tKey];
173                         $GLOBALS["BE_USER"]->pushModuleData("db_list.php/displayFields",$dispFields);
174                 }
175                 $this->setFields=$dispFields;
176         }
177
178         /**
179          * [Describe function...]
180          * 
181          * @return      [type]          ...
182          */
183         function generateList() {
184                         // For each table we wish to show, this->getTable is called.
185                         // Finishes off with a stopper-gif
186                 global $TCA;
187                 reset($TCA);
188                 $tableCount = 0;
189                 while (list($key)=each($TCA))   {
190                         t3lib_div::loadTCA($key);
191                         $val=$TCA[$key];
192                         if ((!$this->table || $key==$this->table) && (!$this->tableList || t3lib_div::inList($this->tableList,$key)) && $GLOBALS["BE_USER"]->check("tables_select",$key))       {               // Checks that we see only permitted/requested tables:
193                                 if ($this->table)       {               // iLimit is set depending on whether we're in single- or multi-table mode
194                                         $this->iLimit=(isset($val["interface"]["maxSingleDBListItems"])?intval($val["interface"]["maxSingleDBListItems"]):$this->itemsLimitSingleTable);
195                                 } else {
196                                         $this->iLimit=(isset($val["interface"]["maxDBListItems"])?intval($val["interface"]["maxDBListItems"]):$this->itemsLimitPerTable);
197                                 }
198                                 if ($this->showLimit)   $this->iLimit = $this->showLimit;
199 //                              $this->iLimit=3;
200                                 $tableCount++;
201
202                                 if ($this->allFields)   {
203                                         $fields = $this->makeFieldList($key);
204                                         $fields[]="_PATH_";
205                                         $fields[]="_CONTROL_";
206                                         if (is_array($this->setFields[$key]))   {
207                                                 $fields = array_intersect($fields,$this->setFields[$key]);
208                                         } else {
209                                                 $fields = array();
210                                         }
211                                 } else {
212                                         $fields = array();
213                                 }
214                                 $this->HTMLcode.=$this->getTable($key, $this->id,implode(",",$fields));
215                         }
216                 }
217         }
218
219         /**
220          * [Describe function...]
221          * 
222          * @param       [type]          $row: ...
223          * @param       [type]          $table: ...
224          * @param       [type]          $field: ...
225          * @return      [type]          ...
226          */
227         function thumbCode($row,$table,$field)  {
228                 return t3lib_BEfunc::thumbCode($row,$table,$field,$this->backPath,$this->thumbScript);
229         }
230
231         /**
232          * [Describe function...]
233          * 
234          * @param       [type]          $table: ...
235          * @param       [type]          $id: ...
236          * @param       [type]          $addWhere: ...
237          * @param       [type]          $fieldList: ...
238          * @return      [type]          ...
239          */
240         function makeQuery($table, $id, $addWhere="",$fieldList="*")    {
241                         // returns the SQL-query to select the records from a table $table with pid = $id
242                         // Depends on the global var $perms_clause to exist!!
243                 global $TCA,$perms_clause;
244                 $orderBy = ($TCA[$table]["ctrl"]["sortby"]) ? "ORDER BY ".$TCA[$table]["ctrl"]["sortby"] : $TCA[$table]["ctrl"]["default_sortby"];
245                 if ($this->sortField)   {
246                         if (in_array($this->sortField,$this->makeFieldList($table,1)))  {
247                                 $orderBy = "ORDER BY ".$this->sortField;
248                                 if ($this->sortRev)     $orderBy.=" DESC";
249                         }
250                 }
251                 
252                 $limit = ($this->iLimit) ? "LIMIT ".($this->firstElementNumber ? ($this->firstElementNumber)."," : "" ).($this->iLimit+1) : "";
253                 $pC = ($table=="pages" && $perms_clause)?" AND ".$perms_clause:"";
254                 $search = $this->makeSearchString($table);
255
256                 $query = sprintf("SELECT ".$fieldList." FROM %s WHERE ".$this->pidSelect." %s %s %s %s %s %s",
257                                 $table, $pC, t3lib_BEfunc::deleteClause($table), $addWhere, $search, $orderBy, $limit);
258                 $this->temp_countQ = sprintf("SELECT count(*) FROM %s WHERE ".$this->pidSelect." %s %s %s %s",
259                                 $table, $pC, t3lib_BEfunc::deleteClause($table), $addWhere, $search);
260 //              debug($query,1);
261                 return $query;
262         }
263
264         /**
265          * [Describe function...]
266          * 
267          * @return      [type]          ...
268          */
269         function setTotalItems()        {
270                 $result = mysql(TYPO3_db,$this->temp_countQ);
271                 if (mysql_error())      {
272                         echo "<HR>
273                         <strong>MySQL error:</strong> ".mysql_error()."<BR>
274                         <strong>Query:</strong> ".$this->temp_countQ."<BR>
275                         <HR>
276                         ";
277                 }
278                 list($rCount) = mysql_fetch_row($result);
279                 $this->totalItems = $rCount;
280         }
281
282         /**
283          * [Describe function...]
284          * 
285          * @param       [type]          $table: ...
286          * @return      [type]          ...
287          */
288         function makeSearchString($table)       {
289                 global $TCA;
290                 if ($TCA[$table] && $this->searchString)        {
291                         t3lib_div::loadTCA($table);
292
293                         $sfields=array();
294                         $sfields[]="uid";
295
296                         $columns = $TCA[$table]["columns"];
297                         reset($columns);
298                         while(list($fieldName,$info)=each($columns))    {
299                                 $type = $info["config"]["type"];
300                                 if ($type=="text" || ($type=="input" && !ereg("date|time|int",$info["config"]["eval"])))        {
301                                         $sfields[]=$fieldName;
302                                 }
303                         }
304                         $like=" LIKE '%".addslashes($this->searchString)."%'";
305                         if (count($sfields))    {
306                                 $queryPart = " AND (".implode($like." OR ",$sfields).$like.")";
307                                 return $queryPart;
308                         }
309                 }
310         }
311
312         /**
313          * [Describe function...]
314          * 
315          * @param       [type]          $table: ...
316          * @param       [type]          $code: ...
317          * @return      [type]          ...
318          */
319         function linkWrapTable($table,$code)    {
320                         // Returns the title (based on $code) of a table ($table) with the proper link around
321                 if ($this->table!=$table)       {
322                         return '<A HREF="'.$this->listURL("",$table).'">'.$code.'</a>';
323                 } else {
324                         return '<A HREF="'.$this->listURL("","","sortField,sortRev,table").'">'.$code.'</a>';
325                 }
326         }
327
328         /**
329          * [Describe function...]
330          * 
331          * @param       [type]          $table: ...
332          * @param       [type]          $uid: ...
333          * @param       [type]          $code: ...
334          * @param       [type]          $row: ...
335          * @return      [type]          ...
336          */
337         function linkWrapItems($table,$uid,$code,$row)  {
338                         // 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...)
339                 if (!strcmp($code,"")) {$code="<i>[".$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.no_title")."]</i> - ".t3lib_BEfunc::getRecordTitle($table,$row);}
340                 $code=t3lib_div::fixed_lgd("&nbsp;".$code,$this->fixedL);
341                 if ($table=="pages")    {
342                         return '<A HREF="'.$this->listURL($uid).'">'.$code.'</a>';
343                 } else {
344                         return $code;
345                 }
346         }
347
348         /**
349          * [Describe function...]
350          * 
351          * @param       [type]          $altId: ...
352          * @param       [type]          $table: ...
353          * @param       [type]          $exclList: ...
354          * @return      [type]          ...
355          */
356         function listURL($altId="",$table=-1,$exclList="")      {
357                 return $this->script.
358                         '?id='.(strcmp($altId,"")?$altId:$this->id).
359                         '&table='.rawurlencode($table==-1?$this->table:$table).
360                         ($this->thumbs?'&imagemode='.$this->thumbs:'').
361                         ($this->returnUrl?"&returnUrl=".rawurlencode($this->returnUrl):"").
362                         ($this->searchString?"&search_field=".rawurlencode($this->searchString):"").
363                         ($this->searchLevels?"&search_levels=".rawurlencode($this->searchLevels):"").
364                         ($this->showLimit?"&showLimit=".rawurlencode($this->showLimit):"").
365                         ((!$exclList || !t3lib_div::inList($exclList,"sortField")) && $this->sortField?"&sortField=".rawurlencode($this->sortField):"").
366                         ((!$exclList || !t3lib_div::inList($exclList,"sortRev")) && $this->sortRev?"&sortRev=".rawurlencode($this->sortRev):"")
367                         ;
368         }
369
370         /**
371          * [Describe function...]
372          * 
373          * @return      [type]          ...
374          */
375         function requestUri()   {
376                 return $this->listURL();
377         }
378
379         /**
380          * [Describe function...]
381          * 
382          * @param       [type]          $formFields: ...
383          * @return      [type]          ...
384          */
385         function getSearchBox($formFields=1)    {
386                 if ($GLOBALS["CLIENT"]["BROWSER"]=="net")       {
387 //                      $content.= '<img src=clear.gif width=1 height=100><BR>';
388                 }
389                 $formElements=array("","");
390                 if ($formFields)        {
391                         $formElements=array('<form action="'.$this->listURL().'" method="POST">','</form>');
392                 }
393                         // Make level selector:
394                 $opt=array();
395                 $parts = explode("|",$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.enterSearchLevels"));
396                 while(list($kv,$label)=each($parts))    {
397                         $opt[] = '<option value="'.$kv.'"'.($kv==intval($this->searchLevels)?" selected":"").'>'.htmlspecialchars($label).'</option>';
398                 }
399                 $lMenu = '<select name="search_levels">'.implode("",$opt).'</select>';
400                 
401                         // Table with the search box:
402                 $content.= '
403                 <table border=0 cellpadding=1 cellspacing=0>
404                 '.$formElements[0].'
405                         <tr>
406                                 <td><img src=clear.gif width='.$this->spaceSearchBoxFromLeft.' height=1></td>
407                                 <td bgcolor="#9BA1A8">
408                                         <table border=0 cellpadding=0 cellspacing=0 bgcolor="'.$GLOBALS["TBE_TEMPLATE"]->bgColor4.'">
409                                         <tr>
410                                                 <td nowrap>&nbsp;'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.enterSearchString").'&nbsp;&nbsp;<input type="Text" name="search_field" value="'.htmlspecialchars($this->searchString).'"'.$GLOBALS["TBE_TEMPLATE"]->formWidth(10).'></td>
411                                                 <td>'.$lMenu.'</td>
412                                                 <td><input type="Submit" name="search" value="'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.search").'"></td>
413                                         </tr>
414                                         <tr>
415                                                 <td nowrap colspan=3>&nbsp;'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.showRecords").':&nbsp;&nbsp;<input type="text" name="showLimit" value="'.($this->showLimit?$this->showLimit:"").'"'.$GLOBALS["SOBE"]->doc->formWidth(4).'></td>
416                                         </tr>
417                                         </table>                        
418                                 </td>
419                         </tr>'.$formElements[1].'
420                 </table>
421                 ';
422                 return $content;
423         }
424
425         /**
426          * [Describe function...]
427          * 
428          * @param       [type]          $table: ...
429          * @param       [type]          $dontCheckUser: ...
430          * @return      [type]          ...
431          */
432         function makeFieldList($table,$dontCheckUser=0) {
433                 global $TCA,$BE_USER;
434                 $fieldListArr = array();
435                 if (is_array($TCA[$table]))     {
436                         t3lib_div::loadTCA($table);
437                         reset($TCA[$table]["columns"]);
438                         while(list($fN,$fieldValue)=each($TCA[$table]["columns"]))      {
439                                 if ($dontCheckUser || 
440                                         ((!$fieldValue["exclude"] || $BE_USER->check("non_exclude_fields",$table.":".$fN)) && $fieldValue["config"]["type"]!="passthrough"))    {
441                                         $fieldListArr[]=$fN;
442                                 }
443                         }
444                         if ($dontCheckUser || $BE_USER->isAdmin())      {
445                                 $fieldListArr[]="uid";
446                                 $fieldListArr[]="pid";
447                                 if ($TCA[$table]["ctrl"]["tstamp"])     $fieldListArr[]=$TCA[$table]["ctrl"]["tstamp"];
448                                 if ($TCA[$table]["ctrl"]["crdate"])     $fieldListArr[]=$TCA[$table]["ctrl"]["crdate"];
449                                 if ($TCA[$table]["ctrl"]["cruser_id"])  $fieldListArr[]=$TCA[$table]["ctrl"]["cruser_id"];
450                                 if ($TCA[$table]["ctrl"]["sortby"])     $fieldListArr[]=$TCA[$table]["ctrl"]["sortby"];
451                         }
452                 }
453                 return $fieldListArr;
454         }
455
456         /**
457          * [Describe function...]
458          * 
459          * @param       [type]          $id: ...
460          * @param       [type]          $depth: ...
461          * @param       [type]          $perms_clause: ...
462          * @return      [type]          ...
463          */
464         function getTreeObject($id,$depth,$perms_clause)        {
465                 $tree = t3lib_div::makeInstance("t3lib_pageTree");
466                 $tree->init("AND ".$perms_clause);
467                 $tree->makeHTML=0;
468                 $tree->fieldArray = Array("uid","php_tree_stop");
469                 if ($depth)     {
470                         $tree->getTree($id, $depth, "");
471                 }
472                 $tree->ids[]=$id;
473 //              debug($tree->ids);
474                 return $tree;
475         }
476
477         /**
478          * [Describe function...]
479          * 
480          * @return      [type]          ...
481          */
482         function showSysNotesForPage()  {
483                 global $TCA;
484
485                 if (!t3lib_extMgm::isLoaded("sys_note"))        return "";
486
487                 $delClause = t3lib_BEfunc::deleteClause("sys_note");
488                 $query = "SELECT * FROM sys_note where pid in (".$this->id.") AND (!personal OR cruser='".$GLOBALS["BE_USER"]->user["uid"]."')".$delClause;
489                 $result = mysql(TYPO3_db,$query);
490                 if (mysql_error()) {echo mysql_error(); debug($query);}
491                 $dbCount = mysql_num_rows($result);
492                 if ($dbCount)   {
493                         $cat = array();
494                         t3lib_div::loadTCA("sys_note");
495                         if ($TCA["sys_note"] && $TCA["sys_note"]["columns"]["category"] && is_array($TCA["sys_note"]["columns"]["category"]["config"]["items"]))        {
496                                 reset($TCA["sys_note"]["columns"]["category"]["config"]["items"]);
497                                 while(list(,$el)=each($TCA["sys_note"]["columns"]["category"]["config"]["items"]))      {
498                                         $cat[$el[1]]=$GLOBALS["LANG"]->sL($el[0]);
499                                 }
500                         }
501                         while($row=mysql_fetch_assoc($result))  {
502                                 $icon= t3lib_iconWorks::getIcon("sys_note",$row);
503                                 $fields=array();
504                                 $subject=$row["subject"];
505
506                                 $fields["Author:"]=$row["author"].($row["email"] && $row["author"] ? ", ":"").$row["email"];
507                                 $fields["Category:"]=$cat[$row["category"]];
508                                 $fields["Note:"]=nl2br($row[message]);
509                                 $bgcol=' bgcolor="'.$GLOBALS["SOBE"]->doc->bgColor2.'"';
510                                 $bgcol2=' bgcolor="'.$GLOBALS["SOBE"]->doc->bgColor4.'"';
511                                 
512                                 $out.='
513                                 <table border=0 cellpadding=1 cellspacing=1 width=1>
514                                         <tr><td colspan=2'.$bgcol.'><img src="'.$icon.'" width=18 height=16 align=top><strong>'.$subject.'</strong></td></tr>
515                                         <tr><td'.$bgcol2.'>'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.category").'</td><td'.$bgcol2.'>'.$fields["Category:"].'</td></tr>
516                                         <tr><td'.$bgcol2.'>'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.author").'</td><td'.$bgcol2.'>'.$fields["Author:"].'</td></tr>
517                                         <tr><td'.$bgcol2.'>'.$GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.note").'</td><td'.$bgcol2.'>'.$fields["Note:"].'</td></tr>
518                                         <tr><td colspan=2><img src=clear.gif width=380 height=1></td></tr>
519                                 </table>
520                                 ';
521 //                              debug($fields);
522                         }
523                 }
524                 return $out ? "".$out : "";
525         }
526 }
527
528
529 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc']) {
530         include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/class.db_list.inc']);
531 }
532 ?>