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