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