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