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