]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/PageList.php
PageList enhanced and improved.
[SourceForge/phpwiki.git] / lib / PageList.php
1 <?php rcs_id('$Id: PageList.php,v 1.53 2004-02-15 21:34:37 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         if ($field == 'content')
211             $this->_heading .= sprintf(_(" ... first %d bytes"),
212                                        $this->bytes);
213         elseif ($field == 'hi_content') {
214             $search = $_POST['admin_replace']['from'];
215             $this->_heading .= sprintf(_(" ... around Â»%s«"),$search);
216         }
217     }
218     function _getValue ($page_handle, &$revision_handle) {
219         if (!$revision_handle)
220             $revision_handle = $page_handle->getCurrentRevision();
221         // Not sure why implode is needed here, I thought
222         // getContent() already did this, but it seems necessary.
223         $c = implode("\n", $revision_handle->getContent());
224         if ($this->_field == 'hi_content') {
225             $search = $_POST['admin_replace']['from'];
226             if ($search and ($i = strpos($c,$search))) {
227                 $l = strlen($search);
228                 $j = max(0,$i - ($this->bytes / 2));
229                 return HTML::div(array('style' => 'font-size:x-small'),
230                                  HTML::div(array('class' => 'transclusion'),
231                                            HTML::span(substr($c, $j, ($this->bytes / 2))),
232                                            HTML::span(array("style"=>"background:yellow"),$search),
233                                            HTML::span(substr($c, $i+$l, ($this->bytes / 2))))
234                                  );
235             } else {
236                 $c = sprintf(_("»%s« not found"),$search);
237                 return HTML::div(array('style' => 'font-size:x-small','align'=>'center'),
238                                  $c);
239             }
240         } elseif (($len = strlen($c)) > $this->bytes) {
241             $c = substr($c, 0, $this->bytes);
242         }
243         include_once('lib/BlockParser.php');
244         // false --> don't bother processing hrefs for embedded WikiLinks
245         $ct = TransformText($c, $revision_handle->get('markup'), false);
246         return HTML::div(array('style' => 'font-size:x-small'),
247                          HTML::div(array('class' => 'transclusion'), $ct),
248                          // Don't show bytes here if size column present too
249                          ($this->parent->_columns_seen['size'] or !$len) ? "" :
250                            ByteFormatter($len, /*$longformat = */true));
251     }
252 };
253
254 class _PageList_Column_author extends _PageList_Column {
255     function _PageList_Column_author ($field, $default_heading, $align = false) {
256         _PageList_Column::_PageList_Column($field, $default_heading, $align);
257         global $WikiNameRegexp, $request;
258         $this->WikiNameRegexp = $WikiNameRegexp;
259         $this->dbi = &$request->getDbh();
260     }
261
262     function _getValue ($page_handle, &$revision_handle) {
263         $author = _PageList_Column::_getValue($page_handle, $revision_handle);
264         if (preg_match("/^$this->WikiNameRegexp\$/", $author) && $this->dbi->isWikiPage($author))
265             return WikiLink($author);
266         else
267             return $author;
268     }
269 };
270
271 class _PageList_Column_pagename extends _PageList_Column_base {
272     var $_field = 'pagename';
273
274     function _PageList_Column_pagename () {
275         $this->_PageList_Column_base(_("Page Name"));
276         global $request;
277         $this->dbi = &$request->getDbh();
278     }
279
280     function _getValue ($page_handle, &$revision_handle) {
281         if ($this->dbi->isWikiPage($pagename = $page_handle->getName()))
282             return WikiLink($page_handle);
283         else
284             return WikiLink($page_handle, 'unknown');
285     }
286 };
287
288
289
290 class PageList {
291     var $_group_rows = 3;
292     var $_columns = array();
293     var $_excluded_pages = array();
294     var $_rows = array();
295     var $_caption = "";
296     var $_pagename_seen = false;
297     var $_types = array();
298     var $_options = array();
299     var $_selected = array();
300
301     function PageList ($columns = false, $exclude = false, $options = false) {
302         $this->_initAvailableColumns();
303         $symbolic_columns = 
304             array(
305                   'all' =>  array_diff(array_keys($this->_types),
306                                        array('checkbox','remove','renamed_pagename','content')),
307                   'most' => array('pagename','mtime','author','size','hits'),
308                   'some' => array('pagename','mtime','author')
309                   );
310         if ($columns) {
311             if (!is_array($columns))
312                 $columns = explode(',', $columns);
313             // expand symbolic columns:
314             foreach ($symbolic_columns as $symbol => $cols) {
315                 if (in_array($symbol,$columns)) { // e.g. 'checkbox,all'
316                     $columns = array_diff(array_merge($columns,$cols),array($symbol));
317                 }
318             }
319             foreach ($columns as $col) {
320                 $this->_addColumn($col);
321             }
322         }
323         $this->_addColumn('pagename');
324
325         if ($exclude) {
326             if (!is_array($exclude))
327                 $exclude = explode(',', $exclude);
328             $this->_excluded_pages = $exclude;
329         }
330
331         $this->_options = $options;
332         $this->_messageIfEmpty = _("<no matches>");
333     }
334
335     function setCaption ($caption_string) {
336         $this->_caption = $caption_string;
337     }
338
339     function getCaption () {
340         // put the total into the caption if needed
341         if (is_string($this->_caption) && strstr($this->_caption, '%d'))
342             return sprintf($this->_caption, $this->getTotal());
343         return $this->_caption;
344     }
345
346     function setMessageIfEmpty ($msg) {
347         $this->_messageIfEmpty = $msg;
348     }
349
350
351     function getTotal () {
352         return count($this->_rows);
353     }
354
355     function isEmpty () {
356         return empty($this->_rows);
357     }
358
359     function addPage ($page_handle) {
360         if (is_string($page_handle)) {
361             if (in_array($page_handle, $this->_excluded_pages))
362                 return;             // exclude page.
363             $dbi = $GLOBALS['request']->getDbh();
364             $page_handle = $dbi->getPage($page_handle);
365         } elseif (is_object($page_handle)) {
366           if (in_array($page_handle->getName(), $this->_excluded_pages))
367             return;             // exclude page.
368         }
369
370         $group = (int)(count($this->_rows) / $this->_group_rows);
371         $class = ($group % 2) ? 'oddrow' : 'evenrow';
372         $revision_handle = false;
373
374         if (count($this->_columns) > 1) {
375             $row = HTML::tr(array('class' => $class));
376             foreach ($this->_columns as $col)
377                 $row->pushContent($col->format($this, $page_handle, $revision_handle));
378         }
379         else {
380             $col = $this->_columns[0];
381             $row = HTML::li(array('class' => $class),
382                             $col->_getValue($page_handle, $revision_handle));
383         }
384
385         $this->_rows[] = $row;
386     }
387
388     function addPages ($page_iter) {
389         while ($page = $page_iter->next())
390             $this->addPage($page);
391     }
392
393     function addPageList (&$list) {
394         reset ($list);
395         while ($page = next($list))
396             $this->addPage($page);
397     }
398
399     function getContent() {
400         // Note that the <caption> element wants inline content.
401         $caption = $this->getCaption();
402
403         if ($this->isEmpty())
404             return $this->_emptyList($caption);
405         elseif (count($this->_columns) == 1)
406             return $this->_generateList($caption);
407         else
408             return $this->_generateTable($caption);
409     }
410
411     function printXML() {
412         PrintXML($this->getContent());
413     }
414
415     function asXML() {
416         return AsXML($this->getContent());
417     }
418
419     /** 
420      * handles sortby requests for the DB iterator and table header links
421      * prefix the column with + or - like "+pagename","-mtime", ...
422      * supported column: 'pagename','mtime','hits'
423      * supported action: 'flip_order', 'db'
424      */
425     function sortby ($column, $action) {
426         if (substr($column,0,1) == '+') {
427             $order = '+'; $column = substr($column,1);
428         } elseif (substr($column,0,1) == '-') {
429             $order = '-'; $column = substr($column,1);
430         }
431         if (in_array($column,array('pagename','mtime','hits'))) {
432             // default order: +pagename, -mtime, -hits
433             if (empty($order))
434                 if (in_array($column,array('mtime','hits')))
435                     $order = '-';
436                 else
437                     $order = '+';
438             //TODO: multiple comma-delimited sortby args: "+hits,+pagename"
439             if ($action == 'flip_order') {
440                 return ($order == '+' ? '-' : '+') . $column;
441             } elseif ($action == 'db') {
442                 // asc or desc: +pagename, -pagename
443                 return $column . ($order == '+' ? ' ASC' : ' DESC');
444             }
445         }
446         return '';
447     }
448
449     // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
450     function explodePageList($input, $perm = false, $sortby = '') {
451         // expand wildcards from list of all pages
452         if (preg_match('/[\?\*]/',$input)) {
453             $dbi = $GLOBALS['request']->getDbh();
454             $allPagehandles = $dbi->getAllPages($perm,$sortby);
455             while ($pagehandle = $allPagehandles->next()) {
456                 $allPages[] = $pagehandle->getName();
457             }
458             return explodeList($input, $allPages);
459         } else {
460             //TODO: do the sorting
461             return explode(',',$input);
462         }
463     }
464
465
466     ////////////////////
467     // private
468     ////////////////////
469     function _initAvailableColumns() {
470         if (!empty($this->_types))
471             return;
472
473         $this->_types =
474             array(
475                   'content'
476                   => new _PageList_Column_content('content', _("Content")),
477
478                   'hi_content'
479                   => new _PageList_Column_content('hi_content', _("Content")),
480                   
481                   'remove'
482                   => new _PageList_Column_remove('remove', _("Remove")),
483
484                   'renamed_pagename'
485                   => new _PageList_Column_renamed_pagename('rename', _("Rename to")),
486
487                   'checkbox'
488                   => new _PageList_Column_checkbox('p', _("Select")),
489
490                   'pagename'
491                   => new _PageList_Column_pagename,
492
493                   'mtime'
494                   => new _PageList_Column_time('rev:mtime',
495                                                _("Last Modified")),
496                   'hits'
497                   => new _PageList_Column('hits', _("Hits"), 'right'),
498
499                   'size'
500                   => new _PageList_Column_size('size', _("Size"), 'right'),
501                                                /*array('align' => 'char', 'char' => ' ')*/
502
503                   'summary'
504                   => new _PageList_Column('rev:summary', _("Last Summary")),
505
506                   'version'
507                   => new _PageList_Column_version('rev:version', _("Version"),
508                                                   'right'),
509                   'author'
510                   => new _PageList_Column_author('rev:author',
511                                                  _("Last Author")),
512                   'locked'
513                   => new _PageList_Column_bool('locked', _("Locked"),
514                                                _("locked")),
515                   'minor'
516                   => new _PageList_Column_bool('rev:is_minor_edit',
517                                                _("Minor Edit"), _("minor")),
518                   'markup'
519                   => new _PageList_Column('rev:markup', _("Markup"))
520                   );
521     }
522
523     function _addColumn ($column) {
524
525         $this->_initAvailableColumns();
526
527         if (isset($this->_columns_seen[$column]))
528             return false;       // Already have this one.
529         $this->_columns_seen[$column] = true;
530
531         if (strstr($column, ':'))
532             list ($column, $heading) = explode(':', $column, 2);
533
534         if (!isset($this->_types[$column])) {
535             trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE);
536             return false;
537         }
538
539         $col = $this->_types[$column];
540         if (!empty($heading))
541             $col->setHeading($heading);
542
543         $this->_columns[] = $col;
544
545         return true;
546     }
547
548     // make a table given the caption
549     function _generateTable($caption) {
550         $table = HTML::table(array('cellpadding' => 0,
551                                    'cellspacing' => 1,
552                                    'border'      => 0,
553                                    'class'       => 'pagelist'));
554         if ($caption)
555             $table->pushContent(HTML::caption(array('align'=>'top'), $caption));
556
557         //Warning: This is quite fragile. It depends solely on a private variable
558         //         in ->_addColumn()
559         if (in_array('checkbox',$this->_columns_seen)) {
560             $table->pushContent($this->_jsFlipAll());
561         }
562         $row = HTML::tr();
563         $table_summary = array();
564         foreach ($this->_columns as $col) {
565             $row->pushContent($col->heading());
566             if (is_string($col->_heading))
567                 $table_summary[] = $col->_heading;
568         }
569         // Table summary for non-visual browsers.
570         $table->setAttr('summary', sprintf(_("Columns: %s."), 
571                                            implode(", ", $table_summary)));
572
573         $table->pushContent(HTML::thead($row),
574                             HTML::tbody(false, $this->_rows));
575         return $table;
576     }
577
578     function _jsFlipAll() {
579       return JavaScript("
580 function flipAll(formObj) {
581   var isFirstSet = -1;
582   for (var i=0;i < formObj.length;i++) {
583       fldObj = formObj.elements[i];
584       if (fldObj.type == 'checkbox') { 
585          if (isFirstSet == -1)
586            isFirstSet = (fldObj.checked) ? true : false;
587          fldObj.checked = (isFirstSet) ? false : true;
588        }
589    }
590 }");
591     }
592
593     function _generateList($caption) {
594         $list = HTML::ul(array('class' => 'pagelist'), $this->_rows);
595         $out = HTML();
596         //Warning: This is quite fragile. It depends solely on a private variable
597         //         in ->_addColumn()
598         if (in_array('checkbox',$this->_columns_seen)) {
599             $out->pushContent($this->_jsFlipAll());
600         }
601         if ($caption)
602             $out->pushContent(HTML::p($caption));
603         $out->pushContent($list);
604         return $out;
605     }
606
607     function _emptyList($caption) {
608         $html = HTML();
609         if ($caption)
610             $html->pushContent(HTML::p($caption));
611         if ($this->_messageIfEmpty)
612             $html->pushContent(HTML::blockquote(HTML::p($this->_messageIfEmpty)));
613         return $html;
614     }
615 };
616
617 /* List pages with checkboxes to select from.
618  * Todo: All, None jscript buttons.
619  */
620
621 class PageList_Selectable
622 extends PageList {
623
624     function PageList_Selectable ($columns=false, $exclude=false) {
625         if ($columns) {
626             if (!is_array($columns))
627                 $columns = explode(',', $columns);
628             if (!in_array('checkbox',$columns))
629                 array_unshift($columns,'checkbox');
630         } else {
631             $columns = array('checkbox','pagename');
632         }
633         PageList::PageList($columns,$exclude);
634     }
635
636     function addPageList ($array) {
637         while (list($pagename,$selected) = each($array)) {
638             if ($selected) $this->addPageSelected($pagename);
639             $this->addPage($pagename);
640         }
641     }
642
643     function addPageSelected ($pagename) {
644         $this->_selected[$pagename] = 1;
645     }
646     //Todo:
647     //insert javascript when clicked on Selected Select/Deselect all
648 }
649
650 // (c-file-style: "gnu")
651 // Local Variables:
652 // mode: php
653 // tab-width: 8
654 // c-basic-offset: 4
655 // c-hanging-comment-ender-p: nil
656 // indent-tabs-mode: nil
657 // End:
658 ?>