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