]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
improved _Selectable columns handling (independent on calling classes info arg),...
[SourceForge/phpwiki.git] / lib / PageList.php
1 <?php rcs_id('$Id: PageList.php,v 1.52 2004-02-15 15:25:23 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  * 'remove'   _("Remove") //todo: move this admin action away, not really an info column
25  *
26  * 'checkbox'  A selectable checkbox appears at the left.
27  * 'all'       All columns except remove, content and renamed_pagename
28  * 'most'      pagename, mtime, author, size, hits, ...
29  * 'some'      pagename, mtime, author
30  *
31  * FIXME: In this refactoring I have un-implemented _ctime, _cauthor, and
32  * number-of-revision.  Note the _ctime and _cauthor as they were implemented
33  * were somewhat flawed: revision 1 of a page doesn't have to exist in the
34  * database.  If lots of revisions have been made to a page, it's more than likely
35  * that some older revisions (include revision 1) have been cleaned (deleted).
36  *
37  * TODO: limit, offset, rows arguments for multiple pages/multiple rows.
38  *       check PagePerm "list" access-type
39  */
40 class _PageList_Column_base {
41     var $_tdattr = array();
42
43     function _PageList_Column_base ($default_heading, $align = false) {
44         $this->_heading = $default_heading;
45
46         if ($align) {
47             // align="char" isn't supported by any browsers yet :(
48             //if (is_array($align))
49             //    $this->_tdattr = $align;
50             //else
51             $this->_tdattr['align'] = $align;
52         }
53     }
54
55     function format ($pagelist, $page_handle, &$revision_handle) {
56         return HTML::td($this->_tdattr,
57                         HTML::raw('&nbsp;'),
58                         $this->_getValue($page_handle, $revision_handle),
59                         HTML::raw('&nbsp;'));
60     }
61
62     function setHeading ($heading) {
63         $this->_heading = $heading;
64     }
65
66     function heading () {
67         if (in_array($this->_field,array('pagename','mtime','hits'))) {
68             // multiple comma-delimited sortby args: "+hits,+pagename"
69             // asc or desc: +pagename, -pagename
70             $sortby = PageList::sortby($this->_field,'flip_order');
71             $s = HTML::a(array('href' => $GLOBALS['request']->GetURLtoSelf(array('sortby' => $sortby)),'class' => 'pagetitle', 'title' => sprintf(_("Sort by %s"),$this->_field)), HTML::raw('&nbsp;'), HTML::u($this->_heading), HTML::raw('&nbsp;'));
72         } else {
73             $s = HTML(HTML::raw('&nbsp;'), HTML::u($this->_heading), HTML::raw('&nbsp;'));
74         }
75         return HTML::td(array('align' => 'center'),$s);
76     }
77 };
78
79 class _PageList_Column extends _PageList_Column_base {
80     function _PageList_Column ($field, $default_heading, $align = false) {
81         $this->_PageList_Column_base($default_heading, $align);
82
83         $this->_need_rev = substr($field, 0, 4) == 'rev:';
84         if ($this->_need_rev)
85             $this->_field = substr($field, 4);
86         else
87             $this->_field = $field;
88     }
89
90     function _getValue ($page_handle, &$revision_handle) {
91         if ($this->_need_rev) {
92             if (!$revision_handle)
93                 $revision_handle = $page_handle->getCurrentRevision();
94             return $revision_handle->get($this->_field);
95         }
96         else {
97             return $page_handle->get($this->_field);
98         }
99     }
100 };
101
102 class _PageList_Column_size extends _PageList_Column {
103     function _getValue ($page_handle, &$revision_handle) {
104         if (!$revision_handle)
105             $revision_handle = $page_handle->getCurrentRevision();
106         return $this->_getSize($revision_handle);
107     }
108
109     function _getSize($revision_handle) {
110         $bytes = strlen($revision_handle->_data['%content']);
111         return ByteFormatter($bytes);
112     }
113 }
114
115
116 class _PageList_Column_bool extends _PageList_Column {
117     function _PageList_Column_bool ($field, $default_heading, $text = 'yes') {
118         $this->_PageList_Column($field, $default_heading, 'center');
119         $this->_textIfTrue = $text;
120         $this->_textIfFalse = new RawXml('&#8212;'); //mdash
121     }
122
123     function _getValue ($page_handle, &$revision_handle) {
124         $val = _PageList_Column::_getValue($page_handle, $revision_handle);
125         return $val ? $this->_textIfTrue : $this->_textIfFalse;
126     }
127 };
128
129 class _PageList_Column_checkbox extends _PageList_Column {
130     function _PageList_Column_checkbox ($field, $default_heading, $name='p') {
131         $this->_name = $name;
132         $heading = HTML::input(array('type'  => 'button',
133                                      'title' => _("Click to de-/select all pages"),
134                                      'name'  => $default_heading,
135                                      'value' => $default_heading,
136                                      'onclick' => "flipAll(this.form)"
137                                      ));
138         $this->_PageList_Column($field, $heading, 'center');
139     }
140     function _getValue ($pagelist, $page_handle, &$revision_handle) {
141         $pagename = $page_handle->getName();
142         if (!empty($pagelist->_selected[$pagename])) {
143             return HTML::input(array('type' => 'checkbox',
144                                      'name' => $this->_name . "[$pagename]",
145                                      'value' => $pagename,
146                                      'checked' => 'CHECKED'));
147         } else {
148             return HTML::input(array('type' => 'checkbox',
149                                      'name' => $this->_name . "[$pagename]",
150                                      'value' => $pagename));
151         }
152     }
153     function format ($pagelist, $page_handle, &$revision_handle) {
154         return HTML::td($this->_tdattr,
155                         HTML::raw('&nbsp;'),
156                         $this->_getValue($pagelist, $page_handle, $revision_handle),
157                         HTML::raw('&nbsp;'));
158     }
159 };
160
161 class _PageList_Column_time extends _PageList_Column {
162     function _PageList_Column_time ($field, $default_heading) {
163         $this->_PageList_Column($field, $default_heading, 'right');
164         global $Theme;
165         $this->Theme = &$Theme;
166     }
167
168     function _getValue ($page_handle, &$revision_handle) {
169         $time = _PageList_Column::_getValue($page_handle, $revision_handle);
170         return $this->Theme->formatDateTime($time);
171     }
172 };
173
174 class _PageList_Column_version extends _PageList_Column {
175     function _getValue ($page_handle, &$revision_handle) {
176         if (!$revision_handle)
177             $revision_handle = $page_handle->getCurrentRevision();
178         return $revision_handle->getVersion();
179     }
180 };
181
182 // If needed this could eventually become a subclass
183 // of a new _PageList_Column_action class for other actions.
184 // only for WikiAdminRemove or WikiAdminSelect
185 class _PageList_Column_remove extends _PageList_Column {
186     function _getValue ($page_handle, &$revision_handle) {
187         return Button(array('action' => 'remove'), _("Remove"),
188                       $page_handle->getName());
189     }
190 };
191
192 // only for WikiAdminRename
193 class _PageList_Column_renamed_pagename extends _PageList_Column {
194     function _getValue ($page_handle, &$revision_handle) {
195         $post_args = $GLOBALS['request']->getArg('admin_rename');
196         $value = str_replace($post_args['from'], $post_args['to'],$page_handle->getName());
197         return HTML::div(" => ",HTML::input(array('type' => 'text',
198                                                   'name' => 'rename[]',
199                                                   'value' => $value)));
200     }
201 };
202
203 // Output is hardcoded to limit of first 50 bytes. Otherwise
204 // on very large Wikis this will fail if used with AllPages
205 // (PHP memory limit exceeded)
206 class _PageList_Column_content extends _PageList_Column {
207     function _PageList_Column_content ($field, $default_heading, $align = false) {
208         _PageList_Column::_PageList_Column($field, $default_heading, $align);
209         $this->bytes = 50;
210         $this->_heading .= sprintf(_(" ... first %d bytes"),
211                                    $this->bytes);
212     }
213     function _getValue ($page_handle, &$revision_handle) {
214         if (!$revision_handle)
215             $revision_handle = $page_handle->getCurrentRevision();
216         // Not sure why implode is needed here, I thought
217         // getContent() already did this, but it seems necessary.
218         $c = implode("\n", $revision_handle->getContent());
219         if (($len = strlen($c)) > $this->bytes) {
220             $c = substr($c, 0, $this->bytes);
221         }
222         include_once('lib/BlockParser.php');
223         // false --> don't bother processing hrefs for embedded WikiLinks
224         $ct = TransformText($c, $revision_handle->get('markup'), false);
225         return HTML::div(array('style' => 'font-size:xx-small'),
226                          HTML::div(array('class' => 'transclusion'), $ct),
227                          // TODO: Don't show bytes here if size column present too
228                          /* Howto??? $this->parent->_columns['size'] ? "" :*/
229                          ByteFormatter($len, /*$longformat = */true));
230     }
231 };
232
233 class _PageList_Column_author extends _PageList_Column {
234     function _PageList_Column_author ($field, $default_heading, $align = false) {
235         _PageList_Column::_PageList_Column($field, $default_heading, $align);
236         global $WikiNameRegexp, $request;
237         $this->WikiNameRegexp = $WikiNameRegexp;
238         $this->dbi = &$request->getDbh();
239     }
240
241     function _getValue ($page_handle, &$revision_handle) {
242         $author = _PageList_Column::_getValue($page_handle, $revision_handle);
243         if (preg_match("/^$this->WikiNameRegexp\$/", $author) && $this->dbi->isWikiPage($author))
244             return WikiLink($author);
245         else
246             return $author;
247     }
248 };
249
250 class _PageList_Column_pagename extends _PageList_Column_base {
251     var $_field = 'pagename';
252
253     function _PageList_Column_pagename () {
254         $this->_PageList_Column_base(_("Page Name"));
255         global $request;
256         $this->dbi = &$request->getDbh();
257     }
258
259     function _getValue ($page_handle, &$revision_handle) {
260         if ($this->dbi->isWikiPage($pagename = $page_handle->getName()))
261             return WikiLink($page_handle);
262         else
263             return WikiLink($page_handle, 'unknown');
264     }
265 };
266
267
268
269 class PageList {
270     var $_group_rows = 3;
271     var $_columns = array();
272     var $_excluded_pages = array();
273     var $_rows = array();
274     var $_caption = "";
275     var $_pagename_seen = false;
276     var $_types = array();
277     var $_options = array();
278     var $_selected = array();
279
280     function PageList ($columns = false, $exclude = false, $options = false) {
281         $this->_initAvailableColumns();
282         $symbolic_columns = 
283             array(
284                   'all' =>  array_diff(array_keys($this->_types),
285                                        array('checkbox','remove','renamed_pagename','content')),
286                   'most' => array('pagename','mtime','author','size','hits'),
287                   'some' => array('pagename','mtime','author')
288                   );
289         if ($columns) {
290             if (!is_array($columns))
291                 $columns = explode(',', $columns);
292             // expand symbolic columns:
293             foreach ($symbolic_columns as $symbol => $cols) {
294                 if (in_array($symbol,$columns)) { // e.g. 'checkbox,all'
295                     $columns = array_diff(array_merge($columns,$cols),array($symbol));
296                 }
297             }
298             foreach ($columns as $col) {
299                 $this->_addColumn($col);
300             }
301         }
302         $this->_addColumn('pagename');
303
304         if ($exclude) {
305             if (!is_array($exclude))
306                 $exclude = explode(',', $exclude);
307             $this->_excluded_pages = $exclude;
308         }
309
310         $this->_options = $options;
311         $this->_messageIfEmpty = _("<no matches>");
312     }
313
314     function setCaption ($caption_string) {
315         $this->_caption = $caption_string;
316     }
317
318     function getCaption () {
319         // put the total into the caption if needed
320         if (is_string($this->_caption) && strstr($this->_caption, '%d'))
321             return sprintf($this->_caption, $this->getTotal());
322         return $this->_caption;
323     }
324
325     function setMessageIfEmpty ($msg) {
326         $this->_messageIfEmpty = $msg;
327     }
328
329
330     function getTotal () {
331         return count($this->_rows);
332     }
333
334     function isEmpty () {
335         return empty($this->_rows);
336     }
337
338     function addPage ($page_handle) {
339         if (is_string($page_handle)) {
340             if (in_array($page_handle, $this->_excluded_pages))
341                 return;             // exclude page.
342             $dbi = $GLOBALS['request']->getDbh();
343             $page_handle = $dbi->getPage($page_handle);
344         } else {
345           if (in_array($page_handle->getName(), $this->_excluded_pages))
346             return;             // exclude page.
347         }
348
349         $group = (int)(count($this->_rows) / $this->_group_rows);
350         $class = ($group % 2) ? 'oddrow' : 'evenrow';
351         $revision_handle = false;
352
353         if (count($this->_columns) > 1) {
354             $row = HTML::tr(array('class' => $class));
355             foreach ($this->_columns as $col)
356                 $row->pushContent($col->format($this, $page_handle, $revision_handle));
357         }
358         else {
359             $col = $this->_columns[0];
360             $row = HTML::li(array('class' => $class),
361                             $col->_getValue($page_handle, $revision_handle));
362         }
363
364         $this->_rows[] = $row;
365     }
366
367     function addPages ($page_iter) {
368         while ($page = $page_iter->next())
369             $this->addPage($page);
370     }
371
372     function addPageList (&$list) {
373         reset ($list);
374         while ($page = next($list))
375             $this->addPage($page);
376     }
377
378     function getContent() {
379         // Note that the <caption> element wants inline content.
380         $caption = $this->getCaption();
381
382         if ($this->isEmpty())
383             return $this->_emptyList($caption);
384         elseif (count($this->_columns) == 1)
385             return $this->_generateList($caption);
386         else
387             return $this->_generateTable($caption);
388     }
389
390     function printXML() {
391         PrintXML($this->getContent());
392     }
393
394     function asXML() {
395         return AsXML($this->getContent());
396     }
397
398     /** 
399      * handles sortby requests for the DB iterator and table header links
400      * prefix the column with + or - like "+pagename","-mtime", ...
401      * supported column: 'pagename','mtime','hits'
402      * supported action: 'flip_order', 'db'
403      */
404     function sortby ($column, $action) {
405         if (substr($column,0,1) == '+') {
406             $order = '+'; $column = substr($column,1);
407         } elseif (substr($column,0,1) == '-') {
408             $order = '-'; $column = substr($column,1);
409         }
410         if (in_array($column,array('pagename','mtime','hits'))) {
411             // default order: +pagename, -mtime, -hits
412             if (empty($order))
413                 if (in_array($column,array('mtime','hits')))
414                     $order = '-';
415                 else
416                     $order = '+';
417             //TODO: multiple comma-delimited sortby args: "+hits,+pagename"
418             if ($action == 'flip_order') {
419                 return ($order == '+' ? '-' : '+') . $column;
420             } elseif ($action == 'db') {
421                 // asc or desc: +pagename, -pagename
422                 return $column . ($order == '+' ? ' ASC' : ' DESC');
423             }
424         }
425         return '';
426     }
427
428     // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
429     function explodePageList($input, $perm = false, $sortby = '') {
430         // expand wildcards from list of all pages
431         if (preg_match('/[\?\*]/',$input)) {
432             $dbi = $GLOBALS['request']->getDbh();
433             $allPagehandles = $dbi->getAllPages($perm,$sortby);
434             while ($pagehandle = $allPagehandles->next()) {
435                 $allPages[] = $pagehandle->getName();
436             }
437             return explodeList($input, $allPages);
438         } else {
439             //TODO: do the sorting
440             return explode(',',$input);
441         }
442     }
443
444
445     ////////////////////
446     // private
447     ////////////////////
448     function _initAvailableColumns() {
449         if (!empty($this->_types))
450             return;
451
452         $this->_types =
453             array(
454                   'content'
455                   => new _PageList_Column_content('content', _("Content")),
456
457                   'remove'
458                   => new _PageList_Column_remove('remove', _("Remove")),
459
460                   'renamed_pagename'
461                   => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
462
463                   'checkbox'
464                   => new _PageList_Column_checkbox('p', _("Select")),
465
466                   'pagename'
467                   => new _PageList_Column_pagename,
468
469                   'mtime'
470                   => new _PageList_Column_time('rev:mtime',
471                                                _("Last Modified")),
472                   'hits'
473                   => new _PageList_Column('hits', _("Hits"), 'right'),
474
475                   'size'
476                   => new _PageList_Column_size('size', _("Size"), 'right'),
477                                                /*array('align' => 'char', 'char' => ' ')*/
478
479                   'summary'
480                   => new _PageList_Column('rev:summary', _("Last Summary")),
481
482                   'version'
483                   => new _PageList_Column_version('rev:version', _("Version"),
484                                                   'right'),
485                   'author'
486                   => new _PageList_Column_author('rev:author',
487                                                  _("Last Author")),
488                   'locked'
489                   => new _PageList_Column_bool('locked', _("Locked"),
490                                                _("locked")),
491                   'minor'
492                   => new _PageList_Column_bool('rev:is_minor_edit',
493                                                _("Minor Edit"), _("minor")),
494                   'markup'
495                   => new _PageList_Column('rev:markup', _("Markup"))
496                   );
497     }
498
499     function _addColumn ($column) {
500
501         $this->_initAvailableColumns();
502
503         if (isset($this->_columns_seen[$column]))
504             return false;       // Already have this one.
505         $this->_columns_seen[$column] = true;
506
507         if (strstr($column, ':'))
508             list ($column, $heading) = explode(':', $column, 2);
509
510         if (!isset($this->_types[$column])) {
511             trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
512             return false;
513         }
514
515         $col = $this->_types[$column];
516         if (!empty($heading))
517             $col->setHeading($heading);
518
519         $this->_columns[] = $col;
520
521         return true;
522     }
523
524     // make a table given the caption
525     function _generateTable($caption) {
526         $table = HTML::table(array('cellpadding' => 0,
527                                    'cellspacing' => 1,
528                                    'border'      => 0,
529                                    'class'       => 'pagelist'));
530         if ($caption)
531             $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
532
533         //Warning: This is quite fragile. It depends solely on a private variable
534         //         in ->_addColumn()
535         if (in_array('checkbox',$this->_columns_seen)) {
536             $table->pushContent($this->_jsFlipAll());
537         }
538         $row = HTML::tr();
539         $table_summary = array();
540         foreach ($this->_columns as $col) {
541             $row->pushContent($col->heading());
542             if (is_string($col->_heading))
543                 $table_summary[] = $col->_heading;
544         }
545         // Table summary for non-visual browsers.
546         $table->setAttr('summary', sprintf(_("Columns: %s."), 
547                                            implode(", ", $table_summary)));
548
549         $table->pushContent(HTML::thead($row),
550                             HTML::tbody(false, $this->_rows));
551         return $table;
552     }
553
554     function _jsFlipAll() {
555       return JavaScript("
556 function flipAll(formObj) {
557   var isFirstSet = -1;
558   for (var i=0;i < formObj.length;i++) {
559       fldObj = formObj.elements[i];
560       if (fldObj.type == 'checkbox') { 
561          if (isFirstSet == -1)
562            isFirstSet = (fldObj.checked) ? true : false;
563          fldObj.checked = (isFirstSet) ? false : true;
564        }
565    }
566 }");
567     }
568
569     function _generateList($caption) {
570         $list = HTML::ul(array('class' => 'pagelist'), $this->_rows);
571         $out = HTML();
572         //Warning: This is quite fragile. It depends solely on a private variable
573         //         in ->_addColumn()
574         if (in_array('checkbox',$this->_columns_seen)) {
575             $out->pushContent($this->_jsFlipAll());
576         }
577         if ($caption)
578             $out->pushContent(HTML::p($caption));
579         $out->pushContent($list);
580         return $out;
581     }
582
583     function _emptyList($caption) {
584         $html = HTML();
585         if ($caption)
586             $html->pushContent(HTML::p($caption));
587         if ($this->_messageIfEmpty)
588             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
589         return $html;
590     }
591 };
592
593 /* List pages with checkboxes to select from.
594  * Todo: All, None jscript buttons.
595  */
596
597 class PageList_Selectable
598 extends PageList {
599
600     function PageList_Selectable ($columns=false, $exclude=false) {
601         if ($columns) {
602             if (!is_array($columns))
603                 $columns = explode(',', $columns);
604             if (!in_array('checkbox',$columns))
605                 array_unshift($columns,'checkbox');
606         } else {
607             $columns = array('checkbox','pagename');
608         }
609         PageList::PageList($columns,$exclude);
610     }
611
612     function addPageList ($array) {
613         while (list($pagename,$selected) = each($array)) {
614             if ($selected) $this->addPageSelected($pagename);
615             $this->addPage($pagename);
616         }
617     }
618
619     function addPageSelected ($pagename) {
620         $this->_selected[$pagename] = 1;
621     }
622     //Todo:
623     //insert javascript when clicked on Selected Select/Deselect all
624 }
625
626 // (c-file-style: "gnu")
627 // Local Variables:
628 // mode: php
629 // tab-width: 8
630 // c-basic-offset: 4
631 // c-hanging-comment-ender-p: nil
632 // indent-tabs-mode: nil
633 // End:
634 ?>