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