]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RecentChanges.php
Starting to fix handling of the HTTP validator headers, Last-Modified,
[SourceForge/phpwiki.git] / lib / plugin / RecentChanges.php
1 <?php // -*-php-*-
2 rcs_id('$Id: RecentChanges.php,v 1.70 2003-02-16 05:09:43 dairiki 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 setValidators($rev) {
114         global $request;
115         if ($request->hasETag()) {
116             $request->addToETag('RecentChanges-top',
117                                 array($rev->getPageName(), $rev->getVersion()));
118             $request->setModificationTime($rev->get('mtime'));
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         $first = true;
297
298         while ($rev = $changes->next()) {
299             if (($date = $this->date($rev)) != $last_date) {
300                 if ($lines)
301                     $html->pushContent($lines);
302                 $html->pushContent(HTML::h3($date));
303                 $lines = HTML::ul();
304                 $last_date = $date;
305
306             }
307             $lines->pushContent($this->format_revision($rev));
308
309             if ($first)
310                 $this->setValidators($rev);
311             $first = false;
312         }
313         if ($lines)
314             $html->pushContent($lines);
315         return $html;
316     }
317
318     function format_revision ($rev) {
319         $args = &$this->_args;
320
321         $class = 'rc-' . $this->importance($rev);
322
323         $time = $this->time($rev);
324         if (! $rev->get('is_minor_edit'))
325             $time = HTML::strong(array('class' => 'pageinfo-majoredit'), $time);
326
327         $line = HTML::li(array('class' => $class));
328
329
330         if ($args['difflinks'])
331             $line->pushContent($this->diffLink($rev), ' ');
332
333         if ($args['historylinks'])
334             $line->pushContent($this->historyLink($rev), ' ');
335
336         $line->pushContent($this->pageLink($rev), ' ',
337                            $time, ' ',
338                            $this->summaryAsHTML($rev),
339                            ' ... ',
340                            $this->authorLink($rev));
341         return $line;
342     }
343 }
344
345
346 class _RecentChanges_SideBarFormatter
347 extends _RecentChanges_HtmlFormatter
348 {
349     function description () {
350         //omit description
351     }
352     function rss_icon () {
353         //omit rssicon
354     }
355     function title () {
356         //title click opens the normal RC or RE page in the main browser frame
357         extract($this->_args);
358         $titlelink = WikiLink($show_minor ? _("RecentEdits") : _("RecentChanges"));
359         $titlelink->setAttr('target', '_content');
360         return HTML($this->logo(), $titlelink);
361     }
362     function logo () {
363         //logo click opens the HomePage in the main browser frame
364         global $Theme;
365         $img = HTML::img(array('src' => $Theme->getImageURL('logo'),
366                                'border' => 0,
367                                'align' => 'right',
368                                'width' => 32
369                                ));
370         $linkurl = WikiLink(HOME_PAGE, false, $img);
371         $linkurl->setAttr('target', '_content');
372         return $linkurl;
373     }
374
375     function authorLink ($rev) {
376         $author = $rev->get('author');
377         if ( $this->authorHasPage($author) ) {
378             $linkurl = WikiLink($author);
379             $linkurl->setAttr('target', '_content'); // way to do this using parent::authorLink ??
380             return $linkurl;
381         } else
382             return $author;
383     }
384     function diffLink ($rev) {
385         $linkurl = parent::diffLink($rev);
386         $linkurl->setAttr('target', '_content');
387         return $linkurl;
388     }
389     function historyLink ($rev) {
390         $linkurl = parent::historyLink($rev);
391         $linkurl->setAttr('target', '_content');
392         return $linkurl;
393     }
394     function pageLink ($rev) {
395         $linkurl = parent::pageLink($rev);
396         $linkurl->setAttr('target', '_content');
397         return $linkurl;
398     }
399     // Overriding summaryAsHTML, because there is no way yet to
400     // return summary as transformed text with
401     // links setAttr('target', '_content') in Mozilla sidebar.
402     // So for now don't create clickable links inside summary
403     // in the sidebar, or else they target the sidebar and not the
404     // main content window.
405     function summaryAsHTML ($rev) {
406         if ( !($summary = $this->summary($rev)) )
407             return '';
408         return HTML::strong(array('class' => 'wiki-summary'),
409                                 "[",
410                                 /*TransformLinks(*/$summary,/* $rev->get('markup')),*/
411                                 "]");
412     }
413
414
415     function format ($changes) {
416         $this->_args['daylist'] = false; //only 1 day for Mozilla sidebar
417         $html = _RecentChanges_HtmlFormatter::format ($changes);
418         $html = HTML::div(array('class' => 'wikitext'), $html);
419
420         printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n", CHARSET);
421         printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"');
422         printf('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
423         printf('<html xmlns="http://www.w3.org/1999/xhtml">');
424
425         printf("<head>\n");
426         extract($this->_args);
427         $title = WIKI_NAME . $show_minor ? _("RecentEdits") : _("RecentChanges");
428         printf("<title>" . $title . "</title>\n");
429         global $Theme;
430         $css = $Theme->getCSS();
431         $css->PrintXML();
432         printf("</head>\n");
433
434         printf("<body class=\"sidebar\">\n");
435         $html->PrintXML();
436         printf("\n</body>\n");
437         printf("</html>\n");
438
439         flush();
440
441         global $request;
442         $request->finish(); // cut rest of page processing short
443     }
444 }
445
446
447 class _RecentChanges_RssFormatter
448 extends _RecentChanges_Formatter
449 {
450     var $_absurls = true;
451
452     function time ($rev) {
453         return Iso8601DateTime($rev->get('mtime'));
454     }
455
456     function pageURI ($rev) {
457         return WikiURL($rev, '', 'absurl');
458     }
459
460     function format ($changes) {
461         include_once('lib/RssWriter.php');
462         $rss = new RssWriter;
463
464
465         $rss->channel($this->channel_properties());
466
467         if (($props = $this->image_properties()))
468             $rss->image($props);
469         if (($props = $this->textinput_properties()))
470             $rss->textinput($props);
471
472         $first = true;
473         while ($rev = $changes->next()) {
474             $rss->addItem($this->item_properties($rev),
475                           $this->pageURI($rev));
476             if ($first)
477                 $this->setValidators($rev);
478             $first = false;
479         }
480
481         $rss->finish();
482         printf("\n<!-- Generated by PhpWiki:\n%s-->\n", $GLOBALS['RCS_IDS']);
483
484         // Flush errors in comment, otherwise it's invalid XML.
485         global $ErrorManager;
486         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
487             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
488
489         global $request;        // FIXME
490         $request->finish();     // NORETURN!!!!
491     }
492
493     function image_properties () {
494         global $Theme;
495
496         $img_url = SERVER_URL . $Theme->getImageURL('logo');
497         if (!$img_url)
498             return false;
499
500         return array('title' => WIKI_NAME,
501                      'link' => WikiURL(HOME_PAGE, false, 'absurl'),
502                      'url' => $img_url);
503     }
504
505     function textinput_properties () {
506         return array('title' => _("Search"),
507                      'description' => _("Title Search"),
508                      'name' => 's',
509                      'link' => WikiURL(_("TitleSearch"), false, 'absurl'));
510     }
511
512     function channel_properties () {
513         global $request;
514
515         $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl');
516
517         return array('title' => WIKI_NAME,
518                      'link' => $rc_url,
519                      'description' => _("RecentChanges"),
520                      'dc:date' => Iso8601DateTime(time()));
521
522         /* FIXME: other things one might like in <channel>:
523          * sy:updateFrequency
524          * sy:updatePeriod
525          * sy:updateBase
526          * dc:subject
527          * dc:publisher
528          * dc:language
529          * dc:rights
530          * rss091:language
531          * rss091:managingEditor
532          * rss091:webmaster
533          * rss091:lastBuildDate
534          * rss091:copyright
535          */
536     }
537
538
539
540
541     function item_properties ($rev) {
542         $page = $rev->getPage();
543         $pagename = $page->getName();
544
545         return array( 'title'           => split_pagename($pagename),
546                       'description'     => $this->summary($rev),
547                       'link'            => $this->pageURL($rev),
548                       'dc:date'         => $this->time($rev),
549                       'dc:contributor'  => $rev->get('author'),
550                       'wiki:version'    => $rev->getVersion(),
551                       'wiki:importance' => $this->importance($rev),
552                       'wiki:status'     => $this->status($rev),
553                       'wiki:diff'       => $this->diffURL($rev),
554                       'wiki:history'    => $this->historyURL($rev)
555                       );
556     }
557 }
558
559 class NonDeletedRevisionIterator extends WikiDB_PageRevisionIterator
560 {
561     /** Constructor
562      *
563      * @param $revisions object a WikiDB_PageRevisionIterator.
564      */
565     function NonDeletedRevisionIterator ($revisions, $check_current_revision = true) {
566         $this->_revisions = $revisions;
567         $this->_check_current_revision = $check_current_revision;
568     }
569
570     function next () {
571         while (($rev = $this->_revisions->next())) {
572             if ($this->_check_current_revision) {
573                 $page = $rev->getPage();
574                 $check_rev = $page->getCurrentRevision();
575             }
576             else {
577                 $check_rev = $rev;
578             }
579             if (! $check_rev->hasDefaultContents())
580                 return $rev;
581         }
582         $this->free();
583         return false;
584     }
585
586     function free () {
587         $this->_revisions->free();
588     }
589 }
590
591 class WikiPlugin_RecentChanges
592 extends WikiPlugin
593 {
594     function getName () {
595         return _("RecentChanges");
596     }
597
598     function getVersion() {
599         return preg_replace("/[Revision: $]/", '',
600                             "\$Revision: 1.70 $");
601     }
602
603     function getDefaultArguments() {
604         return array('days'         => 2,
605                      'show_minor'   => false,
606                      'show_major'   => true,
607                      'show_all'     => false,
608                      'show_deleted' => 'sometimes',
609                      'limit'        => false,
610                      'format'       => false,
611                      'daylist'      => false,
612                      'difflinks'    => true,
613                      'historylinks' => false,
614                      'caption'      => ''
615                      );
616     }
617
618     function getArgs ($argstr, $request, $defaults = false) {
619         $args = WikiPlugin::getArgs($argstr, $request, $defaults);
620
621         $action = $request->getArg('action');
622         if ($action != 'browse' && ! $request->isActionPage($action))
623             $args['format'] = false; // default -> HTML
624
625         if ($args['format'] == 'rss' && empty($args['limit']))
626             $args['limit'] = 15; // Fix default value for RSS.
627
628         if ($args['format'] == 'sidebar' && empty($args['limit']))
629             $args['limit'] = 1; // Fix default value for sidebar.
630
631         return $args;
632     }
633
634     function getMostRecentParams ($args) {
635         extract($args);
636
637         $params = array('include_minor_revisions' => $show_minor,
638                         'exclude_major_revisions' => !$show_major,
639                         'include_all_revisions' => !empty($show_all));
640
641         if ($limit != 0)
642             $params['limit'] = $limit;
643
644         if ($days > 0.0)
645             $params['since'] = time() - 24 * 3600 * $days;
646         elseif ($days < 0.0)
647             $params['since'] = 24 * 3600 * $days - time();
648
649
650         return $params;
651     }
652
653     function getChanges ($dbi, $args) {
654         $changes = $dbi->mostRecent($this->getMostRecentParams($args));
655
656         $show_deleted = $args['show_deleted'];
657         if ($show_deleted == 'sometimes')
658             $show_deleted = $args['show_minor'];
659
660         if (!$show_deleted)
661             $changes = new NonDeletedRevisionIterator($changes, !$args['show_all']);
662
663         return $changes;
664     }
665
666     function format ($changes, $args) {
667         global $Theme;
668         $format = $args['format'];
669
670         $fmt_class = $Theme->getFormatter('RecentChanges', $format);
671         if (!$fmt_class) {
672             if ($format == 'rss')
673                 $fmt_class = '_RecentChanges_RssFormatter';
674             elseif ($format == 'rss091') {
675                 include_once "lib/RSSWriter091.php";
676                 $fmt_class = '_RecentChanges_RssFormatter091';
677             }
678             elseif ($format == 'sidebar')
679                 $fmt_class = '_RecentChanges_SideBarFormatter';
680             else
681                 $fmt_class = '_RecentChanges_HtmlFormatter';
682         }
683
684         $fmt = new $fmt_class($args);
685         return $fmt->format($changes);
686     }
687
688     function run ($dbi, $argstr, $request) {
689         $args = $this->getArgs($argstr, $request);
690
691         // Hack alert: format() is a NORETURN for rss formatters.
692         return $this->format($this->getChanges($dbi, $args), $args);
693     }
694 };
695
696
697 class DayButtonBar extends HtmlElement {
698
699     function DayButtonBar ($plugin_args) {
700         $this->HtmlElement('p', array('class' => 'wiki-rc-action'));
701
702         // Display days selection buttons
703         extract($plugin_args);
704
705         // Custom caption
706         if (! $caption) {
707             if ($show_minor)
708                 $caption = _("Show minor edits for:");
709             elseif ($show_all)
710                 $caption = _("Show all changes for:");
711             else
712                 $caption = _("Show changes for:");
713         }
714
715         $this->pushContent($caption, ' ');
716
717         global $Theme;
718         $sep = $Theme->getButtonSeparator();
719
720         $n = 0;
721         foreach (explode(",", $daylist) as $days) {
722             if ($n++)
723                 $this->pushContent($sep);
724             $this->pushContent($this->_makeDayButton($days));
725         }
726     }
727
728     function _makeDayButton ($days) {
729         global $Theme, $request;
730
731         if ($days == 1)
732             $label = _("1 day");
733         elseif ($days < 1)
734             $label = "..."; //alldays
735         else
736             $label = sprintf(_("%s days"), abs($days));
737
738         $url = $request->getURLtoSelf(array('action' => 'browse', 'days' => $days));
739
740         return $Theme->makeButton($label, $url, 'wiki-rc-action');
741     }
742 }
743
744 // $Log: not supported by cvs2svn $
745 // Revision 1.69  2003/01/18 22:01:43  carstenklapp
746 // Code cleanup:
747 // Reformatting & tabs to spaces;
748 // Added copyleft, getVersion, getDescription, rcs_id.
749 //
750
751 // (c-file-style: "gnu")
752 // Local Variables:
753 // mode: php
754 // tab-width: 8
755 // c-basic-offset: 4
756 // c-hanging-comment-ender-p: nil
757 // indent-tabs-mode: nil
758 // End:
759 ?>