]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
Update WikiAdminSearchReplace plugin
[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, $revision_handle->get('markup'), 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             'markup' => null,
756             'external' => null,
757         );
758     }
759
760     function pagingArgs()
761     {
762         return array('sortby', 'limit', 'paging', 'count', 'dosort');
763     }
764
765     function clearArg($arg_name)
766     {
767         if (isset($this->_options[$arg_name]))
768             unset($this->_options[$arg_name]);
769     }
770
771     /**
772      * @param    mixed $caption    string or HTML
773      */
774     function setCaption($caption)
775     {
776         $this->_caption = $caption;
777     }
778
779     /**
780      * @param    mixed $caption    string or HTML
781      */
782     function addCaption($caption)
783     {
784         $this->_caption = HTML($this->_caption, " ", $caption);
785     }
786
787     function getCaption()
788     {
789         // put the total into the caption if needed
790         if (is_string($this->_caption) && strstr($this->_caption, '%d'))
791             return sprintf($this->_caption, $this->getTotal());
792         return $this->_caption;
793     }
794
795     function setMessageIfEmpty($msg)
796     {
797         $this->_messageIfEmpty = $msg;
798     }
799
800     function getTotal()
801     {
802         return !empty($this->_options['count'])
803             ? (integer)$this->_options['count'] : count($this->_pages);
804     }
805
806     function isEmpty()
807     {
808         return empty($this->_pages);
809     }
810
811     function addPage($page_handle)
812     {
813         if (!empty($this->_excluded_pages)) {
814             if (!in_array((is_string($page_handle) ? $page_handle : $page_handle->getName()),
815                 $this->_excluded_pages)
816             )
817                 $this->_pages[] = $page_handle;
818         } else {
819             $this->_pages[] = $page_handle;
820         }
821     }
822
823     function pageNames()
824     {
825         $pages = array();
826         $limit = @$this->_options['limit'];
827         foreach ($this->_pages as $page_handle) {
828             $pages[] = $page_handle->getName();
829             if ($limit and count($pages) > $limit)
830                 break;
831         }
832         return $pages;
833     }
834
835     function _getPageFromHandle($page_handle)
836     {
837         if (is_string($page_handle)) {
838             if (empty($page_handle)) return $page_handle;
839             $page_handle = $GLOBALS['request']->_dbi->getPage($page_handle);
840         }
841         return $page_handle;
842     }
843
844     /**
845      * Take a PageList_Page object, and return an HTML object to display
846      * it in a table or list row.
847      */
848     function _renderPageRow(&$page_handle, $i = 0)
849     {
850         $page_handle = $this->_getPageFromHandle($page_handle);
851         //FIXME. only on sf.net
852         if (!is_object($page_handle)) {
853             trigger_error("PageList: Invalid page_handle $page_handle", E_USER_WARNING);
854             return;
855         }
856         if (!isset($page_handle)
857             or empty($page_handle)
858             or (!empty($this->_excluded_pages)
859                 and in_array($page_handle->getName(), $this->_excluded_pages))
860         )
861             return; // exclude page.
862
863         // enforce view permission
864         if (!mayAccessPage('view', $page_handle->getName()))
865             return;
866
867         $group = (int)($i / $this->_group_rows);
868         $class = ($group % 2) ? 'oddrow' : 'evenrow';
869         $revision_handle = false;
870         $this->_maxlen = max($this->_maxlen, strlen($page_handle->getName()));
871
872         if (count($this->_columns) > 1) {
873             $row = HTML::tr(array('class' => $class));
874             $j = 0;
875             foreach ($this->_columns as $col) {
876                 $col->current_row = $i;
877                 $col->current_column = $j;
878                 $row->pushContent($col->format($this, $page_handle, $revision_handle));
879                 $j++;
880             }
881         } else {
882             $col = $this->_columns[0];
883             $col->current_row = $i;
884             $col->current_column = 0;
885             $row = $col->_getValue($page_handle, $revision_handle);
886         }
887
888         return $row;
889     }
890
891     /* ignore from, but honor limit */
892     function addPages($page_iter)
893     {
894         // TODO: if limit check max(strlen(pagename))
895         $limit = $page_iter->limit();
896         $i = 0;
897         if ($limit) {
898             list($from, $limit) = $this->limit($limit);
899             $this->_options['slice'] = 0;
900             $limit += $from;
901             while ($page = $page_iter->next()) {
902                 $i++;
903                 if ($from and $i < $from)
904                     continue;
905                 if (!$limit or ($limit and $i < $limit))
906                     $this->addPage($page);
907             }
908         } else {
909             $this->_options['slice'] = 0;
910             while ($page = $page_iter->next()) {
911                 $this->addPage($page);
912             }
913         }
914         if (!is_array($page_iter->_options) || !array_key_exists('limit_by_db', $page_iter->_options) || !$page_iter->_options['limit_by_db'])
915             $this->_options['slice'] = 1;
916         if ($i and empty($this->_options['count']))
917             $this->_options['count'] = $i;
918     }
919
920     function addPageList($list)
921     {
922         if (empty($list)) return; // Protect reset from a null arg
923         if (isset($this->_options['limit'])) { // extract from,count from limit
924             list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
925             $limit += $from;
926         } else {
927             $limit = 0;
928         }
929         $this->_options['slice'] = 0;
930         $i = 0;
931         foreach ($list as $page) {
932             $i++;
933             if ($from and $i < $from)
934                 continue;
935             if (!$limit or ($limit and $i < $limit)) {
936                 if (is_object($page)) $page = $page->_pagename;
937                 $this->addPage((string)$page);
938             }
939         }
940     }
941
942     function maxLen()
943     {
944         global $request;
945         $dbi =& $request->getDbh();
946         if (isa($dbi, 'WikiDB_SQL')) {
947             extract($dbi->_backend->_table_names);
948             $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl");
949             if (DB::isError($res) || empty($res)) return false;
950             else return $res;
951         } elseif (isa($dbi, 'WikiDB_ADODB')) {
952             extract($dbi->_backend->_table_names);
953             $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl");
954             return $row ? $row[0] : false;
955         } else
956             return false;
957     }
958
959     function first()
960     {
961         if (count($this->_pages) > 0) {
962             return $this->_pages[0];
963         }
964         return false;
965     }
966
967     function getContent()
968     {
969         // Note that the <caption> element wants inline content.
970         $caption = $this->getCaption();
971
972         if ($this->isEmpty())
973             return $this->_emptyList($caption);
974         elseif (isset($this->_options['listtype'])
975             and in_array($this->_options['listtype'], array('ol', 'ul', 'comma', 'dl'))
976         )
977             return $this->_generateList($caption); elseif (count($this->_columns) == 1)
978             return $this->_generateList($caption); else
979             return $this->_generateTable($caption);
980     }
981
982     function printXML()
983     {
984         PrintXML($this->getContent());
985     }
986
987     function asXML()
988     {
989         return AsXML($this->getContent());
990     }
991
992     /**
993      * Handle sortby requests for the DB iterator and table header links.
994      * Prefix the column with + or - like "+pagename","-mtime", ...
995      *
996      * Supported actions:
997      *   'init'       :   unify with predefined order. "pagename" => "+pagename"
998      *   'flip_order' :   "mtime" => "+mtime" => "-mtime" ...
999      *   'db'         :   "-pagename" => "pagename DESC"
1000      *   'check'      :
1001      *
1002      * Now all columns are sortable. (patch by DanFr)
1003      * Some columns have native DB backend methods, some not.
1004      */
1005     function sortby($column, $action, $valid_fields = false)
1006     {
1007         global $request;
1008
1009         if (empty($column)) return '';
1010         if (is_int($column)) {
1011             $column = $this->_columns[$column - 1]->_field;
1012         }
1013
1014         // support multiple comma-delimited sortby args: "+hits,+pagename"
1015         // recursive concat
1016         if (strstr($column, ',')) {
1017             $result = ($action == 'check') ? true : array();
1018             foreach (explode(',', $column) as $col) {
1019                 if ($action == 'check')
1020                     $result = $result && $this->sortby($col, $action, $valid_fields);
1021                 else
1022                     $result[] = $this->sortby($col, $action, $valid_fields);
1023             }
1024             // 'check' returns true/false for every col. return true if all are true.
1025             // i.e. the unsupported 'every' operator in functional languages.
1026             if ($action == 'check')
1027                 return $result;
1028             else
1029                 return join(",", $result);
1030         }
1031         if (substr($column, 0, 1) == '+') {
1032             $order = '+';
1033             $column = substr($column, 1);
1034         } elseif (substr($column, 0, 1) == '-') {
1035             $order = '-';
1036             $column = substr($column, 1);
1037         }
1038         // default initial order: +pagename, -mtime, -hits
1039         if (empty($order)) {
1040             if (!empty($this->_sortby[$column]))
1041                 $order = $this->_sortby[$column];
1042             else {
1043                 if (in_array($column, array('mtime', 'hits')))
1044                     $order = '-';
1045                 else
1046                     $order = '+';
1047             }
1048         }
1049         if ($action == 'get') {
1050             return $order . $column;
1051         } elseif ($action == 'flip_order') {
1052             if (0 and DEBUG)
1053                 trigger_error("flip $order $column " . $this->id, E_USER_NOTICE);
1054             return ($order == '+' ? '-' : '+') . $column;
1055         } elseif ($action == 'init') { // only allowed from PageList::PageList
1056             if (0 and DEBUG) {
1057                 if ($this->sortby($column, 'clicked')) {
1058                     trigger_error("clicked $order $column $this->id", E_USER_NOTICE);
1059                 }
1060             }
1061             $this->_sortby[$column] = $order; // forces show icon
1062             return $order . $column;
1063         } elseif ($action == 'check') { // show icon?
1064             //if specified via arg or if clicked
1065             $show = (!empty($this->_sortby[$column]) or $this->sortby($column, 'clicked'));
1066             if (0 and $show and DEBUG) {
1067                 trigger_error("show $order $column " . $this->id, E_USER_NOTICE);
1068             }
1069             return $show;
1070         } elseif ($action == 'clicked') { // flip sort order?
1071             global $request;
1072             $arg = $request->getArg('sortby');
1073             return ($arg
1074                 and strstr($arg, $column)
1075                     and (!isset($request->args['id'])
1076                         or $this->id == $request->getArg('id')));
1077         } elseif ($action == 'db') {
1078             // Performance enhancement: use native DB sort if possible.
1079             if (($valid_fields and in_array($column, $valid_fields))
1080                 or (method_exists($request->_dbi->_backend, 'sortable_columns')
1081                     and (in_array($column, $request->_dbi->_backend->sortable_columns())))
1082             ) {
1083                 // omit this sort method from the _sortPages call at rendering
1084                 // asc or desc: +pagename, -pagename
1085                 return $column . ($order == '+' ? ' ASC' : ' DESC');
1086             } else {
1087                 return '';
1088             }
1089         }
1090         return '';
1091     }
1092
1093     /* Splits pagelist string into array.
1094      * Test* or Test1,Test2
1095      * Limitation: Doesn't split into comma-sep and then expand wildcards.
1096      * "Test1*,Test2*" is expanded into TextSearch "Test1* Test2*"
1097      *
1098      * echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1099      */
1100     function explodePageList($input, $include_empty = false, $sortby = '',
1101                              $limit = '', $exclude = '')
1102     {
1103         if (empty($input)) return array();
1104         if (is_array($input)) return $input;
1105         // expand wildcards from list of all pages
1106         if (preg_match('/[\?\*]/', $input) or substr($input, 0, 1) == "^") {
1107             include_once 'lib/TextSearchQuery.php';
1108             $search = new TextSearchQuery(str_replace(",", " or ", $input), true,
1109                 (substr($input, 0, 1) == "^") ? 'posix' : 'glob');
1110             $dbi = $GLOBALS['request']->getDbh();
1111             $iter = $dbi->titleSearch($search, $sortby, $limit, $exclude);
1112             $pages = array();
1113             while ($pagehandle = $iter->next()) {
1114                 $pages[] = trim($pagehandle->getName());
1115             }
1116             return $pages;
1117         } else {
1118             //TODO: do the sorting, normally not needed if used for exclude only
1119             return array_map("trim", explode(',', $input));
1120         }
1121     }
1122
1123     // TODO: optimize getTotal => store in count
1124     function allPagesByAuthor($wildcard, $include_empty = false, $sortby = '',
1125                               $limit = '', $exclude = '')
1126     {
1127         $dbi = $GLOBALS['request']->getDbh();
1128         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1129         $allPages = array();
1130         if ($wildcard === '[]') {
1131             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1132             if (!$wildcard) return $allPages;
1133         }
1134         $do_glob = preg_match('/[\?\*]/', $wildcard);
1135         while ($pagehandle = $allPagehandles->next()) {
1136             $name = $pagehandle->getName();
1137             $author = $pagehandle->getAuthor();
1138             if ($author) {
1139                 if ($do_glob) {
1140                     if (glob_match($wildcard, $author))
1141                         $allPages[] = $name;
1142                 } elseif ($wildcard == $author) {
1143                     $allPages[] = $name;
1144                 }
1145             }
1146             // TODO: purge versiondata_cache
1147         }
1148         return $allPages;
1149     }
1150
1151     function allPagesByOwner($wildcard, $include_empty = false, $sortby = '',
1152                              $limit = '', $exclude = '')
1153     {
1154         $dbi = $GLOBALS['request']->getDbh();
1155         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1156         $allPages = array();
1157         if ($wildcard === '[]') {
1158             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1159             if (!$wildcard) return $allPages;
1160         }
1161         $do_glob = preg_match('/[\?\*]/', $wildcard);
1162         while ($pagehandle = $allPagehandles->next()) {
1163             $name = $pagehandle->getName();
1164             $owner = $pagehandle->getOwner();
1165             if ($owner) {
1166                 if ($do_glob) {
1167                     if (glob_match($wildcard, $owner))
1168                         $allPages[] = $name;
1169                 } elseif ($wildcard == $owner) {
1170                     $allPages[] = $name;
1171                 }
1172             }
1173         }
1174         return $allPages;
1175     }
1176
1177     function allPagesByCreator($wildcard, $include_empty = false, $sortby = '',
1178                                $limit = '', $exclude = '')
1179     {
1180         $dbi = $GLOBALS['request']->getDbh();
1181         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1182         $allPages = array();
1183         if ($wildcard === '[]') {
1184             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1185             if (!$wildcard) return $allPages;
1186         }
1187         $do_glob = preg_match('/[\?\*]/', $wildcard);
1188         while ($pagehandle = $allPagehandles->next()) {
1189             $name = $pagehandle->getName();
1190             $creator = $pagehandle->getCreator();
1191             if ($creator) {
1192                 if ($do_glob) {
1193                     if (glob_match($wildcard, $creator))
1194                         $allPages[] = $name;
1195                 } elseif ($wildcard == $creator) {
1196                     $allPages[] = $name;
1197                 }
1198             }
1199         }
1200         return $allPages;
1201     }
1202
1203     // UserPages are pages NOT owned by ADMIN_USER
1204     function allUserPages($include_empty = false, $sortby = '',
1205                           $limit = '', $exclude = '')
1206     {
1207         $dbi = $GLOBALS['request']->getDbh();
1208         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1209         $allPages = array();
1210         while ($pagehandle = $allPagehandles->next()) {
1211             $name = $pagehandle->getName();
1212             $owner = $pagehandle->getOwner();
1213             if ($owner !== ADMIN_USER) {
1214                 $allPages[] = $name;
1215             }
1216         }
1217         return $allPages;
1218     }
1219
1220     ////////////////////
1221     // private
1222     ////////////////////
1223     /** Plugin and theme hooks:
1224      *  If the pageList is initialized with $options['types'] these types are also initialized,
1225      *  overriding the standard types.
1226      */
1227     function _initAvailableColumns()
1228     {
1229         global $customPageListColumns;
1230         $standard_types =
1231             array(
1232                 'content'
1233                 => new _PageList_Column_content('rev:content', _("Content")),
1234                 // new: plugin specific column types initialised by the relevant plugins
1235                 /*
1236                 'hi_content' // with highlighted search for SearchReplace
1237                 => new _PageList_Column_content('rev:hi_content', _("Content")),
1238                 'remove'
1239                 => new _PageList_Column_remove('remove', _("Remove")),
1240                 // initialised by the plugin
1241                 'renamed_pagename'
1242                 => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
1243                 */
1244                 'perm'
1245                 => new _PageList_Column_perm('perm', _("Permission")),
1246                 'acl'
1247                 => new _PageList_Column_acl('acl', _("ACL")),
1248                 'checkbox'
1249                 => new _PageList_Column_checkbox('p', _("All")),
1250                 'pagename'
1251                 => new _PageList_Column_pagename,
1252                 'mtime'
1253                 => new _PageList_Column_time('rev:mtime', _("Last Modified")),
1254                 'hits'
1255                 => new _PageList_Column('hits', _("Hits"), 'right'),
1256                 'size'
1257                 => new _PageList_Column_size('rev:size', _("Size"), 'right'),
1258                 'summary'
1259                 => new _PageList_Column('rev:summary', _("Last Summary")),
1260                 'version'
1261                 => new _PageList_Column_version('rev:version', _("Version"),
1262                     'right'),
1263                 'author'
1264                 => new _PageList_Column_author('rev:author', _("Last Author")),
1265                 'owner'
1266                 => new _PageList_Column_owner('author_id', _("Owner")),
1267                 'creator'
1268                 => new _PageList_Column_creator('author_id', _("Creator")),
1269                 /*
1270                 'group'
1271                 => new _PageList_Column_author('group', _("Group")),
1272                 */
1273                 'locked'
1274                 => new _PageList_Column_bool('locked', _("Locked"),
1275                     _("locked")),
1276                 'external'
1277                 => new _PageList_Column_bool('external', _("External"),
1278                     _("external")),
1279                 'minor'
1280                 => new _PageList_Column_bool('rev:is_minor_edit',
1281                     _("Minor Edit"), _("minor")),
1282                 'markup'
1283                 => new _PageList_Column('rev:markup', _("Markup")),
1284                 // 'rating' initialised by the wikilens theme hook: addPageListColumn
1285                 /*
1286                 'rating'
1287                 => new _PageList_Column_rating('rating', _("Rate")),
1288                 */
1289             );
1290         if (empty($this->_types))
1291             $this->_types = array();
1292         // add plugin specific pageList columns, initialized by $options['types']
1293         $this->_types = array_merge($standard_types, $this->_types);
1294         // add theme custom specific pageList columns:
1295         //   set the 4th param as the current pagelist object.
1296         if (!empty($customPageListColumns)) {
1297             foreach ($customPageListColumns as $column => $params) {
1298                 $class_name = array_shift($params);
1299                 $params[3] =& $this;
1300                 // ref to a class does not work with php-4
1301                 $this->_types[$column] = new $class_name($params);
1302             }
1303         }
1304     }
1305
1306     function getOption($option)
1307     {
1308         if (array_key_exists($option, $this->_options)) {
1309             return $this->_options[$option];
1310         } else {
1311             return null;
1312         }
1313     }
1314
1315     /**
1316      * Add a column to this PageList, given a column name.
1317      * The name is a type, and optionally has a : and a label. Examples:
1318      *
1319      *   pagename
1320      *   pagename:This page
1321      *   mtime
1322      *   mtime:Last modified
1323      *
1324      * If this function is called multiple times for the same type, the
1325      * column will only be added the first time, and ignored the succeeding times.
1326      * If you wish to add multiple columns of the same type, use addColumnObject().
1327      *
1328      * @param string column name
1329      * @return bool true if column is added, false otherwise
1330      */
1331     function _addColumn($column)
1332     {
1333         if (isset($this->_columns_seen[$column]))
1334             return false; // Already have this one.
1335         if (!isset($this->_types[$column]))
1336             $this->_initAvailableColumns();
1337         $this->_columns_seen[$column] = true;
1338
1339         if (strstr($column, ':'))
1340             list ($column, $heading) = explode(':', $column, 2);
1341
1342         // FIXME: these column types have hooks (objects) elsewhere
1343         // Omitting this warning should be overridable by the extension
1344         if (!isset($this->_types[$column])) {
1345             $silently_ignore = array('numbacklinks',
1346                 'rating', 'ratingvalue',
1347                 'coagreement', 'minmisery',
1348                 'averagerating', 'top3recs',
1349                 'relation', 'linkto');
1350             if (!in_array($column, $silently_ignore))
1351                 trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
1352             return false;
1353         }
1354         if (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
1355             // FIXME: anon users might rate and see ratings also.
1356             // Defer this logic to the plugin.
1357             if ($column == 'rating' and !$GLOBALS['request']->_user->isSignedIn()) {
1358                 return false;
1359             }
1360         }
1361
1362         $this->addColumnObject($this->_types[$column]);
1363
1364         return true;
1365     }
1366
1367     /**
1368      * Add a column to this PageList, given a column object.
1369      *
1370      * @param $col object   An object derived from _PageList_Column.
1371      **/
1372     function addColumnObject($col)
1373     {
1374         if (is_array($col)) { // custom column object
1375             $params =& $col;
1376             $class_name = array_shift($params);
1377             $params[3] =& $this;
1378             $col = new $class_name($params);
1379         }
1380         $heading = $col->getHeading();
1381         if (!empty($heading))
1382             $col->setHeading($heading);
1383
1384         $this->_columns[] = $col;
1385         $this->_columnsMap[$col->_field] = count($this->_columns); // start with 1
1386     }
1387
1388     /**
1389      * Compare _PageList_Page objects.
1390      **/
1391     function _pageCompare(&$a, &$b)
1392     {
1393         if (empty($this->_sortby) or count($this->_sortby) == 0) {
1394             // No columns to sort by
1395             return 0;
1396         } else {
1397             $pagea = $this->_getPageFromHandle($a); // If a string, convert to page
1398             assert(isa($pagea, 'WikiDB_Page'));
1399             $pageb = $this->_getPageFromHandle($b); // If a string, convert to page
1400             assert(isa($pageb, 'WikiDB_Page'));
1401             foreach ($this->_sortby as $colNum => $direction) {
1402                 // get column type object
1403                 if (!is_int($colNum)) { // or column fieldname
1404                     if (isset($this->_columnsMap[$colNum]))
1405                         $col = $this->_columns[$this->_columnsMap[$colNum] - 1];
1406                     elseif (isset($this->_types[$colNum]))
1407                         $col = $this->_types[$colNum];
1408                 }
1409                 if (empty($col)) {
1410                     return 0;
1411                 }
1412                 assert(isset($col));
1413                 $revision_handle = false;
1414                 $aval = $col->_getSortableValue($pagea, $revision_handle);
1415                 $revision_handle = false;
1416                 $bval = $col->_getSortableValue($pageb, $revision_handle);
1417
1418                 $cmp = $col->_compare($aval, $bval);
1419                 if ($direction === "-") // Reverse the sense of the comparison
1420                     $cmp *= -1;
1421
1422                 if ($cmp !== 0)
1423                     // This is the first comparison that is not equal-- go with it
1424                     return $cmp;
1425             }
1426             return 0;
1427         }
1428     }
1429
1430     /**
1431      * Put pages in order according to the sortby arg, if given
1432      * If the sortby cols are already sorted by the DB call, don't do usort.
1433      * TODO: optimize for multiple sortable cols
1434      */
1435     function _sortPages()
1436     {
1437         if (count($this->_sortby) > 0) {
1438             $need_sort = $this->_options['dosort'];
1439             if (!$need_sort)
1440                 foreach ($this->_sortby as $col => $dir) {
1441                     if (!$this->sortby($col, 'db'))
1442                         $need_sort = true;
1443                 }
1444             if ($need_sort) { // There are some columns to sort by
1445                 // TODO: consider nopage
1446                 usort($this->_pages, array($this, '_pageCompare'));
1447             }
1448         }
1449     }
1450
1451     function limit($limit)
1452     {
1453         if (is_array($limit)) {
1454             list($from, $count) = $limit;
1455             if ((!empty($from) && !is_numeric($from)) or (!empty($count) && !is_numeric($count))) {
1456                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1457             }
1458             return $limit;
1459         }
1460         if (strstr($limit, ',')) {
1461             list($from, $limit) = explode(',', $limit);
1462             if ((!empty($from) && !is_numeric($from)) or (!empty($limit) && !is_numeric($limit))) {
1463                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1464             }
1465             return array($from, $limit);
1466         } else {
1467             if (!empty($limit) && !is_numeric($limit)) {
1468                 return $this->error(_("Illegal 'limit' argument: must be numeric"));
1469             }
1470             return array(0, $limit);
1471         }
1472     }
1473
1474     function pagingTokens($numrows = false, $ncolumns = false, $limit = false)
1475     {
1476         if ($numrows === false)
1477             $numrows = $this->getTotal();
1478         if ($limit === false)
1479             $limit = $this->_options['limit'];
1480         if ($ncolumns === false)
1481             $ncolumns = count($this->_columns);
1482
1483         list($offset, $pagesize) = $this->limit($limit);
1484         if (!$pagesize or
1485             (!$offset and $numrows < $pagesize) or
1486             (($offset + $pagesize) < 0)
1487         )
1488             return false;
1489
1490         $request = &$GLOBALS['request'];
1491         $pagename = $request->getArg('pagename');
1492         $defargs = array_merge(array('id' => $this->id), $request->args);
1493         if (USE_PATH_INFO) unset($defargs['pagename']);
1494         if (isset($defargs['action']) and ($defargs['action'] == 'browse')) {
1495             unset($defargs['action']);
1496         }
1497         $prev = $defargs;
1498
1499         $tokens = array();
1500         $tokens['PREV'] = false;
1501         $tokens['PREV_LINK'] = "";
1502         $tokens['COLS'] = $ncolumns;
1503         $tokens['COUNT'] = $numrows;
1504         $tokens['OFFSET'] = $offset;
1505         $tokens['SIZE'] = $pagesize;
1506         $tokens['NUMPAGES'] = (int)ceil($numrows / $pagesize);
1507         $tokens['ACTPAGE'] = (int)ceil(($offset / $pagesize) + 1);
1508         if ($offset > 0) {
1509             $prev['limit'] = max(0, $offset - $pagesize) . ",$pagesize";
1510             $prev['count'] = $numrows;
1511             $tokens['LIMIT'] = $prev['limit'];
1512             $tokens['PREV'] = true;
1513             $tokens['PREV_LINK'] = WikiURL($pagename, $prev);
1514             $prev['limit'] = "0,$pagesize"; // FIRST_LINK
1515             $tokens['FIRST_LINK'] = WikiURL($pagename, $prev);
1516         }
1517         $next = $defargs;
1518         $tokens['NEXT'] = false;
1519         $tokens['NEXT_LINK'] = "";
1520         if (($offset + $pagesize) < $numrows) {
1521             $next['limit'] = min($offset + $pagesize, $numrows - $pagesize)
1522                 . ",$pagesize";
1523             $next['count'] = $numrows;
1524             $tokens['LIMIT'] = $next['limit'];
1525             $tokens['NEXT'] = true;
1526             $tokens['NEXT_LINK'] = WikiURL($pagename, $next);
1527             $next['limit'] = $numrows - $pagesize . ",$pagesize"; // LAST_LINK
1528             $tokens['LAST_LINK'] = WikiURL($pagename, $next);
1529         }
1530         return $tokens;
1531     }
1532
1533     // make a table given the caption
1534     function _generateTable($caption)
1535     {
1536         if (count($this->_sortby) > 0) $this->_sortPages();
1537
1538         // wikiadminutils hack. that's a way to pagelist non-pages
1539         $rows = isset($this->_rows) ? $this->_rows : array();
1540         $i = 0;
1541         $count = $this->getTotal();
1542         $do_paging = (isset($this->_options['paging'])
1543             and !empty($this->_options['limit'])
1544                 and $count
1545                     and $this->_options['paging'] != 'none');
1546         if ($do_paging) {
1547             $tokens = $this->pagingTokens($count,
1548                 count($this->_columns),
1549                 $this->_options['limit']);
1550             if ($tokens and !empty($this->_options['slice']))
1551                 $this->_pages = array_slice($this->_pages, $tokens['OFFSET'], $tokens['SIZE']);
1552         }
1553         foreach ($this->_pages as $pagenum => $page) {
1554             $one_row = $this->_renderPageRow($page, $i++);
1555             $rows[] = $one_row;
1556         }
1557         $table = HTML::table(array('class' => 'fullwidth pagelist'));
1558         if ($caption) {
1559             $table->pushContent(HTML::caption(array('align' => 'top'), $caption));
1560         }
1561
1562         $row = HTML::tr();
1563         $i = 1; // start with 1!
1564         foreach ($this->_columns as $col) {
1565             $heading = $col->button_heading($this, $i);
1566             if ($do_paging
1567                 and isset($col->_field)
1568                     and $col->_field == 'pagename'
1569                         and ($maxlen = $this->maxLen())
1570             ) {
1571             }
1572             $row->pushContent($heading);
1573             $i++;
1574         }
1575         $table->pushContent(HTML::colgroup(array('span' => count($this->_columns))));
1576         if ($do_paging) {
1577             if ($tokens === false) {
1578                 $table->pushContent(HTML::thead($row),
1579                     HTML::tbody(false, $rows));
1580                 return $table;
1581             }
1582
1583             $paging = Template("pagelink", $tokens);
1584             if ($this->_options['paging'] != 'bottom')
1585                 $table->pushContent(HTML::thead($paging));
1586             if ($this->_options['paging'] != 'top')
1587                 $table->pushContent(HTML::tfoot($paging));
1588             $table->pushContent(HTML::tbody(false, HTML($row, $rows)));
1589             return $table;
1590         } else {
1591             $table->pushContent(HTML::thead($row),
1592                 HTML::tbody(false, $rows));
1593             return $table;
1594         }
1595     }
1596
1597     /* recursive stack for private sublist options (azhead, cols) */
1598     function _saveOptions($opts)
1599     {
1600         $stack = array('pages' => $this->_pages);
1601         foreach ($opts as $k => $v) {
1602             $stack[$k] = $this->_options[$k];
1603             $this->_options[$k] = $v;
1604         }
1605         if (empty($this->_stack))
1606             $this->_stack = new Stack();
1607         $this->_stack->push($stack);
1608     }
1609
1610     function _restoreOptions()
1611     {
1612         assert($this->_stack);
1613         $stack = $this->_stack->pop();
1614         $this->_pages = $stack['pages'];
1615         unset($stack['pages']);
1616         foreach ($stack as $k => $v) {
1617             $this->_options[$k] = $v;
1618         }
1619     }
1620
1621     // 'cols'   - split into several columns
1622     // 'azhead' - support <h3> grouping into initials
1623     // 'ordered' - OL or UL list (not yet inherited to all plugins)
1624     // 'comma'  - condensed comma-list only, 1: no links, >1: with links
1625     // FIXME: only unique list entries, esp. with nopage
1626     function _generateList($caption = '')
1627     {
1628         if (empty($this->_pages)) return; // stop recursion
1629         if (!isset($this->_options['listtype']))
1630             $this->_options['listtype'] = '';
1631         foreach ($this->_pages as $pagenum => $page) {
1632             $one_row = $this->_renderPageRow($page);
1633             $rows[] = array('header' => WikiLink($page), 'render' => $one_row);
1634         }
1635         $out = HTML();
1636         if ($caption) {
1637             $out->pushContent(HTML::p($caption));
1638         }
1639
1640         // Semantic Search et al: only unique list entries, esp. with nopage
1641         if (!is_array($this->_pages[0]) and is_string($this->_pages[0])) {
1642             $this->_pages = array_unique($this->_pages);
1643         }
1644         if (count($this->_sortby) > 0) $this->_sortPages();
1645         $count = $this->getTotal();
1646         $do_paging = (isset($this->_options['paging'])
1647             and !empty($this->_options['limit'])
1648                 and $count
1649                     and $this->_options['paging'] != 'none');
1650         if ($do_paging) {
1651             $tokens = $this->pagingTokens($count,
1652                 count($this->_columns),
1653                 $this->_options['limit']);
1654             if ($tokens) {
1655                 $paging = Template("pagelink", $tokens);
1656                 $out->pushContent(HTML::table(array('width' => '100%'), $paging));
1657             }
1658         }
1659
1660         if (!empty($this->_options['limit']) and !empty($this->_options['slice'])) {
1661             list($offset, $count) = $this->limit($this->_options['limit']);
1662         } else {
1663             $offset = 0;
1664             $count = count($this->_pages);
1665         }
1666         // need a recursive switch here for the azhead and cols grouping.
1667         if (!empty($this->_options['cols']) and $this->_options['cols'] > 1) {
1668             $length = intval($count / ($this->_options['cols']));
1669             // If division does not give an integer, we need one more line
1670             // E.g. 13 pages to display in 3 columns.
1671             if (($length * ($this->_options['cols'])) != $count) {
1672                 $length += 1;
1673             }
1674             $width = sprintf("%d", 100 / $this->_options['cols']) . '%';
1675             $cols = HTML::tr(array('valign' => 'top'));
1676             for ($i = $offset; $i < $offset + $count; $i += $length) {
1677                 $this->_saveOptions(array('cols' => 0, 'paging' => 'none'));
1678                 $this->_pages = array_slice($this->_pages, $i, $length);
1679                 $cols->pushContent(HTML::td( /*array('width' => $width),*/
1680                     $this->_generateList()));
1681                 $this->_restoreOptions();
1682             }
1683             // speed up table rendering by defining colgroups
1684             $out->pushContent(HTML::table(HTML::colgroup
1685                 (array('span' => $this->_options['cols'], 'width' => $width)),
1686                 $cols));
1687             return $out;
1688         }
1689
1690         // Ignore azhead if not sorted by pagename
1691         if (!empty($this->_options['azhead'])
1692             and strstr($this->sortby($this->_options['sortby'], 'init'), "pagename")
1693         ) {
1694             $cur_h = substr($this->_pages[0]->getName(), 0, 1);
1695             $out->pushContent(HTML::h3($cur_h));
1696             // group those pages together with same $h
1697             $j = 0;
1698             for ($i = 0; $i < count($this->_pages); $i++) {
1699                 $page =& $this->_pages[$i];
1700                 $h = substr($page->getName(), 0, 1);
1701                 if ($h != $cur_h and $i > $j) {
1702                     $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j + 1));
1703                     $this->_pages = array_slice($this->_pages, $j, $i - $j);
1704                     $out->pushContent($this->_generateList());
1705                     $this->_restoreOptions();
1706                     $j = $i;
1707                     $out->pushContent(HTML::h3($h));
1708                     $cur_h = $h;
1709                 }
1710             }
1711             if ($i > $j) { // flush the rest
1712                 $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j + 1));
1713                 $this->_pages = array_slice($this->_pages, $j, $i - $j);
1714                 $out->pushContent($this->_generateList());
1715                 $this->_restoreOptions();
1716             }
1717             return $out;
1718         }
1719
1720         if ($this->_options['listtype'] == 'comma')
1721             $this->_options['comma'] = 2;
1722         if (!empty($this->_options['comma'])) {
1723             if ($this->_options['comma'] == 1)
1724                 $out->pushContent($this->_generateCommaListAsString());
1725             else
1726                 $out->pushContent($this->_generateCommaList($this->_options['comma']));
1727             return $out;
1728         }
1729
1730         if ($this->_options['listtype'] == 'ol') {
1731             if (empty($this->_options['ordered'])) {
1732                 $this->_options['ordered'] = $offset + 1;
1733             }
1734         } elseif ($this->_options['listtype'] == 'ul')
1735             $this->_options['ordered'] = 0;
1736         if ($this->_options['listtype'] == 'ol' and !empty($this->_options['ordered'])) {
1737             $list = HTML::ol(array('class' => 'pagelist',
1738                 'start' => $this->_options['ordered']));
1739         } elseif ($this->_options['listtype'] == 'dl') {
1740             $list = HTML::dl(array('class' => 'pagelist'));
1741         } else {
1742             $list = HTML::ul(array('class' => 'pagelist'));
1743         }
1744         $i = 0;
1745         //TODO: currently we ignore limit here and hope that the backend didn't ignore it. (BackLinks)
1746         if (!empty($this->_options['limit']))
1747             list($offset, $pagesize) = $this->limit($this->_options['limit']);
1748         else
1749             $pagesize = 0;
1750         foreach (array_reverse($rows) as $one_row) {
1751             $pagehtml = $one_row['render'];
1752             if (!$pagehtml) continue;
1753             $group = ($i++ / $this->_group_rows);
1754             //TODO: here we switch every row, in tables every third.
1755             //      unification or parametrized?
1756             $class = ($group % 2) ? 'oddrow' : 'evenrow';
1757             if ($this->_options['listtype'] == 'dl') {
1758                 $header = $one_row['header'];
1759                 $list->pushContent(HTML::dt(array('class' => $class), $header),
1760                     HTML::dd(array('class' => $class), $pagehtml));
1761             } else
1762                 $list->pushContent(HTML::li(array('class' => $class), $pagehtml));
1763             if ($pagesize and $i > $pagesize) break;
1764         }
1765         $out->pushContent($list);
1766         if ($do_paging and $tokens) {
1767             $out->pushContent(HTML::table(array('width' => '100%'), $paging));
1768         }
1769         return $out;
1770     }
1771
1772     // comma=1
1773     // Condense list without a href links: "Page1, Page2, ..."
1774     // Alternative $seperator = HTML::Raw(' &middot; ')
1775     // FIXME: only unique list entries, esp. with nopage
1776     function _generateCommaListAsString()
1777     {
1778         if (defined($this->_options['commasep']))
1779             $seperator = $this->_options['commasep'];
1780         else
1781             $seperator = ', ';
1782         $pages = array();
1783         foreach ($this->_pages as $pagenum => $page) {
1784             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1785                 $pages[] = is_string($s) ? $s : $s->asString();
1786         }
1787         return HTML(join($seperator, $pages));
1788     }
1789
1790     // comma=2
1791     // Normal WikiLink list.
1792     // Future: 1 = reserved for plain string (see above)
1793     //         2 and more => HTML link specialization?
1794     // FIXME: only unique list entries, esp. with nopage
1795     function _generateCommaList($style = false)
1796     {
1797         if (defined($this->_options['commasep']))
1798             $seperator = HTML::Raw($this->_options['commasep']);
1799         else
1800             $seperator = ', ';
1801         $html = HTML();
1802         $html->pushContent($this->_renderPageRow($this->_pages[0]));
1803         next($this->_pages);
1804         foreach ($this->_pages as $pagenum => $page) {
1805             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1806                 $html->pushContent($seperator, $s);
1807         }
1808         return $html;
1809     }
1810
1811     function _emptyList($caption)
1812     {
1813         $html = HTML();
1814         if ($caption) {
1815             $html->pushContent(HTML::p($caption));
1816         }
1817         if ($this->_messageIfEmpty)
1818             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
1819         return $html;
1820     }
1821
1822 }
1823
1824 /* List pages with checkboxes to select from.
1825  * The [Select] button toggles via Javascript flipAll
1826  */
1827
1828 class PageList_Selectable
1829     extends PageList
1830 {
1831
1832     function PageList_Selectable($columns = false, $exclude = '', $options = false)
1833     {
1834         if ($columns) {
1835             if (!is_array($columns))
1836                 $columns = explode(',', $columns);
1837             if (!in_array('checkbox', $columns))
1838                 array_unshift($columns, 'checkbox');
1839         } else {
1840             $columns = array('checkbox', 'pagename');
1841         }
1842         $this->PageList($columns, $exclude, $options);
1843     }
1844
1845     function addPageList($array)
1846     {
1847         while (list($pagename, $selected) = each($array)) {
1848             if ($selected) $this->addPageSelected((string)$pagename);
1849             $this->addPage((string)$pagename);
1850         }
1851     }
1852
1853     function addPageSelected($pagename)
1854     {
1855         $this->_selected[$pagename] = 1;
1856     }
1857 }
1858
1859 class PageList_Unselectable
1860     extends PageList
1861 {
1862
1863     function PageList_Unselectable($columns = false, $exclude = '', $options = false)
1864     {
1865         if ($columns) {
1866             if (!is_array($columns))
1867                 $columns = explode(',', $columns);
1868         } else {
1869             $columns = array('pagename');
1870         }
1871         $this->PageList($columns, $exclude, $options);
1872     }
1873
1874     function addPageList($array)
1875     {
1876         while (list($pagename, $selected) = each($array)) {
1877             if ($selected) $this->addPageSelected((string)$pagename);
1878             $this->addPage((string)$pagename);
1879         }
1880     }
1881
1882     function addPageSelected($pagename)
1883     {
1884         $this->_selected[$pagename] = 1;
1885     }
1886 }
1887
1888 // Local Variables:
1889 // mode: php
1890 // tab-width: 8
1891 // c-basic-offset: 4
1892 // c-hanging-comment-ender-p: nil
1893 // indent-tabs-mode: nil
1894 // End: