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