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