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