]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RecentChanges.php
Code cleanup:
[SourceForge/phpwiki.git] / lib / plugin / RecentChanges.php
1 <?php // -*-php-*-
2 rcs_id('$Id: RecentChanges.php,v 1.69 2003-01-18 22:01:43 carstenklapp Exp $');
3 /**
4  Copyright 1999, 2000, 2001, 2002 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  */
25 class _RecentChanges_Formatter
26 {
27     var $_absurls = false;
28
29     function _RecentChanges_Formatter ($rc_args) {
30         $this->_args = $rc_args;
31         $this->_diffargs = array('action' => 'diff');
32
33         if ($rc_args['show_minor'] || !$rc_args['show_major'])
34             $this->_diffargs['previous'] = 'minor';
35
36         // PageHistoryPlugin doesn't have a 'daylist' arg.
37         if (!isset($this->_args['daylist']))
38             $this->_args['daylist'] = false;
39     }
40
41     function include_versions_in_URLs() {
42         return (bool) $this->_args['show_all'];
43     }
44
45     function date ($rev) {
46         global $Theme;
47         return $Theme->getDay($rev->get('mtime'));
48     }
49
50     function time ($rev) {
51         global $Theme;
52         return $Theme->formatTime($rev->get('mtime'));
53     }
54
55     function diffURL ($rev) {
56         $args = $this->_diffargs;
57         if ($this->include_versions_in_URLs())
58             $args['version'] = $rev->getVersion();
59         $page = $rev->getPage();
60         return WikiURL($page->getName(), $args, $this->_absurls);
61     }
62
63     function historyURL ($rev) {
64         $page = $rev->getPage();
65         return WikiURL($page, array('action' => _("PageHistory")),
66                        $this->_absurls);
67     }
68
69     function pageURL ($rev) {
70         return WikiURL($this->include_versions_in_URLs() ? $rev : $rev->getPage(),
71                        '', $this->_absurls);
72     }
73
74     function authorHasPage ($author) {
75         global $WikiNameRegexp, $request;
76         $dbi = $request->getDbh();
77         return preg_match("/^$WikiNameRegexp\$/", $author) && $dbi->isWikiPage($author);
78     }
79
80     function authorURL ($author) {
81         return $this->authorHasPage() ? WikiURL($author) : false;
82     }
83
84
85     function status ($rev) {
86         if ($rev->hasDefaultContents())
87             return 'deleted';
88         $page = $rev->getPage();
89         $prev = $page->getRevisionBefore($rev->getVersion());
90         if ($prev->hasDefaultContents())
91             return 'new';
92         return 'updated';
93     }
94
95     function importance ($rev) {
96         return $rev->get('is_minor_edit') ? 'minor' : 'major';
97     }
98
99     function summary($rev) {
100         if ( ($summary = $rev->get('summary')) )
101             return $summary;
102
103         switch ($this->status($rev)) {
104             case 'deleted':
105                 return _("Deleted.");
106             case 'new':
107                 return _("New page.");
108             default:
109                 return '';
110         }
111     }
112
113     function http_lastmodified_header($mtime) {
114         static $mostrecentlymodified = false;
115         if (! $mostrecentlymodified) {
116             // set http header to date of most recently modified page
117             $mostrecentlymodified = $mtime; //$rev->get('mtime');
118             header("Last-Modified: " . Rfc2822DateTime($mostrecentlymodified));
119         }
120     }
121 }
122
123 class _RecentChanges_HtmlFormatter
124 extends _RecentChanges_Formatter
125 {
126     function diffLink ($rev) {
127         global $Theme;
128         return $Theme->makeButton(_("(diff)"), $this->diffURL($rev), 'wiki-rc-action');
129     }
130
131     function historyLink ($rev) {
132         global $Theme;
133         return $Theme->makeButton(_("(hist)"), $this->historyURL($rev), 'wiki-rc-action');
134     }
135
136     function pageLink ($rev) {
137         $page = $rev->getPage();
138         global $Theme;
139         if ($this->include_versions_in_URLs()) {
140             $version = $rev->getVersion();
141             $exists = !$rev->hasDefaultContents();
142         }
143         else {
144             $version = false;
145             $cur = $page->getCurrentRevision();
146             $exists = !$cur->hasDefaultContents();
147         }
148         if ($exists)
149             return $Theme->linkExistingWikiWord($page->getName(), false, $version);
150         else
151             return $Theme->linkUnknownWikiWord($page->getName(), false, $version);
152     }
153
154     function authorLink ($rev) {
155         $author = $rev->get('author');
156         if ( $this->authorHasPage($author) ) {
157             return WikiLink($author);
158         } else
159             return $author;
160     }
161
162     function summaryAsHTML ($rev) {
163         if ( !($summary = $this->summary($rev)) )
164             return '';
165         return  HTML::strong( array('class' => 'wiki-summary'),
166                               "[",
167                               TransformLinks($summary, $rev->get('markup')),
168                               "]");
169     }
170
171     function rss_icon () {
172         global $request, $Theme;
173
174         $rss_url = $request->getURLtoSelf(array('format' => 'rss'));
175         return $Theme->makeButton("RSS", $rss_url, 'rssicon');
176     }
177
178     function description () {
179         extract($this->_args);
180         // FIXME: say something about show_all.
181         if ($show_major && $show_minor)
182             $edits = _("edits");
183         elseif ($show_major)
184             $edits = _("major edits");
185         else
186             $edits = _("minor edits");
187
188         if ($timespan = $days > 0) {
189             if (intval($days) != $days)
190                 $days = sprintf("%.1f", $days);
191         }
192         $lmt = abs($limit);
193         /**
194          * Depending how this text is split up it can be tricky or
195          * impossible to translate with good grammar. So the seperate
196          * strings for 1 day and %s days are necessary in this case
197          * for translating to multiple languages, due to differing
198          * overlapping ideal word cutting points.
199          *
200          * en: day/days "The %d most recent %s [during (the past] day) are listed below."
201          * de: 1 Tag    "Die %d jüngste %s [innerhalb (von des letzten] Tages) sind unten aufgelistet."
202          * de: %s days  "Die %d jüngste %s [innerhalb (von] %s Tagen) sind unten aufgelistet."
203          *
204          * en: day/days "The %d most recent %s during [the past] (day) are listed below."
205          * fr: 1 jour   "Les %d %s les plus récentes pendant [le dernier (d'une] jour) sont énumérées ci-dessous."
206          * fr: %s jours "Les %d %s les plus récentes pendant [les derniers (%s] jours) sont énumérées ci-dessous."
207          */
208         if ($limit > 0) {
209             if ($timespan) {
210                 if (intval($days) == 1)
211                     $desc = fmt("The %d most recent %s during the past day are listed below.",
212                                 $limit, $edits);
213                 else
214                     $desc = fmt("The %d most recent %s during the past %s days are listed below.",
215                                 $limit, $edits, $days);
216             } else
217                 $desc = fmt("The %d most recent %s are listed below.",
218                             $limit, $edits);
219         }
220         elseif ($limit < 0) {  //$limit < 0 means we want oldest pages
221             if ($timespan) {
222                 if (intval($days) == 1)
223                     $desc = fmt("The %d oldest %s during the past day are listed below.",
224                                 $lmt, $edits);
225                 else
226                     $desc = fmt("The %d oldest %s during the past %s days are listed below.",
227                                 $lmt, $edits, $days);
228             } else
229                 $desc = fmt("The %d oldest %s are listed below.",
230                             $lmt, $edits);
231         }
232
233         else {
234             if ($timespan) {
235                 if (intval($days) == 1)
236                     $desc = fmt("The most recent %s during the past day are listed below.",
237                                 $edits);
238                 else
239                     $desc = fmt("The most recent %s during the past %s days are listed below.",
240                                 $edits, $days);
241             } else
242                 $desc = fmt("All %s are listed below.", $edits);
243         }
244         return $desc;
245     }
246
247
248     function title () {
249         extract($this->_args);
250         return array($show_minor ? _("RecentEdits") : _("RecentChanges"),
251                      ' ',
252                      $this->rss_icon(),
253                      $this->sidebar_link());
254     }
255
256     function sidebar_link() {
257         extract($this->_args);
258         $pagetitle = $show_minor ? _("RecentEdits") : _("RecentChanges");
259
260         global $request;
261         $sidebarurl = WikiURL($pagetitle, false, 'absurl') . "?format=sidebar";
262
263         $addsidebarjsfunc =
264             "function addPanel() {\n"
265             ."    window.sidebar.addPanel (\"" . sprintf("%s - %s", WIKI_NAME, $pagetitle) . "\",\n"
266             ."       \"$sidebarurl\",\"\");\n"
267             ."}\n";
268         $jsf = $this->_javascript($addsidebarjsfunc);
269
270         $addsidebarjsclick = " " . "<small style=\"font-weight:normal;\"><a href=\"javascript:addPanel();\">sidebar</a></small>";
271         $jsc = $this->_javascript("if ((typeof window.sidebar == 'object') &&\n"
272                                 ."    (typeof window.sidebar.addPanel == 'function'))\n"
273                                 ."   {\n"
274                                 ."       document.write('$addsidebarjsclick');\n"
275                                 ."   }\n"
276                                 );
277         return HTML(new RawXML("\n"), $jsf, new RawXML("\n"), $jsc);
278     }
279
280     function _javascript($script) {
281         return HTML::script(array('language' => 'JavaScript',
282                                   'type'     => 'text/javascript'),
283                             new RawXml("<!-- //\n$script\n// -->"));
284     }
285
286     function format ($changes) {
287         $html = HTML(HTML::h2(false, $this->title()));
288         if (($desc = $this->description()))
289             $html->pushContent(HTML::p(false, $desc));
290
291         if ($this->_args['daylist'])
292             $html->pushContent(new DayButtonBar($this->_args));
293
294         $last_date = '';
295         $lines = false;
296
297         while ($rev = $changes->next()) {
298             if (($date = $this->date($rev)) != $last_date) {
299                 if ($lines)
300                     $html->pushContent($lines);
301                 $html->pushContent(HTML::h3($date));
302                 $lines = HTML::ul();
303                 $last_date = $date;
304             }
305             $this->http_lastmodified_header($rev->get('mtime'));
306             $lines->pushContent($this->format_revision($rev));
307         }
308         if ($lines)
309             $html->pushContent($lines);
310         return $html;
311     }
312
313     function format_revision ($rev) {
314         $args = &$this->_args;
315
316         $class = 'rc-' . $this->importance($rev);
317
318         $time = $this->time($rev);
319         if (! $rev->get('is_minor_edit'))
320             $time = HTML::strong(array('class' => 'pageinfo-majoredit'), $time);
321
322         $line = HTML::li(array('class' => $class));
323
324
325         if ($args['difflinks'])
326             $line->pushContent($this->diffLink($rev), ' ');
327
328         if ($args['historylinks'])
329             $line->pushContent($this->historyLink($rev), ' ');
330
331         $line->pushContent($this->pageLink($rev), ' ',
332                            $time, ' ',
333                            $this->summaryAsHTML($rev),
334                            ' ... ',
335                            $this->authorLink($rev));
336         return $line;
337     }
338 }
339
340
341 class _RecentChanges_SideBarFormatter
342 extends _RecentChanges_HtmlFormatter
343 {
344     function description () {
345         //omit description
346     }
347     function rss_icon () {
348         //omit rssicon
349     }
350     function title () {
351         //title click opens the normal RC or RE page in the main browser frame
352         extract($this->_args);
353         $titlelink = WikiLink($show_minor ? _("RecentEdits") : _("RecentChanges"));
354         $titlelink->setAttr('target', '_content');
355         return HTML($this->logo(), $titlelink);
356     }
357     function logo () {
358         //logo click opens the HomePage in the main browser frame
359         global $Theme;
360         $img = HTML::img(array('src' => $Theme->getImageURL('logo'),
361                                'border' => 0,
362                                'align' => 'right',
363                                'width' => 32
364                                ));
365         $linkurl = WikiLink(HOME_PAGE, false, $img);
366         $linkurl->setAttr('target', '_content');
367         return $linkurl;
368     }
369
370     function authorLink ($rev) {
371         $author = $rev->get('author');
372         if ( $this->authorHasPage($author) ) {
373             $linkurl = WikiLink($author);
374             $linkurl->setAttr('target', '_content'); // way to do this using parent::authorLink ??
375             return $linkurl;
376         } else
377             return $author;
378     }
379     function diffLink ($rev) {
380         $linkurl = parent::diffLink($rev);
381         $linkurl->setAttr('target', '_content');
382         return $linkurl;
383     }
384     function historyLink ($rev) {
385         $linkurl = parent::historyLink($rev);
386         $linkurl->setAttr('target', '_content');
387         return $linkurl;
388     }
389     function pageLink ($rev) {
390         $linkurl = parent::pageLink($rev);
391         $linkurl->setAttr('target', '_content');
392         return $linkurl;
393     }
394     // Overriding summaryAsHTML, because there is no way yet to
395     // return summary as transformed text with
396     // links setAttr('target', '_content') in Mozilla sidebar.
397     // So for now don't create clickable links inside summary
398     // in the sidebar, or else they target the sidebar and not the
399     // main content window.
400     function summaryAsHTML ($rev) {
401         if ( !($summary = $this->summary($rev)) )
402             return '';
403         return HTML::strong(array('class' => 'wiki-summary'),
404                                 "[",
405                                 /*TransformLinks(*/$summary,/* $rev->get('markup')),*/
406                                 "]");
407     }
408
409
410     function format ($changes) {
411         $this->_args['daylist'] = false; //only 1 day for Mozilla sidebar
412         $html = _RecentChanges_HtmlFormatter::format ($changes);
413         $html = HTML::div(array('class' => 'wikitext'), $html);
414
415         printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n", CHARSET);
416         printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"');
417         printf('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
418         printf('<html xmlns="http://www.w3.org/1999/xhtml">');
419
420         printf("<head>\n");
421         extract($this->_args);
422         $title = WIKI_NAME . $show_minor ? _("RecentEdits") : _("RecentChanges");
423         printf("<title>" . $title . "</title>\n");
424         global $Theme;
425         $css = $Theme->getCSS();
426         $css->PrintXML();
427         printf("</head>\n");
428
429         printf("<body class=\"sidebar\">\n");
430         $html->PrintXML();
431         printf("\n</body>\n");
432         printf("</html>\n");
433
434         flush();
435
436         global $request;
437         $request->finish(); // cut rest of page processing short
438     }
439 }
440
441
442 class _RecentChanges_RssFormatter
443 extends _RecentChanges_Formatter
444 {
445     var $_absurls = true;
446
447     function time ($rev) {
448         return Iso8601DateTime($rev->get('mtime'));
449     }
450
451     function pageURI ($rev) {
452         return WikiURL($rev, '', 'absurl');
453     }
454
455     function format ($changes) {
456         include_once('lib/RssWriter.php');
457         $rss = new RssWriter;
458
459
460         $rss->channel($this->channel_properties());
461
462         if (($props = $this->image_properties()))
463             $rss->image($props);
464         if (($props = $this->textinput_properties()))
465             $rss->textinput($props);
466
467         while ($rev = $changes->next()) {
468             $rss->addItem($this->item_properties($rev),
469                           $this->pageURI($rev));
470             $this->http_lastmodified_header($rev->get('mtime'));
471         }
472
473         $rss->finish();
474         printf("\n<!-- Generated by PhpWiki:\n%s-->\n", $GLOBALS['RCS_IDS']);
475
476         // Flush errors in comment, otherwise it's invalid XML.
477         global $ErrorManager;
478         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
479             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
480
481         global $request;        // FIXME
482         $request->finish();     // NORETURN!!!!
483     }
484
485     function image_properties () {
486         global $Theme;
487
488         $img_url = SERVER_URL . $Theme->getImageURL('logo');
489         if (!$img_url)
490             return false;
491
492         return array('title' => WIKI_NAME,
493                      'link' => WikiURL(HOME_PAGE, false, 'absurl'),
494                      'url' => $img_url);
495     }
496
497     function textinput_properties () {
498         return array('title' => _("Search"),
499                      'description' => _("Title Search"),
500                      'name' => 's',
501                      'link' => WikiURL(_("TitleSearch"), false, 'absurl'));
502     }
503
504     function channel_properties () {
505         global $request;
506
507         $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl');
508
509         return array('title' => WIKI_NAME,
510                      'link' => $rc_url,
511                      'description' => _("RecentChanges"),
512                      'dc:date' => Iso8601DateTime(time()));
513
514         /* FIXME: other things one might like in <channel>:
515          * sy:updateFrequency
516          * sy:updatePeriod
517          * sy:updateBase
518          * dc:subject
519          * dc:publisher
520          * dc:language
521          * dc:rights
522          * rss091:language
523          * rss091:managingEditor
524          * rss091:webmaster
525          * rss091:lastBuildDate
526          * rss091:copyright
527          */
528     }
529
530
531
532
533     function item_properties ($rev) {
534         $page = $rev->getPage();
535         $pagename = $page->getName();
536
537         return array( 'title'           => split_pagename($pagename),
538                       'description'     => $this->summary($rev),
539                       'link'            => $this->pageURL($rev),
540                       'dc:date'         => $this->time($rev),
541                       'dc:contributor'  => $rev->get('author'),
542                       'wiki:version'    => $rev->getVersion(),
543                       'wiki:importance' => $this->importance($rev),
544                       'wiki:status'     => $this->status($rev),
545                       'wiki:diff'       => $this->diffURL($rev),
546                       'wiki:history'    => $this->historyURL($rev)
547                       );
548     }
549 }
550
551 class NonDeletedRevisionIterator extends WikiDB_PageRevisionIterator
552 {
553     /** Constructor
554      *
555      * @param $revisions object a WikiDB_PageRevisionIterator.
556      */
557     function NonDeletedRevisionIterator ($revisions, $check_current_revision = true) {
558         $this->_revisions = $revisions;
559         $this->_check_current_revision = $check_current_revision;
560     }
561
562     function next () {
563         while (($rev = $this->_revisions->next())) {
564             if ($this->_check_current_revision) {
565                 $page = $rev->getPage();
566                 $check_rev = $page->getCurrentRevision();
567             }
568             else {
569                 $check_rev = $rev;
570             }
571             if (! $check_rev->hasDefaultContents())
572                 return $rev;
573         }
574         $this->free();
575         return false;
576     }
577
578     function free () {
579         $this->_revisions->free();
580     }
581 }
582
583 class WikiPlugin_RecentChanges
584 extends WikiPlugin
585 {
586     function getName () {
587         return _("RecentChanges");
588     }
589
590     function getVersion() {
591         return preg_replace("/[Revision: $]/", '',
592                             "\$Revision: 1.69 $");
593     }
594
595     function getDefaultArguments() {
596         return array('days'         => 2,
597                      'show_minor'   => false,
598                      'show_major'   => true,
599                      'show_all'     => false,
600                      'show_deleted' => 'sometimes',
601                      'limit'        => false,
602                      'format'       => false,
603                      'daylist'      => false,
604                      'difflinks'    => true,
605                      'historylinks' => false,
606                      'caption'      => ''
607                      );
608     }
609
610     function getArgs ($argstr, $request, $defaults = false) {
611         $args = WikiPlugin::getArgs($argstr, $request, $defaults);
612
613         $action = $request->getArg('action');
614         if ($action != 'browse' && ! $request->isActionPage($action))
615             $args['format'] = false; // default -> HTML
616
617         if ($args['format'] == 'rss' && empty($args['limit']))
618             $args['limit'] = 15; // Fix default value for RSS.
619
620         if ($args['format'] == 'sidebar' && empty($args['limit']))
621             $args['limit'] = 1; // Fix default value for sidebar.
622
623         return $args;
624     }
625
626     function getMostRecentParams ($args) {
627         extract($args);
628
629         $params = array('include_minor_revisions' => $show_minor,
630                         'exclude_major_revisions' => !$show_major,
631                         'include_all_revisions' => !empty($show_all));
632
633         if ($limit != 0)
634             $params['limit'] = $limit;
635
636         if ($days > 0.0)
637             $params['since'] = time() - 24 * 3600 * $days;
638         elseif ($days < 0.0)
639             $params['since'] = 24 * 3600 * $days - time();
640
641
642         return $params;
643     }
644
645     function getChanges ($dbi, $args) {
646         $changes = $dbi->mostRecent($this->getMostRecentParams($args));
647
648         $show_deleted = $args['show_deleted'];
649         if ($show_deleted == 'sometimes')
650             $show_deleted = $args['show_minor'];
651
652         if (!$show_deleted)
653             $changes = new NonDeletedRevisionIterator($changes, !$args['show_all']);
654
655         return $changes;
656     }
657
658     function format ($changes, $args) {
659         global $Theme;
660         $format = $args['format'];
661
662         $fmt_class = $Theme->getFormatter('RecentChanges', $format);
663         if (!$fmt_class) {
664             if ($format == 'rss')
665                 $fmt_class = '_RecentChanges_RssFormatter';
666             elseif ($format == 'rss091') {
667                 include_once "lib/RSSWriter091.php";
668                 $fmt_class = '_RecentChanges_RssFormatter091';
669             }
670             elseif ($format == 'sidebar')
671                 $fmt_class = '_RecentChanges_SideBarFormatter';
672             else
673                 $fmt_class = '_RecentChanges_HtmlFormatter';
674         }
675
676         $fmt = new $fmt_class($args);
677         return $fmt->format($changes);
678     }
679
680     function run ($dbi, $argstr, $request) {
681         $args = $this->getArgs($argstr, $request);
682
683         // Hack alert: format() is a NORETURN for rss formatters.
684         return $this->format($this->getChanges($dbi, $args), $args);
685     }
686 };
687
688
689 class DayButtonBar extends HtmlElement {
690
691     function DayButtonBar ($plugin_args) {
692         $this->HtmlElement('p', array('class' => 'wiki-rc-action'));
693
694         // Display days selection buttons
695         extract($plugin_args);
696
697         // Custom caption
698         if (! $caption) {
699             if ($show_minor)
700                 $caption = _("Show minor edits for:");
701             elseif ($show_all)
702                 $caption = _("Show all changes for:");
703             else
704                 $caption = _("Show changes for:");
705         }
706
707         $this->pushContent($caption, ' ');
708
709         global $Theme;
710         $sep = $Theme->getButtonSeparator();
711
712         $n = 0;
713         foreach (explode(",", $daylist) as $days) {
714             if ($n++)
715                 $this->pushContent($sep);
716             $this->pushContent($this->_makeDayButton($days));
717         }
718     }
719
720     function _makeDayButton ($days) {
721         global $Theme, $request;
722
723         if ($days == 1)
724             $label = _("1 day");
725         elseif ($days < 1)
726             $label = "..."; //alldays
727         else
728             $label = sprintf(_("%s days"), abs($days));
729
730         $url = $request->getURLtoSelf(array('action' => 'browse', 'days' => $days));
731
732         return $Theme->makeButton($label, $url, 'wiki-rc-action');
733     }
734 }
735
736 // $Log: not supported by cvs2svn $
737
738 // (c-file-style: "gnu")
739 // Local Variables:
740 // mode: php
741 // tab-width: 8
742 // c-basic-offset: 4
743 // c-hanging-comment-ender-p: nil
744 // indent-tabs-mode: nil
745 // End:
746 ?>