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