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