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