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