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