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