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