]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
notice uninitialized from
[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; $from = 0;
798         if (isa($page_iter->_iter, "WikiDB_backend_dbaBase_pageiter")) {
799             $limit = 0;
800         }
801         elseif (isset($this->_options['limit'])) { // extract from,count from limit
802             list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
803             $limit += $from;
804         } else {
805             $limit = 0;
806         }
807         while ($page = $page_iter->next()) {
808             $i++;       
809             if ($from and $i < $from) 
810                 continue;
811             if (!$limit or ($limit and $i < $limit))
812                 $this->addPage($page);
813         }
814         if (empty($this->_options['count']))
815             $this->_options['count'] = $i;
816     }
817
818     function addPageList (&$list) {
819         if (empty($list)) return;  // Protect reset from a null arg
820         if (isset($this->_options['limit'])) { // extract from,count from limit
821             list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
822             $limit += $from;
823         } else {
824             $limit = 0;
825         }
826         $i = 0;
827         foreach ($list as $page) {
828             $i++;       
829             if ($from and $i < $from) 
830                 continue;
831             if (!$limit or ($limit and $i < $limit)) {
832                 if (is_object($page)) $page = $page->_pagename;
833                 $this->addPage((string)$page);
834             }
835         }
836     }
837
838     function maxLen() {
839         global $request;
840         $dbi =& $request->getDbh();
841         if (isa($dbi,'WikiDB_SQL')) {
842             extract($dbi->_backend->_table_names);
843             $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl");
844             if (DB::isError($res) || empty($res)) return false;
845             else return $res;
846         } elseif (isa($dbi,'WikiDB_ADODB')) {
847             extract($dbi->_backend->_table_names);
848             $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl");
849             return $row ? $row[0] : false;
850         } else 
851             return false;
852     }
853
854     function getContent() {
855         // Note that the <caption> element wants inline content.
856         $caption = $this->getCaption();
857
858         if ($this->isEmpty())
859             return $this->_emptyList($caption);
860         elseif (isset($this->_options['listtype']) 
861                 and in_array($this->_options['listtype'], 
862                              array('ol','ul','comma','dl')))
863             return $this->_generateList($caption);
864         elseif (count($this->_columns) == 1)
865             return $this->_generateList($caption);
866         else
867             return $this->_generateTable($caption);
868     }
869
870     function printXML() {
871         PrintXML($this->getContent());
872     }
873
874     function asXML() {
875         return AsXML($this->getContent());
876     }
877     
878     /** 
879      * Handle sortby requests for the DB iterator and table header links.
880      * Prefix the column with + or - like "+pagename","-mtime", ...
881      *
882      * Supported actions: 
883      *   'init'       :   unify with predefined order. "pagename" => "+pagename"
884      *   'flip_order' :   "mtime" => "+mtime" => "-mtime" ...
885      *   'db'         :   "-pagename" => "pagename DESC"
886      *   'check'      :   
887      *
888      * Now all columns are sortable. (patch by DanFr)
889      * Some columns have native DB backend methods, some not.
890      */
891     function sortby ($column, $action, $valid_fields=false) {
892         global $request;
893
894         if (empty($column)) return '';
895         if (is_int($column)) {
896             $column = $this->_columns[$column - 1]->_field;
897             //$column = $col->_field;
898         }
899         //if (!is_string($column)) return '';
900         // support multiple comma-delimited sortby args: "+hits,+pagename"
901         // recursive concat
902         if (strstr($column, ',')) {
903             $result = ($action == 'check') ? true : array();
904             foreach (explode(',', $column) as $col) {
905                 if ($action == 'check')
906                     $result = $result && $this->sortby($col, $action, $valid_fields);
907                 else
908                     $result[] = $this->sortby($col, $action, $valid_fields);
909             }
910             // 'check' returns true/false for every col. return true if all are true. 
911             // i.e. the unsupported 'every' operator in functional languages.
912             if ($action == 'check')
913                 return $result;
914             else
915                 return join(",", $result);
916         }
917         if (substr($column,0,1) == '+') {
918             $order = '+'; $column = substr($column,1);
919         } elseif (substr($column,0,1) == '-') {
920             $order = '-'; $column = substr($column,1);
921         }
922         // default initial order: +pagename, -mtime, -hits
923         if (empty($order)) {
924             if (!empty($this->_sortby[$column]))
925                 $order = $this->_sortby[$column];
926             else {
927                 if (in_array($column, array('mtime','hits')))
928                     $order = '-';
929                 else
930                     $order = '+';
931             }
932         }
933         if ($action == 'get') {
934             return $order . $column;
935         } elseif ($action == 'flip_order') {
936             if (0 and DEBUG)
937                 trigger_error("flip $order $column ".$this->id,  E_USER_NOTICE); 
938             return ($order == '+' ? '-' : '+') . $column;
939         } elseif ($action == 'init') { // only allowed from PageList::PageList
940             if ($this->sortby($column, 'clicked')) {
941                 if (0 and DEBUG)
942                     trigger_error("clicked $order $column $this->id",  E_USER_NOTICE); 
943                 //$order = ($order == '+' ? '-' : '+'); // $this->sortby($sortby, 'flip_order');
944             }
945             $this->_sortby[$column] = $order; // forces show icon
946             return $order . $column;
947         } elseif ($action == 'check') {   // show icon?
948             //if specified via arg or if clicked
949             $show = (!empty($this->_sortby[$column]) or $this->sortby($column, 'clicked'));
950             if (0 and $show and DEBUG) {
951                 trigger_error("show $order $column ".$this->id, E_USER_NOTICE);
952             }
953             return $show;            
954         } elseif ($action == 'clicked') { // flip sort order?
955             global $request;
956             $arg = $request->getArg('sortby');
957             return ($arg
958                     and strstr($arg, $column)
959                     and (!isset($request->args['id']) 
960                          or $this->id == $request->getArg('id')));
961         } elseif ($action == 'db') {
962             // Performance enhancement: use native DB sort if possible.
963             if (($valid_fields and in_array($column, $valid_fields))
964                 or (method_exists($request->_dbi->_backend, 'sortable_columns')
965                     and (in_array($column, $request->_dbi->_backend->sortable_columns())))) {
966                 // omit this sort method from the _sortPages call at rendering
967                 // asc or desc: +pagename, -pagename
968                 return $column . ($order == '+' ? ' ASC' : ' DESC');
969             } else {
970                 return '';
971             }
972         }
973         return '';
974     }
975
976     /* Splits pagelist string into array.
977      * Test* or Test1,Test2
978      * Limitation: Doesn't split into comma-sep and then expand wildcards.
979      * "Test1*,Test2*" is expanded into TextSearch "Test1* Test2*"
980      *
981      * echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
982      */
983     function explodePageList($input, $include_empty=false, $sortby='', 
984                              $limit='', $exclude='') 
985     {
986         if (empty($input)) return array();
987         if (is_array($input)) return $input;
988         // expand wildcards from list of all pages
989         if (preg_match('/[\?\*]/', $input) or substr($input,0,1) == "^") {
990             include_once("lib/TextSearchQuery.php");
991             $search = new TextSearchQuery(str_replace(",", " ", $input), true, 
992                                          (substr($input,0,1) == "^") ? 'posix' : 'glob'); 
993             $dbi = $GLOBALS['request']->getDbh();
994             $iter = $dbi->titleSearch($search, $sortby, $limit, $exclude);
995             $pages = array();
996             while ($pagehandle = $iter->next()) {
997                 $pages[] = $pagehandle->getName();
998             }
999             return $pages;
1000             /*
1001             //TODO: need an SQL optimization here
1002             $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, 
1003                                                 $exclude);
1004             while ($pagehandle = $allPagehandles->next()) {
1005                 $allPages[] = $pagehandle->getName();
1006             }
1007             return explodeList($input, $allPages);
1008             */
1009         } else {
1010             //TODO: do the sorting, normally not needed if used for exclude only
1011             return explode(',', $input);
1012         }
1013     }
1014
1015     // TODO: optimize getTotal => store in count
1016     function allPagesByAuthor($wildcard, $include_empty=false, $sortby='', 
1017                               $limit='', $exclude='') 
1018     {
1019         $dbi = $GLOBALS['request']->getDbh();
1020         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1021         $allPages = array();
1022         if ($wildcard === '[]') {
1023             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1024             if (!$wildcard) return $allPages;
1025         }
1026         $do_glob = preg_match('/[\?\*]/', $wildcard);
1027         while ($pagehandle = $allPagehandles->next()) {
1028             $name = $pagehandle->getName();
1029             $author = $pagehandle->getAuthor();
1030             if ($author) {
1031                 if ($do_glob) {
1032                     if (glob_match($wildcard, $author))
1033                         $allPages[] = $name;
1034                 } elseif ($wildcard == $author) {
1035                       $allPages[] = $name;
1036                 }
1037             }
1038             // TODO: purge versiondata_cache
1039         }
1040         return $allPages;
1041     }
1042
1043     function allPagesByOwner($wildcard, $include_empty=false, $sortby='', 
1044                              $limit='', $exclude='') {
1045         $dbi = $GLOBALS['request']->getDbh();
1046         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1047         $allPages = array();
1048         if ($wildcard === '[]') {
1049             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1050             if (!$wildcard) return $allPages;
1051         }
1052         $do_glob = preg_match('/[\?\*]/', $wildcard);
1053         while ($pagehandle = $allPagehandles->next()) {
1054             $name = $pagehandle->getName();
1055             $owner = $pagehandle->getOwner();
1056             if ($owner) {
1057                 if ($do_glob) {
1058                     if (glob_match($wildcard, $owner))
1059                         $allPages[] = $name;
1060                 } elseif ($wildcard == $owner) {
1061                       $allPages[] = $name;
1062                 }
1063             }
1064         }
1065         return $allPages;
1066     }
1067
1068     function allPagesByCreator($wildcard, $include_empty=false, $sortby='', 
1069                                $limit='', $exclude='') {
1070         $dbi = $GLOBALS['request']->getDbh();
1071         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1072         $allPages = array();
1073         if ($wildcard === '[]') {
1074             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1075             if (!$wildcard) return $allPages;
1076         }
1077         $do_glob = preg_match('/[\?\*]/', $wildcard);
1078         while ($pagehandle = $allPagehandles->next()) {
1079             $name = $pagehandle->getName();
1080             $creator = $pagehandle->getCreator();
1081             if ($creator) {
1082                 if ($do_glob) {
1083                     if (glob_match($wildcard, $creator))
1084                         $allPages[] = $name;
1085                 } elseif ($wildcard == $creator) {
1086                       $allPages[] = $name;
1087                 }
1088             }
1089         }
1090         return $allPages;
1091     }
1092
1093     // UserPages are pages NOT created by "The PhpWiki programming team"
1094     function allUserPages($include_empty=false, $sortby='',
1095                           $limit='', $exclude='') {
1096         $dbi = $GLOBALS['request']->getDbh();
1097         $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1098         $allPages = array();
1099         while ($pagehandle = $allPagehandles->next()) {
1100             $name = $pagehandle->getName();
1101             $creator = $pagehandle->getCreator();
1102             if ($creator !== _("The PhpWiki programming team")) {
1103                  $allPages[] = $name;
1104             }
1105         }
1106         return $allPages;
1107     }
1108
1109     ////////////////////
1110     // private
1111     ////////////////////
1112     /** Plugin and theme hooks: 
1113      *  If the pageList is initialized with $options['types'] these types are also initialized, 
1114      *  overriding the standard types.
1115      */
1116     function _initAvailableColumns() {
1117         global $customPageListColumns;
1118         $standard_types =
1119             array(
1120                   'content'
1121                   => new _PageList_Column_content('rev:content', _("Content")),
1122                   // new: plugin specific column types initialised by the relevant plugins
1123                   /*
1124                   'hi_content' // with highlighted search for SearchReplace
1125                   => new _PageList_Column_content('rev:hi_content', _("Content")),
1126                   'remove'
1127                   => new _PageList_Column_remove('remove', _("Remove")),
1128                   // initialised by the plugin
1129                   'renamed_pagename'
1130                   => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
1131                   'perm'
1132                   => new _PageList_Column_perm('perm', _("Permission")),
1133                   'acl'
1134                   => new _PageList_Column_acl('acl', _("ACL")),
1135                   */
1136                   'checkbox'
1137                   => new _PageList_Column_checkbox('p', _("All")),
1138                   'pagename'
1139                   => new _PageList_Column_pagename,
1140                   'mtime'
1141                   => new _PageList_Column_time('rev:mtime', _("Last Modified")),
1142                   'hits'
1143                   => new _PageList_Column('hits', _("Hits"), 'right'),
1144                   'size'
1145                   => new _PageList_Column_size('rev:size', _("Size"), 'right'),
1146                                               /*array('align' => 'char', 'char' => ' ')*/
1147                   'summary'
1148                   => new _PageList_Column('rev:summary', _("Last Summary")),
1149                   'version'
1150                   => new _PageList_Column_version('rev:version', _("Version"),
1151                                                  'right'),
1152                   'author'
1153                   => new _PageList_Column_author('rev:author', _("Last Author")),
1154                   'owner'
1155                   => new _PageList_Column_owner('author_id', _("Owner")),
1156                   'creator'
1157                   => new _PageList_Column_creator('author_id', _("Creator")),
1158                   /*
1159                   'group'
1160                   => new _PageList_Column_author('group', _("Group")),
1161                   */
1162                   'locked'
1163                   => new _PageList_Column_bool('locked', _("Locked"),
1164                                                _("locked")),
1165                   'minor'
1166                   => new _PageList_Column_bool('rev:is_minor_edit',
1167                                                _("Minor Edit"), _("minor")),
1168                   'markup'
1169                   => new _PageList_Column('rev:markup', _("Markup")),
1170                   // 'rating' initialised by the wikilens theme hook: addPageListColumn
1171                   /*
1172                   'rating'
1173                   => new _PageList_Column_rating('rating', _("Rate")),
1174                   */
1175                   );
1176         if (empty($this->_types))
1177             $this->_types = array();
1178         // add plugin specific pageList columns, initialized by $options['types']
1179         $this->_types = array_merge($standard_types, $this->_types);
1180         // add theme custom specific pageList columns: 
1181         //   set the 4th param as the current pagelist object.
1182         if (!empty($customPageListColumns)) {
1183             foreach ($customPageListColumns as $column => $params) {
1184                 $class_name = array_shift($params);
1185                 $params[3] =& $this;
1186                 // ref to a class does not work with php-4
1187                 $this->_types[$column] = new $class_name($params);
1188             }
1189         }
1190     }
1191
1192     function getOption($option) {
1193         if (array_key_exists($option, $this->_options)) {
1194             return $this->_options[$option];
1195         }
1196         else {
1197             return null;
1198         }
1199     }
1200
1201     /**
1202      * Add a column to this PageList, given a column name.
1203      * The name is a type, and optionally has a : and a label. Examples:
1204      *
1205      *   pagename
1206      *   pagename:This page
1207      *   mtime
1208      *   mtime:Last modified
1209      *
1210      * If this function is called multiple times for the same type, the
1211      * column will only be added the first time, and ignored the succeeding times.
1212      * If you wish to add multiple columns of the same type, use addColumnObject().
1213      *
1214      * @param column name
1215      * @return  true if column is added, false otherwise
1216      */
1217     function _addColumn ($column) {
1218         
1219         if (isset($this->_columns_seen[$column]))
1220             return false;       // Already have this one.
1221         if (!isset($this->_types[$column]))
1222             $this->_initAvailableColumns();
1223         $this->_columns_seen[$column] = true;
1224
1225         if (strstr($column, ':'))
1226             list ($column, $heading) = explode(':', $column, 2);
1227
1228         // FIXME: these column types have hooks (objects) elsewhere
1229         // Omitting this warning should be overridable by the extension
1230         if (!isset($this->_types[$column])) {
1231             $silently_ignore = array('numbacklinks',
1232                                      'rating','ratingvalue',
1233                                      'coagreement', 'minmisery',
1234                                      /*'prediction',*/
1235                                      'averagerating', 'top3recs', 
1236                                      'relation', 'linkto');
1237             if (!in_array($column, $silently_ignore))
1238                 trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
1239             return false;
1240         }
1241         // FIXME: anon users might rate and see ratings also. 
1242         // Defer this logic to the plugin.
1243         if ($column == 'rating' and !$GLOBALS['request']->_user->isSignedIn())
1244             return false;
1245
1246         $this->addColumnObject($this->_types[$column]);
1247
1248         return true;
1249     }
1250
1251     /**
1252      * Add a column to this PageList, given a column object.
1253      *
1254      * @param $col object   An object derived from _PageList_Column.
1255      **/
1256     function addColumnObject($col) {
1257         if (is_array($col)) {// custom column object
1258             $params =& $col;
1259             $class_name = array_shift($params);
1260             $params[3] =& $this;
1261             $col = new $class_name($params);
1262         }
1263         $heading = $col->getHeading();
1264         if (!empty($heading))
1265             $col->setHeading($heading);
1266
1267         $this->_columns[] = $col;
1268         $this->_columnsMap[$col->_field] = count($this->_columns); // start with 1
1269     }
1270
1271     /**
1272      * Compare _PageList_Page objects.
1273      **/
1274     function _pageCompare(&$a, &$b) {
1275         if (empty($this->_sortby) or count($this->_sortby) == 0) {
1276             // No columns to sort by
1277             return 0;
1278         }
1279         else {
1280             $pagea = $this->_getPageFromHandle($a);  // If a string, convert to page
1281             assert(isa($pagea, 'WikiDB_Page'));
1282             $pageb = $this->_getPageFromHandle($b);  // If a string, convert to page
1283             assert(isa($pageb, 'WikiDB_Page'));
1284             foreach ($this->_sortby as $colNum => $direction) {
1285                 // get column type object
1286                 if (!is_int($colNum)) { // or column fieldname
1287                     if (isset($this->_columnsMap[$colNum]))
1288                         $col = $this->_columns[$this->_columnsMap[$colNum] - 1];
1289                     elseif (isset($this->_types[$colNum]))
1290                         $col = $this->_types[$colNum];
1291                 }
1292
1293                 assert(isset($col));
1294                 $revision_handle = false;
1295                 $aval = $col->_getSortableValue($pagea, $revision_handle);
1296                 $revision_handle = false;
1297                 $bval = $col->_getSortableValue($pageb, $revision_handle);
1298
1299                 $cmp = $col->_compare($aval, $bval);
1300                 if ($direction === "-")  // Reverse the sense of the comparison
1301                     $cmp *= -1;
1302
1303                 if ($cmp !== 0)
1304                     // This is the first comparison that is not equal-- go with it
1305                     return $cmp;
1306             }
1307             return 0;
1308         }
1309     }
1310
1311     /**
1312      * Put pages in order according to the sortby arg, if given
1313      * If the sortby cols are already sorted by the DB call, don't do usort.
1314      * TODO: optimize for multiple sortable cols
1315      */
1316     function _sortPages() {
1317         if (count($this->_sortby) > 0) {
1318             $need_sort = $this->_options['dosort'];
1319             if (!$need_sort)
1320               foreach ($this->_sortby as $col => $dir) {
1321                 if (! $this->sortby($col, 'db'))
1322                     $need_sort = true;
1323               }
1324             if ($need_sort) { // There are some columns to sort by
1325                 // TODO: consider nopage
1326                 usort($this->_pages, array($this, '_pageCompare'));
1327             }
1328         }
1329         //unset($GLOBALS['PhpWiki_pagelist']);
1330     }
1331
1332     function limit($limit) {
1333         if (is_array($limit)) return $limit;
1334         if (strstr($limit, ','))
1335             return split(',', $limit);
1336         else
1337             return array(0, $limit);
1338     }
1339
1340     function pagingTokens($numrows = false, $ncolumns = false, $limit = false) {
1341         if ($numrows === false)
1342             $numrows = $this->getTotal();
1343         if ($limit === false)
1344             $limit = $this->_options['limit'];
1345         if ($ncolumns === false)
1346             $ncolumns = count($this->_columns);
1347
1348         list($offset, $pagesize) = $this->limit($limit);
1349         if (!$pagesize or
1350             (!$offset and $numrows < $pagesize) or
1351             (($offset + $pagesize) < 0))
1352             return false;
1353
1354         $request = &$GLOBALS['request'];
1355         $pagename = $request->getArg('pagename');
1356         $defargs = array_merge(array('id' => $this->id), $request->args);
1357         if (USE_PATH_INFO) unset($defargs['pagename']);
1358         if (isset($defargs['action']) and ($defargs['action'] == 'browse')) {
1359             unset($defargs['action']);
1360         }
1361         $prev = $defargs;
1362
1363         $tokens = array();
1364         $tokens['PREV'] = false; $tokens['PREV_LINK'] = "";
1365         $tokens['COLS'] = $ncolumns;
1366         $tokens['COUNT'] = $numrows; 
1367         $tokens['OFFSET'] = $offset; 
1368         $tokens['SIZE'] = $pagesize;
1369         $tokens['NUMPAGES'] = (int) ceil($numrows / $pagesize);
1370         $tokens['ACTPAGE'] = (int) ceil(($offset / $pagesize)+1);
1371         if ($offset > 0) {
1372             $prev['limit'] = max(0, $offset - $pagesize) . ",$pagesize";
1373             $prev['count'] = $numrows;
1374             $tokens['LIMIT'] = $prev['limit'];
1375             $tokens['PREV'] = true;
1376             $tokens['PREV_LINK'] = WikiURL($pagename, $prev);
1377             $prev['limit'] = "0,$pagesize";
1378             $tokens['FIRST_LINK'] = WikiURL($pagename, $prev);
1379         }
1380         $next = $defargs;
1381         $tokens['NEXT'] = false; $tokens['NEXT_LINK'] = "";
1382         if (($offset + $pagesize) < $numrows) {
1383             $next['limit'] = min($offset + $pagesize, $numrows - $pagesize) . ",$pagesize";
1384             $next['count'] = $numrows;
1385             $tokens['LIMIT'] = $next['limit'];
1386             $tokens['NEXT'] = true;
1387             $tokens['NEXT_LINK'] = WikiURL($pagename, $next);
1388             $next['limit'] = $numrows - $pagesize . ",$pagesize";
1389             $tokens['LAST_LINK'] = WikiURL($pagename, $next);
1390         }
1391         return $tokens;
1392     }
1393     
1394     // make a table given the caption
1395     function _generateTable($caption) {
1396         if (count($this->_sortby) > 0) $this->_sortPages();
1397         
1398         // wikiadminutils hack. that's a way to pagelist non-pages
1399         $rows = isset($this->_rows) ? $this->_rows : array();
1400         $i = 0;
1401         $count = $this->getTotal();
1402         $do_paging = ( isset($this->_options['paging']) 
1403                        and !empty($this->_options['limit']) 
1404                        and $count 
1405                        and $this->_options['paging'] != 'none' );
1406         if ($do_paging) {
1407             $tokens = $this->pagingTokens($count, 
1408                                            count($this->_columns), 
1409                                            $this->_options['limit']);
1410             if ($tokens)                               
1411                 $this->_pages = array_slice($this->_pages, $tokens['OFFSET'], $tokens['COUNT']);
1412         }
1413         foreach ($this->_pages as $pagenum => $page) {
1414             $rows[] = $this->_renderPageRow($page, $i++);
1415         }
1416         $table = HTML::table(array('cellpadding' => 0,
1417                                    'cellspacing' => 1,
1418                                    'border'      => 0,
1419                                    'width'       => '100%', 
1420                                    'class'       => 'pagelist', 
1421                                    ));
1422         if ($caption) {
1423             $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
1424         }
1425
1426         //Warning: This is quite fragile. It depends solely on a private variable
1427         //         in ->_addColumn()
1428         if (!empty($this->_columns_seen['checkbox'])) {
1429             $table->pushContent($this->_jsFlipAll());
1430         }
1431
1432         $row = HTML::tr();
1433         $table_summary = array();
1434         $i = 1; // start with 1!
1435         foreach ($this->_columns as $col) {
1436             $heading = $col->button_heading($this, $i);
1437             if ( $do_paging 
1438                  and isset($col->_field) 
1439                  and $col->_field == 'pagename' 
1440                  and ($maxlen = $this->maxLen())) {
1441                // $heading->setAttr('width', $maxlen * 7);
1442             }
1443             $row->pushContent($heading);
1444             if (is_string($col->getHeading()))
1445                 $table_summary[] = $col->getHeading();
1446             $i++;
1447         }
1448         // Table summary for non-visual browsers.
1449         $table->setAttr('summary', sprintf(_("Columns: %s."), 
1450                                            join(", ", $table_summary)));
1451         $table->pushContent(HTML::colgroup(array('span' => count($this->_columns))));
1452         if ( $do_paging ) {
1453             if ($tokens === false) {
1454                 $table->pushContent(HTML::thead($row),
1455                                     HTML::tbody(false, $rows));
1456                 return $table;
1457             }
1458
1459             $paging = Template("pagelink", $tokens);
1460             if ($this->_options['paging'] != 'bottom')
1461                 $table->pushContent(HTML::thead($paging));
1462             if ($this->_options['paging'] != 'top')
1463                 $table->pushContent(HTML::tfoot($paging));
1464             $table->pushContent(HTML::tbody(false, HTML($row, $rows)));
1465             return $table;
1466         } else {
1467             $table->pushContent(HTML::thead($row),
1468                                 HTML::tbody(false, $rows));
1469             return $table;
1470         }
1471     }
1472
1473     function _jsFlipAll() {
1474       return JavaScript("
1475 function flipAll(formObj) {
1476   var isFirstSet = -1;
1477   for (var i=0; i < formObj.length; i++) {
1478       fldObj = formObj.elements[i];
1479       if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,2) == 'p[')) { 
1480          if (isFirstSet == -1)
1481            isFirstSet = (fldObj.checked) ? true : false;
1482          fldObj.checked = (isFirstSet) ? false : true;
1483        }
1484    }
1485 }");
1486     }
1487
1488     /* recursive stack for private sublist options (azhead, cols) */
1489     function _saveOptions($opts) {
1490         $stack = array('pages' => $this->_pages);
1491         foreach ($opts as $k => $v) {
1492             $stack[$k] = $this->_options[$k];
1493             $this->_options[$k] = $v;
1494         }
1495         if (empty($this->_stack))
1496             $this->_stack = new Stack();
1497         $this->_stack->push($stack);
1498     }
1499     function _restoreOptions() {
1500         assert($this->_stack);
1501         $stack = $this->_stack->pop();
1502         $this->_pages = $stack['pages'];
1503         unset($stack['pages']);
1504         foreach ($stack as $k => $v) {
1505             $this->_options[$k] = $v;
1506         }
1507     }
1508
1509     // 'cols'   - split into several columns
1510     // 'azhead' - support <h3> grouping into initials
1511     // 'ordered' - OL or UL list (not yet inherited to all plugins)
1512     // 'comma'  - condensed comma-list only, 1: no links, >1: with links
1513     // FIXME: only unique list entries, esp. with nopage
1514     function _generateList($caption='') {
1515         if (empty($this->_pages)) return; // stop recursion
1516         if (!isset($this->_options['listtype'])) 
1517             $this->_options['listtype'] = '';
1518         $out = HTML();
1519         if ($caption)
1520             $out->pushContent(HTML::p($caption));
1521         // Semantic Search et al: only unique list entries, esp. with nopage
1522         if (!is_array($this->_pages[0]) and is_string($this->_pages[0])) {
1523             $this->_pages = array_unique($this->_pages);
1524         }
1525         if (count($this->_sortby) > 0) $this->_sortPages();
1526         $count = $this->getTotal();
1527         $do_paging = ( isset($this->_options['paging']) 
1528                        and !empty($this->_options['limit']) 
1529                        and $count 
1530                        and $this->_options['paging'] != 'none' );
1531         if ( $do_paging ) {
1532             $tokens = $this->pagingTokens($count, 
1533                                           count($this->_columns), 
1534                                           $this->_options['limit']);
1535             if ($tokens) {
1536                 $paging = Template("pagelink", $tokens);
1537                 $out->pushContent(HTML::table(array('width'=>'50%'), $paging));
1538             }
1539         }
1540
1541         // need a recursive switch here for the azhead and cols grouping.
1542         if (!empty($this->_options['cols']) and $this->_options['cols'] > 1) {
1543             $count = count($this->_pages);
1544             $length = $count / $this->_options['cols'];
1545             $width = sprintf("%d", 100 / $this->_options['cols']).'%';
1546             $cols = HTML::tr(array('valign' => 'top'));
1547             for ($i=0; $i < $count; $i += $length) {
1548                 $this->_saveOptions(array('cols' => 0, 'paging' => 'none'));
1549                 $this->_pages = array_slice($this->_pages, $i, $length);
1550                 $cols->pushContent(HTML::td(/*array('width' => $width),*/ 
1551                                             $this->_generateList()));
1552                 $this->_restoreOptions();
1553             }
1554             // speed up table rendering by defining colgroups
1555             $out->pushContent(HTML::table(HTML::colgroup(array('span' => $this->_options['cols'],
1556                                                                'width' => $width)),
1557                                           $cols));
1558             return $out;
1559         }
1560         
1561         // Ignore azhead if not sorted by pagename
1562         if (!empty($this->_options['azhead']) 
1563             and strstr($this->sortby($this->_options['sortby'], 'init'), "pagename")
1564             )
1565         {
1566             $cur_h = substr($this->_pages[0]->getName(), 0, 1);
1567             $out->pushContent(HTML::h3($cur_h));
1568             // group those pages together with same $h
1569             $j = 0;
1570             for ($i=0; $i < count($this->_pages); $i++) {
1571                 $page =& $this->_pages[$i];
1572                 $h = substr($page->getName(), 0, 1);
1573                 if ($h != $cur_h and $i > $j) {
1574                     $this->_saveOptions(array('cols' => 0, 'azhead' => 0));
1575                     $this->_pages = array_slice($this->_pages, $j, $i - $j);
1576                     $out->pushContent($this->_generateList());
1577                     $this->_restoreOptions();
1578                     $j = $i;
1579                     $out->pushContent(HTML::h3($h));
1580                     $cur_h = $h;
1581                 }
1582             }
1583             if ($i > $j) { // flush the rest
1584                 $this->_saveOptions(array('cols' => 0, 'azhead' => 0));
1585                 $this->_pages = array_slice($this->_pages, $j, $i - $j);
1586                 $out->pushContent($this->_generateList());
1587                 $this->_restoreOptions();
1588             }
1589             return $out;
1590         }
1591             
1592         if ($this->_options['listtype'] == 'comma')
1593             $this->_options['comma'] = 2;
1594         if (!empty($this->_options['comma'])) {
1595             if ($this->_options['comma'] == 1)
1596                 $out->pushContent($this->_generateCommaListAsString());
1597             else
1598                 $out->pushContent($this->_generateCommaList($this->_options['comma']));
1599             return $out;
1600         }
1601
1602         if ($this->_options['listtype'] == 'ol')
1603             $this->_options['ordered'] = 1;
1604         elseif ($this->_options['listtype'] == 'ul')
1605             $this->_options['ordered'] = 0;
1606         if (!empty($this->_options['ordered']))
1607             $list = HTML::ol(array('class' => 'pagelist'));
1608         elseif ($this->_options['listtype'] == 'dl') {
1609             $list = HTML::dl(array('class' => 'pagelist'));
1610         } else {
1611             $list = HTML::ul(array('class' => 'pagelist'));
1612         }
1613         $i = 0;
1614         //TODO: currently we ignore limit here and hope that the backend didn't ignore it. (BackLinks)
1615         if (!empty($this->_options['limit']))
1616             list($offset, $pagesize) = $this->limit($this->_options['limit']);
1617         else 
1618             $pagesize=0;
1619         foreach ($this->_pages as $pagenum => $page) {
1620             $pagehtml = $this->_renderPageRow($page);
1621             if (!$pagehtml) continue;
1622             $group = ($i++ / $this->_group_rows);
1623             //TODO: here we switch every row, in tables every third. 
1624             //      unification or parametrized?
1625             $class = ($group % 2) ? 'oddrow' : 'evenrow';
1626             if ($this->_options['listtype'] == 'dl') {
1627                 $header = WikiLink($page);
1628                 //if ($this->_sortby['hi_content']) 
1629                 $list->pushContent(HTML::dt(array('class' => $class), $header),
1630                                    HTML::dd(array('class' => $class), $pagehtml));
1631             } else
1632                 $list->pushContent(HTML::li(array('class' => $class), $pagehtml));
1633             if ($pagesize and $i > $pagesize) break;
1634         }
1635         $out->pushContent($list);
1636         if ( $do_paging and $tokens ) {
1637             $out->pushContent(HTML::table($paging));
1638         }
1639         return $out;
1640     }
1641
1642     // comma=1
1643     // Condense list without a href links: "Page1, Page2, ..." 
1644     // Alternative $seperator = HTML::Raw(' &middot; ')
1645     // FIXME: only unique list entries, esp. with nopage
1646     function _generateCommaListAsString() {
1647         if (defined($this->_options['commasep']))
1648             $seperator = $this->_options['commasep'];
1649         else    
1650             $seperator = ', ';
1651         $pages = array();
1652         foreach ($this->_pages as $pagenum => $page) {
1653             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1654                 $pages[] = is_string($s) ? $s : $s->asString();
1655         }
1656         return HTML(join($seperator, $pages));
1657     }
1658
1659     // comma=2
1660     // Normal WikiLink list.
1661     // Future: 1 = reserved for plain string (see above)
1662     //         2 and more => HTML link specialization?
1663     // FIXME: only unique list entries, esp. with nopage
1664     function _generateCommaList($style = false) {
1665         if (defined($this->_options['commasep']))
1666             $seperator = HTLM::Raw($this->_options['commasep']);
1667         else    
1668             $seperator = ', ';
1669         $html = HTML();
1670         $html->pushContent($this->_renderPageRow($this->_pages[0]));
1671         next($this->_pages);
1672         foreach ($this->_pages as $pagenum => $page) {
1673             if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1674                 $html->pushContent($seperator, $s);
1675         }
1676         return $html;
1677     }
1678     
1679     function _emptyList($caption) {
1680         $html = HTML();
1681         if ($caption)
1682             $html->pushContent(HTML::p($caption));
1683         if ($this->_messageIfEmpty)
1684             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
1685         return $html;
1686     }
1687
1688 };
1689
1690 /* List pages with checkboxes to select from.
1691  * The [Select] button toggles via Javascript flipAll
1692  */
1693
1694 class PageList_Selectable
1695 extends PageList {
1696
1697     function PageList_Selectable ($columns=false, $exclude='', $options = false) {
1698         if ($columns) {
1699             if (!is_array($columns))
1700                 $columns = explode(',', $columns);
1701             if (!in_array('checkbox',$columns))
1702                 array_unshift($columns,'checkbox');
1703         } else {
1704             $columns = array('checkbox','pagename');
1705         }
1706         $this->PageList($columns, $exclude, $options);
1707     }
1708
1709     function addPageList ($array) {
1710         while (list($pagename,$selected) = each($array)) {
1711             if ($selected) $this->addPageSelected((string)$pagename);
1712             $this->addPage((string)$pagename);
1713         }
1714     }
1715
1716     function addPageSelected ($pagename) {
1717         $this->_selected[$pagename] = 1;
1718     }
1719 }
1720
1721 // (c-file-style: "gnu")
1722 // Local Variables:
1723 // mode: php
1724 // tab-width: 8
1725 // c-basic-offset: 4
1726 // c-hanging-comment-ender-p: nil
1727 // indent-tabs-mode: nil
1728 // End:
1729 ?>