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