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