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