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