]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
No border for <img>
[SourceForge/phpwiki.git] / lib / PageList.php
1 <?php
2 //rcs_id('$Id$');
3 /* Copyright (C) 2004-2010 $ThePhpWikiProgrammingTeam
4  * Copyright (C) 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with PhpWiki; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  * List a number of pagenames, optionally as table with various columns.
25  * This library relieves some work for these plugins:
26  *
27  * AllPages, BackLinks, LikePages, MostPopular, TitleSearch, WikiAdmin* and more
28  *
29  * It also allows dynamic expansion of those plugins to include more
30  * columns in their output.
31  *
32  * Column 'info=' arguments:
33  *
34  * 'pagename' _("Page Name")
35  * 'mtime'    _("Last Modified")
36  * 'hits'     _("Hits")
37  * 'summary'  _("Last Summary")
38  * 'version'  _("Version")),
39  * 'author'   _("Last Author")),
40  * 'locked'   _("Locked"), _("locked")
41  * 'minor'    _("Minor Edit"), _("minor")
42  * 'markup'   _("Markup")
43  * 'size'     _("Size")
44  * 'creator'  _("Creator")
45  * 'owner'    _("Owner")
46  * 'checkbox'  selectable checkbox at the left.
47  * 'content'  
48  *
49  * Special, custom columns: Either theme or plugin (WikiAdmin*) specific.
50  * 'remove'   _("Remove")     
51  * 'perm'     _("Permission Mask")
52  * 'acl'      _("ACL")
53  * 'renamed_pagename'   _("Rename to")
54  * 'ratingwidget', ... wikilens theme specific.
55  * 'custom'   See plugin/_WikiTranslation
56  *
57  * Symbolic 'info=' arguments:
58  * 'all'       All columns except the special columns
59  * 'most'      pagename, mtime, author, size, hits, ...
60  * 'some'      pagename, mtime, author
61  *
62  * FIXME: In this refactoring I (Jeff) have un-implemented _ctime, _cauthor, and
63  * number-of-revision.  Note the _ctime and _cauthor as they were implemented
64  * were somewhat flawed: revision 1 of a page doesn't have to exist in the
65  * database.  If lots of revisions have been made to a page, it's more than likely
66  * that some older revisions (include revision 1) have been cleaned (deleted).
67  *
68  * DONE: 
69  *   paging support: limit, offset args
70  *   check PagePerm "list" access-type,
71  *   all columns are sortable. Thanks to the wikilens team.
72  *   cols > 1, comma, azhead, ordered (OL lists)
73  *   ->supportedArgs() which arguments are supported, so that the plugin 
74  *                     doesn't explictly need to declare it
75  *   added slice option when the page_iter (e.g. ->_pages) is already sliced.
76  *
77  * TODO:
78  *   fix sortby logic, fix multiple sortby and other paging args per page.
79  *   info=relation,linkto nopage=1
80  *   use custom format method (RecentChanges, rss, ...)
81  *
82  * FIXED: 
83  *   fix memory exhaustion on large pagelists with old --memory-limit php's only. 
84  *   Status: improved 2004-06-25 16:19:36 rurban 
85  */
86 class _PageList_Column_base {
87     var $_tdattr = array();
88
89     function _PageList_Column_base ($default_heading, $align = false) {
90         $this->_heading = $default_heading;
91
92         if ($align) {
93             // align="char" isn't supported by any browsers yet :(
94             //if (is_array($align))
95             //    $this->_tdattr = $align;
96             //else
97             $this->_tdattr['align'] = $align;
98         }
99     }
100
101     function format ($pagelist, $page_handle, &$revision_handle) {
102         $nbsp = HTML::raw('&nbsp;');
103         return HTML::td($this->_tdattr,
104                         $nbsp,
105                         $this->_getValue($page_handle, $revision_handle),
106                         $nbsp);
107     }
108
109     function getHeading () {
110         return $this->_heading;
111     }
112
113     function setHeading ($heading) {
114         $this->_heading = $heading;
115     }
116
117     // old-style heading
118     function heading () {
119         global $request;
120         $nbsp = HTML::raw('&nbsp;');
121         // allow sorting?
122         if (1 /* or in_array($this->_field, PageList::sortable_columns())*/) {
123             // multiple comma-delimited sortby args: "+hits,+pagename"
124             // asc or desc: +pagename, -pagename
125             $sortby = PageList::sortby($this->_field, 'flip_order');
126             //Fixme: pass all also other GET args along. (limit, p[])
127             //TODO: support GET and POST
128             $s = HTML::a(array('href' => 
129                                $request->GetURLtoSelf(array('sortby' => $sortby)),
130                                'class' => 'pagetitle',
131                                'title' => sprintf(_("Sort by %s"), $this->_field)), 
132                          $nbsp, HTML::u($this->_heading), $nbsp);
133         } else {
134             $s = HTML($nbsp, HTML::u($this->_heading), $nbsp);
135         }
136         return HTML::th(array('align' => 'center'),$s);
137     }
138
139     // new grid-style sortable heading
140     // TODO: via activeui.js ? (fast dhtml sorting)
141     function button_heading (&$pagelist, $colNum) {
142         global $WikiTheme, $request;
143         // allow sorting?
144         $nbsp = HTML::raw('&nbsp;');
145         if (!$WikiTheme->DUMP_MODE /* or in_array($this->_field, PageList::sortable_columns()) */) {
146             // TODO: add to multiple comma-delimited sortby args: "+hits,+pagename"
147             $src = false; 
148             $noimg_src = $WikiTheme->getButtonURL('no_order');
149             if ($noimg_src)
150                 $noimg = HTML::img(array('src'    => $noimg_src,
151                                          'alt'    => '.'));
152             else 
153                 $noimg = $nbsp;
154             if ($pagelist->sortby($colNum, 'check')) { // show icon? request or plugin arg
155                 $sortby = $pagelist->sortby($colNum, 'flip_order');
156                 $desc = (substr($sortby,0,1) == '-'); // +pagename or -pagename
157                 $src = $WikiTheme->getButtonURL($desc ? 'asc_order' : 'desc_order');
158                 $reverse = $desc ? _("reverse")." " : "";
159             } else {
160                 // initially unsorted
161                 $sortby = $pagelist->sortby($colNum, 'get');
162             }
163             if (!$src) {
164                 $img = $noimg;
165                 $reverse = "";
166                 $img->setAttr('alt', ".");
167             } else {
168                 $img = HTML::img(array('src' => $src, 
169                                        'alt' => _("Click to reverse sort order")));
170             }
171             $s = HTML::a(array('href' => 
172                                  //Fixme: pass all also other GET args along. (limit is ok, p[])
173                                  $request->GetURLtoSelf(array('sortby' => $sortby, 
174                                                               'id' => $pagelist->id)),
175                                'class' => 'gridbutton', 
176                                'title' => sprintf(_("Click to sort by %s"), $reverse . $this->_field)),
177                          $nbsp, $this->_heading,
178                          $nbsp, $img,
179                          $nbsp);
180         } else {
181             $s = HTML($nbsp, $this->_heading, $nbsp);
182         }
183         return HTML::th(array('align' => 'center', 'valign' => 'middle', 
184                               'class' => 'gridbutton'), $s);
185     }
186
187     /**
188      * Take two columns of this type and compare them.
189      * An undefined value is defined to be < than the smallest defined value.
190      * This base class _compare only works if the value is simple (e.g., a number).
191      *
192      * @param  $colvala  $this->_getValue() of column a
193      * @param  $colvalb  $this->_getValue() of column b
194      *
195      * @return -1 if $a < $b, 1 if $a > $b, 0 otherwise.
196      */
197     function _compare($colvala, $colvalb) {
198         if (is_string($colvala))
199             return strcmp($colvala,$colvalb);
200         $ret = 0;
201         if (($colvala === $colvalb) || (!isset($colvala) && !isset($colvalb))) {
202             ;
203         } else {
204             $ret = (!isset($colvala) || ($colvala < $colvalb)) ? -1 : 1;
205         }
206         return $ret; 
207     }
208 };
209
210 class _PageList_Column extends _PageList_Column_base {
211     function _PageList_Column ($field, $default_heading, $align = false) {
212         $this->_PageList_Column_base($default_heading, $align);
213
214         $this->_need_rev = substr($field, 0, 4) == 'rev:';
215         $this->_iscustom = substr($field, 0, 7) == 'custom:';
216         if ($this->_iscustom) {
217             $this->_field = substr($field, 7);
218         }
219         elseif ($this->_need_rev)
220             $this->_field = substr($field, 4);
221         else
222             $this->_field = $field;
223     }
224
225     function _getValue ($page_handle, &$revision_handle) {
226         if ($this->_need_rev) {
227             if (!$revision_handle)
228                 // columns which need the %content should override this. (size, hi_content)
229                 $revision_handle = $page_handle->getCurrentRevision(false);
230             return $revision_handle->get($this->_field);
231         }
232         else {
233             return $page_handle->get($this->_field);
234         }
235     }
236     
237     function _getSortableValue ($page_handle, &$revision_handle) {
238         $val = $this->_getValue($page_handle, $revision_handle);
239         if ($this->_field == 'hits')
240             return (int) $val;
241         elseif (is_object($val) && method_exists($val, 'asString'))
242             return $val->asString();
243         else
244             return (string) $val;
245     }
246 };
247
248 /* overcome a call_user_func limitation by not being able to do:
249  * call_user_func_array(array(&$class, $class_name), $params);
250  * So we need $class = new $classname($params);
251  * And we add a 4th param to get at the parent $pagelist object
252  */
253 class _PageList_Column_custom extends _PageList_Column {
254     function _PageList_Column_custom($params) {
255         $this->_pagelist =& $params[3];
256         $this->_PageList_Column($params[0], $params[1], $params[2]);
257     }
258 }
259
260 class _PageList_Column_size extends _PageList_Column {
261     function format (&$pagelist, $page_handle, &$revision_handle) {
262         return HTML::td($this->_tdattr,
263                         HTML::raw('&nbsp;'),
264                         $this->_getValue($pagelist, $page_handle, $revision_handle),
265                         HTML::raw('&nbsp;'));
266     }
267     
268     function _getValue (&$pagelist, $page_handle, &$revision_handle) {
269         if (!$revision_handle or (!$revision_handle->_data['%content'] 
270                                   or $revision_handle->_data['%content'] === true)) {
271             $revision_handle = $page_handle->getCurrentRevision(true);
272             unset($revision_handle->_data['%pagedata']['_cached_html']);
273         }
274         $size = $this->_getSize($revision_handle);
275         // we can safely purge the content when it is not sortable
276         if (empty($pagelist->_sortby[$this->_field]))
277             unset($revision_handle->_data['%content']);
278         return $size;
279     }
280     
281     function _getSortableValue ($page_handle, &$revision_handle) {
282         if (!$revision_handle)
283             $revision_handle = $page_handle->getCurrentRevision(true);
284         return (empty($revision_handle->_data['%content'])) 
285                ? 0 : strlen($revision_handle->_data['%content']);
286     }
287
288     function _getSize($revision_handle) {
289         $bytes = @strlen($revision_handle->_data['%content']);
290         return ByteFormatter($bytes);
291     }
292 }
293
294
295 class _PageList_Column_bool extends _PageList_Column {
296     function _PageList_Column_bool ($field, $default_heading, $text = 'yes') {
297         $this->_PageList_Column($field, $default_heading, 'center');
298         $this->_textIfTrue = $text;
299         $this->_textIfFalse = new RawXml('&#8212;'); //mdash
300     }
301
302     function _getValue ($page_handle, &$revision_handle) {
303         //FIXME: check if $this is available in the parent (->need_rev)
304         $val = _PageList_Column::_getValue($page_handle, $revision_handle);
305         return $val ? $this->_textIfTrue : $this->_textIfFalse;
306     }
307 };
308
309 class _PageList_Column_checkbox extends _PageList_Column {
310     function _PageList_Column_checkbox ($field, $default_heading, $name='p') {
311         $this->_name = $name;
312         $heading = HTML::input(array('type'  => 'button',
313                                      'title' => _("Click to de-/select all pages"),
314                                      'name'  => $default_heading,
315                                      'value' => $default_heading,
316                                      'onclick' => "flipAll(this.form)"
317                                      ));
318         $this->_PageList_Column($field, $heading, 'center');
319     }
320     function _getValue ($pagelist, $page_handle, &$revision_handle) {
321         $pagename = $page_handle->getName();
322         $selected = !empty($pagelist->_selected[$pagename]);
323         if (strstr($pagename,'[') or strstr($pagename,']')) {
324             $pagename = str_replace(array('[',']'),array('%5B','%5D'),$pagename);
325         }
326         if ($selected) {
327             return HTML::input(array('type' => 'checkbox',
328                                      'name' => $this->_name . "[$pagename]",
329                                      'value' => 1,
330                                      'checked' => 'checked'));
331         } else {
332             return HTML::input(array('type' => 'checkbox',
333                                      'name' => $this->_name . "[$pagename]",
334                                      'value' => 1));
335         }
336     }
337     function format ($pagelist, $page_handle, &$revision_handle) {
338         return HTML::td($this->_tdattr,
339                         HTML::raw('&nbsp;'),
340                         $this->_getValue($pagelist, $page_handle, $revision_handle),
341                         HTML::raw('&nbsp;'));
342     }
343     // don't sort this javascript button
344     function button_heading ($pagelist, $colNum) {
345         $s = HTML(HTML::raw('&nbsp;'), $this->_heading, HTML::raw('&nbsp;'));
346         return HTML::th(array('align' => 'center', 'valign' => 'middle', 
347                               'class' => 'gridbutton'), $s);
348     }
349 };
350
351 class _PageList_Column_time extends _PageList_Column {
352     function _PageList_Column_time ($field, $default_heading) {
353         $this->_PageList_Column($field, $default_heading, 'right');
354         global $WikiTheme;
355         $this->WikiTheme = &$WikiTheme;
356     }
357
358     function _getValue ($page_handle, &$revision_handle) {
359         $time = _PageList_Column::_getValue($page_handle, $revision_handle);
360         return $this->WikiTheme->formatDateTime($time);
361     }
362
363     function _getSortableValue ($page_handle, &$revision_handle) {
364         return _PageList_Column::_getValue($page_handle, $revision_handle);
365     }
366 };
367
368 class _PageList_Column_version extends _PageList_Column {
369     function _getValue ($page_handle, &$revision_handle) {
370         if (!$revision_handle)
371             $revision_handle = $page_handle->getCurrentRevision();
372         return $revision_handle->getVersion();
373     }
374 };
375
376 // Output is hardcoded to limit of first 50 bytes. Otherwise
377 // on very large Wikis this will fail if used with AllPages
378 // (PHP memory limit exceeded)
379 class _PageList_Column_content extends _PageList_Column {
380     function _PageList_Column_content ($field, $default_heading, $align=false, 
381                                        $search=false, $hilight_re=false) 
382     {
383         $this->_PageList_Column($field, $default_heading, $align);
384         $this->bytes = 50;
385         $this->search = $search;
386         $this->hilight_re = $hilight_re;
387         if ($field == 'content') {
388             $this->_heading .= sprintf(_(" ... first %d bytes"),
389                                        $this->bytes);
390         } elseif ($field == 'rev:hi_content') {
391             global $HTTP_POST_VARS;
392             if (!$this->search and !empty($HTTP_POST_VARS['admin_replace'])) {
393                 $this->search = $HTTP_POST_VARS['admin_replace']['from'];
394             }
395             $this->_heading .= sprintf(_(" ... around %s"),
396                                       '»'.$this->search.'«');
397         }
398     }
399     
400     function _getValue ($page_handle, &$revision_handle) {
401         if (!$revision_handle or (!$revision_handle->_data['%content'] 
402                                   or $revision_handle->_data['%content'] === true)) {
403             $revision_handle = $page_handle->getCurrentRevision(true);
404         }
405         //if (!empty($pagelist->_sortby) and empty($pagelist->_sortby[$this->_field]))
406         //    unset($revision_handle->_data['%content']);
407         if ($this->_field == 'hi_content') {
408             if (!empty($revision_handle->_data['%pagedata'])) {
409                 $revision_handle->_data['%pagedata']['_cached_html'] = '';
410                 // PHP Fatal error:  Cannot unset string offsets
411                 //unset($revision_handle->_data['%pagedata']['_cached_html']);
412             }
413             $search = $this->search;
414             $score = '';
415             if (is_object($page_handle) and !empty($page_handle->score))
416                 $score = $page_handle->score;
417             elseif (is_array($page_handle) and !empty($page_handle['score']))
418                 $score = $page_handle['score'];
419                 
420             $hilight_re = $this->hilight_re;
421             // use the TextSearchQuery highlighter
422             if ($search and $hilight_re) {
423                 $matches = preg_grep("/$hilight_re/i", $revision_handle->getContent());
424                 $html = array();
425                 foreach (array_slice($matches,0,5) as $line) {
426                     $line = WikiPlugin_FullTextSearch::highlight_line($line, $hilight_re);
427                     $html[] = HTML::p(HTML::small(array('class' => 'search-context'), $line));
428                 }
429                 if ($score)
430                     $html[] = HTML::small(sprintf("... [%0.1f]", $score));
431                 return $html;
432             }
433             // Remove special characters so that highlighting works
434             $search = preg_replace('/^[\^\*]/', '', $search);
435             $search = preg_replace('/[\^\*]$/', '', $search);
436             $c =& $revision_handle->getPackedContent();
437             if ($search and ($i = strpos(strtolower($c), strtolower($search))) !== false) {
438                 $l = strlen($search);
439                 $j = max(0, $i - ($this->bytes / 2));
440                 return HTML::div(array('style' => 'font-size:x-small'),
441                                  HTML::div(array('class' => 'transclusion'),
442                                            HTML::span(($j ? '...' : '')
443                                                       .substr($c, $j, ($j ? $this->bytes / 2 : $i))),
444                                            HTML::span(array("style"=>"background:yellow"),
445                                                       substr($c, $i, $l)),
446                                            HTML::span(substr($c, $i+$l, ($this->bytes / 2))
447                                                       ."..."." "
448                                                       .($score ? sprintf("[%0.1f]",$score):""))));
449             } else {
450                 if (strpos($c," ") !== false)
451                     $c = "";
452                 else    
453                     $c = sprintf(_("%s not found"), '»'.$search.'«');
454                 return HTML::div(array('style' => 'font-size:x-small','align'=>'center'),
455                                  $c." ".($score ? sprintf("[%0.1f]",$score):""));
456             }
457         } elseif (($len = strlen($c)) > $this->bytes) {
458             $c = substr($c, 0, $this->bytes);
459         }
460         include_once('lib/BlockParser.php');
461         // false --> don't bother processing hrefs for embedded WikiLinks
462         $ct = TransformText($c, $revision_handle->get('markup'), false);
463         if (empty($pagelist->_sortby[$this->_field]))
464             unset($revision_handle->_data['%pagedata']['_cached_html']);
465         return HTML::div(array('style' => 'font-size:x-small'),
466                          HTML::div(array('class' => 'transclusion'), $ct),
467                          // Don't show bytes here if size column present too
468                          ($this->parent->_columns_seen['size'] or !$len) ? "" :
469                            ByteFormatter($len, /*$longformat = */true));
470     }
471     function _getSortableValue ($page_handle, &$revision_handle) {
472         if (is_object($page_handle) and !empty($page_handle->score))
473             return $page_handle->score;
474         elseif (is_array($page_handle) and !empty($page_handle['score']))
475             return $page_handle['score'];
476         else
477             return substr(_PageList_Column::_getValue($page_handle, $revision_handle),0,50);
478     }
479 };
480
481 class _PageList_Column_author extends _PageList_Column {
482     function _PageList_Column_author ($field, $default_heading, $align = false) {
483         _PageList_Column::_PageList_Column($field, $default_heading, $align);
484         $this->dbi =& $GLOBALS['request']->getDbh();
485     }
486
487     function _getValue ($page_handle, &$revision_handle) {
488         $author = _PageList_Column::_getValue($page_handle, $revision_handle);
489         if ($this->dbi->isWikiPage($author))
490             return WikiLink($author);
491         else
492             return $author;
493     }
494     
495     function _getSortableValue ($page_handle, &$revision_handle) {
496         return _PageList_Column::_getValue($page_handle, $revision_handle);
497     }
498 };
499
500 class _PageList_Column_owner extends _PageList_Column_author {
501     function _getValue ($page_handle, &$revision_handle) {
502         $author = $page_handle->getOwner();
503         if ($this->dbi->isWikiPage($author))
504             return WikiLink($author);
505         else
506             return $author;
507     }
508     function _getSortableValue ($page_handle, &$revision_handle) {
509         return _PageList_Column::_getValue($page_handle, $revision_handle);
510     }
511 };
512
513 class _PageList_Column_creator extends _PageList_Column_author {
514     function _getValue ($page_handle, &$revision_handle) {
515         $author = $page_handle->getCreator();
516         if ($this->dbi->isWikiPage($author))
517             return WikiLink($author);
518         else
519             return $author;
520     }
521     function _getSortableValue ($page_handle, &$revision_handle) {
522         return _PageList_Column::_getValue($page_handle, $revision_handle);
523     }
524 };
525
526 class _PageList_Column_pagename extends _PageList_Column_base {
527     var $_field = 'pagename';
528
529     function _PageList_Column_pagename () {
530         $this->_PageList_Column_base(_("Page Name"));
531         global $request;
532         $this->dbi = &$request->getDbh();
533     }
534
535     function _getValue ($page_handle, &$revision_handle) {
536         if ($this->dbi->isWikiPage($page_handle->getName()))
537             return WikiLink($page_handle, 'known');
538         else
539             return WikiLink($page_handle, 'unknown');
540     }
541
542     function _getSortableValue ($page_handle, &$revision_handle) {
543         return $page_handle->getName();
544     }
545
546     /**
547      * Compare two pagenames for sorting.  See _PageList_Column::_compare.
548      **/
549     function _compare($colvala, $colvalb) {
550         return strcmp($colvala, $colvalb);
551     }
552 };
553
554 class PageList {
555     var $_group_rows = 3;
556     var $_columns = array();
557     var $_columnsMap = array();      // Maps column name to column number.
558     var $_excluded_pages = array();
559     var $_pages = array();
560     var $_caption = "";
561     var $_pagename_seen = false;
562     var $_types = array();
563     var $_options = array();
564     var $_selected = array();
565     var $_sortby = array();
566     var $_maxlen = 0;
567
568     function PageList ($columns = false, $exclude = false, $options = false) {
569         // unique id per pagelist on each page.
570         if (!isset($GLOBALS['request']->_pagelist))
571             $GLOBALS['request']->_pagelist = 0;
572         else 
573             $GLOBALS['request']->_pagelist++;    
574         $this->id = $GLOBALS['request']->_pagelist;
575         if ($GLOBALS['request']->getArg('count'))
576             $options['count'] = $GLOBALS['request']->getArg('count');
577         if ($options)
578             $this->_options = $options;
579
580         $this->_initAvailableColumns();
581         // let plugins predefine only certain objects, such its own custom pagelist columns
582         $symbolic_columns = 
583             array(
584                   'all' =>  array_diff(array_keys($this->_types), // all but...
585                                        array('checkbox','remove','renamed_pagename',
586                                              'content','hi_content','perm','acl')),
587                   'most' => array('pagename','mtime','author','hits'),
588                   'some' => array('pagename','mtime','author')
589                   );
590         if (isset($this->_options['listtype']) 
591             and $this->_options['listtype'] == 'dl')
592             $this->_options['nopage'] = 1;
593         if ($columns) {
594             if (!is_array($columns))
595                 $columns = explode(',', $columns);
596             // expand symbolic columns:
597             foreach ($symbolic_columns as $symbol => $cols) {
598                 if (in_array($symbol,$columns)) { // e.g. 'checkbox,all'
599                     $columns = array_diff(array_merge($columns,$cols),array($symbol));
600                 }
601             }
602             unset($cols);
603             if (empty($this->_options['nopage']) and !in_array('pagename',$columns))
604                 $this->_addColumn('pagename');
605             foreach ($columns as $col) {
606                 if (!empty($col))
607                     $this->_addColumn($col);
608             }
609             unset($col);
610         }
611         // If 'pagename' is already present, _addColumn() will not add it again
612         if (empty($this->_options['nopage']))
613             $this->_addColumn('pagename');
614
615         if (!empty($this->_options['types'])) {
616             foreach ($this->_options['types'] as $type) {
617                 $this->_types[$type->_field] = $type;
618                 $this->_addColumn($type->_field);
619             }
620             unset($this->_options['types']);
621         }
622
623         global $request;
624         // explicit header options: ?id=x&sortby=... override options[]
625         // support multiple sorts. check multiple, no nested elseif
626         if (($this->id == $request->getArg("id")) 
627              and $request->getArg('sortby')) 
628         {
629             // add it to the front of the sortby array
630             $this->sortby($request->getArg('sortby'), 'init');
631             $this->_options['sortby'] = $request->getArg('sortby');
632         } // plugin options
633         if (!empty($options['sortby'])) {
634             if (empty($this->_options['sortby']))
635                 $this->_options['sortby'] = $options['sortby'];
636             $this->sortby($options['sortby'], 'init');
637         } // global options 
638         if (!isset($request->args["id"]) and $request->getArg('sortby') 
639              and empty($this->_options['sortby'])) 
640         {
641             $this->_options['sortby'] = $request->getArg('sortby');
642             $this->sortby($this->_options['sortby'], 'init');
643         }
644         // same as above but without the special sortby push, and mutually exclusive (elseif)
645         foreach ($this->pagingArgs() as $key) {
646             if ($key == 'sortby') continue;     
647             if (($this->id == $request->getArg("id")) 
648                 and $request->getArg($key)) 
649             {
650                 $this->_options[$key] = $request->getArg($key);
651             } // plugin options
652             elseif (!empty($options) and !empty($options[$key])) {
653                 $this->_options[$key] = $options[$key];
654             } // global options 
655             elseif (!isset($request->args["id"]) and $request->getArg($key)) {
656                 $this->_options[$key] = $request->getArg($key);
657             }
658             else 
659                 $this->_options[$key] = false;
660         }
661         if ($exclude) {
662             if (is_string($exclude) and !is_array($exclude))
663                 $exclude = $this->explodePageList($exclude, false,
664                                                   $this->_options['sortby'],
665                                                   $this->_options['limit']);
666             $this->_excluded_pages = $exclude;
667         }
668         $this->_messageIfEmpty = _("<no matches>");
669     }
670
671     // Currently PageList takes these arguments:
672     // 1: info, 2: exclude, 3: hash of options
673     // Here we declare which options are supported, so that 
674     // the calling plugin may simply merge this with its own default arguments 
675     function supportedArgs () {
676         // Todo: add all supported Columns, like locked, minor, ...
677         return array(// Currently supported options:
678                      /* what columns, what pages */
679                      'info'     => 'pagename',
680                      'exclude'  => '',          // also wildcards, comma-seperated lists 
681                                                 // and <!plugin-list !> arrays
682                      /* select pages by meta-data: */
683                      'author'   => false, // current user by []
684                      'owner'    => false, // current user by []
685                      'creator'  => false, // current user by []
686
687                      /* for the sort buttons in <th> */
688                      'sortby'   => '', // same as for WikiDB::getAllPages 
689                                        // (unsorted is faster)
690
691                      /* PageList pager options:
692                       * These options may also be given to _generate(List|Table) later
693                       * But limit and offset might help the query WikiDB::getAllPages()
694                       */
695                      'limit'    => 50,       // number of rows (pagesize)
696                      'paging'   => 'auto',  // 'auto'   top + bottom rows if applicable
697                      //                     // 'top'    top only if applicable
698                      //                     // 'bottom' bottom only if applicable
699                      //                     // 'none'   don't page at all 
700                      // (TODO: clarify what if $paging==false ?)
701
702                      /* list-style options (with single pagename column only so far) */
703                      'cols'     => 1,       // side-by-side display of list (1-3)
704                      'azhead'   => 0,       // 1: group by initials
705                                             // 2: provide shortcut links to initials also
706                      'comma'    => 0,       // condensed comma-seperated list, 
707                                             // 1 if without links, 2 if with
708                      'commasep' => false,   // Default: ', '
709                      'listtype' => '',      // ul (default), ol, dl, comma
710                      'ordered'  => false,   // OL or just UL lists (ignored for comma)
711                      'linkmore' => '',      // If count>0 and limit>0 display a link with 
712                      // the number of all results, linked to the given pagename.
713                      
714                      'nopage'   => false,   // for info=col omit the pagename column
715                      // array_keys($this->_types). filter by columns: e.g. locked=1
716                      'pagename' => null, // string regex
717                      'locked'   => null,
718                      'minor'    => null,
719                      'mtime'    => null,
720                      'hits'     => null,
721                      'size'     => null,
722                      'version'  => null,
723                      'markup'   => null,
724                      'external' => null,
725                      );
726     }
727     
728     function pagingArgs() {
729         return array('sortby','limit','paging','count','dosort');
730     }
731
732     /**
733      * @param   caption string or HTML
734      */
735     function setCaption ($caption) {
736         $this->_caption = $caption;
737     }
738
739     /**
740      * @param   caption string or HTML
741      */
742     function addCaption ($caption) {
743         $this->_caption = HTML($this->_caption," ",$caption);
744     }
745
746     function getCaption () {
747         // put the total into the caption if needed
748         if (is_string($this->_caption) && strstr($this->_caption, '%d'))
749             return sprintf($this->_caption, $this->getTotal());
750         return $this->_caption;
751     }
752
753     function setMessageIfEmpty ($msg) {
754         $this->_messageIfEmpty = $msg;
755     }
756
757
758     function getTotal () {
759         return !empty($this->_options['count'])
760                ? (integer) $this->_options['count'] : count($this->_pages);
761     }
762
763     function isEmpty () {
764         return empty($this->_pages);
765     }
766
767     function addPage($page_handle) {
768         if (!empty($this->_excluded_pages)) {
769             if (!in_array((is_string($page_handle) ? $page_handle : $page_handle->getName()),
770                           $this->_excluded_pages))
771                 $this->_pages[] = $page_handle;
772         } else {
773             $this->_pages[] = $page_handle;
774         }
775     }
776
777     function pageNames() {
778         $pages = array();
779         $limit = @$this->_options['limit'];
780         foreach ($this->_pages as $page_handle) {
781             $pages[] = $page_handle->getName();
782             if ($limit and count($pages) > $limit)
783                 break;
784         }
785         return $pages;
786     }
787
788     function _getPageFromHandle($page_handle) {
789         if (is_string($page_handle)) {
790             if (empty($page_handle)) return $page_handle;
791             //$dbi = $GLOBALS['request']->getDbh(); // no, safe some memory!
792             $page_handle = $GLOBALS['request']->_dbi->getPage($page_handle);
793         }
794         return $page_handle;
795     }
796
797     /**
798      * Take a PageList_Page object, and return an HTML object to display
799      * it in a table or list row.
800      */
801     function _renderPageRow (&$page_handle, $i = 0) {
802         $page_handle = $this->_getPageFromHandle($page_handle);
803         //FIXME. only on sf.net
804         if (!is_object($page_handle)) {
805             trigger_error("PageList: Invalid page_handle $page_handle", E_USER_WARNING);
806             return;
807         }
808         if (!isset($page_handle)
809             or empty($page_handle)
810             or (!empty($this->_excluded_pages)
811                 and in_array($page_handle->getName(), $this->_excluded_pages)))
812             return; // exclude page.
813             
814         // enforce view permission
815         if (!mayAccessPage('view', $page_handle->getName()))
816             return;
817
818         $group = (int)($i / $this->_group_rows);
819         $class = ($group % 2) ? 'oddrow' : 'evenrow';
820         $revision_handle = false;
821         $this->_maxlen = max($this->_maxlen, strlen($page_handle->getName()));
822
823         if (count($this->_columns) > 1) {
824             $row = HTML::tr(array('class' => $class));
825             $j = 0;
826             foreach ($this->_columns as $col) {
827                 $col->current_row = $i;
828                 $col->current_column = $j;
829                 $row->pushContent($col->format($this, $page_handle, $revision_handle));
830                 $j++;
831             }
832         } else {
833             $col = $this->_columns[0];
834             $col->current_row = $i;
835             $col->current_column = 0;
836             $row = $col->_getValue($page_handle, $revision_handle);
837         }
838
839         return $row;
840     }
841
842     /* ignore from, but honor limit */
843     function addPages ($page_iter) {
844         // TODO: if limit check max(strlen(pagename))
845         $limit = $page_iter->limit();
846         $i = 0;
847         if ($limit) {
848             list($from, $limit) = $this->limit($limit);
849             $this->_options['slice'] = 0;
850             $limit += $from;
851             while ($page = $page_iter->next()) {
852                 $i++;
853                 if ($from and $i < $from) 
854                     continue;
855                 if (!$limit or ($limit and $i < $limit))
856                     $this->addPage($page);
857             }
858         } else {
859             $this->_options['slice'] = 0;
860             while ($page = $page_iter->next()) {
861                 $this->addPage($page);
862             }
863         }
864         if ($i and empty($this->_options['count']))
865             $this->_options['count'] = $i;
866     }
867
868     function addPageList (&$list) {
869         if (empty($list)) return;  // Protect reset from a null arg
870         if (isset($this->_options['limit'])) { // extract from,count from limit
871             list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
872             $limit += $from;
873         } else {
874             $limit = 0;
875         }
876         $this->_options['slice'] = 0;
877         $i = 0;
878         foreach ($list as $page) {
879             $i++;       
880             if ($from and $i < $from) 
881                 continue;
882             if (!$limit or ($limit and $i < $limit)) {
883                 if (is_object($page)) $page = $page->_pagename;
884                 $this->addPage((string)$page);
885             }
886         }
887     }
888
889     function maxLen() {
890         global $request;
891         $dbi =& $request->getDbh();
892         if (isa($dbi,'WikiDB_SQL')) {
893             extract($dbi->_backend->_table_names);
894             $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl");
895             if (DB::isError($res) || empty($res)) return false;
896             else return $res;
897         } elseif (isa($dbi,'WikiDB_ADODB')) {
898             extract($dbi->_backend->_table_names);
899             $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl");
900             return $row ? $row[0] : false;
901         } else 
902             return false;
903     }
904
905     function first() {
906         if (count($this->_pages) > 0) {
907             return $this->_pages[0];
908         }
909         return false;
910     }
911
912     function getContent() {
913         // Note that the <caption> element wants inline content.
914         $caption = $this->getCaption();
915
916         if ($this->isEmpty())
917             return $this->_emptyList($caption);
918         elseif (isset($this->_options['listtype']) 
919                 and in_array($this->_options['listtype'], 
920                              array('ol','ul','comma','dl')))
921             return $this->_generateList($caption);
922         elseif (count($this->_columns) == 1)
923             return $this->_generateList($caption);
924         else
925             return $this->_generateTable($caption);
926     }
927
928     function printXML() {
929         PrintXML($this->getContent());
930     }
931
932     function asXML() {
933         return AsXML($this->getContent());
934     }
935     
936     /** 
937      * Handle sortby requests for the DB iterator and table header links.
938      * Prefix the column with + or - like "+pagename","-mtime", ...
939      *
940      * Supported actions: 
941      *   'init'       :   unify with predefined order. "pagename" => "+pagename"
942      *   'flip_order' :   "mtime" => "+mtime" => "-mtime" ...
943      *   'db'         :   "-pagename" => "pagename DESC"
944      *   'check'      :   
945      *
946      * Now all columns are sortable. (patch by DanFr)
947      * Some columns have native DB backend methods, some not.
948      */
949     function sortby ($column, $action, $valid_fields=false) {
950         global $request;
951
952         if (empty($column)) return '';
953         if (is_int($column)) {
954             $column = $this->_columns[$column - 1]->_field;
955             //$column = $col->_field;
956         }
957         //if (!is_string($column)) return '';
958         // support multiple comma-delimited sortby args: "+hits,+pagename"
959         // recursive concat
960         if (strstr($column, ',')) {
961             $result = ($action == 'check') ? true : array();
962             foreach (explode(',', $column) as $col) {
963                 if ($action == 'check')
964                     $result = $result && $this->sortby($col, $action, $valid_fields);
965                 else
966                     $result[] = $this->sortby($col, $action, $valid_fields);
967             }
968             // 'check' returns true/false for every col. return true if all are true. 
969             // i.e. the unsupported 'every' operator in functional languages.
970             if ($action == 'check')
971                 return $result;
972             else
973                 return join(",", $result);
974         }
975         if (substr($column,0,1) == '+') {
976             $order = '+'; $column = substr($column,1);
977         } elseif (substr($column,0,1) == '-') {
978             $order = '-'; $column = substr($column,1);
979         }
980         // default initial order: +pagename, -mtime, -hits
981         if (empty($order)) {
982             if (!empty($this->_sortby[$column]))
983                 $order = $this->_sortby[$column];
984             else {
985                 if (in_array($column, array('mtime','hits')))
986                     $order = '-';
987                 else
988                     $order = '+';
989             }
990         }
991         if ($action == 'get') {
992             return $order . $column;
993         } elseif ($action == 'flip_order') {
994             if (0 and DEBUG)
995                 trigger_error("flip $order $column ".$this->id,  E_USER_NOTICE); 
996             return ($order == '+' ? '-' : '+') . $column;
997         } elseif ($action == 'init') { // only allowed from PageList::PageList
998             if (0 and DEBUG) {
999                 if ($this->sortby($column, 'clicked')) {
1000                     trigger_error("clicked $order $column $this->id",  E_USER_NOTICE); 
1001                 //$order = ($order == '+' ? '-' : '+'); // $this->sortby($sortby, 'flip_order');
1002                 }
1003             }
1004             $this->_sortby[$column] = $order; // forces show icon
1005             return $order . $column;
1006         } elseif ($action == 'check') {   // show icon?
1007             //if specified via arg or if clicked
1008             $show = (!empty($this->_sortby[$column]) or $this->sortby($column, 'clicked'));
1009             if (0 and $show and DEBUG) {
1010                 trigger_error("show $order $column ".$this->id, E_USER_NOTICE);
1011             }
1012             return $show;            
1013         } elseif ($action == 'clicked') { // flip sort order?
1014             global $request;
1015             $arg = $request->getArg('sortby');
1016             return ($arg
1017                     and strstr($arg, $column)
1018                     and (!isset($request->args['id']) 
1019                          or $this->id == $request->getArg('id')));
1020         } elseif ($action == 'db') {
1021             // Performance enhancement: use native DB sort if possible.
1022             if (($valid_fields and in_array($column, $valid_fields))
1023                 or (method_exists($request->_dbi->_backend, 'sortable_columns')
1024                     and (in_array($column, $request->_dbi->_backend->sortable_columns())))) {
1025                 // omit this sort method from the _sortPages call at rendering
1026                 // asc or desc: +pagename, -pagename
1027                 return $column . ($order == '+' ? ' ASC' : ' DESC');
1028             } else {
1029                 return '';
1030             }
1031         }
1032         return '';
1033     }
1034
1035     /* Splits pagelist string into array.
1036      * Test* or Test1,Test2
1037      * Limitation: Doesn't split into comma-sep and then expand wildcards.
1038      * "Test1*,Test2*" is expanded into TextSearch "Test1* Test2*"
1039      *
1040      * echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1041      */
1042     function explodePageList($input, $include_empty=false, $sortby='', 
1043                              $limit='', $exclude='') 
1044     {
1045         if (empty($input)) return array();
1046         if (is_array($input)) return $input;
1047         // expand wildcards from list of all pages
1048         if (preg_match('/[\?\*]/', $input) or substr($input,0,1) == "^") {
1049             include_once("lib/TextSearchQuery.php");
1050             $search = new TextSearchQuery(str_replace(",", " ", $input), true, 
1051                                          (substr($input,0,1) == "^") ? 'posix' : 'glob'); 
1052             $dbi = $GLOBALS['request']->getDbh();
1053             $iter = $dbi->titleSearch($search, $sortby, $limit, $exclude);
1054             $pages = array();
1055             while ($pagehandle = $iter->next()) {
1056                 $pages[] = trim($pagehandle->getName());
1057             }
1058             return $pages;
1059             /*
1060             //TODO: need an SQL optimization here
1061             $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, 
1062                                                 $exclude);
1063             while ($pagehandle = $allPagehandles->next()) {
1064                 $allPages[] = $pagehandle->getName();
1065             }
1066             return explodeList($input, $allPages);
1067             */
1068         } else {
1069             //TODO: do the sorting, normally not needed if used for exclude only
1070             return array_map("trim", explode(',', $input));
1071         }
1072     }
1073
1074     // TODO: optimize getTotal => store in count
1075     function allPagesByAuthor($wildcard, $include_empty=false, $sortby='', 
1076                               $limit='', $exclude='') 
1077     {
1078         $dbi = $GLOBALS['request']->getDbh();
1079         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1080         $allPages = array();
1081         if ($wildcard === '[]') {
1082             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1083             if (!$wildcard) return $allPages;
1084         }
1085         $do_glob = preg_match('/[\?\*]/', $wildcard);
1086         while ($pagehandle = $allPagehandles->next()) {
1087             $name = $pagehandle->getName();
1088             $author = $pagehandle->getAuthor();
1089             if ($author) {
1090                 if ($do_glob) {
1091                     if (glob_match($wildcard, $author))
1092                         $allPages[] = $name;
1093                 } elseif ($wildcard == $author) {
1094                       $allPages[] = $name;
1095                 }
1096             }
1097             // TODO: purge versiondata_cache
1098         }
1099         return $allPages;
1100     }
1101
1102     function allPagesByOwner($wildcard, $include_empty=false, $sortby='', 
1103                              $limit='', $exclude='') {
1104         $dbi = $GLOBALS['request']->getDbh();
1105         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1106         $allPages = array();
1107         if ($wildcard === '[]') {
1108             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1109             if (!$wildcard) return $allPages;
1110         }
1111         $do_glob = preg_match('/[\?\*]/', $wildcard);
1112         while ($pagehandle = $allPagehandles->next()) {
1113             $name = $pagehandle->getName();
1114             $owner = $pagehandle->getOwner();
1115             if ($owner) {
1116                 if ($do_glob) {
1117                     if (glob_match($wildcard, $owner))
1118                         $allPages[] = $name;
1119                 } elseif ($wildcard == $owner) {
1120                       $allPages[] = $name;
1121                 }
1122             }
1123         }
1124         return $allPages;
1125     }
1126
1127     function allPagesByCreator($wildcard, $include_empty=false, $sortby='', 
1128                                $limit='', $exclude='') {
1129         $dbi = $GLOBALS['request']->getDbh();
1130         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1131         $allPages = array();
1132         if ($wildcard === '[]') {
1133             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1134             if (!$wildcard) return $allPages;
1135         }
1136         $do_glob = preg_match('/[\?\*]/', $wildcard);
1137         while ($pagehandle = $allPagehandles->next()) {
1138             $name = $pagehandle->getName();
1139             $creator = $pagehandle->getCreator();
1140             if ($creator) {
1141                 if ($do_glob) {
1142                     if (glob_match($wildcard, $creator))
1143                         $allPages[] = $name;
1144                 } elseif ($wildcard == $creator) {
1145                       $allPages[] = $name;
1146                 }
1147             }
1148         }
1149         return $allPages;
1150     }
1151
1152     // UserPages are pages NOT owned by ADMIN_USER
1153     function allUserPages($include_empty=false, $sortby='',
1154                           $limit='', $exclude='') {
1155         $dbi = $GLOBALS['request']->getDbh();
1156         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1157         $allPages = array();
1158         while ($pagehandle = $allPagehandles->next()) {
1159             $name = $pagehandle->getName();
1160             $owner = $pagehandle->getOwner();
1161             if ($owner !== ADMIN_USER) {
1162                  $allPages[] = $name;
1163             }
1164         }
1165         return $allPages;
1166     }
1167
1168     ////////////////////
1169     // private
1170     ////////////////////
1171     /** Plugin and theme hooks: 
1172      *  If the pageList is initialized with $options['types'] these types are also initialized, 
1173      *  overriding the standard types.
1174      */
1175     function _initAvailableColumns() {
1176         global $customPageListColumns;
1177         $standard_types =
1178             array(
1179                   'content'
1180                   => new _PageList_Column_content('rev:content', _("Content")),
1181                   // new: plugin specific column types initialised by the relevant plugins
1182                   /*
1183                   'hi_content' // with highlighted search for SearchReplace
1184                   => new _PageList_Column_content('rev:hi_content', _("Content")),
1185                   'remove'
1186                   => new _PageList_Column_remove('remove', _("Remove")),
1187                   // initialised by the plugin
1188                   'renamed_pagename'
1189                   => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
1190                   'perm'
1191                   => new _PageList_Column_perm('perm', _("Permission")),
1192                   'acl'
1193                   => new _PageList_Column_acl('acl', _("ACL")),
1194                   */
1195                   'checkbox'
1196                   => new _PageList_Column_checkbox('p', _("All")),
1197                   'pagename'
1198                   => new _PageList_Column_pagename,
1199                   'mtime'
1200                   => new _PageList_Column_time('rev:mtime', _("Last Modified")),
1201                   'hits'
1202                   => new _PageList_Column('hits', _("Hits"), 'right'),
1203                   'size'
1204                   => new _PageList_Column_size('rev:size', _("Size"), 'right'),
1205                                               /*array('align' => 'char', 'char' => ' ')*/
1206                   'summary'
1207                   => new _PageList_Column('rev:summary', _("Last Summary")),
1208                   'version'
1209                   => new _PageList_Column_version('rev:version', _("Version"),
1210                                                  'right'),
1211                   'author'
1212                   => new _PageList_Column_author('rev:author', _("Last Author")),
1213                   'owner'
1214                   => new _PageList_Column_owner('author_id', _("Owner")),
1215                   'creator'
1216                   => new _PageList_Column_creator('author_id', _("Creator")),
1217                   /*
1218                   'group'
1219                   => new _PageList_Column_author('group', _("Group")),
1220                   */
1221                   'locked'
1222                   => new _PageList_Column_bool('locked', _("Locked"),
1223                                                _("locked")),
1224                   'external'
1225                   => new _PageList_Column_bool('external', _("External"),
1226                                                _("external")),
1227                   'minor'
1228                   => new _PageList_Column_bool('rev:is_minor_edit',
1229                                                _("Minor Edit"), _("minor")),
1230                   'markup'
1231                   => new _PageList_Column('rev:markup', _("Markup")),
1232                   // 'rating' initialised by the wikilens theme hook: addPageListColumn
1233                   /*
1234                   'rating'
1235                   => new _PageList_Column_rating('rating', _("Rate")),
1236                   */
1237                   );
1238         if (empty($this->_types))
1239             $this->_types = array();
1240         // add plugin specific pageList columns, initialized by $options['types']
1241         $this->_types = array_merge($standard_types, $this->_types);
1242         // add theme custom specific pageList columns: 
1243         //   set the 4th param as the current pagelist object.
1244         if (!empty($customPageListColumns)) {
1245             foreach ($customPageListColumns as $column => $params) {
1246                 $class_name = array_shift($params);
1247                 $params[3] =& $this;
1248                 // ref to a class does not work with php-4
1249                 $this->_types[$column] = new $class_name($params);
1250             }
1251         }
1252     }
1253
1254     function getOption($option) {
1255         if (array_key_exists($option, $this->_options)) {
1256             return $this->_options[$option];
1257         }
1258         else {
1259             return null;
1260         }
1261     }
1262
1263     /**
1264      * Add a column to this PageList, given a column name.
1265      * The name is a type, and optionally has a : and a label. Examples:
1266      *
1267      *   pagename
1268      *   pagename:This page
1269      *   mtime
1270      *   mtime:Last modified
1271      *
1272      * If this function is called multiple times for the same type, the
1273      * column will only be added the first time, and ignored the succeeding times.
1274      * If you wish to add multiple columns of the same type, use addColumnObject().
1275      *
1276      * @param column name
1277      * @return  true if column is added, false otherwise
1278      */
1279     function _addColumn ($column) {
1280         
1281         if (isset($this->_columns_seen[$column]))
1282             return false;       // Already have this one.
1283         if (!isset($this->_types[$column]))
1284             $this->_initAvailableColumns();
1285         $this->_columns_seen[$column] = true;
1286
1287         if (strstr($column, ':'))
1288             list ($column, $heading) = explode(':', $column, 2);
1289
1290         // FIXME: these column types have hooks (objects) elsewhere
1291         // Omitting this warning should be overridable by the extension
1292         if (!isset($this->_types[$column])) {
1293             $silently_ignore = array('numbacklinks',
1294                                      'rating','ratingvalue',
1295                                      'coagreement', 'minmisery',
1296                                      /*'prediction',*/
1297                                      'averagerating', 'top3recs', 
1298                                      'relation', 'linkto');
1299             if (!in_array($column, $silently_ignore))
1300                 trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
1301             return false;
1302         }
1303         if (!GFORGE) {
1304             // FIXME: anon users might rate and see ratings also. 
1305             // Defer this logic to the plugin.
1306             if ($column == 'rating' and !$GLOBALS['request']->_user->isSignedIn()) {
1307                 return false;
1308             }
1309         }
1310
1311         $this->addColumnObject($this->_types[$column]);
1312
1313         return true;
1314     }
1315
1316     /**
1317      * Add a column to this PageList, given a column object.
1318      *
1319      * @param $col object   An object derived from _PageList_Column.
1320      **/
1321     function addColumnObject($col) {
1322         if (is_array($col)) {// custom column object
1323             $params =& $col;
1324             $class_name = array_shift($params);
1325             $params[3] =& $this;
1326             $col = new $class_name($params);
1327         }
1328         $heading = $col->getHeading();
1329         if (!empty($heading))
1330             $col->setHeading($heading);
1331
1332         $this->_columns[] = $col;
1333         $this->_columnsMap[$col->_field] = count($this->_columns); // start with 1
1334     }
1335
1336     /**
1337      * Compare _PageList_Page objects.
1338      **/
1339     function _pageCompare(&$a, &$b) {
1340         if (empty($this->_sortby) or count($this->_sortby) == 0) {
1341             // No columns to sort by
1342             return 0;
1343         }
1344         else {
1345             $pagea = $this->_getPageFromHandle($a);  // If a string, convert to page
1346             assert(isa($pagea, 'WikiDB_Page'));
1347             $pageb = $this->_getPageFromHandle($b);  // If a string, convert to page
1348             assert(isa($pageb, 'WikiDB_Page'));
1349             foreach ($this->_sortby as $colNum => $direction) {
1350                 // get column type object
1351                 if (!is_int($colNum)) { // or column fieldname
1352                     if (isset($this->_columnsMap[$colNum]))
1353                         $col = $this->_columns[$this->_columnsMap[$colNum] - 1];
1354                     elseif (isset($this->_types[$colNum]))
1355                         $col = $this->_types[$colNum];
1356                 }
1357                 if (empty($col)){
1358                     return 0;
1359                 }
1360                 assert(isset($col));
1361                 $revision_handle = false;
1362                 $aval = $col->_getSortableValue($pagea, $revision_handle);
1363                 $revision_handle = false;
1364                 $bval = $col->_getSortableValue($pageb, $revision_handle);
1365
1366                 $cmp = $col->_compare($aval, $bval);
1367                 if ($direction === "-")  // Reverse the sense of the comparison
1368                     $cmp *= -1;
1369
1370                 if ($cmp !== 0)
1371                     // This is the first comparison that is not equal-- go with it
1372                     return $cmp;
1373             }
1374             return 0;
1375         }
1376     }
1377
1378     /**
1379      * Put pages in order according to the sortby arg, if given
1380      * If the sortby cols are already sorted by the DB call, don't do usort.
1381      * TODO: optimize for multiple sortable cols
1382      */
1383     function _sortPages() {
1384         if (count($this->_sortby) > 0) {
1385             $need_sort = $this->_options['dosort'];
1386             if (!$need_sort)
1387               foreach ($this->_sortby as $col => $dir) {
1388                 if (! $this->sortby($col, 'db'))
1389                     $need_sort = true;
1390               }
1391             if ($need_sort) { // There are some columns to sort by
1392                 // TODO: consider nopage
1393                 usort($this->_pages, array($this, '_pageCompare'));
1394             }
1395         }
1396         //unset($GLOBALS['PhpWiki_pagelist']);
1397     }
1398
1399     function limit($limit) {
1400         if (is_array($limit)) {
1401             list($from, $count) = $limit;
1402             if ((!empty($from) && !is_numeric($from)) or (!empty($count) && !is_numeric($count))) {
1403                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1404             }
1405             return $limit;
1406         }
1407         if (strstr($limit, ',')) {
1408             list($from, $limit) = explode(',', $limit);
1409             if ((!empty($from) && !is_numeric($from)) or (!empty($limit) && !is_numeric($limit))) {
1410                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1411             }
1412             return array($from, $limit);
1413         }
1414         else {
1415             if (!empty($limit) && !is_numeric($limit)) {
1416                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1417             }
1418             return array(0, $limit);
1419         }
1420     }
1421
1422     function pagingTokens($numrows = false, $ncolumns = false, $limit = false) {
1423         if ($numrows === false)
1424             $numrows = $this->getTotal();
1425         if ($limit === false)
1426             $limit = $this->_options['limit'];
1427         if ($ncolumns === false)
1428             $ncolumns = count($this->_columns);
1429
1430         list($offset, $pagesize) = $this->limit($limit);
1431         if (!$pagesize or
1432             (!$offset and $numrows < $pagesize) or
1433             (($offset + $pagesize) < 0))
1434             return false;
1435
1436         $request = &$GLOBALS['request'];
1437         $pagename = $request->getArg('pagename');
1438         $defargs = array_merge(array('id' => $this->id), $request->args);
1439         if (USE_PATH_INFO) unset($defargs['pagename']);
1440         if (isset($defargs['action']) and ($defargs['action'] == 'browse')) {
1441             unset($defargs['action']);
1442         }
1443         $prev = $defargs;
1444
1445         $tokens = array();
1446         $tokens['PREV'] = false; $tokens['PREV_LINK'] = "";
1447         $tokens['COLS'] = $ncolumns;
1448         $tokens['COUNT'] = $numrows; 
1449         $tokens['OFFSET'] = $offset; 
1450         $tokens['SIZE'] = $pagesize;
1451         $tokens['NUMPAGES'] = (int) ceil($numrows / $pagesize);
1452         $tokens['ACTPAGE'] = (int) ceil(($offset / $pagesize)+1);
1453         if ($offset > 0) {
1454             $prev['limit'] = max(0, $offset - $pagesize) . ",$pagesize";
1455             $prev['count'] = $numrows;
1456             $tokens['LIMIT'] = $prev['limit'];
1457             $tokens['PREV'] = true;
1458             $tokens['PREV_LINK'] = WikiURL($pagename, $prev);
1459             $prev['limit'] = "0,$pagesize"; // FIRST_LINK
1460             $tokens['FIRST_LINK'] = WikiURL($pagename, $prev);
1461         }
1462         $next = $defargs;
1463         $tokens['NEXT'] = false; $tokens['NEXT_LINK'] = "";
1464         if (($offset + $pagesize) < $numrows) {
1465             $next['limit'] = min($offset + $pagesize, $numrows - $pagesize) 
1466                              . ",$pagesize";
1467             $next['count'] = $numrows;
1468             $tokens['LIMIT'] = $next['limit'];
1469             $tokens['NEXT'] = true;
1470             $tokens['NEXT_LINK'] = WikiURL($pagename, $next);
1471             $next['limit'] = $numrows - $pagesize . ",$pagesize"; // LAST_LINK
1472             $tokens['LAST_LINK'] = WikiURL($pagename, $next);
1473         }
1474         return $tokens;
1475     }
1476     
1477     // make a table given the caption
1478     function _generateTable($caption) {
1479         if (count($this->_sortby) > 0) $this->_sortPages();
1480         
1481         // wikiadminutils hack. that's a way to pagelist non-pages
1482         $rows = isset($this->_rows) ? $this->_rows : array();
1483         $i = 0;
1484         $count = $this->getTotal();
1485         $do_paging = ( isset($this->_options['paging']) 
1486                        and !empty($this->_options['limit']) 
1487                        and $count 
1488                        and $this->_options['paging'] != 'none' );
1489         if ($do_paging) {
1490             $tokens = $this->pagingTokens($count, 
1491                                            count($this->_columns), 
1492                                            $this->_options['limit']);
1493             if ($tokens and !empty($this->_options['slice']))
1494                 $this->_pages = array_slice($this->_pages, $tokens['OFFSET'], $tokens['COUNT']);
1495         }
1496         foreach ($this->_pages as $pagenum => $page) {
1497             $one_row = $this->_renderPageRow($page, $i++);
1498             $rows[] = $one_row;
1499         }
1500         $table = HTML::table(array('cellpadding' => 0,
1501                                    'cellspacing' => 1,
1502                                    'border'      => 0,
1503                                    'width'       => '100%', 
1504                                    'class'       => 'pagelist', 
1505                                    ));
1506         if ($caption) {
1507             $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
1508         }
1509
1510         $row = HTML::tr();
1511         $table_summary = array();
1512         $i = 1; // start with 1!
1513         foreach ($this->_columns as $col) {
1514             $heading = $col->button_heading($this, $i);
1515             if ( $do_paging 
1516                  and isset($col->_field) 
1517                  and $col->_field == 'pagename' 
1518                  and ($maxlen = $this->maxLen())) {
1519                // $heading->setAttr('width', $maxlen * 7);
1520             }
1521             $row->pushContent($heading);
1522             if (is_string($col->getHeading()))
1523                 $table_summary[] = $col->getHeading();
1524             $i++;
1525         }
1526         // Table summary for non-visual browsers.
1527         $table->setAttr('summary', sprintf(_("Columns: %s."), 
1528                                            join(", ", $table_summary)));
1529         $table->pushContent(HTML::colgroup(array('span' => count($this->_columns))));
1530         if ( $do_paging ) {
1531             if ($tokens === false) {
1532                 $table->pushContent(HTML::thead($row),
1533                                     HTML::tbody(false, $rows));
1534                 return $table;
1535             }
1536
1537             $paging = Template("pagelink", $tokens);
1538             if ($this->_options['paging'] != 'bottom')
1539                 $table->pushContent(HTML::thead($paging));
1540             if ($this->_options['paging'] != 'top')
1541                 $table->pushContent(HTML::tfoot($paging));
1542             $table->pushContent(HTML::tbody(false, HTML($row, $rows)));
1543             return $table;
1544         } else {
1545             $table->pushContent(HTML::thead($row),
1546                                 HTML::tbody(false, $rows));
1547             return $table;
1548         }
1549     }
1550
1551     /* recursive stack for private sublist options (azhead, cols) */
1552     function _saveOptions($opts) {
1553         $stack = array('pages' => $this->_pages);
1554         foreach ($opts as $k => $v) {
1555             $stack[$k] = $this->_options[$k];
1556             $this->_options[$k] = $v;
1557         }
1558         if (empty($this->_stack))
1559             $this->_stack = new Stack();
1560         $this->_stack->push($stack);
1561     }
1562     function _restoreOptions() {
1563         assert($this->_stack);
1564         $stack = $this->_stack->pop();
1565         $this->_pages = $stack['pages'];
1566         unset($stack['pages']);
1567         foreach ($stack as $k => $v) {
1568             $this->_options[$k] = $v;
1569         }
1570     }
1571
1572     // 'cols'   - split into several columns
1573     // 'azhead' - support <h3> grouping into initials
1574     // 'ordered' - OL or UL list (not yet inherited to all plugins)
1575     // 'comma'  - condensed comma-list only, 1: no links, >1: with links
1576     // FIXME: only unique list entries, esp. with nopage
1577     function _generateList($caption='') {
1578         if (empty($this->_pages)) return; // stop recursion
1579         if (!isset($this->_options['listtype'])) 
1580             $this->_options['listtype'] = '';
1581         foreach ($this->_pages as $pagenum => $page) {
1582             $one_row = $this->_renderPageRow($page);
1583             $rows[] = array('header' => WikiLink($page), 'render' => $one_row);
1584         }
1585         $out = HTML();
1586         if ($caption) {
1587             $out->pushContent(HTML::p($caption));
1588         }
1589         // Semantic Search et al: only unique list entries, esp. with nopage
1590         if (!is_array($this->_pages[0]) and is_string($this->_pages[0])) {
1591             $this->_pages = array_unique($this->_pages);
1592         }
1593         if (count($this->_sortby) > 0) $this->_sortPages();
1594         $count = $this->getTotal();
1595         $do_paging = ( isset($this->_options['paging']) 
1596                        and !empty($this->_options['limit']) 
1597                        and $count 
1598                        and $this->_options['paging'] != 'none' );
1599         if ( $do_paging ) {
1600             $tokens = $this->pagingTokens($count, 
1601                                           count($this->_columns), 
1602                                           $this->_options['limit']);
1603             if ($tokens) {
1604                 $paging = Template("pagelink", $tokens);
1605                 $out->pushContent(HTML::table(array('width'=>'50%'), $paging));
1606             }
1607         }
1608
1609         if (!empty($this->_options['limit']) and !empty($this->_options['slice'])) {
1610             list($offset, $count) = $this->limit($this->_options['limit']);
1611         } else {
1612             $offset = 0; $count = count($this->_pages);
1613         }
1614         // need a recursive switch here for the azhead and cols grouping.
1615         if (!empty($this->_options['cols']) and $this->_options['cols'] > 1) {
1616             $length = intval($count / ($this->_options['cols']));
1617             // If division does not give an integer, we need one more line
1618             // E.g. 13 pages to display in 3 columns.
1619             if (($length * ($this->_options['cols'])) != $count) {
1620                 $length += 1;
1621             }
1622             $width = sprintf("%d", 100 / $this->_options['cols']).'%';
1623             $cols = HTML::tr(array('valign' => 'top'));
1624             for ($i=$offset; $i < $offset+$count; $i += $length) {
1625                 $this->_saveOptions(array('cols' => 0, 'paging' => 'none'));
1626                 $this->_pages = array_slice($this->_pages, $i, $length);
1627                 $cols->pushContent(HTML::td(/*array('width' => $width),*/ 
1628                                             $this->_generateList()));
1629                 $this->_restoreOptions();
1630             }
1631             // speed up table rendering by defining colgroups
1632             $out->pushContent(HTML::table(HTML::colgroup
1633                 (array('span' => $this->_options['cols'],
1634                        'width' => $width)),
1635                 $cols));
1636             return $out;
1637         }
1638         
1639         // Ignore azhead if not sorted by pagename
1640         if (!empty($this->_options['azhead']) 
1641             and strstr($this->sortby($this->_options['sortby'], 'init'), "pagename")
1642             )
1643         {
1644             $cur_h = substr($this->_pages[0]->getName(), 0, 1);
1645             $out->pushContent(HTML::h3($cur_h));
1646             // group those pages together with same $h
1647             $j = 0;
1648             for ($i=0; $i < count($this->_pages); $i++) {
1649                 $page =& $this->_pages[$i];
1650                 $h = substr($page->getName(), 0, 1);
1651                 if ($h != $cur_h and $i > $j) {
1652                     $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j+1));
1653                     $this->_pages = array_slice($this->_pages, $j, $i - $j);
1654                     $out->pushContent($this->_generateList());
1655                     $this->_restoreOptions();
1656                     $j = $i;
1657                     $out->pushContent(HTML::h3($h));
1658                     $cur_h = $h;
1659                 }
1660             }
1661             if ($i > $j) { // flush the rest
1662                 $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j+1));
1663                 $this->_pages = array_slice($this->_pages, $j, $i - $j);
1664                 $out->pushContent($this->_generateList());
1665                 $this->_restoreOptions();
1666             }
1667             return $out;
1668         }
1669             
1670         if ($this->_options['listtype'] == 'comma')
1671             $this->_options['comma'] = 2;
1672         if (!empty($this->_options['comma'])) {
1673             if ($this->_options['comma'] == 1)
1674                 $out->pushContent($this->_generateCommaListAsString());
1675             else
1676                 $out->pushContent($this->_generateCommaList($this->_options['comma']));
1677             return $out;
1678         }
1679
1680         if ($this->_options['listtype'] == 'ol') {
1681             if (empty($this->_options['ordered'])) {
1682                 $this->_options['ordered'] = $offset+1;
1683             }
1684         } elseif ($this->_options['listtype'] == 'ul')
1685             $this->_options['ordered'] = 0;
1686         if ($this->_options['listtype'] == 'ol' and !empty($this->_options['ordered'])) {
1687             $list = HTML::ol(array('class' => 'pagelist', 
1688                                    'start' => $this->_options['ordered']));
1689         } elseif ($this->_options['listtype'] == 'dl') {
1690             $list = HTML::dl(array('class' => 'pagelist'));
1691         } else {
1692             $list = HTML::ul(array('class' => 'pagelist'));
1693         }
1694         $i = 0;
1695         //TODO: currently we ignore limit here and hope that the backend didn't ignore it. (BackLinks)
1696         if (!empty($this->_options['limit']))
1697             list($offset, $pagesize) = $this->limit($this->_options['limit']);
1698         else 
1699             $pagesize=0;
1700             foreach (array_reverse($rows) as $one_row) {
1701                 $pagehtml = $one_row['render'];
1702             if (!$pagehtml) continue;
1703             $group = ($i++ / $this->_group_rows);
1704             //TODO: here we switch every row, in tables every third. 
1705             //      unification or parametrized?
1706             $class = ($group % 2) ? 'oddrow' : 'evenrow';
1707             if ($this->_options['listtype'] == 'dl') {
1708                 $header = $one_row['header'];
1709                 //if ($this->_sortby['hi_content']) 
1710                 $list->pushContent(HTML::dt(array('class' => $class), $header),
1711                                    HTML::dd(array('class' => $class), $pagehtml));
1712             } else
1713                 $list->pushContent(HTML::li(array('class' => $class), $pagehtml));
1714             if ($pagesize and $i > $pagesize) break;
1715         }
1716         $out->pushContent($list);
1717         if ( $do_paging and $tokens ) {
1718             $out->pushContent(HTML::table($paging));
1719         }
1720         return $out;
1721     }
1722
1723     // comma=1
1724     // Condense list without a href links: "Page1, Page2, ..." 
1725     // Alternative $seperator = HTML::Raw(' &middot; ')
1726     // FIXME: only unique list entries, esp. with nopage
1727     function _generateCommaListAsString() {
1728         if (defined($this->_options['commasep']))
1729             $seperator = $this->_options['commasep'];
1730         else    
1731             $seperator = ', ';
1732         $pages = array();
1733         foreach ($this->_pages as $pagenum => $page) {
1734             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1735                 $pages[] = is_string($s) ? $s : $s->asString();
1736         }
1737         return HTML(join($seperator, $pages));
1738     }
1739
1740     // comma=2
1741     // Normal WikiLink list.
1742     // Future: 1 = reserved for plain string (see above)
1743     //         2 and more => HTML link specialization?
1744     // FIXME: only unique list entries, esp. with nopage
1745     function _generateCommaList($style = false) {
1746         if (defined($this->_options['commasep']))
1747             $seperator = HTLM::Raw($this->_options['commasep']);
1748         else    
1749             $seperator = ', ';
1750         $html = HTML();
1751         $html->pushContent($this->_renderPageRow($this->_pages[0]));
1752         next($this->_pages);
1753         foreach ($this->_pages as $pagenum => $page) {
1754             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1755                 $html->pushContent($seperator, $s);
1756         }
1757         return $html;
1758     }
1759     
1760     function _emptyList($caption) {
1761         $html = HTML();
1762         if ($caption) {
1763             $html->pushContent(HTML::p($caption));
1764         }
1765         if ($this->_messageIfEmpty)
1766             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
1767         return $html;
1768     }
1769
1770 };
1771
1772 /* List pages with checkboxes to select from.
1773  * The [Select] button toggles via Javascript flipAll
1774  */
1775
1776 class PageList_Selectable
1777 extends PageList {
1778
1779     function PageList_Selectable ($columns=false, $exclude='', $options = false) {
1780         if ($columns) {
1781             if (!is_array($columns))
1782                 $columns = explode(',', $columns);
1783             if (!in_array('checkbox',$columns))
1784                 array_unshift($columns,'checkbox');
1785         } else {
1786             $columns = array('checkbox','pagename');
1787         }
1788         $this->PageList($columns, $exclude, $options);
1789     }
1790
1791     function addPageList ($array) {
1792         while (list($pagename,$selected) = each($array)) {
1793             if ($selected) $this->addPageSelected((string)$pagename);
1794             $this->addPage((string)$pagename);
1795         }
1796     }
1797
1798     function addPageSelected ($pagename) {
1799         $this->_selected[$pagename] = 1;
1800     }
1801 }
1802
1803 class PageList_Unselectable
1804 extends PageList {
1805
1806     function PageList_Unselectable ($columns=false, $exclude='', $options = false) {
1807         if ($columns) {
1808             if (!is_array($columns))
1809                 $columns = explode(',', $columns);
1810         } else {
1811             $columns = array('pagename');
1812         }
1813         $this->PageList($columns, $exclude, $options);
1814     }
1815
1816     function addPageList ($array) {
1817         while (list($pagename,$selected) = each($array)) {
1818             if ($selected) $this->addPageSelected((string)$pagename);
1819             $this->addPage((string)$pagename);
1820         }
1821     }
1822
1823     function addPageSelected ($pagename) {
1824         $this->_selected[$pagename] = 1;
1825     }
1826 }
1827
1828 // (c-file-style: "gnu")
1829 // Local Variables:
1830 // mode: php
1831 // tab-width: 8
1832 // c-basic-offset: 4
1833 // c-hanging-comment-ender-p: nil
1834 // indent-tabs-mode: nil
1835 // End:
1836 ?>