3 /* Copyright (C) 2004-2009 $ThePhpWikiProgrammingTeam
4 * Copyright (C) 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6 * This file is part of PhpWiki.
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with PhpWiki; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * List a number of pagenames, optionally as table with various columns.
25 * This library relieves some work for these plugins:
27 * AllPages, BackLinks, LikePages, MostPopular, TitleSearch, WikiAdmin* and more
29 * It also allows dynamic expansion of those plugins to include more
30 * columns in their output.
32 * Column 'info=' arguments:
34 * 'pagename' _("Page Name")
35 * 'mtime' _("Last Modified")
37 * 'summary' _("Last Summary")
38 * 'version' _("Version")),
39 * 'author' _("Last Author")),
40 * 'locked' _("Locked"), _("locked")
41 * 'minor' _("Minor Edit"), _("minor")
42 * 'markup' _("Markup")
44 * 'creator' _("Creator")
46 * 'checkbox' selectable checkbox at the left.
49 * Special, custom columns: Either theme or plugin (WikiAdmin*) specific.
50 * 'remove' _("Remove")
51 * 'perm' _("Permission Mask")
53 * 'renamed_pagename' _("Rename to")
54 * 'ratingwidget', ... wikilens theme specific.
55 * 'custom' See plugin/_WikiTranslation
57 * Symbolic 'info=' arguments:
58 * 'all' All columns except the special columns
59 * 'most' pagename, mtime, author, size, hits, ...
60 * 'some' pagename, mtime, author
62 * FIXME: In this refactoring I (Jeff) have un-implemented _ctime, _cauthor, and
63 * number-of-revision. Note the _ctime and _cauthor as they were implemented
64 * were somewhat flawed: revision 1 of a page doesn't have to exist in the
65 * database. If lots of revisions have been made to a page, it's more than likely
66 * that some older revisions (include revision 1) have been cleaned (deleted).
69 * paging support: limit, offset args
70 * check PagePerm "list" access-type,
71 * all columns are sortable. Thanks to the wikilens team.
72 * cols > 1, comma, azhead, ordered (OL lists)
73 * ->supportedArgs() which arguments are supported, so that the plugin
74 * doesn't explictly need to declare it
76 * fix sortby logic, fix multiple sortby and other paging args per page.
77 * info=relation,linkto nopage=1
78 * use custom format method (RecentChanges, rss, ...)
81 * fix memory exhaustion on large pagelists with old --memory-limit php's only.
82 * Status: improved 2004-06-25 16:19:36 rurban
84 class _PageList_Column_base {
85 var $_tdattr = array();
87 function _PageList_Column_base ($default_heading, $align = false) {
88 $this->_heading = $default_heading;
91 // align="char" isn't supported by any browsers yet :(
92 //if (is_array($align))
93 // $this->_tdattr = $align;
95 $this->_tdattr['align'] = $align;
99 function format ($pagelist, $page_handle, &$revision_handle) {
100 $nbsp = HTML::raw(' ');
101 return HTML::td($this->_tdattr,
103 $this->_getValue($page_handle, $revision_handle),
107 function getHeading () {
108 return $this->_heading;
111 function setHeading ($heading) {
112 $this->_heading = $heading;
116 function heading () {
118 $nbsp = HTML::raw(' ');
120 if (1 /* or in_array($this->_field, PageList::sortable_columns())*/) {
121 // multiple comma-delimited sortby args: "+hits,+pagename"
122 // asc or desc: +pagename, -pagename
123 $sortby = PageList::sortby($this->_field, 'flip_order');
124 //Fixme: pass all also other GET args along. (limit, p[])
125 //TODO: support GET and POST
126 $s = HTML::a(array('href' =>
127 $request->GetURLtoSelf(array('sortby' => $sortby)),
128 'class' => 'pagetitle',
129 'title' => sprintf(_("Sort by %s"), $this->_field)),
130 $nbsp, HTML::u($this->_heading), $nbsp);
132 $s = HTML($nbsp, HTML::u($this->_heading), $nbsp);
134 return HTML::th(array('align' => 'center'),$s);
137 // new grid-style sortable heading
138 // TODO: via activeui.js ? (fast dhtml sorting)
139 function button_heading (&$pagelist, $colNum) {
140 global $WikiTheme, $request;
142 $nbsp = HTML::raw(' ');
143 if (!$WikiTheme->DUMP_MODE /* or in_array($this->_field, PageList::sortable_columns()) */) {
144 // TODO: add to multiple comma-delimited sortby args: "+hits,+pagename"
146 $noimg_src = $WikiTheme->getButtonURL('no_order');
148 $noimg = HTML::img(array('src' => $noimg_src,
153 if ($pagelist->sortby($colNum, 'check')) { // show icon? request or plugin arg
154 $sortby = $pagelist->sortby($colNum, 'flip_order');
155 $desc = (substr($sortby,0,1) == '-'); // +pagename or -pagename
156 $src = $WikiTheme->getButtonURL($desc ? 'asc_order' : 'desc_order');
157 $reverse = $desc ? _("reverse")." " : "";
159 // initially unsorted
160 $sortby = $pagelist->sortby($colNum, 'get');
165 $img->setAttr('alt', ".");
167 $img = HTML::img(array('src' => $src,
169 'alt' => _("Click to reverse sort order")));
171 $s = HTML::a(array('href' =>
172 //Fixme: pass all also other GET args along. (limit is ok, p[])
173 $request->GetURLtoSelf(array('sortby' => $sortby,
174 'id' => $pagelist->id)),
175 'class' => 'gridbutton',
176 'title' => sprintf(_("Click to sort by %s"), $reverse . $this->_field)),
177 $nbsp, $this->_heading,
181 $s = HTML($nbsp, $this->_heading, $nbsp);
183 return HTML::th(array('align' => 'center', 'valign' => 'middle',
184 'class' => 'gridbutton'), $s);
188 * Take two columns of this type and compare them.
189 * An undefined value is defined to be < than the smallest defined value.
190 * This base class _compare only works if the value is simple (e.g., a number).
192 * @param $colvala $this->_getValue() of column a
193 * @param $colvalb $this->_getValue() of column b
195 * @return -1 if $a < $b, 1 if $a > $b, 0 otherwise.
197 function _compare($colvala, $colvalb) {
198 if (is_string($colvala))
199 return strcmp($colvala,$colvalb);
201 if (($colvala === $colvalb) || (!isset($colvala) && !isset($colvalb))) {
204 $ret = (!isset($colvala) || ($colvala < $colvalb)) ? -1 : 1;
210 class _PageList_Column extends _PageList_Column_base {
211 function _PageList_Column ($field, $default_heading, $align = false) {
212 $this->_PageList_Column_base($default_heading, $align);
214 $this->_need_rev = substr($field, 0, 4) == 'rev:';
215 $this->_iscustom = substr($field, 0, 7) == 'custom:';
216 if ($this->_iscustom) {
217 $this->_field = substr($field, 7);
219 elseif ($this->_need_rev)
220 $this->_field = substr($field, 4);
222 $this->_field = $field;
225 function _getValue ($page_handle, &$revision_handle) {
226 if ($this->_need_rev) {
227 if (!$revision_handle)
228 // columns which need the %content should override this. (size, hi_content)
229 $revision_handle = $page_handle->getCurrentRevision(false);
230 return $revision_handle->get($this->_field);
233 return $page_handle->get($this->_field);
237 function _getSortableValue ($page_handle, &$revision_handle) {
238 $val = $this->_getValue($page_handle, $revision_handle);
239 if ($this->_field == 'hits')
241 elseif (is_object($val) && method_exists($val, 'asString'))
242 return $val->asString();
244 return (string) $val;
248 /* overcome a call_user_func limitation by not being able to do:
249 * call_user_func_array(array(&$class, $class_name), $params);
250 * So we need $class = new $classname($params);
251 * And we add a 4th param to get at the parent $pagelist object
253 class _PageList_Column_custom extends _PageList_Column {
254 function _PageList_Column_custom($params) {
255 $this->_pagelist =& $params[3];
256 $this->_PageList_Column($params[0], $params[1], $params[2]);
260 class _PageList_Column_size extends _PageList_Column {
261 function format (&$pagelist, $page_handle, &$revision_handle) {
262 return HTML::td($this->_tdattr,
264 $this->_getValue($pagelist, $page_handle, $revision_handle),
265 HTML::raw(' '));
268 function _getValue (&$pagelist, $page_handle, &$revision_handle) {
269 if (!$revision_handle or (!$revision_handle->_data['%content']
270 or $revision_handle->_data['%content'] === true)) {
271 $revision_handle = $page_handle->getCurrentRevision(true);
272 unset($revision_handle->_data['%pagedata']['_cached_html']);
274 $size = $this->_getSize($revision_handle);
275 // we can safely purge the content when it is not sortable
276 if (empty($pagelist->_sortby[$this->_field]))
277 unset($revision_handle->_data['%content']);
281 function _getSortableValue ($page_handle, &$revision_handle) {
282 if (!$revision_handle)
283 $revision_handle = $page_handle->getCurrentRevision(true);
284 return (empty($revision_handle->_data['%content']))
285 ? 0 : strlen($revision_handle->_data['%content']);
288 function _getSize($revision_handle) {
289 $bytes = @strlen($revision_handle->_data['%content']);
290 return ByteFormatter($bytes);
295 class _PageList_Column_bool extends _PageList_Column {
296 function _PageList_Column_bool ($field, $default_heading, $text = 'yes') {
297 $this->_PageList_Column($field, $default_heading, 'center');
298 $this->_textIfTrue = $text;
299 $this->_textIfFalse = new RawXml('—'); //mdash
302 function _getValue ($page_handle, &$revision_handle) {
303 //FIXME: check if $this is available in the parent (->need_rev)
304 $val = _PageList_Column::_getValue($page_handle, $revision_handle);
305 return $val ? $this->_textIfTrue : $this->_textIfFalse;
309 class _PageList_Column_checkbox extends _PageList_Column {
310 function _PageList_Column_checkbox ($field, $default_heading, $name='p') {
311 $this->_name = $name;
312 $heading = HTML::input(array('type' => 'button',
313 'title' => _("Click to de-/select all pages"),
314 'name' => $default_heading,
315 'value' => $default_heading,
316 'onclick' => "flipAll(this.form)"
318 $this->_PageList_Column($field, $heading, 'center');
320 function _getValue ($pagelist, $page_handle, &$revision_handle) {
321 $pagename = $page_handle->getName();
322 $selected = !empty($pagelist->_selected[$pagename]);
323 if (strstr($pagename,'[') or strstr($pagename,']')) {
324 $pagename = str_replace(array('[',']'),array('%5B','%5D'),$pagename);
327 return HTML::input(array('type' => 'checkbox',
328 'name' => $this->_name . "[$pagename]",
330 'checked' => 'checked'));
332 return HTML::input(array('type' => 'checkbox',
333 'name' => $this->_name . "[$pagename]",
337 function format ($pagelist, $page_handle, &$revision_handle) {
338 return HTML::td($this->_tdattr,
340 $this->_getValue($pagelist, $page_handle, $revision_handle),
341 HTML::raw(' '));
343 // don't sort this javascript button
344 function button_heading ($pagelist, $colNum) {
345 $s = HTML(HTML::raw(' '), $this->_heading, HTML::raw(' '));
346 return HTML::th(array('align' => 'center', 'valign' => 'middle',
347 'class' => 'gridbutton'), $s);
351 class _PageList_Column_time extends _PageList_Column {
352 function _PageList_Column_time ($field, $default_heading) {
353 $this->_PageList_Column($field, $default_heading, 'right');
355 $this->WikiTheme = &$WikiTheme;
358 function _getValue ($page_handle, &$revision_handle) {
359 $time = _PageList_Column::_getValue($page_handle, $revision_handle);
360 return $this->WikiTheme->formatDateTime($time);
363 function _getSortableValue ($page_handle, &$revision_handle) {
364 return _PageList_Column::_getValue($page_handle, $revision_handle);
368 class _PageList_Column_version extends _PageList_Column {
369 function _getValue ($page_handle, &$revision_handle) {
370 if (!$revision_handle)
371 $revision_handle = $page_handle->getCurrentRevision();
372 return $revision_handle->getVersion();
376 // Output is hardcoded to limit of first 50 bytes. Otherwise
377 // on very large Wikis this will fail if used with AllPages
378 // (PHP memory limit exceeded)
379 class _PageList_Column_content extends _PageList_Column {
380 function _PageList_Column_content ($field, $default_heading, $align = false, $search = false) {
381 $this->_PageList_Column($field, $default_heading, $align);
383 $this->search = $search;
384 if ($field == 'content') {
385 $this->_heading .= sprintf(_(" ... first %d bytes"),
387 } elseif ($field == 'rev:hi_content') {
388 global $HTTP_POST_VARS;
389 if (!$this->search and !empty($HTTP_POST_VARS['admin_replace'])) {
390 $this->search = $HTTP_POST_VARS['admin_replace']['from'];
392 $this->_heading .= sprintf(_(" ... around %s"),
393 '»'.$this->search.'«');
397 function _getValue ($page_handle, &$revision_handle) {
398 if (!$revision_handle or (!$revision_handle->_data['%content']
399 or $revision_handle->_data['%content'] === true)) {
400 $revision_handle = $page_handle->getCurrentRevision(true);
402 // Not sure why implode is needed here, I thought
403 // getContent() already did this, but it seems necessary.
404 $c = implode("\n", $revision_handle->getContent());
405 if (empty($pagelist->_sortby[$this->_field]))
406 unset($revision_handle->_data['%content']);
407 if ($this->_field == 'hi_content') {
408 if (!empty($revision_handle->_data['%pagedata'])) {
409 $revision_handle->_data['%pagedata']['_cached_html'] = '';
410 // PHP Fatal error: Cannot unset string offsets
411 //unset($revision_handle->_data['%pagedata']['_cached_html']);
413 $search = $this->search;
415 if (is_object($page_handle) and !empty($page_handle->score))
416 $score = $page_handle->score;
417 elseif (is_array($page_handle) and !empty($page_handle['score']))
418 $score = $page_handle['score'];
419 if ($search and ($i = strpos(strtolower($c), strtolower($search))) !== false) {
420 $l = strlen($search);
421 $j = max(0, $i - ($this->bytes / 2));
422 return HTML::div(array('style' => 'font-size:x-small'),
423 HTML::div(array('class' => 'transclusion'),
424 HTML::span(($j ? '...' : '').substr($c, $j, ($j ? $this->bytes / 2 : $i))),
425 HTML::span(array("style"=>"background:yellow"),substr($c, $i, $l)),
426 HTML::span(substr($c, $i+$l, ($this->bytes / 2))."..."." ".($score ? sprintf("[%0.1f]",$score):""))));
428 if (strpos($c," ") !== false)
431 $c = sprintf(_("%s not found"), '»'.$search.'«');
432 return HTML::div(array('style' => 'font-size:x-small','align'=>'center'),
433 $c." ".($score ? sprintf("[%0.1f]",$score):""));
435 } elseif (($len = strlen($c)) > $this->bytes) {
436 $c = substr($c, 0, $this->bytes);
438 include_once('lib/BlockParser.php');
439 // false --> don't bother processing hrefs for embedded WikiLinks
440 $ct = TransformText($c, $revision_handle->get('markup'), false);
441 if (empty($pagelist->_sortby[$this->_field]))
442 unset($revision_handle->_data['%pagedata']['_cached_html']);
443 return HTML::div(array('style' => 'font-size:x-small'),
444 HTML::div(array('class' => 'transclusion'), $ct),
445 // Don't show bytes here if size column present too
446 ($this->parent->_columns_seen['size'] or !$len) ? "" :
447 ByteFormatter($len, /*$longformat = */true));
449 function _getSortableValue ($page_handle, &$revision_handle) {
450 if (is_object($page_handle) and !empty($page_handle->score))
451 return $page_handle->score;
452 elseif (is_array($page_handle) and !empty($page_handle['score']))
453 return $page_handle['score'];
455 return substr(_PageList_Column::_getValue($page_handle, $revision_handle),0,50);
459 class _PageList_Column_author extends _PageList_Column {
460 function _PageList_Column_author ($field, $default_heading, $align = false) {
461 _PageList_Column::_PageList_Column($field, $default_heading, $align);
462 $this->dbi =& $GLOBALS['request']->getDbh();
465 function _getValue ($page_handle, &$revision_handle) {
466 $author = _PageList_Column::_getValue($page_handle, $revision_handle);
467 if ($this->dbi->isWikiPage($author))
468 return WikiLink($author);
473 function _getSortableValue ($page_handle, &$revision_handle) {
474 return _PageList_Column::_getValue($page_handle, $revision_handle);
478 class _PageList_Column_owner extends _PageList_Column_author {
479 function _getValue ($page_handle, &$revision_handle) {
480 $author = $page_handle->getOwner();
481 if ($this->dbi->isWikiPage($author))
482 return WikiLink($author);
486 function _getSortableValue ($page_handle, &$revision_handle) {
487 return _PageList_Column::_getValue($page_handle, $revision_handle);
491 class _PageList_Column_creator extends _PageList_Column_author {
492 function _getValue ($page_handle, &$revision_handle) {
493 $author = $page_handle->getCreator();
494 if ($this->dbi->isWikiPage($author))
495 return WikiLink($author);
499 function _getSortableValue ($page_handle, &$revision_handle) {
500 return _PageList_Column::_getValue($page_handle, $revision_handle);
504 class _PageList_Column_pagename extends _PageList_Column_base {
505 var $_field = 'pagename';
507 function _PageList_Column_pagename () {
508 $this->_PageList_Column_base(_("Page Name"));
510 $this->dbi = &$request->getDbh();
513 function _getValue ($page_handle, &$revision_handle) {
514 if ($this->dbi->isWikiPage($page_handle->getName()))
515 return WikiLink($page_handle, 'known');
517 return WikiLink($page_handle, 'unknown');
520 function _getSortableValue ($page_handle, &$revision_handle) {
521 return $page_handle->getName();
525 * Compare two pagenames for sorting. See _PageList_Column::_compare.
527 function _compare($colvala, $colvalb) {
528 return strcmp($colvala, $colvalb);
533 var $_group_rows = 3;
534 var $_columns = array();
535 var $_columnsMap = array(); // Maps column name to column number.
536 var $_excluded_pages = array();
537 var $_pages = array();
539 var $_pagename_seen = false;
540 var $_types = array();
541 var $_options = array();
542 var $_selected = array();
543 var $_sortby = array();
546 function PageList ($columns = false, $exclude = false, $options = false) {
547 // unique id per pagelist on each page.
548 if (!isset($GLOBALS['request']->_pagelist))
549 $GLOBALS['request']->_pagelist = 0;
551 $GLOBALS['request']->_pagelist++;
552 $this->id = $GLOBALS['request']->_pagelist;
553 if ($GLOBALS['request']->getArg('count'))
554 $options['count'] = $GLOBALS['request']->getArg('count');
556 $this->_options = $options;
558 $this->_initAvailableColumns();
559 // let plugins predefine only certain objects, such its own custom pagelist columns
562 'all' => array_diff(array_keys($this->_types), // all but...
563 array('checkbox','remove','renamed_pagename',
564 'content','hi_content','perm','acl')),
565 'most' => array('pagename','mtime','author','hits'),
566 'some' => array('pagename','mtime','author')
568 if (isset($this->_options['listtype'])
569 and $this->_options['listtype'] == 'dl')
570 $this->_options['nopage'] = 1;
572 if (!is_array($columns))
573 $columns = explode(',', $columns);
574 // expand symbolic columns:
575 foreach ($symbolic_columns as $symbol => $cols) {
576 if (in_array($symbol,$columns)) { // e.g. 'checkbox,all'
577 $columns = array_diff(array_merge($columns,$cols),array($symbol));
581 if (empty($this->_options['nopage']) and !in_array('pagename',$columns))
582 $this->_addColumn('pagename');
583 foreach ($columns as $col) {
585 $this->_addColumn($col);
589 // If 'pagename' is already present, _addColumn() will not add it again
590 if (empty($this->_options['nopage']))
591 $this->_addColumn('pagename');
593 if (!empty($this->_options['types'])) {
594 foreach ($this->_options['types'] as $type) {
595 $this->_types[$type->_field] = $type;
596 $this->_addColumn($type->_field);
598 unset($this->_options['types']);
602 // explicit header options: ?id=x&sortby=... override options[]
603 // support multiple sorts. check multiple, no nested elseif
604 if (($this->id == $request->getArg("id"))
605 and $request->getArg('sortby'))
607 // add it to the front of the sortby array
608 $this->sortby($request->getArg('sortby'), 'init');
609 $this->_options['sortby'] = $request->getArg('sortby');
611 if (!empty($options['sortby'])) {
612 if (empty($this->_options['sortby']))
613 $this->_options['sortby'] = $options['sortby'];
614 $this->sortby($options['sortby'], 'init');
616 if (!isset($request->args["id"]) and $request->getArg('sortby')
617 and empty($this->_options['sortby']))
619 $this->_options['sortby'] = $request->getArg('sortby');
620 $this->sortby($this->_options['sortby'], 'init');
622 // same as above but without the special sortby push, and mutually exclusive (elseif)
623 foreach ($this->pagingArgs() as $key) {
624 if ($key == 'sortby') continue;
625 if (($this->id == $request->getArg("id"))
626 and $request->getArg($key))
628 $this->_options[$key] = $request->getArg($key);
630 elseif (!empty($options) and !empty($options[$key])) {
631 $this->_options[$key] = $options[$key];
633 elseif (!isset($request->args["id"]) and $request->getArg($key)) {
634 $this->_options[$key] = $request->getArg($key);
637 $this->_options[$key] = false;
640 if (is_string($exclude) and !is_array($exclude))
641 $exclude = $this->explodePageList($exclude, false,
642 $this->_options['sortby'],
643 $this->_options['limit']);
644 $this->_excluded_pages = $exclude;
646 $this->_messageIfEmpty = _("<no matches>");
649 // Currently PageList takes these arguments:
650 // 1: info, 2: exclude, 3: hash of options
651 // Here we declare which options are supported, so that
652 // the calling plugin may simply merge this with its own default arguments
653 function supportedArgs () {
654 // Todo: add all supported Columns, like locked, minor, ...
655 return array(// Currently supported options:
656 /* what columns, what pages */
657 'info' => 'pagename',
658 'exclude' => '', // also wildcards, comma-seperated lists
659 // and <!plugin-list !> arrays
660 /* select pages by meta-data: */
661 'author' => false, // current user by []
662 'owner' => false, // current user by []
663 'creator' => false, // current user by []
665 /* for the sort buttons in <th> */
666 'sortby' => '', // same as for WikiDB::getAllPages
667 // (unsorted is faster)
669 /* PageList pager options:
670 * These options may also be given to _generate(List|Table) later
671 * But limit and offset might help the query WikiDB::getAllPages()
673 'limit' => 50, // number of rows (pagesize)
674 'paging' => 'auto', // 'auto' top + bottom rows if applicable
675 // // 'top' top only if applicable
676 // // 'bottom' bottom only if applicable
677 // // 'none' don't page at all
678 // (TODO: clarify what if $paging==false ?)
680 /* list-style options (with single pagename column only so far) */
681 'cols' => 1, // side-by-side display of list (1-3)
682 'azhead' => 0, // 1: group by initials
683 // 2: provide shortcut links to initials also
684 'comma' => 0, // condensed comma-seperated list,
685 // 1 if without links, 2 if with
686 'commasep' => false, // Default: ', '
687 'listtype' => '', // ul (default), ol, dl, comma
688 'ordered' => false, // OL or just UL lists (ignored for comma)
689 'linkmore' => '', // If count>0 and limit>0 display a link with
690 // the number of all results, linked to the given pagename.
692 'nopage' => false, // for info=col omit the pagename column
693 // array_keys($this->_types). filter by columns: e.g. locked=1
694 'pagename' => null, // string regex
706 function pagingArgs() {
707 return array('sortby','limit','paging','count','dosort');
710 function setCaption ($caption_string) {
711 $this->_caption = $caption_string;
714 function addCaption ($caption_string) {
715 $this->_caption = HTML($this->_caption," ",$caption_string);
718 function getCaption () {
719 // put the total into the caption if needed
720 if (is_string($this->_caption) && strstr($this->_caption, '%d'))
721 return sprintf($this->_caption, $this->getTotal());
722 return $this->_caption;
725 function setMessageIfEmpty ($msg) {
726 $this->_messageIfEmpty = $msg;
730 function getTotal () {
731 return !empty($this->_options['count'])
732 ? (integer) $this->_options['count'] : count($this->_pages);
735 function isEmpty () {
736 return empty($this->_pages);
739 function addPage($page_handle) {
740 if (!empty($this->_excluded_pages)) {
741 if (!in_array((is_string($page_handle) ? $page_handle : $page_handle->getName()),
742 $this->_excluded_pages))
743 $this->_pages[] = $page_handle;
745 $this->_pages[] = $page_handle;
749 function pageNames() {
751 $limit = @$this->_options['limit'];
752 foreach ($this->_pages as $page_handle) {
753 $pages[] = $page_handle->getName();
754 if ($limit and count($pages) > $limit)
760 function _getPageFromHandle($page_handle) {
761 if (is_string($page_handle)) {
762 if (empty($page_handle)) return $page_handle;
763 //$dbi = $GLOBALS['request']->getDbh(); // no, safe some memory!
764 $page_handle = $GLOBALS['request']->_dbi->getPage($page_handle);
770 * Take a PageList_Page object, and return an HTML object to display
771 * it in a table or list row.
773 function _renderPageRow (&$page_handle, $i = 0) {
774 $page_handle = $this->_getPageFromHandle($page_handle);
775 //FIXME. only on sf.net
776 if (!is_object($page_handle)) {
777 trigger_error("PageList: Invalid page_handle $page_handle", E_USER_WARNING);
780 if (!isset($page_handle)
781 or empty($page_handle)
782 or (!empty($this->_excluded_pages)
783 and in_array($page_handle->getName(), $this->_excluded_pages)))
784 return; // exclude page.
786 // enforce view permission
787 if (!mayAccessPage('view', $page_handle->getName()))
790 $group = (int)($i / $this->_group_rows);
791 $class = ($group % 2) ? 'oddrow' : 'evenrow';
792 $revision_handle = false;
793 $this->_maxlen = max($this->_maxlen, strlen($page_handle->getName()));
795 if (count($this->_columns) > 1) {
796 $row = HTML::tr(array('class' => $class));
798 foreach ($this->_columns as $col) {
799 $col->current_row = $i;
800 $col->current_column = $j;
801 $row->pushContent($col->format($this, $page_handle, $revision_handle));
805 $col = $this->_columns[0];
806 $col->current_row = $i;
807 $col->current_column = 0;
808 $row = $col->_getValue($page_handle, $revision_handle);
814 /* ignore from, but honor limit */
815 function addPages ($page_iter) {
816 // TODO: if limit check max(strlen(pagename))
818 if (isa($page_iter->_iter, "WikiDB_backend_dbaBase_pageiter")) {
821 elseif (isset($this->_options['limit'])) { // extract from,count from limit
822 list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
827 while ($page = $page_iter->next()) {
829 if ($from and $i < $from)
831 if (!$limit or ($limit and $i < $limit))
832 $this->addPage($page);
834 if (empty($this->_options['count']))
835 $this->_options['count'] = $i;
838 function addPageList (&$list) {
839 if (empty($list)) return; // Protect reset from a null arg
840 if (isset($this->_options['limit'])) { // extract from,count from limit
841 list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
847 foreach ($list as $page) {
849 if ($from and $i < $from)
851 if (!$limit or ($limit and $i < $limit)) {
852 if (is_object($page)) $page = $page->_pagename;
853 $this->addPage((string)$page);
860 $dbi =& $request->getDbh();
861 if (isa($dbi,'WikiDB_SQL')) {
862 extract($dbi->_backend->_table_names);
863 $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl");
864 if (DB::isError($res) || empty($res)) return false;
866 } elseif (isa($dbi,'WikiDB_ADODB')) {
867 extract($dbi->_backend->_table_names);
868 $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl");
869 return $row ? $row[0] : false;
874 function getContent() {
875 // Note that the <caption> element wants inline content.
876 $caption = $this->getCaption();
878 if ($this->isEmpty())
879 return $this->_emptyList($caption);
880 elseif (isset($this->_options['listtype'])
881 and in_array($this->_options['listtype'],
882 array('ol','ul','comma','dl')))
883 return $this->_generateList($caption);
884 elseif (count($this->_columns) == 1)
885 return $this->_generateList($caption);
887 return $this->_generateTable($caption);
890 function printXML() {
891 PrintXML($this->getContent());
895 return AsXML($this->getContent());
899 * Handle sortby requests for the DB iterator and table header links.
900 * Prefix the column with + or - like "+pagename","-mtime", ...
903 * 'init' : unify with predefined order. "pagename" => "+pagename"
904 * 'flip_order' : "mtime" => "+mtime" => "-mtime" ...
905 * 'db' : "-pagename" => "pagename DESC"
908 * Now all columns are sortable. (patch by DanFr)
909 * Some columns have native DB backend methods, some not.
911 function sortby ($column, $action, $valid_fields=false) {
914 if (empty($column)) return '';
915 if (is_int($column)) {
916 $column = $this->_columns[$column - 1]->_field;
917 //$column = $col->_field;
919 //if (!is_string($column)) return '';
920 // support multiple comma-delimited sortby args: "+hits,+pagename"
922 if (strstr($column, ',')) {
923 $result = ($action == 'check') ? true : array();
924 foreach (explode(',', $column) as $col) {
925 if ($action == 'check')
926 $result = $result && $this->sortby($col, $action, $valid_fields);
928 $result[] = $this->sortby($col, $action, $valid_fields);
930 // 'check' returns true/false for every col. return true if all are true.
931 // i.e. the unsupported 'every' operator in functional languages.
932 if ($action == 'check')
935 return join(",", $result);
937 if (substr($column,0,1) == '+') {
938 $order = '+'; $column = substr($column,1);
939 } elseif (substr($column,0,1) == '-') {
940 $order = '-'; $column = substr($column,1);
942 // default initial order: +pagename, -mtime, -hits
944 if (!empty($this->_sortby[$column]))
945 $order = $this->_sortby[$column];
947 if (in_array($column, array('mtime','hits')))
953 if ($action == 'get') {
954 return $order . $column;
955 } elseif ($action == 'flip_order') {
957 trigger_error("flip $order $column ".$this->id, E_USER_NOTICE);
958 return ($order == '+' ? '-' : '+') . $column;
959 } elseif ($action == 'init') { // only allowed from PageList::PageList
961 if ($this->sortby($column, 'clicked')) {
962 trigger_error("clicked $order $column $this->id", E_USER_NOTICE);
963 //$order = ($order == '+' ? '-' : '+'); // $this->sortby($sortby, 'flip_order');
966 $this->_sortby[$column] = $order; // forces show icon
967 return $order . $column;
968 } elseif ($action == 'check') { // show icon?
969 //if specified via arg or if clicked
970 $show = (!empty($this->_sortby[$column]) or $this->sortby($column, 'clicked'));
971 if (0 and $show and DEBUG) {
972 trigger_error("show $order $column ".$this->id, E_USER_NOTICE);
975 } elseif ($action == 'clicked') { // flip sort order?
977 $arg = $request->getArg('sortby');
979 and strstr($arg, $column)
980 and (!isset($request->args['id'])
981 or $this->id == $request->getArg('id')));
982 } elseif ($action == 'db') {
983 // Performance enhancement: use native DB sort if possible.
984 if (($valid_fields and in_array($column, $valid_fields))
985 or (method_exists($request->_dbi->_backend, 'sortable_columns')
986 and (in_array($column, $request->_dbi->_backend->sortable_columns())))) {
987 // omit this sort method from the _sortPages call at rendering
988 // asc or desc: +pagename, -pagename
989 return $column . ($order == '+' ? ' ASC' : ' DESC');
997 /* Splits pagelist string into array.
998 * Test* or Test1,Test2
999 * Limitation: Doesn't split into comma-sep and then expand wildcards.
1000 * "Test1*,Test2*" is expanded into TextSearch "Test1* Test2*"
1002 * echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1004 function explodePageList($input, $include_empty=false, $sortby='',
1005 $limit='', $exclude='')
1007 if (empty($input)) return array();
1008 if (is_array($input)) return $input;
1009 // expand wildcards from list of all pages
1010 if (preg_match('/[\?\*]/', $input) or substr($input,0,1) == "^") {
1011 include_once("lib/TextSearchQuery.php");
1012 $search = new TextSearchQuery(str_replace(",", " ", $input), true,
1013 (substr($input,0,1) == "^") ? 'posix' : 'glob');
1014 $dbi = $GLOBALS['request']->getDbh();
1015 $iter = $dbi->titleSearch($search, $sortby, $limit, $exclude);
1017 while ($pagehandle = $iter->next()) {
1018 $pages[] = trim($pagehandle->getName());
1022 //TODO: need an SQL optimization here
1023 $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit,
1025 while ($pagehandle = $allPagehandles->next()) {
1026 $allPages[] = $pagehandle->getName();
1028 return explodeList($input, $allPages);
1031 //TODO: do the sorting, normally not needed if used for exclude only
1032 return array_map("trim", explode(',', $input));
1036 // TODO: optimize getTotal => store in count
1037 function allPagesByAuthor($wildcard, $include_empty=false, $sortby='',
1038 $limit='', $exclude='')
1040 $dbi = $GLOBALS['request']->getDbh();
1041 $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1042 $allPages = array();
1043 if ($wildcard === '[]') {
1044 $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1045 if (!$wildcard) return $allPages;
1047 $do_glob = preg_match('/[\?\*]/', $wildcard);
1048 while ($pagehandle = $allPagehandles->next()) {
1049 $name = $pagehandle->getName();
1050 $author = $pagehandle->getAuthor();
1053 if (glob_match($wildcard, $author))
1054 $allPages[] = $name;
1055 } elseif ($wildcard == $author) {
1056 $allPages[] = $name;
1059 // TODO: purge versiondata_cache
1064 function allPagesByOwner($wildcard, $include_empty=false, $sortby='',
1065 $limit='', $exclude='') {
1066 $dbi = $GLOBALS['request']->getDbh();
1067 $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1068 $allPages = array();
1069 if ($wildcard === '[]') {
1070 $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1071 if (!$wildcard) return $allPages;
1073 $do_glob = preg_match('/[\?\*]/', $wildcard);
1074 while ($pagehandle = $allPagehandles->next()) {
1075 $name = $pagehandle->getName();
1076 $owner = $pagehandle->getOwner();
1079 if (glob_match($wildcard, $owner))
1080 $allPages[] = $name;
1081 } elseif ($wildcard == $owner) {
1082 $allPages[] = $name;
1089 function allPagesByCreator($wildcard, $include_empty=false, $sortby='',
1090 $limit='', $exclude='') {
1091 $dbi = $GLOBALS['request']->getDbh();
1092 $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1093 $allPages = array();
1094 if ($wildcard === '[]') {
1095 $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
1096 if (!$wildcard) return $allPages;
1098 $do_glob = preg_match('/[\?\*]/', $wildcard);
1099 while ($pagehandle = $allPagehandles->next()) {
1100 $name = $pagehandle->getName();
1101 $creator = $pagehandle->getCreator();
1104 if (glob_match($wildcard, $creator))
1105 $allPages[] = $name;
1106 } elseif ($wildcard == $creator) {
1107 $allPages[] = $name;
1114 // UserPages are pages NOT owned by ADMIN_USER
1115 function allUserPages($include_empty=false, $sortby='',
1116 $limit='', $exclude='') {
1117 $dbi = $GLOBALS['request']->getDbh();
1118 $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude);
1119 $allPages = array();
1120 while ($pagehandle = $allPagehandles->next()) {
1121 $name = $pagehandle->getName();
1122 $owner = $pagehandle->getOwner();
1123 if ($owner !== ADMIN_USER) {
1124 $allPages[] = $name;
1130 ////////////////////
1132 ////////////////////
1133 /** Plugin and theme hooks:
1134 * If the pageList is initialized with $options['types'] these types are also initialized,
1135 * overriding the standard types.
1137 function _initAvailableColumns() {
1138 global $customPageListColumns;
1142 => new _PageList_Column_content('rev:content', _("Content")),
1143 // new: plugin specific column types initialised by the relevant plugins
1145 'hi_content' // with highlighted search for SearchReplace
1146 => new _PageList_Column_content('rev:hi_content', _("Content")),
1148 => new _PageList_Column_remove('remove', _("Remove")),
1149 // initialised by the plugin
1151 => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
1153 => new _PageList_Column_perm('perm', _("Permission")),
1155 => new _PageList_Column_acl('acl', _("ACL")),
1158 => new _PageList_Column_checkbox('p', _("All")),
1160 => new _PageList_Column_pagename,
1162 => new _PageList_Column_time('rev:mtime', _("Last Modified")),
1164 => new _PageList_Column('hits', _("Hits"), 'right'),
1166 => new _PageList_Column_size('rev:size', _("Size"), 'right'),
1167 /*array('align' => 'char', 'char' => ' ')*/
1169 => new _PageList_Column('rev:summary', _("Last Summary")),
1171 => new _PageList_Column_version('rev:version', _("Version"),
1174 => new _PageList_Column_author('rev:author', _("Last Author")),
1176 => new _PageList_Column_owner('author_id', _("Owner")),
1178 => new _PageList_Column_creator('author_id', _("Creator")),
1181 => new _PageList_Column_author('group', _("Group")),
1184 => new _PageList_Column_bool('locked', _("Locked"),
1187 => new _PageList_Column_bool('external', _("External"),
1190 => new _PageList_Column_bool('rev:is_minor_edit',
1191 _("Minor Edit"), _("minor")),
1193 => new _PageList_Column('rev:markup', _("Markup")),
1194 // 'rating' initialised by the wikilens theme hook: addPageListColumn
1197 => new _PageList_Column_rating('rating', _("Rate")),
1200 if (empty($this->_types))
1201 $this->_types = array();
1202 // add plugin specific pageList columns, initialized by $options['types']
1203 $this->_types = array_merge($standard_types, $this->_types);
1204 // add theme custom specific pageList columns:
1205 // set the 4th param as the current pagelist object.
1206 if (!empty($customPageListColumns)) {
1207 foreach ($customPageListColumns as $column => $params) {
1208 $class_name = array_shift($params);
1209 $params[3] =& $this;
1210 // ref to a class does not work with php-4
1211 $this->_types[$column] = new $class_name($params);
1216 function getOption($option) {
1217 if (array_key_exists($option, $this->_options)) {
1218 return $this->_options[$option];
1226 * Add a column to this PageList, given a column name.
1227 * The name is a type, and optionally has a : and a label. Examples:
1230 * pagename:This page
1232 * mtime:Last modified
1234 * If this function is called multiple times for the same type, the
1235 * column will only be added the first time, and ignored the succeeding times.
1236 * If you wish to add multiple columns of the same type, use addColumnObject().
1238 * @param column name
1239 * @return true if column is added, false otherwise
1241 function _addColumn ($column) {
1243 if (isset($this->_columns_seen[$column]))
1244 return false; // Already have this one.
1245 if (!isset($this->_types[$column]))
1246 $this->_initAvailableColumns();
1247 $this->_columns_seen[$column] = true;
1249 if (strstr($column, ':'))
1250 list ($column, $heading) = explode(':', $column, 2);
1252 // FIXME: these column types have hooks (objects) elsewhere
1253 // Omitting this warning should be overridable by the extension
1254 if (!isset($this->_types[$column])) {
1255 $silently_ignore = array('numbacklinks',
1256 'rating','ratingvalue',
1257 'coagreement', 'minmisery',
1259 'averagerating', 'top3recs',
1260 'relation', 'linkto');
1261 if (!in_array($column, $silently_ignore))
1262 trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
1265 // FIXME: anon users might rate and see ratings also.
1266 // Defer this logic to the plugin.
1267 if ($column == 'rating' and !$GLOBALS['request']->_user->isSignedIn())
1270 $this->addColumnObject($this->_types[$column]);
1276 * Add a column to this PageList, given a column object.
1278 * @param $col object An object derived from _PageList_Column.
1280 function addColumnObject($col) {
1281 if (is_array($col)) {// custom column object
1283 $class_name = array_shift($params);
1284 $params[3] =& $this;
1285 $col = new $class_name($params);
1287 $heading = $col->getHeading();
1288 if (!empty($heading))
1289 $col->setHeading($heading);
1291 $this->_columns[] = $col;
1292 $this->_columnsMap[$col->_field] = count($this->_columns); // start with 1
1296 * Compare _PageList_Page objects.
1298 function _pageCompare(&$a, &$b) {
1299 if (empty($this->_sortby) or count($this->_sortby) == 0) {
1300 // No columns to sort by
1304 $pagea = $this->_getPageFromHandle($a); // If a string, convert to page
1305 assert(isa($pagea, 'WikiDB_Page'));
1306 $pageb = $this->_getPageFromHandle($b); // If a string, convert to page
1307 assert(isa($pageb, 'WikiDB_Page'));
1308 foreach ($this->_sortby as $colNum => $direction) {
1309 // get column type object
1310 if (!is_int($colNum)) { // or column fieldname
1311 if (isset($this->_columnsMap[$colNum]))
1312 $col = $this->_columns[$this->_columnsMap[$colNum] - 1];
1313 elseif (isset($this->_types[$colNum]))
1314 $col = $this->_types[$colNum];
1319 assert(isset($col));
1320 $revision_handle = false;
1321 $aval = $col->_getSortableValue($pagea, $revision_handle);
1322 $revision_handle = false;
1323 $bval = $col->_getSortableValue($pageb, $revision_handle);
1325 $cmp = $col->_compare($aval, $bval);
1326 if ($direction === "-") // Reverse the sense of the comparison
1330 // This is the first comparison that is not equal-- go with it
1338 * Put pages in order according to the sortby arg, if given
1339 * If the sortby cols are already sorted by the DB call, don't do usort.
1340 * TODO: optimize for multiple sortable cols
1342 function _sortPages() {
1343 if (count($this->_sortby) > 0) {
1344 $need_sort = $this->_options['dosort'];
1346 foreach ($this->_sortby as $col => $dir) {
1347 if (! $this->sortby($col, 'db'))
1350 if ($need_sort) { // There are some columns to sort by
1351 // TODO: consider nopage
1352 usort($this->_pages, array($this, '_pageCompare'));
1355 //unset($GLOBALS['PhpWiki_pagelist']);
1358 function limit($limit) {
1359 if (is_array($limit)) return $limit;
1360 if (strstr($limit, ','))
1361 return split(',', $limit);
1363 return array(0, $limit);
1366 function pagingTokens($numrows = false, $ncolumns = false, $limit = false) {
1367 if ($numrows === false)
1368 $numrows = $this->getTotal();
1369 if ($limit === false)
1370 $limit = $this->_options['limit'];
1371 if ($ncolumns === false)
1372 $ncolumns = count($this->_columns);
1374 list($offset, $pagesize) = $this->limit($limit);
1376 (!$offset and $numrows < $pagesize) or
1377 (($offset + $pagesize) < 0))
1380 $request = &$GLOBALS['request'];
1381 $pagename = $request->getArg('pagename');
1382 $defargs = array_merge(array('id' => $this->id), $request->args);
1383 if (USE_PATH_INFO) unset($defargs['pagename']);
1384 if (isset($defargs['action']) and ($defargs['action'] == 'browse')) {
1385 unset($defargs['action']);
1390 $tokens['PREV'] = false; $tokens['PREV_LINK'] = "";
1391 $tokens['COLS'] = $ncolumns;
1392 $tokens['COUNT'] = $numrows;
1393 $tokens['OFFSET'] = $offset;
1394 $tokens['SIZE'] = $pagesize;
1395 $tokens['NUMPAGES'] = (int) ceil($numrows / $pagesize);
1396 $tokens['ACTPAGE'] = (int) ceil(($offset / $pagesize)+1);
1398 $prev['limit'] = max(0, $offset - $pagesize) . ",$pagesize";
1399 $prev['count'] = $numrows;
1400 $tokens['LIMIT'] = $prev['limit'];
1401 $tokens['PREV'] = true;
1402 $tokens['PREV_LINK'] = WikiURL($pagename, $prev);
1403 $prev['limit'] = "0,$pagesize";
1404 $tokens['FIRST_LINK'] = WikiURL($pagename, $prev);
1407 $tokens['NEXT'] = false; $tokens['NEXT_LINK'] = "";
1408 if (($offset + $pagesize) < $numrows) {
1409 $next['limit'] = min($offset + $pagesize, $numrows - $pagesize) . ",$pagesize";
1410 $next['count'] = $numrows;
1411 $tokens['LIMIT'] = $next['limit'];
1412 $tokens['NEXT'] = true;
1413 $tokens['NEXT_LINK'] = WikiURL($pagename, $next);
1414 $next['limit'] = $numrows - $pagesize . ",$pagesize";
1415 $tokens['LAST_LINK'] = WikiURL($pagename, $next);
1420 // make a table given the caption
1421 function _generateTable($caption) {
1422 if (count($this->_sortby) > 0) $this->_sortPages();
1424 // wikiadminutils hack. that's a way to pagelist non-pages
1425 $rows = isset($this->_rows) ? $this->_rows : array();
1427 $count = $this->getTotal();
1428 $do_paging = ( isset($this->_options['paging'])
1429 and !empty($this->_options['limit'])
1431 and $this->_options['paging'] != 'none' );
1433 $tokens = $this->pagingTokens($count,
1434 count($this->_columns),
1435 $this->_options['limit']);
1437 $this->_pages = array_slice($this->_pages, $tokens['OFFSET'], $tokens['COUNT']);
1440 foreach ($this->_pages as $pagenum => $page) {
1441 $one_row = $this->_renderPageRow($page, $i++);
1443 if ($one_row) $nb_row++;
1445 $table = HTML::table(array('cellpadding' => 0,
1449 'class' => 'pagelist',
1452 $caption = preg_replace('/{total}/', $nb_row, asString($caption));
1453 $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
1457 $table_summary = array();
1458 $i = 1; // start with 1!
1459 foreach ($this->_columns as $col) {
1460 $heading = $col->button_heading($this, $i);
1462 and isset($col->_field)
1463 and $col->_field == 'pagename'
1464 and ($maxlen = $this->maxLen())) {
1465 // $heading->setAttr('width', $maxlen * 7);
1467 $row->pushContent($heading);
1468 if (is_string($col->getHeading()))
1469 $table_summary[] = $col->getHeading();
1472 // Table summary for non-visual browsers.
1473 $table->setAttr('summary', sprintf(_("Columns: %s."),
1474 join(", ", $table_summary)));
1475 $table->pushContent(HTML::colgroup(array('span' => count($this->_columns))));
1477 if ($tokens === false) {
1478 $table->pushContent(HTML::thead($row),
1479 HTML::tbody(false, $rows));
1483 $paging = Template("pagelink", $tokens);
1484 if ($this->_options['paging'] != 'bottom')
1485 $table->pushContent(HTML::thead($paging));
1486 if ($this->_options['paging'] != 'top')
1487 $table->pushContent(HTML::tfoot($paging));
1488 $table->pushContent(HTML::tbody(false, HTML($row, $rows)));
1491 $table->pushContent(HTML::thead($row),
1492 HTML::tbody(false, $rows));
1497 /* recursive stack for private sublist options (azhead, cols) */
1498 function _saveOptions($opts) {
1499 $stack = array('pages' => $this->_pages);
1500 foreach ($opts as $k => $v) {
1501 $stack[$k] = $this->_options[$k];
1502 $this->_options[$k] = $v;
1504 if (empty($this->_stack))
1505 $this->_stack = new Stack();
1506 $this->_stack->push($stack);
1508 function _restoreOptions() {
1509 assert($this->_stack);
1510 $stack = $this->_stack->pop();
1511 $this->_pages = $stack['pages'];
1512 unset($stack['pages']);
1513 foreach ($stack as $k => $v) {
1514 $this->_options[$k] = $v;
1518 // 'cols' - split into several columns
1519 // 'azhead' - support <h3> grouping into initials
1520 // 'ordered' - OL or UL list (not yet inherited to all plugins)
1521 // 'comma' - condensed comma-list only, 1: no links, >1: with links
1522 // FIXME: only unique list entries, esp. with nopage
1523 function _generateList($caption='') {
1524 if (empty($this->_pages)) return; // stop recursion
1525 if (!isset($this->_options['listtype']))
1526 $this->_options['listtype'] = '';
1528 foreach ($this->_pages as $pagenum => $page) {
1529 $one_row = $this->_renderPageRow($page);
1530 $rows[] = array('header' => WikiLink($page), 'render' => $one_row);
1531 if ($one_row) $nb_row++;
1535 $caption = preg_replace('/{total}/', $nb_row, asString($caption));
1536 $out->pushContent(HTML::p($caption));
1538 // Semantic Search et al: only unique list entries, esp. with nopage
1539 if (!is_array($this->_pages[0]) and is_string($this->_pages[0])) {
1540 $this->_pages = array_unique($this->_pages);
1542 if (count($this->_sortby) > 0) $this->_sortPages();
1543 $count = $this->getTotal();
1544 $do_paging = ( isset($this->_options['paging'])
1545 and !empty($this->_options['limit'])
1547 and $this->_options['paging'] != 'none' );
1549 $tokens = $this->pagingTokens($count,
1550 count($this->_columns),
1551 $this->_options['limit']);
1553 $paging = Template("pagelink", $tokens);
1554 $out->pushContent(HTML::table(array('width'=>'50%'), $paging));
1558 // need a recursive switch here for the azhead and cols grouping.
1559 if (!empty($this->_options['cols']) and $this->_options['cols'] > 1) {
1560 $count = count($this->_pages);
1561 $length = intval($count / ($this->_options['cols']));
1562 // If division does not give an integer, we need one more line
1563 // E.g. 13 pages to display in 3 columns.
1564 if (($length * ($this->_options['cols'])) != $count) {
1567 $width = sprintf("%d", 100 / $this->_options['cols']).'%';
1568 $cols = HTML::tr(array('valign' => 'top'));
1569 for ($i=0; $i < $count; $i += $length) {
1570 $this->_saveOptions(array('cols' => 0, 'paging' => 'none'));
1571 $this->_pages = array_slice($this->_pages, $i, $length);
1572 $cols->pushContent(HTML::td(/*array('width' => $width),*/
1573 $this->_generateList()));
1574 $this->_restoreOptions();
1576 // speed up table rendering by defining colgroups
1577 $out->pushContent(HTML::table(HTML::colgroup(array('span' => $this->_options['cols'],
1578 'width' => $width)),
1583 // Ignore azhead if not sorted by pagename
1584 if (!empty($this->_options['azhead'])
1585 and strstr($this->sortby($this->_options['sortby'], 'init'), "pagename")
1588 $cur_h = substr($this->_pages[0]->getName(), 0, 1);
1589 $out->pushContent(HTML::h3($cur_h));
1590 // group those pages together with same $h
1592 for ($i=0; $i < count($this->_pages); $i++) {
1593 $page =& $this->_pages[$i];
1594 $h = substr($page->getName(), 0, 1);
1595 if ($h != $cur_h and $i > $j) {
1596 $this->_saveOptions(array('cols' => 0, 'azhead' => 0));
1597 $this->_pages = array_slice($this->_pages, $j, $i - $j);
1598 $out->pushContent($this->_generateList());
1599 $this->_restoreOptions();
1601 $out->pushContent(HTML::h3($h));
1605 if ($i > $j) { // flush the rest
1606 $this->_saveOptions(array('cols' => 0, 'azhead' => 0));
1607 $this->_pages = array_slice($this->_pages, $j, $i - $j);
1608 $out->pushContent($this->_generateList());
1609 $this->_restoreOptions();
1614 if ($this->_options['listtype'] == 'comma')
1615 $this->_options['comma'] = 2;
1616 if (!empty($this->_options['comma'])) {
1617 if ($this->_options['comma'] == 1)
1618 $out->pushContent($this->_generateCommaListAsString());
1620 $out->pushContent($this->_generateCommaList($this->_options['comma']));
1624 if ($this->_options['listtype'] == 'ol')
1625 $this->_options['ordered'] = 1;
1626 elseif ($this->_options['listtype'] == 'ul')
1627 $this->_options['ordered'] = 0;
1628 if (!empty($this->_options['ordered']))
1629 $list = HTML::ol(array('class' => 'pagelist'));
1630 elseif ($this->_options['listtype'] == 'dl') {
1631 $list = HTML::dl(array('class' => 'pagelist'));
1633 $list = HTML::ul(array('class' => 'pagelist'));
1636 //TODO: currently we ignore limit here and hope that the backend didn't ignore it. (BackLinks)
1637 if (!empty($this->_options['limit']))
1638 list($offset, $pagesize) = $this->limit($this->_options['limit']);
1641 foreach (array_reverse($rows) as $one_row) {
1642 $pagehtml = $one_row['render'];
1643 if (!$pagehtml) continue;
1644 $group = ($i++ / $this->_group_rows);
1645 //TODO: here we switch every row, in tables every third.
1646 // unification or parametrized?
1647 $class = ($group % 2) ? 'oddrow' : 'evenrow';
1648 if ($this->_options['listtype'] == 'dl') {
1649 $header = $one_row['header'];
1650 //if ($this->_sortby['hi_content'])
1651 $list->pushContent(HTML::dt(array('class' => $class), $header),
1652 HTML::dd(array('class' => $class), $pagehtml));
1654 $list->pushContent(HTML::li(array('class' => $class), $pagehtml));
1655 if ($pagesize and $i > $pagesize) break;
1657 $out->pushContent($list);
1658 if ( $do_paging and $tokens ) {
1659 $out->pushContent(HTML::table($paging));
1665 // Condense list without a href links: "Page1, Page2, ..."
1666 // Alternative $seperator = HTML::Raw(' · ')
1667 // FIXME: only unique list entries, esp. with nopage
1668 function _generateCommaListAsString() {
1669 if (defined($this->_options['commasep']))
1670 $seperator = $this->_options['commasep'];
1674 foreach ($this->_pages as $pagenum => $page) {
1675 if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1676 $pages[] = is_string($s) ? $s : $s->asString();
1678 return HTML(join($seperator, $pages));
1682 // Normal WikiLink list.
1683 // Future: 1 = reserved for plain string (see above)
1684 // 2 and more => HTML link specialization?
1685 // FIXME: only unique list entries, esp. with nopage
1686 function _generateCommaList($style = false) {
1687 if (defined($this->_options['commasep']))
1688 $seperator = HTLM::Raw($this->_options['commasep']);
1692 $html->pushContent($this->_renderPageRow($this->_pages[0]));
1693 next($this->_pages);
1694 foreach ($this->_pages as $pagenum => $page) {
1695 if ($s = $this->_renderPageRow($page)) // some pages are not viewable
1696 $html->pushContent($seperator, $s);
1701 function _emptyList($caption) {
1704 $caption = preg_replace('/{total}/', '0', asString($caption));
1705 $html->pushContent(HTML::p($caption));
1707 if ($this->_messageIfEmpty)
1708 $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
1714 /* List pages with checkboxes to select from.
1715 * The [Select] button toggles via Javascript flipAll
1718 class PageList_Selectable
1721 function PageList_Selectable ($columns=false, $exclude='', $options = false) {
1723 if (!is_array($columns))
1724 $columns = explode(',', $columns);
1725 if (!in_array('checkbox',$columns))
1726 array_unshift($columns,'checkbox');
1728 $columns = array('checkbox','pagename');
1730 $this->PageList($columns, $exclude, $options);
1733 function addPageList ($array) {
1734 while (list($pagename,$selected) = each($array)) {
1735 if ($selected) $this->addPageSelected((string)$pagename);
1736 $this->addPage((string)$pagename);
1740 function addPageSelected ($pagename) {
1741 $this->_selected[$pagename] = 1;
1745 class PageList_Unselectable
1748 function PageList_Unselectable ($columns=false, $exclude='', $options = false) {
1750 if (!is_array($columns))
1751 $columns = explode(',', $columns);
1753 $columns = array('pagename');
1755 $this->PageList($columns, $exclude, $options);
1758 function addPageList ($array) {
1759 while (list($pagename,$selected) = each($array)) {
1760 if ($selected) $this->addPageSelected((string)$pagename);
1761 $this->addPage((string)$pagename);
1765 function addPageSelected ($pagename) {
1766 $this->_selected[$pagename] = 1;
1770 // (c-file-style: "gnu")
1774 // c-basic-offset: 4
1775 // c-hanging-comment-ender-p: nil
1776 // indent-tabs-mode: nil