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