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