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