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