]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
add DEFAULT_DUMP_DIR and HTML_DUMP_DIR constants, for easier cmdline dumps,
[SourceForge/phpwiki.git] / lib / PageList.php
1 <?php rcs_id('$Id: PageList.php,v 1.91 2004-06-21 16:22:29 rurban Exp $');
2
3 /**
4  * List a number of pagenames, optionally as table with various columns.
5  * This library relieves some work for these plugins:
6  *
7  * AllPages, BackLinks, LikePages, MostPopular, TitleSearch, WikiAdmin* and more
8  *
9  * It also allows dynamic expansion of those plugins to include more
10  * columns in their output.
11  *
12  * Column 'info=' arguments:
13  *
14  * 'pagename' _("Page Name")
15  * 'mtime'    _("Last Modified")
16  * 'hits'     _("Hits")
17  * 'summary'  _("Last Summary")
18  * 'version'  _("Version")),
19  * 'author'   _("Last Author")),
20  * 'locked'   _("Locked"), _("locked")
21  * 'minor'    _("Minor Edit"), _("minor")
22  * 'markup'   _("Markup")
23  * 'size'     _("Size")
24  * 'creator'  _("Creator")
25  * 'owner'    _("Owner")
26  * 'checkbox'  selectable checkbox at the left.
27  * 'content'  
28  *
29  * Special, custom columns: Either theme or plugin (WikiAdmin*) specific.
30  * 'remove'   _("Remove")     
31  * 'perm'     _("Permission Mask")
32  * 'acl'      _("ACL")
33  * 'renamed_pagename'   _("Rename to")
34  * 'ratingwidget', ... wikilens theme specific.
35  * 'custom'   See plugin/WikiTranslation
36  *
37  * Symbolic 'info=' arguments:
38  * 'all'       All columns except the special columns
39  * 'most'      pagename, mtime, author, size, hits, ...
40  * 'some'      pagename, mtime, author
41  *
42  * FIXME: In this refactoring I (Jeff) have un-implemented _ctime, _cauthor, and
43  * number-of-revision.  Note the _ctime and _cauthor as they were implemented
44  * were somewhat flawed: revision 1 of a page doesn't have to exist in the
45  * database.  If lots of revisions have been made to a page, it's more than likely
46  * that some older revisions (include revision 1) have been cleaned (deleted).
47  *
48  * DONE: 
49  *   check PagePerm "list" access-type,
50  *   all columns are sortable (Thanks to the wikilens team).
51  *
52  * TODO: 
53  *   limit, offset, rows arguments for multiple pages/multiple rows.
54  *
55  *   ->supportedArgs() which arguments are supported, so that the plugin 
56  *                     doesn't explictly need to declare it
57  *   new method:
58  *     list not as <ul> or table, but as simple comma-seperated list
59  */
60 class _PageList_Column_base {
61     var $_tdattr = array();
62
63     function _PageList_Column_base ($default_heading, $align = false) {
64         $this->_heading = $default_heading;
65
66         if ($align) {
67             // align="char" isn't supported by any browsers yet :(
68             //if (is_array($align))
69             //    $this->_tdattr = $align;
70             //else
71             $this->_tdattr['align'] = $align;
72         }
73     }
74
75     function format ($pagelist, $page_handle, &$revision_handle) {
76         return HTML::td($this->_tdattr,
77                         HTML::raw('&nbsp;'),
78                         $this->_getValue($page_handle, $revision_handle),
79                         HTML::raw('&nbsp;'));
80     }
81
82     function getHeading () {
83         return $this->_heading;
84     }
85
86     function setHeading ($heading) {
87         $this->_heading = $heading;
88     }
89
90     // old-style heading
91     function heading () {
92         // allow sorting?
93         if (1 or in_array($this->_field, PageList::sortable_columns())) {
94             // multiple comma-delimited sortby args: "+hits,+pagename"
95             // asc or desc: +pagename, -pagename
96             $sortby = PageList::sortby($this->_field, 'flip_order');
97             //Fixme: pass all also other GET args along. (limit, p[])
98             //TODO: support GET and POST
99             $s = HTML::a(array('href' => 
100                                $GLOBALS['request']->GetURLtoSelf(array('sortby' => $sortby,
101                                                                        'nocache' => '1')),
102                                'class' => 'pagetitle',
103                                'title' => sprintf(_("Sort by %s"), $this->_field)), 
104                          HTML::raw('&nbsp;'), HTML::u($this->_heading), HTML::raw('&nbsp;'));
105         } else {
106             $s = HTML(HTML::raw('&nbsp;'), HTML::u($this->_heading), HTML::raw('&nbsp;'));
107         }
108         return HTML::th(array('align' => 'center'),$s);
109     }
110
111     // new grid-style
112     // see activeui.js 
113     function button_heading ($pagelist, $colNum) {
114         global $WikiTheme, $request;
115         // allow sorting?
116         if (1 or in_array($this->_field, PageList::sortable_columns())) {
117             // multiple comma-delimited sortby args: "+hits,+pagename"
118             $src = false; 
119             $noimg_src = $WikiTheme->getButtonURL('no_order');
120             if ($noimg_src)
121                 $noimg = HTML::img(array('src' => $noimg_src,
122                                          'width' => '7', 
123                                          'height' => '7',
124                                          'border' => 0,
125                                          'alt'    => '.'));
126             else 
127                 $noimg = HTML::raw('&nbsp;');
128             if ($request->getArg('sortby')) {
129                 if ($pagelist->sortby($colNum, 'check')) { // show icon?
130                     $sortby = $pagelist->sortby($request->getArg('sortby'), 'flip_order');
131                     $request->setArg('sortby', $sortby);
132                     $desc = (substr($sortby,0,1) == '-'); // asc or desc? (+pagename, -pagename)
133                     $src = $WikiTheme->getButtonURL($desc ? 'asc_order' : 'desc_order');
134                 } else {
135                     $sortby = $pagelist->sortby($colNum, 'init');
136                 }
137             } else {
138                 $sortby = $pagelist->sortby($colNum, 'init');
139             }
140             if (!$src) {
141                 $img = $noimg;
142                 //$img->setAttr('alt', _("Click to sort"));
143             } else {
144                 $img = HTML::img(array('src' => $src, 
145                                        'width' => '7', 
146                                        'height' => '7', 
147                                        'border' => 0,
148                                        'alt' => _("Click to reverse sort order")));
149             }
150             $s = HTML::a(array('href' => 
151                                //Fixme: pass all also other GET args along. (limit, p[])
152                                //Fixme: convert to POST submit[sortby]
153                                $request->GetURLtoSelf(array('sortby' => $sortby,
154                                                             'nocache' => '1')),
155                                'class' => 'gridbutton', 
156                                'title' => sprintf(_("Click to sort by %s"), $this->_field)),
157                          HTML::raw('&nbsp;'),
158                          $noimg,
159                          HTML::raw('&nbsp;'),
160                          $this->_heading,
161                          HTML::raw('&nbsp;'),
162                          $img,
163                          HTML::raw('&nbsp;'));
164         } else {
165             $s = HTML(HTML::raw('&nbsp;'), $this->_heading, HTML::raw('&nbsp;'));
166         }
167         return HTML::th(array('align' => 'center', 'valign' => 'middle', 
168                               'class' => 'gridbutton'), $s);
169     }
170
171     /**
172      * Take two columns of this type and compare them.
173      * An undefined value is defined to be < than the smallest defined value.
174      * This base class _compare only works if the value is simple (e.g., a number).
175      *
176      * @param  $colvala  $this->_getValue() of column a
177      * @param  $colvalb  $this->_getValue() of column b
178      *
179      * @return -1 if $a < $b, 1 if $a > $b, 0 otherwise.
180      */
181     function _compare($colvala, $colvalb) {
182         if (is_string($colvala))
183             return strcmp($colvala,$colvalb);
184         $ret = 0;
185         if (($colvala === $colvalb) || (!isset($colvala) && !isset($colvalb))) {
186             ;
187         } else {
188             $ret = (!isset($colvala) || ($colvala < $colvalb)) ? -1 : 1;
189         }
190         return $ret; 
191     }
192 };
193
194 class _PageList_Column extends _PageList_Column_base {
195     function _PageList_Column ($field, $default_heading, $align = false) {
196         $this->_PageList_Column_base($default_heading, $align);
197
198         $this->_need_rev = substr($field, 0, 4) == 'rev:';
199         $this->_iscustom = substr($field, 0, 7) == 'custom:';
200         if ($this->_iscustom) {
201             $this->_field = substr($field, 7);
202         }
203         elseif ($this->_need_rev)
204             $this->_field = substr($field, 4);
205         else
206             $this->_field = $field;
207     }
208
209     function _getValue ($page_handle, &$revision_handle) {
210         if ($this->_need_rev) {
211             if (!$revision_handle)
212                 $revision_handle = $page_handle->getCurrentRevision();
213             return $revision_handle->get($this->_field);
214         }
215         else {
216             return $page_handle->get($this->_field);
217         }
218     }
219     
220     function _getSortableValue ($page_handle, &$revision_handle) {
221         return _PageList_Column::_getValue($page_handle, $revision_handle);
222     }
223 };
224
225 /* overcome a call_user_func limitation by not being able to do:
226  * call_user_func_array(array(&$class, $class_name), $params);
227  * So we need $class = new $classname($params);
228  * And we add a 4th param for the parent $pagelist object
229  */
230 class _PageList_Column_custom extends _PageList_Column {
231     function _PageList_Column_custom($params) {
232         $this->_pagelist =& $params[3];
233         $this->_PageList_Column($params[0], $params[1], $params[2]);
234     }
235 }
236
237 class _PageList_Column_size extends _PageList_Column {
238     function _getValue ($page_handle, &$revision_handle) {
239         if (!$revision_handle)
240             $revision_handle = $page_handle->getCurrentRevision();
241         return $this->_getSize($revision_handle);
242     }
243     
244     function _getSortableValue ($page_handle, &$revision_handle) {
245         if (!$revision_handle)
246             $revision_handle = $page_handle->getCurrentRevision();
247         return (empty($revision_handle->_data['%content'])) 
248                ? 0 : strlen($revision_handle->_data['%content']);
249     }
250
251     function _getSize($revision_handle) {
252         $bytes = @strlen($revision_handle->_data['%content']);
253         return ByteFormatter($bytes);
254     }
255 }
256
257
258 class _PageList_Column_bool extends _PageList_Column {
259     function _PageList_Column_bool ($field, $default_heading, $text = 'yes') {
260         $this->_PageList_Column($field, $default_heading, 'center');
261         $this->_textIfTrue = $text;
262         $this->_textIfFalse = new RawXml('&#8212;'); //mdash
263     }
264
265     function _getValue ($page_handle, &$revision_handle) {
266         //FIXME: check if $this is available in the parent (->need_rev)
267         $val = _PageList_Column::_getValue($page_handle, $revision_handle);
268         return $val ? $this->_textIfTrue : $this->_textIfFalse;
269     }
270 };
271
272 class _PageList_Column_checkbox extends _PageList_Column {
273     function _PageList_Column_checkbox ($field, $default_heading, $name='p') {
274         $this->_name = $name;
275         $heading = HTML::input(array('type'  => 'button',
276                                      'title' => _("Click to de-/select all pages"),
277                                      //'width' => '100%',
278                                      'name'  => $default_heading,
279                                      'value' => $default_heading,
280                                      'onclick' => "flipAll(this.form)"
281                                      ));
282         $this->_PageList_Column($field, $heading, 'center');
283     }
284     function _getValue ($pagelist, $page_handle, &$revision_handle) {
285         $pagename = $page_handle->getName();
286         $selected = !empty($pagelist->_selected[$pagename]);
287         if (strstr($pagename,'[') or strstr($pagename,']')) {
288             $pagename = str_replace(array('[',']'),array('%5B','%5D'),$pagename);
289         }
290         if ($selected) {
291             return HTML::input(array('type' => 'checkbox',
292                                      'name' => $this->_name . "[$pagename]",
293                                      'value' => 1,
294                                      'checked' => 'CHECKED'));
295         } else {
296             return HTML::input(array('type' => 'checkbox',
297                                      'name' => $this->_name . "[$pagename]",
298                                      'value' => 1));
299         }
300     }
301     function format ($pagelist, $page_handle, &$revision_handle) {
302         return HTML::td($this->_tdattr,
303                         HTML::raw('&nbsp;'),
304                         $this->_getValue($pagelist, $page_handle, $revision_handle),
305                         HTML::raw('&nbsp;'));
306     }
307 };
308
309 class _PageList_Column_time extends _PageList_Column {
310     function _PageList_Column_time ($field, $default_heading) {
311         $this->_PageList_Column($field, $default_heading, 'right');
312         global $WikiTheme;
313         $this->Theme = &$WikiTheme;
314     }
315
316     function _getValue ($page_handle, &$revision_handle) {
317         $time = _PageList_Column::_getValue($page_handle, $revision_handle);
318         return $this->Theme->formatDateTime($time);
319     }
320 };
321
322 class _PageList_Column_version extends _PageList_Column {
323     function _getValue ($page_handle, &$revision_handle) {
324         if (!$revision_handle)
325             $revision_handle = $page_handle->getCurrentRevision();
326         return $revision_handle->getVersion();
327     }
328 };
329
330 // Output is hardcoded to limit of first 50 bytes. Otherwise
331 // on very large Wikis this will fail if used with AllPages
332 // (PHP memory limit exceeded)
333 // FIXME: old PHP without superglobals
334 class _PageList_Column_content extends _PageList_Column {
335     function _PageList_Column_content ($field, $default_heading, $align = false) {
336         $this->_PageList_Column($field, $default_heading, $align);
337         $this->bytes = 50;
338         if ($field == 'content') {
339             $this->_heading .= sprintf(_(" ... first %d bytes"),
340                                        $this->bytes);
341         } elseif ($field == 'hi_content') {
342             if (!empty($_POST['admin_replace'])) {
343                 $search = $_POST['admin_replace']['from'];
344                 $this->_heading .= sprintf(_(" ... around %s"),
345                                            '»'.$search.'«');
346             }
347         }
348     }
349     function _getValue ($page_handle, &$revision_handle) {
350         if (!$revision_handle)
351             $revision_handle = $page_handle->getCurrentRevision();
352         // Not sure why implode is needed here, I thought
353         // getContent() already did this, but it seems necessary.
354         $c = implode("\n", $revision_handle->getContent());
355         if ($this->_field == 'hi_content') {
356             $search = $_POST['admin_replace']['from'];
357             if ($search and ($i = strpos($c,$search))) {
358                 $l = strlen($search);
359                 $j = max(0,$i - ($this->bytes / 2));
360                 return HTML::div(array('style' => 'font-size:x-small'),
361                                  HTML::div(array('class' => 'transclusion'),
362                                            HTML::span(substr($c, $j, ($this->bytes / 2))),
363                                            HTML::span(array("style"=>"background:yellow"),$search),
364                                            HTML::span(substr($c, $i+$l, ($this->bytes / 2))))
365                                  );
366             } else {
367                 $c = sprintf(_("%s not found"),
368                              '»'.$search.'«');
369                 return HTML::div(array('style' => 'font-size:x-small','align'=>'center'),
370                                  $c);
371             }
372         } elseif (($len = strlen($c)) > $this->bytes) {
373             $c = substr($c, 0, $this->bytes);
374         }
375         include_once('lib/BlockParser.php');
376         // false --> don't bother processing hrefs for embedded WikiLinks
377         $ct = TransformText($c, $revision_handle->get('markup'), false);
378         return HTML::div(array('style' => 'font-size:x-small'),
379                          HTML::div(array('class' => 'transclusion'), $ct),
380                          // Don't show bytes here if size column present too
381                          ($this->parent->_columns_seen['size'] or !$len) ? "" :
382                            ByteFormatter($len, /*$longformat = */true));
383     }
384     
385     function _getSortableValue ($page_handle, &$revision_handle) {
386         return substr(_PageList_Column::_getValue($page_handle, $revision_handle),0,50);
387     }
388 };
389
390 class _PageList_Column_author extends _PageList_Column {
391     function _PageList_Column_author ($field, $default_heading, $align = false) {
392         _PageList_Column::_PageList_Column($field, $default_heading, $align);
393         $this->dbi =& $GLOBALS['request']->getDbh();
394     }
395
396     function _getValue ($page_handle, &$revision_handle) {
397         $author = _PageList_Column::_getValue($page_handle, $revision_handle);
398         if (isWikiWord($author) && $this->dbi->isWikiPage($author))
399             return WikiLink($author);
400         else
401             return $author;
402     }
403 };
404
405 class _PageList_Column_owner extends _PageList_Column_author {
406     function _getValue ($page_handle, &$revision_handle) {
407         $author = $page_handle->getOwner();
408         if (isWikiWord($author) && $this->dbi->isWikiPage($author))
409             return WikiLink($author);
410         else
411             return $author;
412     }
413 };
414
415 class _PageList_Column_creator extends _PageList_Column_author {
416     function _getValue ($page_handle, &$revision_handle) {
417         $author = $page_handle->getCreator();
418         if (isWikiWord($author) && $this->dbi->isWikiPage($author))
419             return WikiLink($author);
420         else
421             return $author;
422     }
423 };
424
425 class _PageList_Column_pagename extends _PageList_Column_base {
426     var $_field = 'pagename';
427
428     function _PageList_Column_pagename () {
429         $this->_PageList_Column_base(_("Page Name"));
430         global $request;
431         $this->dbi = &$request->getDbh();
432     }
433
434     function _getValue ($page_handle, &$revision_handle) {
435         if ($this->dbi->isWikiPage($page_handle->getName()))
436             return WikiLink($page_handle);
437         else
438             return WikiLink($page_handle, 'unknown');
439     }
440     
441     function _getSortableValue ($page_handle, &$revision_handle) {
442         return $page_handle->getName();
443     }
444
445     /**
446      * Compare two pagenames for sorting.  See _PageList_Column::_compare.
447      **/
448     function _compare($colvala, $colvalb) {
449         return strcmp($colvala, $colvalb);
450     }
451 };
452
453 /**
454  * A class to bundle up a page with a reference to PageList, so that
455  * the compare function for usort() has access to it all.
456  * This is a hack necessitated by the interface to usort()-- comparators
457  * can't get information upon construction; you get a comparator by class
458  * name, not by instance.
459  */
460 class _PageList_Page {
461     var $_pagelist;
462     var $_page;
463
464     function _PageList_Page($pagelist, $page_handle) {
465         $this->_pagelist = $pagelist;
466         $this->_page = $page_handle;
467     }
468
469     function getPageList() {
470         return $this->_pagelist;
471     }
472
473     function getPage() {
474         return $this->_page;
475     }
476 }
477
478 class PageList {
479     var $_group_rows = 3;
480     var $_columns = array();
481     var $_columnsMap = array();      // Maps column name to column number.
482     var $_excluded_pages = array();
483     var $_pages = array();
484     var $_caption = "";
485     var $_pagename_seen = false;
486     var $_types = array();
487     var $_options = array();
488     var $_selected = array();
489     var $_sortby = array();
490     var $_maxlen = 0;
491
492     function PageList ($columns = false, $exclude = false, $options = false) {
493         if ($options)
494             $this->_options = $options;
495
496         // let plugins predefine only certain objects, such its own custom pagelist columns
497         if (!empty($this->_options['types'])) {
498             $this->_types = $this->_options['types'];
499             unset($this->_options['types']);
500         }
501         $this->_initAvailableColumns();
502         $symbolic_columns = 
503             array(
504                   'all' =>  array_diff(array_keys($this->_types), // all but...
505                                        array('checkbox','remove','renamed_pagename',
506                                              'content','hi_content','perm','acl')),
507                   'most' => array('pagename','mtime','author','size','hits'),
508                   'some' => array('pagename','mtime','author')
509                   );
510         if ($columns) {
511             if (!is_array($columns))
512                 $columns = explode(',', $columns);
513             // expand symbolic columns:
514             foreach ($symbolic_columns as $symbol => $cols) {
515                 if (in_array($symbol,$columns)) { // e.g. 'checkbox,all'
516                     $columns = array_diff(array_merge($columns,$cols),array($symbol));
517                 }
518             }
519             if (!in_array('pagename',$columns))
520                 $this->_addColumn('pagename');
521             foreach ($columns as $col) {
522                 $this->_addColumn($col);
523             }
524         }
525         // If 'pagename' is already present, _addColumn() will not add it again
526         $this->_addColumn('pagename');
527
528         foreach (array('sortby','limit','paging','count') as $key) {
529           if (!empty($options) and !empty($options[$key])) {
530             $this->_options[$key] = $options[$key];
531           } else {
532             $this->_options[$key] = $GLOBALS['request']->getArg($key);
533           }
534         }
535         $this->_options['sortby'] = $this->sortby($this->_options['sortby'], 'init');
536         if ($exclude) {
537             if (!is_array($exclude))
538                 $exclude = $this->explodePageList($exclude,false,
539                                                   $this->_options['sortby'],
540                                                   $this->_options['limit']);
541             $this->_excluded_pages = $exclude;
542         }
543         $this->_messageIfEmpty = _("<no matches>");
544     }
545
546     // Currently PageList takes these arguments:
547     // 1: info, 2: exclude, 3: hash of options
548     // Here we declare which options are supported, so that 
549     // the calling plugin may simply merge this with its own default arguments 
550     function supportedArgs () {
551         return array(//Currently supported options:
552                      'info'              => 'pagename',
553                      'exclude'           => '',          // also wildcards and comma-seperated lists
554
555                      /* select pages by meta-data: */
556                      'author'   => false, // current user by []
557                      'owner'    => false, // current user by []
558                      'creator'  => false, // current user by []
559
560                      // for the sort buttons in <th>
561                      'sortby'            => 'pagename', // same as for WikiDB::getAllPages
562
563                      //PageList pager options:
564                      // These options may also be given to _generate(List|Table) later
565                      // But limit and offset might help the query WikiDB::getAllPages()
566                      'cols'     => 1,       // side-by-side display of list (1-3)
567                      'limit'    => 0,       // number of rows (pagesize)
568                      'paging'   => 'auto',  // 'auto'  normal paging mode
569                      //                     // 'smart' drop 'info' columns and enhance rows 
570                      //                     //         when the list becomes large
571                      //                     // 'none'  don't page at all
572                      //'azhead' => 0        // provide shortcut links to pages starting with different letters
573                      );
574     }
575
576     function setCaption ($caption_string) {
577         $this->_caption = $caption_string;
578     }
579
580     function getCaption () {
581         // put the total into the caption if needed
582         if (is_string($this->_caption) && strstr($this->_caption, '%d'))
583             return sprintf($this->_caption, $this->getTotal());
584         return $this->_caption;
585     }
586
587     function setMessageIfEmpty ($msg) {
588         $this->_messageIfEmpty = $msg;
589     }
590
591
592     function getTotal () {
593         return !empty($this->_options['count'])
594                ? (integer) $this->_options['count'] : count($this->_pages);
595     }
596
597     function isEmpty () {
598         return empty($this->_pages);
599     }
600
601     function addPage($page_handle) {
602         $this->_pages[] = new _PageList_Page($this, $page_handle);
603     }
604
605     function _getPageFromHandle($ph) {
606         $page_handle = $ph;
607         if (is_string($page_handle)) {
608             if (empty($page_handle)) return $page_handle;
609             $dbi = $GLOBALS['request']->getDbh();
610             $page_handle = $dbi->getPage($page_handle);
611         }
612         return $page_handle;
613     }
614
615     /**
616      * Take a PageList_Page object, and return an HTML object to display
617      * it in a table or list row.
618      */
619     function _renderPageRow ($pagelist_page) {
620         $page_handle = $pagelist_page->getPage();
621
622         $page_handle = $this->_getPageFromHandle($page_handle);
623         if (!isset($page_handle) || empty($page_handle)
624             || in_array($page_handle->getName(), $this->_excluded_pages))
625             return; // exclude page.
626             
627         //FIXME. only on sf.net
628         if (!is_object($page_handle)) {
629             trigger_error("PageList: Invalid page_handle $page_handle", E_USER_WARNING);
630             return;
631         }
632         // enforce view permission
633         if (!mayAccessPage('view',$page_handle->getName()))
634             return;
635
636         $group = (int)($this->getTotal() / $this->_group_rows);
637         $class = ($group % 2) ? 'oddrow' : 'evenrow';
638         $revision_handle = false;
639         $this->_maxlen = max($this->_maxlen, strlen($page_handle->getName()));
640
641         if (count($this->_columns) > 1) {
642             $row = HTML::tr(array('class' => $class));
643             foreach ($this->_columns as $col)
644                 $row->pushContent($col->format($this, $page_handle, $revision_handle));
645         }
646         else {
647             $col = $this->_columns[0];
648             $row = $col->_getValue($page_handle, $revision_handle);
649         }
650
651         return $row;
652     }
653
654     function addPages ($page_iter) {
655         //Todo: if limit check max(strlen(pagename))
656         while ($page = $page_iter->next())
657             $this->addPage($page);
658     }
659
660     function addPageList (&$list) {
661         reset ($list);
662         while ($page = next($list))
663             $this->addPage((string)$page);
664     }
665
666     function maxLen() {
667         global $DBParams, $request;
668         if ($DBParams['dbtype'] == 'SQL' or $DBParams['dbtype'] == 'ADODB') {
669             $dbi =& $request->getDbh();
670             extract($dbi->_backend->_table_names);
671             if ($DBParams['dbtype'] == 'SQL') {
672                 $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl LIMIT 1");
673                 if (DB::isError($res) || empty($res)) return false;
674                 else return $res;
675             } elseif ($DBParams['dbtype'] == 'ADODB') {
676                 $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl LIMIT 1");
677                 return $row ? $row[0] : false;
678             }
679         } else 
680             return false;
681     }
682
683     function getContent() {
684         // Note that the <caption> element wants inline content.
685         $caption = $this->getCaption();
686
687         if ($this->isEmpty())
688             return $this->_emptyList($caption);
689         elseif (count($this->_columns) == 1)
690             return $this->_generateList($caption);
691         else
692             return $this->_generateTable($caption);
693     }
694
695     function printXML() {
696         PrintXML($this->getContent());
697     }
698
699     function asXML() {
700         return AsXML($this->getContent());
701     }
702     
703     /** Now all columns are sortable. 
704      *  These are the colums which have native WikiDB backend methods. 
705      */
706     function sortable_columns() {
707         return array('pagename','mtime','hits');
708     }
709
710     /** 
711      * Handle sortby requests for the DB iterator and table header links.
712      * Prefix the column with + or - like "+pagename","-mtime", ...
713      * supported actions: 'flip_order' "mtime" => "+mtime" => "-mtime" ...
714      *                    'db'         "-pagename" => "pagename DESC"
715      * Now all columns are sortable. (patch by DanFr)
716      */
717     function sortby ($column, $action) {
718         if (empty($column)) return;
719         //support multiple comma-delimited sortby args: "+hits,+pagename"
720         if (strstr($column,',')) {
721             $result = array();
722             foreach (explode(',',$column) as $col) {
723                 $result[] = $this->sortby($col,$action);
724             }
725             return join(",",$result);
726         }
727         if (substr($column,0,1) == '+') {
728             $order = '+'; $column = substr($column,1);
729         } elseif (substr($column,0,1) == '-') {
730             $order = '-'; $column = substr($column,1);
731         }
732         // default order: +pagename, -mtime, -hits
733         if (empty($order))
734             if (in_array($column,array('mtime','hits')))
735                 $order = '-';
736             else
737                 $order = '+';
738         if ($action == 'flip_order') {
739             return ($order == '+' ? '-' : '+') . $column;
740         } elseif ($action == 'init') {
741             $this->_sortby[$column] = $order;
742             return $order . $column;
743         } elseif ($action == 'check') {
744             return (!empty($this->_sortby[$column]) or 
745                     ($GLOBALS['request']->getArg('sortby') and 
746                      strstr($GLOBALS['request']->getArg('sortby'),$column)));
747         } elseif ($action == 'db') {
748             // asc or desc: +pagename, -pagename
749             return $column . ($order == '+' ? ' ASC' : ' DESC');
750         }
751         return '';
752     }
753
754     // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
755     function explodePageList($input, $perm = false, $sortby=false, $limit=false) {
756         // expand wildcards from list of all pages
757         if (preg_match('/[\?\*]/',$input)) {
758             $dbi = $GLOBALS['request']->getDbh();
759             $allPagehandles = $dbi->getAllPages($perm,$sortby,$limit);
760             while ($pagehandle = $allPagehandles->next()) {
761                 $allPages[] = $pagehandle->getName();
762             }
763             return explodeList($input, $allPages);
764         } else {
765             //TODO: do the sorting, normally not needed if used for exclude only
766             return explode(',',$input);
767         }
768     }
769
770     function allPagesByAuthor($wildcard, $perm=false, $sortby=false, $limit=false) {
771         $dbi = $GLOBALS['request']->getDbh();
772         $allPagehandles = $dbi->getAllPages($perm, $sortby, $limit);
773         $allPages = array();
774         if ($wildcard === '[]') {
775             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
776             if (!$wildcard) return $allPages;
777         }
778         while ($pagehandle = $allPagehandles->next()) {
779             $name = $pagehandle->getName();
780             $author = $pagehandle->getAuthor();
781             if ($author) {
782                 if (preg_match('/[\?\*]/', $wildcard)) {
783                     if (glob_match($wildcard, $author))
784                         $allPages[] = $name;
785                 } elseif ($wildcard == $author) {
786                       $allPages[] = $name;
787                 }
788             }
789         }
790         return $allPages;
791     }
792
793     function allPagesByOwner($wildcard, $perm=false, $sortby=false, $limit=false) {
794         $dbi = $GLOBALS['request']->getDbh();
795         $allPagehandles = $dbi->getAllPages($perm, $sortby, $limit);
796         $allPages = array();
797         if ($wildcard === '[]') {
798             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
799             if (!$wildcard) return $allPages;
800         }
801         while ($pagehandle = $allPagehandles->next()) {
802             $name = $pagehandle->getName();
803             $owner = $pagehandle->getOwner();
804             if ($owner) {
805                 if (preg_match('/[\?\*]/', $wildcard)) {
806                     if (glob_match($wildcard, $owner))
807                         $allPages[] = $name;
808                 } elseif ($wildcard == $owner) {
809                       $allPages[] = $name;
810                 }
811             }
812         }
813         return $allPages;
814     }
815
816     function allPagesByCreator($wildcard, $perm=false, $sortby=false, $limit=false) {
817         $dbi = $GLOBALS['request']->getDbh();
818         $allPagehandles = $dbi->getAllPages($perm, $sortby, $limit);
819         $allPages = array();
820         if ($wildcard === '[]') {
821             $wildcard = $GLOBALS['request']->_user->getAuthenticatedId();
822             if (!$wildcard) return $allPages;
823         }
824         while ($pagehandle = $allPagehandles->next()) {
825             $name = $pagehandle->getName();
826             $creator = $pagehandle->getCreator();
827             if ($creator) {
828                 if (preg_match('/[\?\*]/', $wildcard)) {
829                     if (glob_match($wildcard, $creator))
830                         $allPages[] = $name;
831                 } elseif ($wildcard == $creator) {
832                       $allPages[] = $name;
833                 }
834             }
835         }
836         return $allPages;
837     }
838
839     ////////////////////
840     // private
841     ////////////////////
842     /** Plugin and theme hooks: 
843      *  If the pageList is initialized with $options['types'] these types are also initialized, 
844      *  overriding the standard types.
845      */
846     function _initAvailableColumns() {
847         global $customPageListColumns;
848         $standard_types =
849             array(
850                   'content'
851                   => new _PageList_Column_content('rev:content', _("Content")),
852                   // new: plugin specific column types initialised by the relevant plugins
853                   /*
854                   'hi_content' // with highlighted search for SearchReplace
855                   => new _PageList_Column_content('rev:hi_content', _("Content")),
856                   'remove'
857                   => new _PageList_Column_remove('remove', _("Remove")),
858                   // initialised by the plugin
859                   'renamed_pagename'
860                   => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
861                   'perm'
862                   => new _PageList_Column_perm('perm', _("Permission")),
863                   'acl'
864                   => new _PageList_Column_acl('acl', _("ACL")),
865                   */
866                   'checkbox'
867                   => new _PageList_Column_checkbox('p', _("Select")),
868                   'pagename'
869                   => new _PageList_Column_pagename,
870                   'mtime'
871                   => new _PageList_Column_time('rev:mtime', _("Last Modified")),
872                   'hits'
873                   => new _PageList_Column('hits', _("Hits"), 'right'),
874                   'size'
875                   => new _PageList_Column_size('rev:size', _("Size"), 'right'),
876                                               /*array('align' => 'char', 'char' => ' ')*/
877                   'summary'
878                   => new _PageList_Column('rev:summary', _("Last Summary")),
879                   'version'
880                   => new _PageList_Column_version('rev:version', _("Version"),
881                                                  'right'),
882                   'author'
883                   => new _PageList_Column_author('rev:author', _("Last Author")),
884                   'owner'
885                   => new _PageList_Column_owner('author_id', _("Owner")),
886                   'creator'
887                   => new _PageList_Column_creator('author_id', _("Creator")),
888                   /*
889                   'group'
890                   => new _PageList_Column_author('group', _("Group")),
891                   */
892                   'locked'
893                   => new _PageList_Column_bool('locked', _("Locked"),
894                                                _("locked")),
895                   'minor'
896                   => new _PageList_Column_bool('rev:is_minor_edit',
897                                                _("Minor Edit"), _("minor")),
898                   'markup'
899                   => new _PageList_Column('rev:markup', _("Markup")),
900                   // 'rating' initialised by the wikilens theme hook: addPageListColumn
901                   /*
902                   'rating'
903                   => new _PageList_Column_rating('rating', _("Rate")),
904                   */
905                   );
906         if (empty($this->_types))
907             $this->_types = array();
908         // add plugin specific pageList columns, initialized by $options['types']
909         $this->_types = array_merge($standard_types, $this->_types);
910         // add theme custom specific pageList columns: 
911         //   set the 4th param as the current pagelist object.
912         if (!empty($customPageListColumns)) {
913             foreach ($customPageListColumns as $column => $params) {
914                 $class_name = array_shift($params);
915                 $params[3] =& $this;
916                 $class = new $class_name($params);
917             }
918             $this->_types = array_merge($this->_types, $customPageListColumns);
919         }
920     }
921
922     function getOption($option) {
923         if (array_key_exists($option, $this->_options)) {
924             return $this->_options[$option];
925         }
926         else {
927             return null;
928         }
929     }
930
931     /**
932      * Add a column to this PageList, given a column name.
933      * The name is a type, and optionally has a : and a label. Examples:
934      *
935      *   pagename
936      *   pagename:This page
937      *   mtime
938      *   mtime:Last modified
939      *
940      * If this function is called multiple times for the same type, the
941      * column will only be added the first time, and ignored the succeeding times.
942      * If you wish to add multiple columns of the same type, use addColumnObject().
943      *
944      * @param column name
945      * @return  true if column is added, false otherwise
946      */
947     function _addColumn ($column) {
948         
949         if (isset($this->_columns_seen[$column]))
950             return false;       // Already have this one.
951         if (!isset($this->_types[$column]))
952             $this->_initAvailableColumns();
953         $this->_columns_seen[$column] = true;
954
955         if (strstr($column, ':'))
956             list ($column, $heading) = explode(':', $column, 2);
957
958         if (!isset($this->_types[$column])) {
959             $silently_ignore = array('numbacklinks','rating','coagreement','minmisery',
960                                      'averagerating','top3recs');
961             if (!in_array($column,$silently_ignore))
962                 trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
963             return false;
964         }
965         if ($column == 'ratingwidget' and !$GLOBALS['request']->_user->isSignedIn())
966             return false;
967
968         $this->addColumnObject($this->_types[$column]);
969
970         return true;
971     }
972
973     /**
974      * Add a column to this PageList, given a column object.
975      *
976      * @param $col object   An object derived from _PageList_Column.
977      **/
978     function addColumnObject($col) {
979         if (is_array($col)) {// custom column object
980             $params =& $col;
981             $class_name = array_shift($params);
982             $$params[3] =& $this;
983             $col = new $class_name($params);
984         }
985         $heading = $col->getHeading();
986         if (!empty($heading))
987             $col->setHeading($heading);
988
989         $this->_columns[] = $col;
990         $this->_columnsMap[$col->_field] = count($this->_columns)-1;
991     }
992
993     /**
994      * Compare _PageList_Page objects.
995      **/
996     function _pageCompare($a, $b) {
997         $pagelist = $a->getPageList();
998         $pagea = $a->getPage();
999         $pageb = $b->getPage();
1000         if (count($pagelist->_sortby) == 0) {
1001             // No columns to sort by
1002             return 0;
1003         }
1004         else {
1005             foreach ($pagelist->_sortby as $colNum => $direction) {
1006                 if (!isset($pagelist->_columns_seen[$colNum])) return 0;
1007                 $colkey = $colNum;
1008                 if (!is_int($colkey)) { // or column fieldname
1009                     $colkey = $pagelist->_columnsMap[$colNum];
1010                 }
1011                 $col = $pagelist->_columns[$colkey];
1012
1013                 $revision_handle = false;
1014                 $pagea = PageList::_getPageFromHandle($pagea);  // If a string, convert to page
1015                 assert(isa($pagea, 'WikiDB_Page'));
1016                 assert(isset($col));
1017                 $aval = $col->_getSortableValue($pagea, $revision_handle);
1018                 $pageb = PageList::_getPageFromHandle($pageb);  // If a string, convert to page
1019                 
1020                 $revision_handle = false;
1021                 assert(isa($pageb, 'WikiDB_Page'));
1022                 $bval = $col->_getSortableValue($pageb, $revision_handle);
1023
1024                 $cmp = $col->_compare($aval, $bval);
1025                 if ($direction === "-") {
1026                     // Reverse the sense of the comparison
1027                     $cmp *= -1;
1028                 }
1029
1030                 if ($cmp !== 0) {
1031                     // This is the first comparison that is not equal-- go with it
1032                     return $cmp;
1033                 }
1034             }
1035             return 0;
1036         }
1037     }
1038
1039     /**
1040      * Put pages in order according to the sortby arg, if given
1041      */
1042     function _sortPages() {
1043         if (count($this->_sortby) > 0) {
1044             // There are columns to sort by
1045             usort($this->_pages, array('PageList', '_pageCompare'));
1046         }        
1047     }
1048
1049     function limit($limit) {
1050         if (strstr($limit,','))
1051             return split(',',$limit);
1052         else
1053             return array(0,$limit);
1054     }
1055     
1056     // make a table given the caption
1057     function _generateTable($caption) {
1058         $this->_sortPages();
1059
1060         $rows = array();
1061         foreach ($this->_pages as $pagenum => $page) {
1062             $rows[] = $this->_renderPageRow($page);
1063         }
1064
1065         $table = HTML::table(array('cellpadding' => 0,
1066                                    'cellspacing' => 1,
1067                                    'border'      => 0,
1068                                    'class'       => 'pagelist'));
1069         if ($caption)
1070             $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
1071
1072         //Warning: This is quite fragile. It depends solely on a private variable
1073         //         in ->_addColumn()
1074         if (!empty($this->_columns_seen['checkbox'])) {
1075             $table->pushContent($this->_jsFlipAll());
1076         }
1077         $do_paging = ( isset($this->_options['paging']) and 
1078                        !empty($this->_options['limit']) and $this->getTotal() and
1079                        $this->_options['paging'] != 'none' );
1080         $row = HTML::tr();
1081         $table_summary = array();
1082         $i = 0;
1083         foreach ($this->_columns as $col) {
1084             $heading = $col->button_heading($this, $i);
1085             if ($do_paging and 
1086                 isset($col->_field) and $col->_field == 'pagename' and 
1087                 ($maxlen = $this->maxLen()))
1088                 $heading->setAttr('width',$maxlen * 7);
1089             $row->pushContent($heading);
1090             if (is_string($col->getHeading()))
1091                 $table_summary[] = $col->getHeading();
1092             $i++;
1093         }
1094         // Table summary for non-visual browsers.
1095         $table->setAttr('summary', sprintf(_("Columns: %s."), 
1096                                            implode(", ", $table_summary)));
1097
1098         if ( $do_paging ) {
1099             // if there are more pages than the limit, show a table-header, -footer
1100             list($offset,$pagesize) = $this->limit($this->_options['limit']);
1101             $numrows = $this->getTotal();
1102             if (!$pagesize or
1103                 (!$offset and $numrows <= $pagesize) or
1104                 ($offset + $pagesize < 0)) 
1105             {
1106                 $table->pushContent(HTML::thead($row),
1107                                     HTML::tbody(false, $rows));
1108                 return $table;
1109             }
1110             global $request;
1111             include_once('lib/Template.php');
1112
1113             $tokens = array();
1114             $pagename = $request->getArg('pagename');
1115             $defargs = $request->args;
1116             unset($defargs['pagename']); unset($defargs['action']);
1117             //$defargs['nocache'] = 1;
1118             $prev = $defargs;
1119             $tokens['PREV'] = false; $tokens['PREV_LINK'] = "";
1120             $tokens['COLS'] = count($this->_columns);
1121             $tokens['COUNT'] = $numrows; 
1122             $tokens['OFFSET'] = $offset; 
1123             $tokens['SIZE'] = $pagesize;
1124             $tokens['NUMPAGES'] = (int)($numrows / $pagesize)+1;
1125             $tokens['ACTPAGE'] = (int) (($offset+1) / $pagesize)+1;
1126             if ($offset > 0) {
1127                 $prev['limit'] = min(0,$offset - $pagesize) . ",$pagesize";
1128                 $prev['count'] = $numrows;
1129                 $tokens['LIMIT'] = $prev['limit'];
1130                 $tokens['PREV'] = true;
1131                 $tokens['PREV_LINK'] = WikiURL($pagename,$prev);
1132                 $prev['limit'] = "0,$pagesize";
1133                 $tokens['FIRST_LINK'] = WikiURL($pagename,$prev);
1134             }
1135             $next = $defargs;
1136             $tokens['NEXT'] = false; $tokens['NEXT_LINK'] = "";
1137             if ($offset + $pagesize < $numrows) {
1138                 $next['limit'] = min($offset + $pagesize,$numrows - $pagesize) . ",$pagesize";
1139                 $next['count'] = $numrows;
1140                 $tokens['LIMIT'] = $next['limit'];
1141                 $tokens['NEXT'] = true;
1142                 $tokens['NEXT_LINK'] = WikiURL($pagename,$next);
1143                 $next['limit'] = $numrows - $pagesize . ",$pagesize";
1144                 $tokens['LAST_LINK'] = WikiURL($pagename,$next);
1145             }
1146             $paging = new Template("pagelink", $request, $tokens);
1147             $table->pushContent(HTML::thead($paging),
1148                                 HTML::tbody(false, HTML($row, $rows)),
1149                                 HTML::tfoot($paging));
1150             return $table;
1151         }
1152         $table->pushContent(HTML::thead($row),
1153                             HTML::tbody(false, $rows));
1154         return $table;
1155     }
1156
1157     function _jsFlipAll() {
1158       return JavaScript("
1159 function flipAll(formObj) {
1160   var isFirstSet = -1;
1161   for (var i=0;i < formObj.length;i++) {
1162       fldObj = formObj.elements[i];
1163       if (fldObj.type == 'checkbox') { 
1164          if (isFirstSet == -1)
1165            isFirstSet = (fldObj.checked) ? true : false;
1166          fldObj.checked = (isFirstSet) ? false : true;
1167        }
1168    }
1169 }");
1170     }
1171
1172     function _generateList($caption) {
1173         $list = HTML::ul(array('class' => 'pagelist'));
1174         $i = 0;
1175         foreach ($this->_pages as $pagenum => $page) {
1176             $pagehtml = $this->_renderPageRow($page);
1177             $group = ($i++ / $this->_group_rows);
1178             $class = ($group % 2) ? 'oddrow' : 'evenrow';
1179             $list->pushContent(HTML::li(array('class' => $class),$pagehtml));
1180         }
1181         $out = HTML();
1182         //Warning: This is quite fragile. It depends solely on a private variable
1183         //         in ->_addColumn()
1184         // Questionable if its of use here anyway. This is a one-col pagename list only.
1185         //if (!empty($this->_columns_seen['checkbox'])) $out->pushContent($this->_jsFlipAll());
1186         if ($caption)
1187             $out->pushContent(HTML::p($caption));
1188         $out->pushContent($list);
1189         return $out;
1190     }
1191
1192     function _emptyList($caption) {
1193         $html = HTML();
1194         if ($caption)
1195             $html->pushContent(HTML::p($caption));
1196         if ($this->_messageIfEmpty)
1197             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
1198         return $html;
1199     }
1200
1201     // Condense list: "Page1, Page2, ..." 
1202     // Alternative $seperator = HTML::Raw(' &middot; ')
1203     function _generateCommaList($seperator = ', ') {
1204         return HTML(join($seperator, $list));
1205     }
1206
1207 };
1208
1209 /* List pages with checkboxes to select from.
1210  * The [Select] button toggles via _jsFlipAll
1211  */
1212
1213 class PageList_Selectable
1214 extends PageList {
1215
1216     function PageList_Selectable ($columns=false, $exclude=false, $options = false) {
1217         if ($columns) {
1218             if (!is_array($columns))
1219                 $columns = explode(',', $columns);
1220             if (!in_array('checkbox',$columns))
1221                 array_unshift($columns,'checkbox');
1222         } else {
1223             $columns = array('checkbox','pagename');
1224         }
1225         PageList::PageList($columns, $exclude, $options);
1226     }
1227
1228     function addPageList ($array) {
1229         while (list($pagename,$selected) = each($array)) {
1230             if ($selected) $this->addPageSelected((string)$pagename);
1231             $this->addPage((string)$pagename);
1232         }
1233     }
1234
1235     function addPageSelected ($pagename) {
1236         $this->_selected[$pagename] = 1;
1237     }
1238 }
1239
1240 // $Log: not supported by cvs2svn $
1241 // Revision 1.90  2004/06/18 14:38:21  rurban
1242 // adopt new PageList style
1243 //
1244 // Revision 1.89  2004/06/17 13:16:08  rurban
1245 // apply wikilens work to PageList: all columns are sortable (slightly fixed)
1246 //
1247 // Revision 1.88  2004/06/14 11:31:35  rurban
1248 // renamed global $Theme to $WikiTheme (gforge nameclash)
1249 // inherit PageList default options from PageList
1250 //   default sortby=pagename
1251 // use options in PageList_Selectable (limit, sortby, ...)
1252 // added action revert, with button at action=diff
1253 // added option regex to WikiAdminSearchReplace
1254 //
1255 // Revision 1.87  2004/06/13 16:02:12  rurban
1256 // empty list of pages if user=[] and not authenticated.
1257 //
1258 // Revision 1.86  2004/06/13 15:51:37  rurban
1259 // Support pagelist filter for current author,owner,creator by []
1260 //
1261 // Revision 1.85  2004/06/13 15:33:19  rurban
1262 // new support for arguments owner, author, creator in most relevant
1263 // PageList plugins. in WikiAdmin* via preSelectS()
1264 //
1265 // Revision 1.84  2004/06/08 13:51:56  rurban
1266 // some comments only
1267 //
1268 // Revision 1.83  2004/05/18 13:35:39  rurban
1269 //  improve Pagelist layout by equal pagename width for limited lists
1270 //
1271 // Revision 1.82  2004/05/16 22:07:35  rurban
1272 // check more config-default and predefined constants
1273 // various PagePerm fixes:
1274 //   fix default PagePerms, esp. edit and view for Bogo and Password users
1275 //   implemented Creator and Owner
1276 //   BOGOUSERS renamed to BOGOUSER
1277 // fixed syntax errors in signin.tmpl
1278 //
1279 // Revision 1.81  2004/05/13 12:30:35  rurban
1280 // fix for MacOSX border CSS attr, and if sort buttons are not found
1281 //
1282 // Revision 1.80  2004/04/20 00:56:00  rurban
1283 // more paging support and paging fix for shorter lists
1284 //
1285 // Revision 1.79  2004/04/20 00:34:16  rurban
1286 // more paging support
1287 //
1288 // Revision 1.78  2004/04/20 00:06:03  rurban
1289 // themable paging support
1290 //
1291 // Revision 1.77  2004/04/18 01:11:51  rurban
1292 // more numeric pagename fixes.
1293 // fixed action=upload with merge conflict warnings.
1294 // charset changed from constant to global (dynamic utf-8 switching)
1295 //
1296
1297 // (c-file-style: "gnu")
1298 // Local Variables:
1299 // mode: php
1300 // tab-width: 8
1301 // c-basic-offset: 4
1302 // c-hanging-comment-ender-p: nil
1303 // indent-tabs-mode: nil
1304 // End:
1305 ?>