]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RecentChanges.php
simplify RSS: add RSS2 link (rss tag only, new content-type)
[SourceForge/phpwiki.git] / lib / plugin / RecentChanges.php
1 <?php // -*-php-*-
2 rcs_id('$Id: RecentChanges.php,v 1.102 2004-12-06 19:29:24 rurban 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 $WikiTheme;
47         return $WikiTheme->getDay($rev->get('mtime'));
48     }
49
50     function time ($rev) {
51         global $WikiTheme;
52         return $WikiTheme->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 isWikiWord($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($most_recent_rev) {
114         $rev = $most_recent_rev;
115         $validators = array('RecentChanges-top' =>
116                             array($rev->getPageName(), $rev->getVersion()),
117                             '%mtime' => $rev->get('mtime'));
118         global $request;
119         $request->appendValidators($validators);
120     }
121 }
122
123 class _RecentChanges_HtmlFormatter
124 extends _RecentChanges_Formatter
125 {
126     function diffLink ($rev) {
127         global $WikiTheme;
128         return $WikiTheme->makeButton(_("(diff)"), $this->diffURL($rev), 'wiki-rc-action');
129     }
130
131     function historyLink ($rev) {
132         global $WikiTheme;
133         return $WikiTheme->makeButton(_("(hist)"), $this->historyURL($rev), 'wiki-rc-action');
134     }
135
136     function pageLink ($rev, $link_text=false) {
137
138         return WikiLink($rev,'auto',$link_text);
139         /*
140         $page = $rev->getPage();
141         global $WikiTheme;
142         if ($this->include_versions_in_URLs()) {
143             $version = $rev->getVersion();
144             if ($rev->isCurrent())
145                 $version = false;
146             $exists = !$rev->hasDefaultContents();
147         }
148         else {
149             $version = false;
150             $cur = $page->getCurrentRevision();
151             $exists = !$cur->hasDefaultContents();
152         }
153         if ($exists)
154             return $WikiTheme->linkExistingWikiWord($page->getName(), $link_text, $version);
155         else
156             return $WikiTheme->linkUnknownWikiWord($page->getName(), $link_text);
157         */
158     }
159
160     function authorLink ($rev) {
161         $author = $rev->get('author');
162         if ( $this->authorHasPage($author) ) {
163             return WikiLink($author);
164         } else
165             return $author;
166     }
167
168     function summaryAsHTML ($rev) {
169         if ( !($summary = $this->summary($rev)) )
170             return '';
171         return  HTML::strong( array('class' => 'wiki-summary'),
172                               "[",
173                               TransformLinks($summary, $rev->get('markup'), $rev->getPageName()),
174                               "]");
175     }
176
177     function rss_icon () {
178         global $request, $WikiTheme;
179
180         $rss_url = $request->getURLtoSelf(array('format' => 'rss'));
181         return HTML::small(array('style' => 'font-weight:normal;vertical-align:middle;'), 
182                            $WikiTheme->makeButton("RSS", $rss_url, 'rssicon'));
183     }
184     function rss2_icon () {
185         global $request, $WikiTheme;
186
187         $rss_url = $request->getURLtoSelf(array('format' => 'rss2'));
188         return HTML::small(array('style' => 'font-weight:normal;vertical-align:middle;'), 
189                            $WikiTheme->makeButton("RSS2", $rss_url, 'rssicon'));
190     }
191
192     function description () {
193         extract($this->_args);
194         // FIXME: say something about show_all.
195         if ($show_major && $show_minor)
196             $edits = _("edits");
197         elseif ($show_major)
198             $edits = _("major edits");
199         else
200             $edits = _("minor edits");
201         if (isset($caption) and $caption == _("Recent Comments"))
202             $edits = _("comments");
203
204         if ($timespan = $days > 0) {
205             if (intval($days) != $days)
206                 $days = sprintf("%.1f", $days);
207         }
208         $lmt = abs($limit);
209         /**
210          * Depending how this text is split up it can be tricky or
211          * impossible to translate with good grammar. So the seperate
212          * strings for 1 day and %s days are necessary in this case
213          * for translating to multiple languages, due to differing
214          * overlapping ideal word cutting points.
215          *
216          * en: day/days "The %d most recent %s [during (the past] day) are listed below."
217          * de: 1 Tag    "Die %d jüngste %s [innerhalb (von des letzten] Tages) sind unten aufgelistet."
218          * de: %s days  "Die %d jüngste %s [innerhalb (von] %s Tagen) sind unten aufgelistet."
219          *
220          * en: day/days "The %d most recent %s during [the past] (day) are listed below."
221          * fr: 1 jour   "Les %d %s les plus récentes pendant [le dernier (d'une] jour) sont énumérées ci-dessous."
222          * fr: %s jours "Les %d %s les plus récentes pendant [les derniers (%s] jours) sont énumérées ci-dessous."
223          */
224         if ($limit > 0) {
225             if ($timespan) {
226                 if (intval($days) == 1)
227                     $desc = fmt("The %d most recent %s during the past day are listed below.",
228                                 $limit, $edits);
229                 else
230                     $desc = fmt("The %d most recent %s during the past %s days are listed below.",
231                                 $limit, $edits, $days);
232             } else
233                 $desc = fmt("The %d most recent %s are listed below.",
234                             $limit, $edits);
235         }
236         elseif ($limit < 0) {  //$limit < 0 means we want oldest pages
237             if ($timespan) {
238                 if (intval($days) == 1)
239                     $desc = fmt("The %d oldest %s during the past day are listed below.",
240                                 $lmt, $edits);
241                 else
242                     $desc = fmt("The %d oldest %s during the past %s days are listed below.",
243                                 $lmt, $edits, $days);
244             } else
245                 $desc = fmt("The %d oldest %s are listed below.",
246                             $lmt, $edits);
247         }
248
249         else {
250             if ($timespan) {
251                 if (intval($days) == 1)
252                     $desc = fmt("The most recent %s during the past day are listed below.",
253                                 $edits);
254                 else
255                     $desc = fmt("The most recent %s during the past %s days are listed below.",
256                                 $edits, $days);
257             } else
258                 $desc = fmt("All %s are listed below.", $edits);
259         }
260         if (isset($this->_args['page'])) // RelatedChanges
261             return HTML::p(false, $desc, HTML::br(), fmt("(to pages linked from \"%s\")",$this->_args['page']));
262         return HTML::p(false, $desc);
263     }
264
265
266     function title () {
267         extract($this->_args);
268         return array($show_minor ? _("RecentEdits") : _("RecentChanges"),
269                      ' ',
270                      $this->rss_icon(), HTML::raw('&nbsp;'), $this->rss2_icon(),
271                      $this->sidebar_link());
272     }
273
274     function empty_message () {
275         if (isset($this->_args['caption']) and $this->_args['caption'] == _("Recent Comments"))
276             return _("No comments found");
277         else 
278             return _("No changes found");
279     }
280         
281     function sidebar_link() {
282         extract($this->_args);
283         $pagetitle = $show_minor ? _("RecentEdits") : _("RecentChanges");
284
285         global $request;
286         $sidebarurl = WikiURL($pagetitle, array('format' => 'sidebar'), 'absurl');
287
288         $addsidebarjsfunc =
289             "function addPanel() {\n"
290             ."    window.sidebar.addPanel (\"" . sprintf("%s - %s", WIKI_NAME, $pagetitle) . "\",\n"
291             ."       \"$sidebarurl\",\"\");\n"
292             ."}\n";
293         $jsf = JavaScript($addsidebarjsfunc);
294
295         global $WikiTheme;
296         $sidebar_button = $WikiTheme->makeButton("sidebar", 'javascript:addPanel();', 'sidebaricon');
297         $addsidebarjsclick = asXML(HTML::small(array('style' => 'font-weight:normal;vertical-align:middle;'), $sidebar_button));
298         $jsc = JavaScript("if ((typeof window.sidebar == 'object') &&\n"
299                                 ."    (typeof window.sidebar.addPanel == 'function'))\n"
300                                 ."   {\n"
301                                 ."       document.write('$addsidebarjsclick');\n"
302                                 ."   }\n"
303                                 );
304         return HTML(new RawXML("\n"), $jsf, new RawXML("\n"), $jsc);
305     }
306
307     function format ($changes) {
308         include_once('lib/InlineParser.php');
309         
310         $html = HTML(HTML::h2(false, $this->title()));
311         if (($desc = $this->description()))
312             $html->pushContent($desc);
313         
314         if ($this->_args['daylist'])
315             $html->pushContent(new DayButtonBar($this->_args));
316
317         $last_date = '';
318         $lines = false;
319         $first = true;
320
321         while ($rev = $changes->next()) {
322             if (($date = $this->date($rev)) != $last_date) {
323                 if ($lines)
324                     $html->pushContent($lines);
325                 $html->pushContent(HTML::h3($date));
326                 $lines = HTML::ul();
327                 $last_date = $date;
328
329             }
330             // enforce view permission
331             if (mayAccessPage('view', $rev->_pagename)) {
332                 $lines->pushContent($this->format_revision($rev));
333
334                 if ($first)
335                     $this->setValidators($rev);
336                 $first = false;
337             }
338         }
339         if ($lines)
340             $html->pushContent($lines);
341         if ($first)
342             $html->pushContent(HTML::p(array('class' => 'rc-empty'),
343                                        $this->empty_message()));
344         
345         return $html;
346     }
347
348     function format_revision ($rev) {
349         $args = &$this->_args;
350
351         $class = 'rc-' . $this->importance($rev);
352
353         $time = $this->time($rev);
354         if (! $rev->get('is_minor_edit'))
355             $time = HTML::strong(array('class' => 'pageinfo-majoredit'), $time);
356
357         $line = HTML::li(array('class' => $class));
358
359
360         if ($args['difflinks'])
361             $line->pushContent($this->diffLink($rev), ' ');
362
363         if ($args['historylinks'])
364             $line->pushContent($this->historyLink($rev), ' ');
365
366         $line->pushContent($this->pageLink($rev), ' ',
367                            $time, ' ',
368                            $this->summaryAsHTML($rev),
369                            ' ... ',
370                            $this->authorLink($rev));
371         return $line;
372     }
373 }
374
375
376 class _RecentChanges_SideBarFormatter
377 extends _RecentChanges_HtmlFormatter
378 {
379     function rss_icon () {
380         //omit rssicon
381     }
382     function rss2_icon () { }
383     function title () {
384         //title click opens the normal RC or RE page in the main browser frame
385         extract($this->_args);
386         $titlelink = WikiLink($show_minor ? _("RecentEdits") : _("RecentChanges"));
387         $titlelink->setAttr('target', '_content');
388         return HTML($this->logo(), $titlelink);
389     }
390     function logo () {
391         //logo click opens the HomePage in the main browser frame
392         global $WikiTheme;
393         $img = HTML::img(array('src' => $WikiTheme->getImageURL('logo'),
394                                'border' => 0,
395                                'align' => 'right',
396                                'style' => 'height:2.5ex'
397                                ));
398         $linkurl = WikiLink(HOME_PAGE, false, $img);
399         $linkurl->setAttr('target', '_content');
400         return $linkurl;
401     }
402
403     function authorLink ($rev) {
404         $author = $rev->get('author');
405         if ( $this->authorHasPage($author) ) {
406             $linkurl = WikiLink($author);
407             $linkurl->setAttr('target', '_content'); // way to do this using parent::authorLink ??
408             return $linkurl;
409         } else
410             return $author;
411     }
412
413     function diffLink ($rev) {
414         $linkurl = parent::diffLink($rev);
415         $linkurl->setAttr('target', '_content');
416         // FIXME: Smelly hack to get smaller diff buttons in sidebar
417         $linkurl = new RawXML(str_replace('<img ', '<img style="height:2ex" ', asXML($linkurl)));
418         return $linkurl;
419     }
420     function historyLink ($rev) {
421         $linkurl = parent::historyLink($rev);
422         $linkurl->setAttr('target', '_content');
423         // FIXME: Smelly hack to get smaller history buttons in sidebar
424         $linkurl = new RawXML(str_replace('<img ', '<img style="height:2ex" ', asXML($linkurl)));
425         return $linkurl;
426     }
427     function pageLink ($rev) {
428         $linkurl = parent::pageLink($rev);
429         $linkurl->setAttr('target', '_content');
430         return $linkurl;
431     }
432     // Overriding summaryAsHTML, because there is no way yet to
433     // return summary as transformed text with
434     // links setAttr('target', '_content') in Mozilla sidebar.
435     // So for now don't create clickable links inside summary
436     // in the sidebar, or else they target the sidebar and not the
437     // main content window.
438     function summaryAsHTML ($rev) {
439         if ( !($summary = $this->summary($rev)) )
440             return '';
441         return HTML::strong(array('class' => 'wiki-summary'),
442                                 "[",
443                                 /*TransformLinks(*/$summary,/* $rev->get('markup')),*/
444                                 "]");
445     }
446
447
448     function format ($changes) {
449         $this->_args['daylist'] = false; //don't show day buttons in Mozilla sidebar
450         $html = _RecentChanges_HtmlFormatter::format ($changes);
451         $html = HTML::div(array('class' => 'wikitext'), $html);
452         global $request;
453         $request->discardOutput();
454         
455         printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n", $GLOBALS['charset']);
456         printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"');
457         printf('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
458         printf('<html xmlns="http://www.w3.org/1999/xhtml">');
459
460         printf("<head>\n");
461         extract($this->_args);
462         $title = WIKI_NAME . $show_minor ? _("RecentEdits") : _("RecentChanges");
463         printf("<title>" . $title . "</title>\n");
464         global $WikiTheme;
465         $css = $WikiTheme->getCSS();
466         $css->PrintXML();
467         printf("</head>\n");
468
469         printf("<body class=\"sidebar\">\n");
470         $html->PrintXML();
471         echo '<a href="http://www.feedvalidator.org/check.cgi?url=http://phpwiki.org/RecentChanges?format=rss"><img src="themes/default/buttons/valid-rss.png" alt="[Valid RSS]" title="Validate the RSS feed" width="44" height="15" /></a>';
472         printf("\n</body>\n");
473         printf("</html>\n");
474
475         $request->finish(); // cut rest of page processing short
476     }
477 }
478
479 class _RecentChanges_BoxFormatter
480 extends _RecentChanges_HtmlFormatter
481 {
482     function rss_icon () {
483     }
484     function rss2_icon () {
485     }
486     function title () {
487     }
488     function authorLink ($rev) {
489     }
490     function diffLink ($rev) {
491     }
492     function historyLink ($rev) {
493     }
494     function summaryAsHTML ($rev) {
495     }
496     function description () {
497     }
498     function format ($changes) {
499         include_once('lib/InlineParser.php');
500         $last_date = '';
501         $first = true;
502         $html = HTML();
503         $counter = 1;
504         $sp = HTML::Raw('&middot; ');
505         while ($rev = $changes->next()) {
506             // enforce view permission
507             if (mayAccessPage('view',$rev->_pagename)) {
508                 $html->pushContent($sp,$this->pageLink($rev),HTML::br());
509                 if ($first)
510                     $this->setValidators($rev);
511                 $first = false;
512             }
513         }
514         if ($first)
515             $html->pushContent(HTML::p(array('class' => 'rc-empty'),
516                                        $this->empty_message()));
517         return $html;
518     }
519 }
520
521 class _RecentChanges_RssFormatter
522 extends _RecentChanges_Formatter
523 {
524     var $_absurls = true;
525
526     function time ($rev) {
527         return Iso8601DateTime($rev->get('mtime'));
528     }
529
530     function pageURI ($rev) {
531         return WikiURL($rev, '', 'absurl');
532     }
533
534     function format ($changes) {
535         
536         include_once('lib/RssWriter.php');
537         $rss = new RssWriter;
538
539         $rss->channel($this->channel_properties());
540
541         if (($props = $this->image_properties()))
542             $rss->image($props);
543         if (($props = $this->textinput_properties()))
544             $rss->textinput($props);
545
546         $first = true;
547         while ($rev = $changes->next()) {
548             // enforce view permission
549             if (mayAccessPage('view', $rev->_pagename)) {
550                 $rss->addItem($this->item_properties($rev),
551                               $this->pageURI($rev));
552                 if ($first)
553                     $this->setValidators($rev);
554                 $first = false;
555             }
556         }
557
558         global $request;
559         $request->discardOutput();
560         $rss->finish();
561         printf("\n<!-- Generated by PhpWiki-%s:\n%s-->\n", PHPWIKI_VERSION, $GLOBALS['RCS_IDS']);
562
563         // Flush errors in comment, otherwise it's invalid XML.
564         global $ErrorManager;
565         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
566             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
567
568         $request->finish();     // NORETURN!!!!
569     }
570
571     function image_properties () {
572         global $WikiTheme;
573
574         $img_url = AbsoluteURL($WikiTheme->getImageURL('logo'));
575         if (!$img_url)
576             return false;
577
578         return array('title' => WIKI_NAME,
579                      'link' => WikiURL(HOME_PAGE, false, 'absurl'),
580                      'url' => $img_url);
581     }
582
583     function textinput_properties () {
584         return array('title' => _("Search"),
585                      'description' => _("Title Search"),
586                      'name' => 's',
587                      'link' => WikiURL(_("TitleSearch"), false, 'absurl'));
588     }
589
590     function channel_properties () {
591         global $request;
592
593         $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl');
594         return array('title' => WIKI_NAME,
595                      'link' => $rc_url,
596                      'description' => _("RecentChanges"),
597                      'dc:date' => Iso8601DateTime(time()),
598                      'dc:language' => $GLOBALS['LANG']);
599
600         /* FIXME: other things one might like in <channel>:
601          * sy:updateFrequency
602          * sy:updatePeriod
603          * sy:updateBase
604          * dc:subject
605          * dc:publisher
606          * dc:language
607          * dc:rights
608          * rss091:language
609          * rss091:managingEditor
610          * rss091:webmaster
611          * rss091:lastBuildDate
612          * rss091:copyright
613          */
614     }
615
616     function item_properties ($rev) {
617         $page = $rev->getPage();
618         $pagename = $page->getName();
619
620         return array( 'title'           => SplitPagename($pagename),
621                       'description'     => $this->summary($rev),
622                       'link'            => $this->pageURL($rev),
623                       'dc:date'         => $this->time($rev),
624                       'dc:contributor'  => $rev->get('author'),
625                       'wiki:version'    => $rev->getVersion(),
626                       'wiki:importance' => $this->importance($rev),
627                       'wiki:status'     => $this->status($rev),
628                       'wiki:diff'       => $this->diffURL($rev),
629                       'wiki:history'    => $this->historyURL($rev)
630                       );
631     }
632 }
633
634 /** explicit application/rss+xml Content-Type,
635  * simplified xml structure (no namespace),
636  * support for xml-rpc cloud registerProcedure (not yet)
637  */
638 class _RecentChanges_Rss2Formatter
639 extends _RecentChanges_RssFormatter {
640
641     function format ($changes) {
642         include_once('lib/RssWriter2.php');
643         $rss = new RssWriter2;
644
645         $rss->channel($this->channel_properties());
646         if (($props = $this->cloud_properties()))
647             $rss->cloud($props);
648         if (($props = $this->image_properties()))
649             $rss->image($props);
650         if (($props = $this->textinput_properties()))
651             $rss->textinput($props);
652         $first = true;
653         while ($rev = $changes->next()) {
654             // enforce view permission
655             if (mayAccessPage('view', $rev->_pagename)) {
656                 $rss->addItem($this->item_properties($rev),
657                               $this->pageURI($rev));
658                 if ($first)
659                     $this->setValidators($rev);
660                 $first = false;
661             }
662         }
663
664         global $request;
665         $request->discardOutput();
666         $rss->finish();
667         printf("\n<!-- Generated by PhpWiki-%s:\n%s-->\n", PHPWIKI_VERSION, $GLOBALS['RCS_IDS']);
668         // Flush errors in comment, otherwise it's invalid XML.
669         global $ErrorManager;
670         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
671             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
672
673         $request->finish();     // NORETURN!!!!
674     }
675
676     function channel_properties () {
677         $chann_10 = parent::channel_properties();
678         return array_merge($chann_10,
679                            array('generator' => 'PhpWiki-'.PHPWIKI_VERSION,
680                                  //<pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
681                                  //<lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
682                                  //<docs>http://blogs.law.harvard.edu/tech/rss</docs>
683                                  'copyright' => COPYRIGHTPAGE_URL
684                                  ));
685     }
686
687     function cloud_properties () { return false; } // xml-rpc registerProcedure not yet implemented
688     function cloud_properties_test () {
689         return array('protocol' => 'xml-rpc', // xml-rpc or soap or http-post
690                      'registerProcedure' => 'wiki.rssPleaseNotify',
691                      'path' => DATA_PATH.'/RPC2.php',
692                      'port' => !SERVER_PORT ? '80' : (SERVER_PROTOCOL == 'https' ? '443' : '80'),
693                      'domain' => SERVER_NAME);
694     }
695 }
696
697 class NonDeletedRevisionIterator extends WikiDB_PageRevisionIterator
698 {
699     /** Constructor
700      *
701      * @param $revisions object a WikiDB_PageRevisionIterator.
702      */
703     function NonDeletedRevisionIterator ($revisions, $check_current_revision = true) {
704         $this->_revisions = $revisions;
705         $this->_check_current_revision = $check_current_revision;
706     }
707
708     function next () {
709         while (($rev = $this->_revisions->next())) {
710             if ($this->_check_current_revision) {
711                 $page = $rev->getPage();
712                 $check_rev = $page->getCurrentRevision();
713             }
714             else {
715                 $check_rev = $rev;
716             }
717             if (! $check_rev->hasDefaultContents())
718                 return $rev;
719         }
720         $this->free();
721         return false;
722     }
723
724 }
725
726 class WikiPlugin_RecentChanges
727 extends WikiPlugin
728 {
729     function getName () {
730         return _("RecentChanges");
731     }
732
733     function getVersion() {
734         return preg_replace("/[Revision: $]/", '',
735                             "\$Revision: 1.102 $");
736     }
737
738     function managesValidators() {
739         // Note that this is a bit of a fig.
740         // We set validators based on the most recently changed page,
741         // but this fails when the most-recent page is deleted.
742         // (Consider that the Last-Modified time will decrease
743         // when this happens.)
744
745         // We might be better off, leaving this as false (and junking
746         // the validator logic above) and just falling back to the
747         // default behavior (handled by WikiPlugin) of just using
748         // the WikiDB global timestamp as the mtime.
749
750         // Nevertheless, for now, I leave this here, mostly as an
751         // example for how to use appendValidators() and managesValidators().
752         
753         return true;
754     }
755             
756     function getDefaultArguments() {
757         return array('days'         => 2,
758                      'show_minor'   => false,
759                      'show_major'   => true,
760                      'show_all'     => false,
761                      'show_deleted' => 'sometimes',
762                      'limit'        => false,
763                      'format'       => false,
764                      'daylist'      => false,
765                      'difflinks'    => true,
766                      'historylinks' => false,
767                      'caption'      => ''
768                      );
769     }
770
771     function getArgs ($argstr, $request, $defaults = false) {
772         $args = WikiPlugin::getArgs($argstr, $request, $this->getDefaultArguments());
773
774         $action = $request->getArg('action');
775         if ($action != 'browse' && ! $request->isActionPage($action))
776             $args['format'] = false; // default -> HTML
777
778         if ($args['format'] == 'rss' && empty($args['limit']))
779             $args['limit'] = 15; // Fix default value for RSS.
780         if ($args['format'] == 'rss2' && empty($args['limit']))
781             $args['limit'] = 15; // Fix default value for RSS2.
782
783         if ($args['format'] == 'sidebar' && empty($args['limit']))
784             $args['limit'] = 10; // Fix default value for sidebar.
785
786         return $args;
787     }
788
789     function getMostRecentParams ($args) {
790         extract($args);
791
792         $params = array('include_minor_revisions' => $show_minor,
793                         'exclude_major_revisions' => !$show_major,
794                         'include_all_revisions' => !empty($show_all));
795         if ($limit != 0)
796             $params['limit'] = $limit;
797
798         if ($days > 0.0)
799             $params['since'] = time() - 24 * 3600 * $days;
800         elseif ($days < 0.0)
801             $params['since'] = 24 * 3600 * $days - time();
802
803         return $params;
804     }
805
806     function getChanges ($dbi, $args) {
807         $changes = $dbi->mostRecent($this->getMostRecentParams($args));
808
809         $show_deleted = $args['show_deleted'];
810         if ($show_deleted == 'sometimes')
811             $show_deleted = $args['show_minor'];
812
813         if (!$show_deleted)
814             $changes = new NonDeletedRevisionIterator($changes, !$args['show_all']);
815
816         return $changes;
817     }
818
819     function format ($changes, $args) {
820         global $WikiTheme;
821         $format = $args['format'];
822
823         $fmt_class = $WikiTheme->getFormatter('RecentChanges', $format);
824         if (!$fmt_class) {
825             if ($format == 'rss')
826                 $fmt_class = '_RecentChanges_RssFormatter';
827             elseif ($format == 'rss2')
828                 $fmt_class = '_RecentChanges_Rss2Formatter';
829             elseif ($format == 'rss091') {
830                 include_once "lib/RSSWriter091.php";
831                 $fmt_class = '_RecentChanges_RssFormatter091';
832             }
833             elseif ($format == 'sidebar')
834                 $fmt_class = '_RecentChanges_SideBarFormatter';
835             elseif ($format == 'box')
836                 $fmt_class = '_RecentChanges_BoxFormatter';
837             else
838                 $fmt_class = '_RecentChanges_HtmlFormatter';
839         }
840
841         $fmt = new $fmt_class($args);
842         return $fmt->format($changes);
843     }
844
845     function run($dbi, $argstr, &$request, $basepage) {
846         $args = $this->getArgs($argstr, $request);
847
848         // HACKish: fix for SF bug #622784  (1000 years of RecentChanges ought
849         // to be enough for anyone.)
850         $args['days'] = min($args['days'], 365000);
851         
852         // Hack alert: format() is a NORETURN for rss formatters.
853         return $this->format($this->getChanges($dbi, $args), $args);
854     }
855
856     // box is used to display a fixed-width, narrow version with common header.
857     // just a numbered list of limit pagenames, without date.
858     function box($args = false, $request = false, $basepage = false) {
859         if (!$request) $request =& $GLOBALS['request'];
860         if (!isset($args['limit'])) $args['limit'] = 15;
861         $args['format'] = 'box';
862         $args['show_minor'] = false;
863         $args['show_major'] = true;
864         $args['show_deleted'] = 'sometimes';
865         $args['show_all'] = false;
866         $args['days'] = 90;
867         return $this->makeBox(WikiLink($this->getName(),'',SplitPagename($this->getName())),
868                               $this->format($this->getChanges($request->_dbi, $args), $args));
869     }
870
871 };
872
873
874 class DayButtonBar extends HtmlElement {
875
876     function DayButtonBar ($plugin_args) {
877         $this->__construct('p', array('class' => 'wiki-rc-action'));
878
879         // Display days selection buttons
880         extract($plugin_args);
881
882         // Custom caption
883         if (! $caption) {
884             if ($show_minor)
885                 $caption = _("Show minor edits for:");
886             elseif ($show_all)
887                 $caption = _("Show all changes for:");
888             else
889                 $caption = _("Show changes for:");
890         }
891
892         $this->pushContent($caption, ' ');
893
894         global $WikiTheme;
895         $sep = $WikiTheme->getButtonSeparator();
896
897         $n = 0;
898         foreach (explode(",", $daylist) as $days) {
899             if ($n++)
900                 $this->pushContent($sep);
901             $this->pushContent($this->_makeDayButton($days));
902         }
903     }
904
905     function _makeDayButton ($days) {
906         global $WikiTheme, $request;
907
908         if ($days == 1)
909             $label = _("1 day");
910         elseif ($days < 1)
911             $label = "..."; //alldays
912         else
913             $label = sprintf(_("%s days"), abs($days));
914
915         $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'days' => $days));
916
917         return $WikiTheme->makeButton($label, $url, 'wiki-rc-action');
918     }
919 }
920
921 // $Log: not supported by cvs2svn $
922 // Revision 1.101  2004/11/10 19:32:24  rurban
923 // * optimize increaseHitCount, esp. for mysql.
924 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
925 // * Pear_DB version logic (awful but needed)
926 // * fix broken ADODB quote
927 // * _extract_page_data simplification
928 //
929 // Revision 1.100  2004/06/28 16:35:12  rurban
930 // prevent from shell commands
931 //
932 // Revision 1.99  2004/06/20 14:42:54  rurban
933 // various php5 fixes (still broken at blockparser)
934 //
935 // Revision 1.98  2004/06/14 11:31:39  rurban
936 // renamed global $Theme to $WikiTheme (gforge nameclash)
937 // inherit PageList default options from PageList
938 //   default sortby=pagename
939 // use options in PageList_Selectable (limit, sortby, ...)
940 // added action revert, with button at action=diff
941 // added option regex to WikiAdminSearchReplace
942 //
943 // Revision 1.97  2004/06/03 18:58:27  rurban
944 // days links requires action=RelatedChanges arg
945 //
946 // Revision 1.96  2004/05/18 16:23:40  rurban
947 // rename split_pagename to SplitPagename
948 //
949 // Revision 1.95  2004/05/16 22:07:35  rurban
950 // check more config-default and predefined constants
951 // various PagePerm fixes:
952 //   fix default PagePerms, esp. edit and view for Bogo and Password users
953 //   implemented Creator and Owner
954 //   BOGOUSERS renamed to BOGOUSER
955 // fixed syntax errors in signin.tmpl
956 //
957 // Revision 1.94  2004/05/14 20:55:03  rurban
958 // simplified RecentComments
959 //
960 // Revision 1.93  2004/05/14 17:33:07  rurban
961 // new plugin RecentChanges
962 //
963 // Revision 1.92  2004/04/21 04:29:10  rurban
964 // Two convenient RecentChanges extensions
965 //   RelatedChanges (only links from current page)
966 //   RecentEdits (just change the default args)
967 //
968 // Revision 1.91  2004/04/19 18:27:46  rurban
969 // Prevent from some PHP5 warnings (ref args, no :: object init)
970 //   php5 runs now through, just one wrong XmlElement object init missing
971 // Removed unneccesary UpgradeUser lines
972 // Changed WikiLink to omit version if current (RecentChanges)
973 //
974 // Revision 1.90  2004/04/18 01:11:52  rurban
975 // more numeric pagename fixes.
976 // fixed action=upload with merge conflict warnings.
977 // charset changed from constant to global (dynamic utf-8 switching)
978 //
979 // Revision 1.89  2004/04/10 02:30:49  rurban
980 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
981 // Fixed "cannot setlocale..." (sf.net problem)
982 //
983 // Revision 1.88  2004/04/01 15:57:10  rurban
984 // simplified Sidebar theme: table, not absolute css positioning
985 // added the new box methods.
986 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
987 //
988 // Revision 1.87  2004/03/30 02:14:03  rurban
989 // fixed yet another Prefs bug
990 // added generic PearDb_iter
991 // $request->appendValidators no so strict as before
992 // added some box plugin methods
993 // PageList commalist for condensed output
994 //
995 // Revision 1.86  2004/03/12 13:31:43  rurban
996 // enforce PagePermissions, errormsg if not Admin
997 //
998 // Revision 1.85  2004/02/17 12:11:36  rurban
999 // added missing 4th basepage arg at plugin->run() to almost all plugins. This caused no harm so far, because it was silently dropped on normal usage. However on plugin internal ->run invocations it failed. (InterWikiSearch, IncludeSiteMap, ...)
1000 //
1001 // Revision 1.84  2004/02/15 22:29:42  rurban
1002 // revert premature performance fix
1003 //
1004 // Revision 1.83  2004/02/15 21:34:37  rurban
1005 // PageList enhanced and improved.
1006 // fixed new WikiAdmin... plugins
1007 // editpage, Theme with exp. htmlarea framework
1008 //   (htmlarea yet committed, this is really questionable)
1009 // WikiUser... code with better session handling for prefs
1010 // enhanced UserPreferences (again)
1011 // RecentChanges for show_deleted: how should pages be deleted then?
1012 //
1013 // Revision 1.82  2004/01/25 03:58:43  rurban
1014 // use stdlib:isWikiWord()
1015 //
1016 // Revision 1.81  2003/11/28 21:06:31  carstenklapp
1017 // Enhancement: Mozilla RecentChanges sidebar now defaults to 10 changes
1018 // instead of 1. Make diff buttons smaller with css. Added description
1019 // line back in at the top.
1020 //
1021 // Revision 1.80  2003/11/27 15:17:01  carstenklapp
1022 // Theme & appearance tweaks: Converted Mozilla sidebar link into a Theme
1023 // button, to allow an image button for it to be added to Themes. Output
1024 // RSS button in small text size when theme has no button image.
1025 //
1026 // Revision 1.79  2003/04/29 14:34:20  dairiki
1027 // Bug fix: "add sidebar" link didn't work when USE_PATH_INFO was false.
1028 //
1029 // Revision 1.78  2003/03/04 01:55:05  dairiki
1030 // Fix to ensure absolute URL for logo in RSS recent changes.
1031 //
1032 // Revision 1.77  2003/02/27 23:23:38  dairiki
1033 // Fix my breakage of CSS and sidebar RecentChanges output.
1034 //
1035 // Revision 1.76  2003/02/27 22:48:44  dairiki
1036 // Fixes invalid HTML generated by PageHistory plugin.
1037 //
1038 // (<noscript> is block-level and not allowed within <p>.)
1039 //
1040 // Revision 1.75  2003/02/22 21:39:05  dairiki
1041 // Hackish fix for SF bug #622784.
1042 //
1043 // (The root of the problem is clearly a PHP bug.)
1044 //
1045 // Revision 1.74  2003/02/21 22:52:21  dairiki
1046 // Make sure to interpret relative links (like [/Subpage]) in summary
1047 // relative to correct basepage.
1048 //
1049 // Revision 1.73  2003/02/21 04:12:06  dairiki
1050 // Minor fixes for new cached markup.
1051 //
1052 // Revision 1.72  2003/02/17 02:19:01  dairiki
1053 // Fix so that PageHistory will work when the current revision
1054 // of a page has been "deleted".
1055 //
1056 // Revision 1.71  2003/02/16 20:04:48  dairiki
1057 // Refactor the HTTP validator generation/checking code.
1058 //
1059 // This also fixes a number of bugs with yesterdays validator mods.
1060 //
1061 // Revision 1.70  2003/02/16 05:09:43  dairiki
1062 // Starting to fix handling of the HTTP validator headers, Last-Modified,
1063 // and ETag.
1064 //
1065 // Last-Modified was being set incorrectly (but only when DEBUG was not
1066 // defined!)  Setting a Last-Modified without setting an appropriate
1067 // Expires: and/or Cache-Control: header results in browsers caching
1068 // the page unconditionally (for a certain period of time).
1069 // This is generally bad, since it means people don't see updated
1070 // page contents right away --- this is particularly confusing to
1071 // the people who are editing pages since their edits don't show up
1072 // next time they browse the page.
1073 //
1074 // Now, we don't allow caching of pages without revalidation
1075 // (via the If-Modified-Since and/or If-None-Match request headers.)
1076 // (You can allow caching by defining CACHE_CONTROL_MAX_AGE to an
1077 // appropriate value in index.php, but I advise against it.)
1078 //
1079 // Problems:
1080 //
1081 //   o Even when request is aborted due to the content not being
1082 //     modified, we currently still do almost all the work involved
1083 //     in producing the page.  So the only real savings from all
1084 //     this logic is in network bandwidth.
1085 //
1086 //   o Plugins which produce "dynamic" output need to be inspected
1087 //     and made to call $request->addToETag() and
1088 //     $request->setModificationTime() appropriately, otherwise the
1089 //     page can change without the change being detected.
1090 //     This leads to stale pages in cache again...
1091 //
1092 // Revision 1.69  2003/01/18 22:01:43  carstenklapp
1093 // Code cleanup:
1094 // Reformatting & tabs to spaces;
1095 // Added copyleft, getVersion, getDescription, rcs_id.
1096 //
1097
1098 // (c-file-style: "gnu")
1099 // Local Variables:
1100 // mode: php
1101 // tab-width: 8
1102 // c-basic-offset: 4
1103 // c-hanging-comment-ender-p: nil
1104 // indent-tabs-mode: nil
1105 // End:
1106 ?>