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