]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/RecentChanges.php
Let us be more explicit
[SourceForge/phpwiki.git] / lib / plugin / RecentChanges.php
1 <?php // -*-php-*-
2 rcs_id('$Id$');
3 /**
4  Copyright 1999,2000,2001,2002,2007 $ThePhpWikiProgrammingTeam
5  Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6
7  This file is part of PhpWiki.
8
9  PhpWiki is free software; you can redistribute it and/or modify
10  it under the terms of the GNU General Public License as published by
11  the Free Software Foundation; either version 2 of the License, or
12  (at your option) any later version.
13
14  PhpWiki is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  GNU General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with PhpWiki; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 include_once("lib/WikiPlugin.php");
25
26 /**
27  */
28 class _RecentChanges_Formatter
29 {
30     var $_absurls = false;
31     var $action = "RecentChanges";
32
33     function _RecentChanges_Formatter ($rc_args) {
34         $this->_args = $rc_args;
35         $this->_diffargs = array('action' => 'diff');
36
37         if ($rc_args['show_minor'] || !$rc_args['show_major'])
38             $this->_diffargs['previous'] = 'minor';
39
40         // PageHistoryPlugin doesn't have a 'daylist' arg.
41         if (!isset($this->_args['daylist']))
42             $this->_args['daylist'] = false;
43     }
44
45     function title () {
46         global $request;
47         extract($this->_args);
48         if ($author == '[]') $author = $request->_user->getID();
49         if ($owner  == '[]') $owner = $request->_user->getID();
50         if ($author) $title = _("UserContribs").":$author";
51         elseif ($owner) $title = _("UserContribs").":$owner";
52         elseif ($only_new) $title = _("RecentNewPages");
53         elseif ($show_minor) $title = _("RecentEdits");
54         else $title = _("RecentChanges");
55
56         if (!empty($category))
57             $title = $category;
58         elseif (!empty($pagematch))
59             $title .= ":$pagematch";
60         return $title;
61     }
62
63     function include_versions_in_URLs() {
64         return (bool) $this->_args['show_all'];
65     }
66
67     function date ($rev) {
68         global $WikiTheme;
69         return $WikiTheme->getDay($rev->get('mtime'));
70     }
71
72     function time ($rev) {
73         global $WikiTheme;
74         return $WikiTheme->formatTime($rev->get('mtime'));
75     }
76
77     function diffURL ($rev) {
78         $args = $this->_diffargs;
79         if ($this->include_versions_in_URLs())
80             $args['version'] = $rev->getVersion();
81         $page = $rev->getPage();
82         return WikiURL($page->getName(), $args, $this->_absurls);
83     }
84
85     function historyURL ($rev) {
86         $page = $rev->getPage();
87         return WikiURL($page, array('action' => _("PageHistory")),
88                        $this->_absurls);
89     }
90
91     function pageURL ($rev) {
92         return WikiURL($this->include_versions_in_URLs() ? $rev : $rev->getPage(),
93                        '', $this->_absurls);
94     }
95
96     function authorHasPage ($author) {
97         global $WikiNameRegexp, $request;
98         $dbi = $request->getDbh();
99         return isWikiWord($author) && $dbi->isWikiPage($author);
100     }
101
102     function authorURL ($author) {
103         return $this->authorHasPage() ? WikiURL($author) : false;
104     }
105
106
107     function status ($rev) {
108         if ($rev->hasDefaultContents())
109             return 'deleted';
110         $page = $rev->getPage();
111         $prev = $page->getRevisionBefore($rev->getVersion());
112         if ($prev->hasDefaultContents())
113             return 'new';
114         return 'updated';
115     }
116
117     function importance ($rev) {
118         return $rev->get('is_minor_edit') ? 'minor' : 'major';
119     }
120
121     function summary($rev) {
122         if ( ($summary = $rev->get('summary')) )
123             return $summary;
124
125         switch ($this->status($rev)) {
126             case 'deleted':
127                 return _("Deleted");
128             case 'new':
129                 return _("New page");
130             default:
131                 return '';
132         }
133     }
134
135     function setValidators($most_recent_rev) {
136         $rev = $most_recent_rev;
137         $validators = array('RecentChanges-top' =>
138                             array($rev->getPageName(), $rev->getVersion()),
139                             '%mtime' => $rev->get('mtime'));
140         global $request;
141         $request->appendValidators($validators);
142     }
143 }
144
145 class _RecentChanges_HtmlFormatter
146 extends _RecentChanges_Formatter
147 {
148     function diffLink ($rev) {
149         global $WikiTheme;
150         $button = $WikiTheme->makeButton(_("diff"), $this->diffURL($rev), 'wiki-rc-action');
151         $button->setAttr('rel', 'nofollow');
152         return HTML("(",$button,")");
153     }
154
155     /* deletions: red, additions: green */
156     function diffSummary ($rev) {
157         $html = $this->diffURL($rev);
158         return '';
159     }
160
161     function historyLink ($rev) {
162         global $WikiTheme;
163         $button = $WikiTheme->makeButton(_("hist"), $this->historyURL($rev), 'wiki-rc-action');
164         $button->setAttr('rel', 'nofollow');
165         return HTML("(",$button,")");
166     }
167
168     function pageLink ($rev, $link_text=false) {
169
170         return WikiLink($this->include_versions_in_URLs() ? $rev : $rev->getPage(),
171                         'auto', $link_text);
172         /*
173         $page = $rev->getPage();
174         global $WikiTheme;
175         if ($this->include_versions_in_URLs()) {
176             $version = $rev->getVersion();
177             if ($rev->isCurrent())
178                 $version = false;
179             $exists = !$rev->hasDefaultContents();
180         }
181         else {
182             $version = false;
183             $cur = $page->getCurrentRevision();
184             $exists = !$cur->hasDefaultContents();
185         }
186         if ($exists)
187             return $WikiTheme->linkExistingWikiWord($page->getName(), $link_text, $version);
188         else
189             return $WikiTheme->linkUnknownWikiWord($page->getName(), $link_text);
190         */
191     }
192
193     function authorLink ($rev) {
194         return WikiLink($rev->get('author'), 'if_known');
195     }
196
197     /* Link to all users contributions (contribs and owns) */
198     function authorContribs ($rev) {
199         $author = $rev->get('author');
200         if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $author)) return '';
201         return HTML('(',
202                     Button(array('action' => _("RecentChanges"), 
203                                  'format' => 'contribs',
204                                  'author' => $author,
205                                  'days' => 360),
206                            _("contribs"),
207                            $author),
208                     ' | ',
209                     Button(array('action' => _("RecentChanges"), 
210                                  'format' => 'contribs',
211                                  'owner' => $author,
212                                  'days' => 360),
213                            _("new pages"),
214                            $author),
215                     ')');
216     }
217
218     function summaryAsHTML ($rev) {
219         if ( !($summary = $this->summary($rev)) )
220             return '';
221         return  HTML::span( array('class' => 'wiki-summary'),
222                             "(",
223                             TransformLinks($summary, $rev->get('markup'), $rev->getPageName()),
224                             ")");
225     }
226
227     function format_icon ($format, $filter = array()) {
228         global $request, $WikiTheme;
229         $args = $this->_args;
230         // remove links not used for those formats
231         unset($args['daylist']);
232         unset($args['difflinks']);
233         unset($args['historylinks']);
234         $rss_url = $request->getURLtoSelf
235                 (array_merge($args,
236                              array('action' => $this->action, 'format' => $format), 
237                              $filter));
238         return $WikiTheme->makeButton($format, $rss_url, 'rssicon');
239     }
240
241     function rss_icon ($args=array())  { return $this->format_icon("rss", $args); }
242     function rss2_icon ($args=array()) { return $this->format_icon("rss2", $args); }
243     function atom_icon ($args=array()) { return $this->format_icon("atom", $args); }
244     function rdf_icon ($args=array())  { return DEBUG ? $this->format_icon("rdf", $args) : ''; }
245     function rdfs_icon ($args=array()) { return DEBUG ? $this->format_icon("rdfs", $args) : ''; }
246     function owl_icon ($args=array())  { return DEBUG ? $this->format_icon("owl", $args) : ''; }
247
248     function grazr_icon ($args = array()) {
249         global $request, $WikiTheme;
250         if (is_localhost()) return '';
251         if (SERVER_PROTOCOL == "https") return '';
252         $our_url = WikiURL($request->getArg('pagename'),
253                     array_merge(array('action' => $this->action, 'format' => 'rss2'), $args), 
254                     true);
255         $rss_url = 'http://grazr.com/gzpanel.html?' . $our_url;
256         return $WikiTheme->makeButton("grazr", $rss_url, 'rssicon');
257     }
258
259     function pre_description () {
260         extract($this->_args);
261         // FIXME: say something about show_all.
262         if ($show_major && $show_minor)
263             $edits = _("edits");
264         elseif ($show_major)
265             $edits = _("major edits");
266         else
267             $edits = _("minor edits");
268         if (isset($caption) and $caption == _("Recent Comments"))
269             $edits = _("comments");
270         if (!empty($only_new)) {
271             $edits = _("created new pages");
272         }
273         if (!empty($author)) {
274             global $request;
275             if ($author == '[]')
276                 $author = $request->_user->getID();
277             $edits .= sprintf(_(" for pages changed by %s"), $author);
278         }
279         if (!empty($owner)) {
280             global $request;
281             if ($owner == '[]')
282                 $owner = $request->_user->getID();
283             $edits .= sprintf(_(" for pages owned by %s"), $owner);
284         }
285         if (!empty($category)) {
286             $edits .= sprintf(_(" for all pages linking to %s"), $category);
287         }
288         if (!empty($pagematch)) {
289             $edits .= sprintf(_(" for all pages matching '%s'"), $pagematch);
290         }
291         if ($timespan = $days > 0) {
292             if (intval($days) != $days)
293                 $days = sprintf("%.1f", $days);
294         }
295         $lmt = abs($limit);
296         /**
297          * Depending how this text is split up it can be tricky or
298          * impossible to translate with good grammar. So the seperate
299          * strings for 1 day and %s days are necessary in this case
300          * for translating to multiple languages, due to differing
301          * overlapping ideal word cutting points.
302          *
303          * en: day/days "The %d most recent %s [during (the past] day) are listed below."
304          * de: 1 Tag    "Die %d jüngste %s [innerhalb (von des letzten] Tages) sind unten aufgelistet."
305          * de: %s days  "Die %d jüngste %s [innerhalb (von] %s Tagen) sind unten aufgelistet."
306          *
307          * en: day/days "The %d most recent %s during [the past] (day) are listed below."
308          * fr: 1 jour   "Les %d %s les plus récentes pendant [le dernier (d'une] jour) sont Ã©numérées ci-dessous."
309          * fr: %s jours "Les %d %s les plus récentes pendant [les derniers (%s] jours) sont Ã©numérées ci-dessous."
310          */
311         if ($limit > 0) {
312             if ($timespan) {
313                 if (intval($days) == 1)
314                     $desc = fmt("The %d most recent %s during the past day are listed below.",
315                                 $limit, $edits);
316                 else
317                     $desc = fmt("The %d most recent %s during the past %s days are listed below.",
318                                 $limit, $edits, $days);
319             } else
320                 $desc = fmt("The %d most recent %s are listed below.",
321                             $limit, $edits);
322         }
323         elseif ($limit < 0) {  //$limit < 0 means we want oldest pages
324             if ($timespan) {
325                 if (intval($days) == 1)
326                     $desc = fmt("The %d oldest %s during the past day are listed below.",
327                                 $lmt, $edits);
328                 else
329                     $desc = fmt("The %d oldest %s during the past %s days are listed below.",
330                                 $lmt, $edits, $days);
331             } else
332                 $desc = fmt("The %d oldest %s are listed below.",
333                             $lmt, $edits);
334         }
335
336         else {
337             if ($timespan) {
338                 if (intval($days) == 1)
339                     $desc = fmt("The most recent %s during the past day are listed below.",
340                                 $edits);
341                 else
342                     $desc = fmt("The most recent %s during the past %s days are listed below.",
343                                 $edits, $days);
344             } else
345                 $desc = fmt("All %s are listed below.", $edits);
346         }
347         return $desc;
348     }    
349
350     function description() {
351         return HTML::p(false, $this->pre_description());
352     }
353
354     /* was title */
355     function headline () {
356         extract($this->_args);
357         return array($this->title(),
358                      ' ',
359                      $this->rss_icon(), 
360                      $this->rss2_icon(),
361                      $this->atom_icon(),
362                      $this->rdf_icon(),
363                      /*$this->rdfs_icon(),
364                        $this->owl_icon(),*/
365                      $this->grazr_icon(),
366                      $this->sidebar_link());
367     }
368
369     function empty_message() {
370         if (isset($this->_args['caption']) and $this->_args['caption'] == _("Recent Comments"))
371             return _("No comments found");
372         else 
373             return _("No changes found");
374     }
375         
376     function sidebar_link() {
377         extract($this->_args);
378         $pagetitle = $show_minor ? _("RecentEdits") : _("RecentChanges");
379
380         global $request;
381         $sidebarurl = WikiURL($pagetitle, array('format' => 'sidebar'), 'absurl');
382
383         $addsidebarjsfunc =
384             "function addPanel() {\n"
385             ."    window.sidebar.addPanel (\"" . sprintf("%s - %s", WIKI_NAME, $pagetitle) . "\",\n"
386             ."       \"$sidebarurl\",\"\");\n"
387             ."}\n";
388         $jsf = JavaScript($addsidebarjsfunc);
389
390         global $WikiTheme;
391         $sidebar_button = $WikiTheme->makeButton("sidebar", 'javascript:addPanel();', 'sidebaricon', 
392                                                  array('title' => _("Click to add this feed to your sidebar"),
393                                                        'style' => 'font-size:9pt;font-weight:normal; vertical-align:middle;'));
394         $addsidebarjsclick = asXML($sidebar_button);
395         $jsc = JavaScript("if ((typeof window.sidebar == 'object') &&\n"
396                                 ."    (typeof window.sidebar.addPanel == 'function'))\n"
397                                 ."   {\n"
398                                 ."       document.write('$addsidebarjsclick');\n"
399                                 ."   }\n"
400                                 );
401         return HTML(new RawXML("\n"), $jsf, new RawXML("\n"), $jsc);
402     }
403
404     function format ($changes) {
405         include_once('lib/InlineParser.php');
406         
407         $html = HTML(HTML::h2(false, $this->headline()));
408         if (($desc = $this->description()))
409             $html->pushContent($desc);
410         
411         if ($this->_args['daylist'])
412             $html->pushContent(new DayButtonBar($this->_args));
413
414         $last_date = '';
415         $lines = false;
416         $first = true;
417
418         while ($rev = $changes->next()) {
419             if (($date = $this->date($rev)) != $last_date) {
420                 if ($lines)
421                     $html->pushContent($lines);
422                 // for user contributions no extra date line
423                 $html->pushContent(HTML::h3($date));
424                 $lines = HTML::ul();
425                 $last_date = $date;
426
427             }
428             // enforce view permission
429             if (mayAccessPage('view', $rev->_pagename)) {
430                 $lines->pushContent($this->format_revision($rev));
431                 if ($first)
432                     $this->setValidators($rev);
433                 $first = false;
434             }
435         }
436         if ($lines)
437             $html->pushContent($lines);
438         if ($first)
439             $html->pushContent(HTML::p(array('class' => 'rc-empty'),
440                                        $this->empty_message()));
441         
442         return $html;
443     }
444
445     function format_revision ($rev) {
446         global $WikiTheme;
447         $args = &$this->_args;
448
449         $class = 'rc-' . $this->importance($rev);
450
451         $time = $this->time($rev);
452         if (! $rev->get('is_minor_edit'))
453             $time = HTML::span(array('class' => 'pageinfo-majoredit'), $time);
454
455         $line = HTML::li(array('class' => $class));
456
457         if ($args['difflinks'])
458             $line->pushContent($this->diffLink($rev), ' ');
459
460         if ($args['historylinks'])
461             $line->pushContent($this->historyLink($rev), ' ');
462
463         // Do not display a link for a deleted page, just the page name
464         if ($rev->hasDefaultContents()) {
465             $linkorname = $rev->_pagename;
466         } else {
467             $linkorname = $this->pageLink($rev);
468         }
469
470         if ((isa($WikiTheme, 'WikiTheme_MonoBook')) or (isa($WikiTheme, 'WikiTheme_gforge'))) {
471             $line->pushContent(
472                                $args['historylinks'] ? '' : $this->historyLink($rev),
473                                ' . . ', $linkorname, '; ',
474                                $time, ' . . ',
475                                $this->authorLink($rev),' ',
476                                $this->authorContribs($rev),' ',
477                                $this->summaryAsHTML($rev));
478         } else {
479             $line->pushContent($linkorname, ' ',
480                                $time, ' ',
481                                $this->summaryAsHTML($rev),
482                                ' ... ',
483                                $this->authorLink($rev));
484         }
485         return $line;
486     }
487
488 }
489
490 /* format=contribs: no seperation into extra dates
491  * 14:41, 3 December 2006 (hist) (diff) Talk:PhpWiki (added diff link)  (top)
492  */
493 class _RecentChanges_UserContribsFormatter
494 extends _RecentChanges_HtmlFormatter
495 {
496     function headline () {
497         global $request;
498         extract($this->_args);
499         if ($author == '[]') $author = $request->_user->getID();
500         if ($owner  == '[]') $owner = $request->_user->getID();
501         $author_args = $owner
502             ? array('owner' => $owner)
503             : array('author' => $author);
504         return array(_("UserContribs"),":",$owner ? $owner : $author,
505                      ' ',
506                      $this->rss_icon($author_args), 
507                      $this->rss2_icon($author_args),
508                      $this->atom_icon($author_args),
509                      $this->rdf_icon($author_args),
510                      $this->grazr_icon($author_args));
511     }
512
513     function format ($changes) {
514         include_once('lib/InlineParser.php');
515         
516         $html = HTML(HTML::h2(false, $this->headline()));
517         $lines = HTML::ol();
518         $first = true; $count = 0;
519         while ($rev = $changes->next()) {
520             if (mayAccessPage('view', $rev->_pagename)) {
521                 $lines->pushContent($this->format_revision($rev));
522                 if ($first)
523                     $this->setValidators($rev);
524                 $first = false;
525             }
526             $count++;
527         }
528         $this->_args['limit'] = $count;
529         if (($desc = $this->description()))
530             $html->pushContent($desc);
531         if ($this->_args['daylist'])
532             $html->pushContent(new DayButtonBar($this->_args));
533         if ($first)
534             $html->pushContent(HTML::p(array('class' => 'rc-empty'),
535                                        $this->empty_message()));
536         else                               
537             $html->pushContent($lines);
538         
539         return $html;
540     }
541
542     function format_revision ($rev) {
543         $args = &$this->_args;
544         $class = 'rc-' . $this->importance($rev);
545         $time = $this->time($rev);
546         if (! $rev->get('is_minor_edit'))
547             $time = HTML::span(array('class' => 'pageinfo-majoredit'), $time);
548
549         $line = HTML::li(array('class' => $class));
550
551         $line->pushContent($this->time($rev),", ");
552         $line->pushContent($this->date($rev)," ");
553         $line->pushContent($this->diffLink($rev), ' ');
554         $line->pushContent($this->historyLink($rev), ' ');
555         $line->pushContent($this->pageLink($rev), ' ',
556                            $this->summaryAsHTML($rev));
557         return $line;
558     }
559 }
560
561 class _RecentChanges_SideBarFormatter
562 extends _RecentChanges_HtmlFormatter
563 {
564     function rss_icon () {
565         //omit rssicon
566     }
567     function rss2_icon () { }
568     function headline () {
569         //title click opens the normal RC or RE page in the main browser frame
570         extract($this->_args);
571         $titlelink = WikiLink($this->title());
572         $titlelink->setAttr('target', '_content');
573         return HTML($this->logo(), $titlelink);
574     }
575     function logo () {
576         //logo click opens the HomePage in the main browser frame
577         global $WikiTheme;
578         $img = HTML::img(array('src' => $WikiTheme->getImageURL('logo'),
579                                'border' => 0,
580                                'align' => 'right',
581                                'style' => 'height:2.5ex'
582                                ));
583         $linkurl = WikiLink(HOME_PAGE, false, $img);
584         $linkurl->setAttr('target', '_content');
585         return $linkurl;
586     }
587
588     function authorLink ($rev) {
589         $author = $rev->get('author');
590         if ( $this->authorHasPage($author) ) {
591             $linkurl = WikiLink($author);
592             $linkurl->setAttr('target', '_content'); // way to do this using parent::authorLink ??
593             return $linkurl;
594         } else
595             return $author;
596     }
597
598     function diffLink ($rev) {
599         $linkurl = parent::diffLink($rev);
600         $linkurl->setAttr('target', '_content');
601         $linkurl->setAttr('rel', 'nofollow');
602         // FIXME: Smelly hack to get smaller diff buttons in sidebar
603         $linkurl = new RawXML(str_replace('<img ', '<img style="height:2ex" ', asXML($linkurl)));
604         return $linkurl;
605     }
606     function historyLink ($rev) {
607         $linkurl = parent::historyLink($rev);
608         $linkurl->setAttr('target', '_content');
609         // FIXME: Smelly hack to get smaller history buttons in sidebar
610         $linkurl = new RawXML(str_replace('<img ', '<img style="height:2ex" ', asXML($linkurl)));
611         return $linkurl;
612     }
613     function pageLink ($rev) {
614         $linkurl = parent::pageLink($rev);
615         $linkurl->setAttr('target', '_content');
616         return $linkurl;
617     }
618     // Overriding summaryAsHTML, because there is no way yet to
619     // return summary as transformed text with
620     // links setAttr('target', '_content') in Mozilla sidebar.
621     // So for now don't create clickable links inside summary
622     // in the sidebar, or else they target the sidebar and not the
623     // main content window.
624     function summaryAsHTML ($rev) {
625         if ( !($summary = $this->summary($rev)) )
626             return '';
627         return HTML::span(array('class' => 'wiki-summary'),
628                           "[",
629                           /*TransformLinks(*/$summary,/* $rev->get('markup')),*/
630                           "]");
631     }
632
633
634     function format ($changes) {
635         $this->_args['daylist'] = false; //don't show day buttons in Mozilla sidebar
636         $html = _RecentChanges_HtmlFormatter::format ($changes);
637         $html = HTML::div(array('class' => 'wikitext'), $html);
638         global $request;
639         $request->discardOutput();
640         
641         printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n", $GLOBALS['charset']);
642         printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"');
643         printf('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
644         printf('<html xmlns="http://www.w3.org/1999/xhtml">');
645
646         printf("<head>\n");
647         extract($this->_args);
648         if (!empty($category))
649             $title = $category;
650         elseif (!empty($pagematch))
651             $title = $pagematch;
652         else
653             $title = WIKI_NAME . $show_minor ? _("RecentEdits") : _("RecentChanges");
654         printf("<title>" . $title . "</title>\n");
655         global $WikiTheme;
656         $css = $WikiTheme->getCSS();
657         $css->PrintXML();
658         printf("</head>\n");
659
660         printf("<body class=\"sidebar\">\n");
661         $html->PrintXML();
662         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>';
663         printf("\n</body>\n");
664         printf("</html>\n");
665
666         $request->finish(); // cut rest of page processing short
667     }
668 }
669
670 class _RecentChanges_BoxFormatter
671 extends _RecentChanges_HtmlFormatter
672 {
673     function rss_icon () {
674     }
675     function rss2_icon () {
676     }
677     function headline () {
678     }
679     function authorLink ($rev) {
680     }
681     function diffLink ($rev) {
682     }
683     function historyLink ($rev) {
684     }
685     function summaryAsHTML ($rev) {
686     }
687     function description () {
688     }
689     function format ($changes) {
690         include_once('lib/InlineParser.php');
691         $last_date = '';
692         $first = true;
693         $html = HTML();
694         $counter = 1;
695         $sp = HTML::Raw("\n&nbsp;&middot;&nbsp;");
696         while ($rev = $changes->next()) {
697             // enforce view permission
698             if (mayAccessPage('view',$rev->_pagename)) {
699                 if ($link = $this->pageLink($rev)) // some entries may be empty 
700                                                    // (/Blog/.. interim pages)
701                     $html->pushContent($sp, $link, HTML::br());
702                 if ($first)
703                     $this->setValidators($rev);
704                 $first = false;
705             }
706         }
707         if ($first)
708             $html->pushContent(HTML::p(array('class' => 'rc-empty'),
709                                        $this->empty_message()));
710         return $html;
711     }
712 }
713
714 class _RecentChanges_RssFormatter
715 extends _RecentChanges_Formatter
716 {
717     var $_absurls = true;
718
719     function time ($rev) {
720         return Iso8601DateTime($rev->get('mtime'));
721     }
722
723     function pageURI ($rev) {
724         return WikiURL($rev, '', 'absurl');
725     }
726
727     function format ($changes) {
728         
729         include_once('lib/RssWriter.php');
730         $rss = new RssWriter;
731         $rss->channel($this->channel_properties());
732
733         if (($props = $this->image_properties()))
734             $rss->image($props);
735         if (($props = $this->textinput_properties()))
736             $rss->textinput($props);
737
738         $first = true;
739         while ($rev = $changes->next()) {
740             // enforce view permission
741             if (mayAccessPage('view', $rev->_pagename)) {
742                 $rss->addItem($this->item_properties($rev),
743                               $this->pageURI($rev));
744                 if ($first)
745                     $this->setValidators($rev);
746                 $first = false;
747             }
748         }
749
750         global $request;
751         $request->discardOutput();
752         $rss->finish();
753         //header("Content-Type: application/rss+xml; charset=" . $GLOBALS['charset']);
754         printf("\n<!-- Generated by PhpWiki-%s:\n%s-->\n", PHPWIKI_VERSION, $GLOBALS['RCS_IDS']);
755
756         // Flush errors in comment, otherwise it's invalid XML.
757         global $ErrorManager;
758         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
759             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
760
761         $request->finish();     // NORETURN!!!!
762     }
763
764     function image_properties () {
765         global $WikiTheme;
766
767         $img_url = AbsoluteURL($WikiTheme->getImageURL('logo'));
768         if (!$img_url)
769             return false;
770
771         return array('title' => WIKI_NAME,
772                      'link' => WikiURL(HOME_PAGE, false, 'absurl'),
773                      'url' => $img_url);
774     }
775
776     function textinput_properties () {
777         return array('title' => _("Search"),
778                      'description' => _("Title Search"),
779                      'name' => 's',
780                      'link' => WikiURL(_("TitleSearch"), false, 'absurl'));
781     }
782
783     function channel_properties () {
784         global $request;
785
786         $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl');
787         extract($this->_args);
788         $title = WIKI_NAME;
789         $description = $this->title();
790         if ($category)
791             $title = $category;
792         elseif ($pagematch)
793             $title = $pagematch;
794         return array('title' => $title,
795                      'link' => $rc_url,
796                      'description' => $description,
797                      'dc:date' => Iso8601DateTime(time()),
798                      'dc:language' => $GLOBALS['LANG']);
799
800         /* FIXME: other things one might like in <channel>:
801          * sy:updateFrequency
802          * sy:updatePeriod
803          * sy:updateBase
804          * dc:subject
805          * dc:publisher
806          * dc:language
807          * dc:rights
808          * rss091:language
809          * rss091:managingEditor
810          * rss091:webmaster
811          * rss091:lastBuildDate
812          * rss091:copyright
813          */
814     }
815
816     function item_properties ($rev) {
817         $page = $rev->getPage();
818         $pagename = $page->getName();
819
820         return array( 'title'           => SplitPagename($pagename),
821                       'description'     => $this->summary($rev),
822                       'link'            => $this->pageURL($rev),
823                       'dc:date'         => $this->time($rev),
824                       'dc:contributor'  => $rev->get('author'),
825                       'wiki:version'    => $rev->getVersion(),
826                       'wiki:importance' => $this->importance($rev),
827                       'wiki:status'     => $this->status($rev),
828                       'wiki:diff'       => $this->diffURL($rev),
829                       'wiki:history'    => $this->historyURL($rev)
830                       );
831     }
832 }
833
834 /** explicit application/rss+xml Content-Type,
835  * simplified xml structure (no namespace),
836  * support for xml-rpc cloud registerProcedure (not yet)
837  */
838 class _RecentChanges_Rss2Formatter
839 extends _RecentChanges_RssFormatter {
840
841     function format ($changes) {
842         include_once('lib/RssWriter2.php');
843         $rss = new RssWriter2;
844
845         $rss->channel($this->channel_properties());
846         if (($props = $this->cloud_properties()))
847             $rss->cloud($props);
848         if (($props = $this->image_properties()))
849             $rss->image($props);
850         if (($props = $this->textinput_properties()))
851             $rss->textinput($props);
852         $first = true;
853         while ($rev = $changes->next()) {
854             // enforce view permission
855             if (mayAccessPage('view', $rev->_pagename)) {
856                 $rss->addItem($this->item_properties($rev),
857                               $this->pageURI($rev));
858                 if ($first) {
859                     $this->setValidators($rev);
860                     $first = false;
861                 }
862             }
863         }
864
865         global $request;
866         $request->discardOutput();
867         $rss->finish();
868         //header("Content-Type: application/rss+xml; charset=" . $GLOBALS['charset']);
869         printf("\n<!-- Generated by PhpWiki-%s:\n%s-->\n", PHPWIKI_VERSION, $GLOBALS['RCS_IDS']);
870         // Flush errors in comment, otherwise it's invalid XML.
871         global $ErrorManager;
872         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
873             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
874
875         $request->finish();     // NORETURN!!!!
876     }
877
878     function channel_properties () {
879         $chann_10 = parent::channel_properties();
880         return array_merge($chann_10,
881                            array('generator' => 'PhpWiki-'.PHPWIKI_VERSION,
882                                  //<pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
883                                  //<lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
884                                  //<docs>http://blogs.law.harvard.edu/tech/rss</docs>
885                                  'copyright' => COPYRIGHTPAGE_URL
886                                  ));
887     }
888
889     // xml-rpc registerProcedure not yet implemented
890     function cloud_properties () { return false; } 
891     function cloud_properties_test () {
892         return array('protocol' => 'xml-rpc', // xml-rpc or soap or http-post
893                      'registerProcedure' => 'wiki.rssPleaseNotify',
894                      'path' => DATA_PATH.'/RPC2.php',
895                      'port' => !SERVER_PORT ? '80' : (SERVER_PROTOCOL == 'https' ? '443' : '80'),
896                      'domain' => SERVER_NAME);
897     }
898 }
899
900 /** Explicit application/atom+xml Content-Type
901  *  A weird, questionable format
902  */
903 class _RecentChanges_AtomFormatter
904 extends _RecentChanges_RssFormatter {
905
906     function format ($changes) {
907         global $request;
908         include_once('lib/RssWriter.php');
909         $rss = new AtomFeed;
910
911         // "channel" is called "feed" in atom
912         $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl');
913         extract($this->_args);
914         $title = WIKI_NAME;
915         $description = $this->title();
916         if ($category)
917             $title = $category;
918         elseif ($pagematch)
919             $title = $pagematch;
920         $feed_props = array('title' => $description,
921                             'link' => array('rel'=>"alternate",
922                                             'type'=>"text/html",
923                                             'href' => $rc_url),
924                             'id' => md5($rc_url),                
925                             'modified' => Iso8601DateTime(time()),
926                             'generator' => 'PhpWiki-'.PHPWIKI_VERSION,
927                             'tagline' => '');
928         $rss->feed($feed_props);
929         $first = true;
930         while ($rev = $changes->next()) {
931             // enforce view permission
932             if (mayAccessPage('view', $rev->_pagename)) {
933                 $props = $this->item_properties($rev);
934                 $rss->addItem($props,
935                               false,
936                               $this->pageURI($rev));
937                 if ($first)
938                     $this->setValidators($rev);
939                 $first = false;
940             }
941         }
942
943         $request->discardOutput();
944         $rss->finish();
945         //header("Content-Type: application/atom; charset=" . $GLOBALS['charset']);
946         printf("\n<!-- Generated by PhpWiki-%s:\n%s-->\n", PHPWIKI_VERSION, $GLOBALS['RCS_IDS']);
947         // Flush errors in comment, otherwise it's invalid XML.
948         global $ErrorManager;
949         if (($errors = $ErrorManager->getPostponedErrorsAsHTML()))
950             printf("\n<!-- PHP Warnings:\n%s-->\n", AsXML($errors));
951
952         $request->finish();     // NORETURN!!!!
953     }
954
955     function item_properties ($rev) {
956         $page = $rev->getPage();
957         $pagename = $page->getName();
958         return array( 'title'           => $pagename,
959                       'link'            => array('rel' => 'alternate',
960                                                  'type' => 'text/html',
961                                                  'href' => $this->pageURL($rev)),
962                       'summary'         => $this->summary($rev),
963                       'modified'        => $this->time($rev)."Z",
964                       'issued'          => $this->time($rev),
965                       'created'         => $this->time($rev)."Z",
966                       'author'          => new XmlElement('author', new XmlElement('name', $rev->get('author')))
967                       );
968     }
969 }
970
971 /**
972  * Filter by non-empty
973  */
974 class NonDeletedRevisionIterator extends WikiDB_PageRevisionIterator
975 {
976     /** Constructor
977      *
978      * @param $revisions object a WikiDB_PageRevisionIterator.
979      */
980     function NonDeletedRevisionIterator ($revisions, $check_current_revision = true) {
981         $this->_revisions = $revisions;
982         $this->_check_current_revision = $check_current_revision;
983     }
984
985     function next () {
986         while (($rev = $this->_revisions->next())) {
987             if ($this->_check_current_revision) {
988                 $page = $rev->getPage();
989                 $check_rev = $page->getCurrentRevision();
990             }
991             else {
992                 $check_rev = $rev;
993             }
994             if (! $check_rev->hasDefaultContents())
995                 return $rev;
996         }
997         $this->free();
998         return false;
999     }
1000
1001 }
1002
1003 /**
1004  * Filter by only_new.
1005  * Only new created pages
1006  */
1007 class NewPageRevisionIterator extends WikiDB_PageRevisionIterator
1008 {
1009     /** Constructor
1010      *
1011      * @param $revisions object a WikiDB_PageRevisionIterator.
1012      */
1013     function NewPageRevisionIterator ($revisions) {
1014         $this->_revisions = $revisions;
1015     }
1016
1017     function next () {
1018         while (($rev = $this->_revisions->next())) {
1019             if ($rev->getVersion() == 1)
1020                 return $rev;
1021         }
1022         $this->free();
1023         return false;
1024     }
1025 }
1026
1027 /**
1028  * Only pages with links to a certain category
1029  */
1030 class LinkRevisionIterator extends WikiDB_PageRevisionIterator
1031 {
1032     function LinkRevisionIterator ($revisions, $category) {
1033         $this->_revisions = $revisions;
1034         if (preg_match("/[\?\.\*]/", $category)) {
1035           $backlinkiter = $this->_revisions->_wikidb->linkSearch
1036             (new TextSearchQuery("*", true), 
1037              new TextSearchQuery($category, true), 
1038              "linkfrom");
1039         } else {
1040           $basepage = $GLOBALS['request']->getPage($category);
1041           $backlinkiter = $basepage->getBackLinks(true);
1042         }
1043         $this->links = array();
1044         foreach ($backlinkiter->asArray() as $p) {
1045             if (is_object($p)) $this->links[] = $p->getName();
1046             elseif (is_array($p)) $this->links[] = $p['pagename'];
1047             else $this->links[] = $p;
1048         }
1049         $backlinkiter->free();
1050         sort($this->links);
1051     }
1052
1053     function next () {
1054         while (($rev = $this->_revisions->next())) {
1055             if (binary_search($rev->getName(), $this->links) != false)
1056                 return $rev;
1057         }
1058         $this->free();
1059         return false;
1060     }
1061
1062     function free () {
1063         unset ($this->links);
1064     }
1065 }
1066
1067 class PageMatchRevisionIterator extends WikiDB_PageRevisionIterator
1068 {
1069     function PageMatchRevisionIterator ($revisions, $match) {
1070         $this->_revisions = $revisions;
1071         $this->search = new TextSearchQuery($match, true);
1072     }
1073
1074     function next () {
1075         while (($rev = $this->_revisions->next())) {
1076             if ($this->search->match($rev->getName()))
1077                 return $rev;
1078         }
1079         $this->free();
1080         return false;
1081     }
1082
1083     function free () {
1084         unset ($this->search);
1085     }
1086 }
1087
1088 /**
1089  * Filter by author
1090  */
1091 class AuthorPageRevisionIterator extends WikiDB_PageRevisionIterator
1092 {
1093     function AuthorPageRevisionIterator ($revisions, $author) {
1094         $this->_revisions = $revisions;
1095         $this->_author = $author;
1096     }
1097
1098     function next () {
1099         while (($rev = $this->_revisions->next())) {
1100             if ($rev->get('author_id') == $this->_author)
1101                 return $rev;
1102         }
1103         $this->free();
1104         return false;
1105     }
1106 }
1107
1108 /**
1109  * Filter by owner
1110  */
1111 class OwnerPageRevisionIterator extends WikiDB_PageRevisionIterator
1112 {
1113     function OwnerPageRevisionIterator ($revisions, $owner) {
1114         $this->_revisions = $revisions;
1115         $this->_owner = $owner;
1116     }
1117
1118     function next () {
1119         while (($rev = $this->_revisions->next())) {
1120             $page = $rev->getPage();
1121             if ($page->getOwner() == $this->_owner)
1122                 return $rev;
1123         }
1124         $this->free();
1125         return false;
1126     }
1127 }
1128
1129 class WikiPlugin_RecentChanges
1130 extends WikiPlugin
1131 {
1132     function getName () {
1133         return _("RecentChanges");
1134     }
1135
1136     function getVersion() {
1137         return preg_replace("/[Revision: $]/", '',
1138                             "\$Revision$");
1139     }
1140
1141     function managesValidators() {
1142         // Note that this is a bit of a fig.
1143         // We set validators based on the most recently changed page,
1144         // but this fails when the most-recent page is deleted.
1145         // (Consider that the Last-Modified time will decrease
1146         // when this happens.)
1147
1148         // We might be better off, leaving this as false (and junking
1149         // the validator logic above) and just falling back to the
1150         // default behavior (handled by WikiPlugin) of just using
1151         // the WikiDB global timestamp as the mtime.
1152
1153         // Nevertheless, for now, I leave this here, mostly as an
1154         // example for how to use appendValidators() and managesValidators().
1155         
1156         return true;
1157     }
1158             
1159     function getDefaultArguments() {
1160         return array('days'         => 2,
1161                      'show_minor'   => false,
1162                      'show_major'   => true,
1163                      'show_all'     => false,
1164                      'show_deleted' => 'sometimes',
1165                      'only_new'     => false,
1166                      'author'       => false,
1167                      'owner'        => false,
1168                      'limit'        => false,
1169                      'format'       => false,
1170                      'daylist'      => false,
1171                      'difflinks'    => true,
1172                      'historylinks' => false,
1173                      'caption'      => '',
1174                      'category'     => '',
1175                      'pagematch'    => ''
1176                      );
1177     }
1178
1179     function getArgs ($argstr, $request, $defaults = false) {
1180         if (!$defaults) $defaults = $this->getDefaultArguments();
1181         $args = WikiPlugin::getArgs($argstr, $request, $defaults);
1182
1183         $action = $request->getArg('action');
1184         if ($action != 'browse' && ! $request->isActionPage($action))
1185             $args['format'] = false; // default -> HTML
1186
1187         if ($args['format'] == 'rss' && empty($args['limit']))
1188             $args['limit'] = 15; // Fix default value for RSS.
1189         if ($args['format'] == 'rss2' && empty($args['limit']))
1190             $args['limit'] = 15; // Fix default value for RSS2.
1191
1192         if ($args['format'] == 'sidebar' && empty($args['limit']))
1193             $args['limit'] = 10; // Fix default value for sidebar.
1194
1195         return $args;
1196     }
1197
1198     function getMostRecentParams (&$args) {
1199         $show_all = false; $show_minor = false; $show_major = false;
1200         $limit = false;
1201         extract($args);
1202
1203         $params = array('include_minor_revisions' => $show_minor,
1204                         'exclude_major_revisions' => !$show_major,
1205                         'include_all_revisions' => !empty($show_all));
1206         if ($limit != 0)
1207             $params['limit'] = $limit;
1208         if (!empty($args['author'])) {
1209             global $request;
1210             if ($args['author'] == '[]')
1211                 $args['author'] = $request->_user->getID();
1212             $params['author'] = $args['author'];
1213         }
1214         if (!empty($args['owner'])) {
1215             global $request;
1216             if ($args['owner'] == '[]')
1217                 $args['owner'] = $request->_user->getID();
1218             $params['owner'] = $args['owner'];
1219         }
1220         if (!empty($days)) {
1221           if ($days > 0.0)
1222             $params['since'] = time() - 24 * 3600 * $days;
1223           elseif ($days < 0.0)
1224             $params['since'] = 24 * 3600 * $days - time();
1225         }
1226
1227         return $params;
1228     }
1229
1230     function getChanges ($dbi, $args) {
1231         $changes = $dbi->mostRecent($this->getMostRecentParams($args));
1232
1233         $show_deleted = @$args['show_deleted'];
1234         $show_all = @$args['show_all'];
1235         if ($show_deleted == 'sometimes')
1236             $show_deleted = @$args['show_minor'];
1237
1238         // only pages (e.g. PageHistory of subpages)
1239         if (!empty($args['pagematch'])) {
1240             require_once("lib/TextSearchQuery.php");
1241             $changes = new PageMatchRevisionIterator($changes, $args['pagematch']);
1242         }
1243         if (!empty($args['category'])) {
1244             require_once("lib/TextSearchQuery.php");
1245             $changes = new LinkRevisionIterator($changes, $args['category']);
1246         }
1247         if (!empty($args['only_new']))
1248             $changes = new NewPageRevisionIterator($changes);
1249         if (!empty($args['author']))
1250             $changes = new AuthorPageRevisionIterator($changes, $args['author']);
1251         if (!empty($args['owner']))
1252             $changes = new OwnerPageRevisionIterator($changes, $args['owner']);
1253         if (!$show_deleted)
1254             $changes = new NonDeletedRevisionIterator($changes, !$show_all);
1255
1256         return $changes;
1257     }
1258
1259     function format ($changes, $args) {
1260         global $WikiTheme;
1261         $format = $args['format'];
1262
1263         $fmt_class = $WikiTheme->getFormatter('RecentChanges', $format);
1264         if (!$fmt_class) {
1265             if ($format == 'rss')
1266                 $fmt_class = '_RecentChanges_RssFormatter';
1267             elseif ($format == 'rss2')
1268                 $fmt_class = '_RecentChanges_Rss2Formatter';
1269             elseif ($format == 'atom')
1270                 $fmt_class = '_RecentChanges_AtomFormatter';
1271             elseif ($format == 'rss091') {
1272                 include_once "lib/RSSWriter091.php";
1273                 $fmt_class = '_RecentChanges_RssFormatter091';
1274             }
1275             elseif ($format == 'sidebar')
1276                 $fmt_class = '_RecentChanges_SideBarFormatter';
1277             elseif ($format == 'box')
1278                 $fmt_class = '_RecentChanges_BoxFormatter';
1279             elseif ($format == 'contribs')
1280                 $fmt_class = '_RecentChanges_UserContribsFormatter';
1281             else
1282                 $fmt_class = '_RecentChanges_HtmlFormatter';
1283         }
1284
1285         $fmt = new $fmt_class($args);
1286         return $fmt->format($changes);
1287     }
1288
1289     function run($dbi, $argstr, &$request, $basepage) {
1290         $args = $this->getArgs($argstr, $request);
1291
1292         // HACKish: fix for SF bug #622784  (1000 years of RecentChanges ought
1293         // to be enough for anyone.)
1294         $args['days'] = min($args['days'], 365000);
1295
1296         // Within Categories just display Category Backlinks
1297         if (empty($args['category']) and empty($args['pagematch'])
1298             and preg_match("/^Category/", $request->getArg('pagename'))) 
1299         {
1300             $args['category'] = $request->getArg('pagename');
1301         }
1302         
1303         // Hack alert: format() is a NORETURN for rss formatters.
1304         return $this->format($this->getChanges($dbi, $args), $args);
1305     }
1306
1307     // box is used to display a fixed-width, narrow version with common header.
1308     // just a numbered list of limit pagenames, without date.
1309     function box($args = false, $request = false, $basepage = false) {
1310         if (!$request) $request =& $GLOBALS['request'];
1311         if (!isset($args['limit'])) $args['limit'] = 15;
1312         $args['format'] = 'box';
1313         $args['show_minor'] = false;
1314         $args['show_major'] = true;
1315         $args['show_deleted'] = 'sometimes';
1316         $args['show_all'] = false;
1317         $args['days'] = 90;
1318         return $this->makeBox(WikiLink($this->getName(),'',
1319                                        SplitPagename($this->getName())),
1320                               $this->format
1321                               ($this->getChanges($request->_dbi, $args), $args));
1322     }
1323
1324 };
1325
1326
1327 class DayButtonBar extends HtmlElement {
1328
1329     function DayButtonBar ($plugin_args) {
1330         $this->__construct('p', array('class' => 'wiki-rc-action'));
1331
1332         // Display days selection buttons
1333         extract($plugin_args);
1334
1335         // Custom caption
1336         if (! $caption) {
1337             if ($show_minor)
1338                 $caption = _("Show minor edits for:");
1339             elseif ($show_all)
1340                 $caption = _("Show all changes for:");
1341             else
1342                 $caption = _("Show changes for:");
1343             if ($only_new)
1344                 $caption = _("All new pages since:");
1345         }
1346
1347         $this->pushContent($caption, ' ');
1348
1349         global $WikiTheme;
1350         $sep = $WikiTheme->getButtonSeparator();
1351
1352         $n = 0;
1353         foreach (explode(",", $daylist) as $days) {
1354             if ($n++)
1355                 $this->pushContent($sep);
1356             $this->pushContent($this->_makeDayButton($days));
1357         }
1358     }
1359
1360     function _makeDayButton ($days) {
1361         global $WikiTheme, $request;
1362
1363         if ($days == 1)
1364             $label = _("1 day");
1365         elseif ($days < 1)
1366             $label = _("All time");
1367         else
1368             $label = sprintf(_("%s days"), abs($days));
1369
1370         $url = $request->getURLtoSelf(array('action' => $request->getArg('action'), 'days' => $days));
1371
1372         return $WikiTheme->makeButton($label, $url, 'wiki-rc-action');
1373     }
1374 }
1375
1376 // (c-file-style: "gnu")
1377 // Local Variables:
1378 // mode: php
1379 // tab-width: 8
1380 // c-basic-offset: 4
1381 // c-hanging-comment-ender-p: nil
1382 // indent-tabs-mode: nil
1383 // End:
1384 ?>