xref: /dokuwiki/feed.php (revision 68321121b4d24c7489400c950afdbe6eba0f417d)
1<?php
2/**
3 * XML feed export
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 *
8 * @global array $conf
9 * @global Input $INPUT
10 */
11
12if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/');
13require_once(DOKU_INC.'inc/init.php');
14
15//close session
16session_write_close();
17
18// get params
19$opt = rss_parseOptions();
20
21// the feed is dynamic - we need a cache for each combo
22// (but most people just use the default feed so it's still effective)
23$key   = join('', array_values($opt)).'$'.$_SERVER['REMOTE_USER'].'$'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'];
24$cache = new cache($key, '.feed');
25
26// prepare cache depends
27$depends['files'] = getConfigFiles('main');
28$depends['age']   = $conf['rss_update'];
29$depends['purge'] = $INPUT->bool('purge');
30
31// check cacheage and deliver if nothing has changed since last
32// time or the update interval has not passed, also handles conditional requests
33header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
34header('Pragma: public');
35header('Content-Type: application/xml; charset=utf-8');
36header('X-Robots-Tag: noindex');
37if($cache->useCache($depends)) {
38    http_conditionalRequest($cache->_time);
39    if($conf['allowdebug']) header("X-CacheUsed: $cache->cache");
40    print $cache->retrieveCache();
41    exit;
42} else {
43    http_conditionalRequest(time());
44}
45
46// create new feed
47$rss                 = new DokuWikiFeedCreator();
48$rss->title          = $conf['title'].(($opt['namespace']) ? ' '.$opt['namespace'] : '');
49$rss->link           = DOKU_URL;
50$rss->syndicationURL = DOKU_URL.'feed.php';
51$rss->cssStyleSheet  = DOKU_URL.'lib/exe/css.php?s=feed';
52
53$image        = new FeedImage();
54$image->title = $conf['title'];
55$image->url   = tpl_getMediaFile(array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico'), true);
56$image->link  = DOKU_URL;
57$rss->image   = $image;
58
59$data  = null;
60$modes = array(
61    'list'   => 'rssListNamespace',
62    'search' => 'rssSearch',
63    'recent' => 'rssRecentChanges'
64);
65if(isset($modes[$opt['feed_mode']])) {
66    $data = $modes[$opt['feed_mode']]($opt);
67} else {
68    $eventData = array(
69        'opt'  => &$opt,
70        'data' => &$data,
71    );
72    $event     = new Doku_Event('FEED_MODE_UNKNOWN', $eventData);
73    if($event->advise_before(true)) {
74        echo sprintf('<error>Unknown feed mode %s</error>', hsc($opt['feed_mode']));
75        exit;
76    }
77    $event->advise_after();
78}
79
80rss_buildItems($rss, $data, $opt);
81$feed = $rss->createFeed($opt['feed_type'], 'utf-8');
82
83// save cachefile
84$cache->storeCache($feed);
85
86// finally deliver
87print $feed;
88
89// ---------------------------------------------------------------- //
90
91/**
92 * Get URL parameters and config options and return an initialized option array
93 *
94 * @author Andreas Gohr <andi@splitbrain.org>
95 */
96function rss_parseOptions() {
97    global $conf;
98    global $INPUT;
99
100    $opt = array();
101
102    foreach(array(
103                // Basic feed properties
104                // Plugins may probably want to add new values to these
105                // properties for implementing own feeds
106
107                // One of: list, search, recent
108                'feed_mode'    => array('str', 'mode', 'recent'),
109                // One of: diff, page, rev, current
110                'link_to'      => array('str', 'linkto', $conf['rss_linkto']),
111                // One of: abstract, diff, htmldiff, html
112                'item_content' => array('str', 'content', $conf['rss_content']),
113
114                // Special feed properties
115                // These are only used by certain feed_modes
116
117                // String, used for feed title, in list and rc mode
118                'namespace'    => array('str', 'ns', null),
119                // Positive integer, only used in rc mode
120                'items'        => array('int', 'num', $conf['recent']),
121                // Boolean, only used in rc mode
122                'show_minor'   => array('bool', 'minor', false),
123                // String, only used in search mode
124                'search_query' => array('str', 'q', null),
125                // One of: pages, media, both
126                'content_type' => array('str', 'view', $conf['rss_media'])
127
128            ) as $name => $val) {
129        $opt[$name] = $INPUT->$val[0]($val[1], $val[2], true);
130    }
131
132    $opt['items']      = max(0, (int) $opt['items']);
133    $opt['show_minor'] = (bool) $opt['show_minor'];
134
135    $opt['guardmail'] = ($conf['mailguard'] != '' && $conf['mailguard'] != 'none');
136
137    $type = valid_input_set(
138        'type', array(
139                     'rss', 'rss2', 'atom', 'atom1', 'rss1',
140                     'default' => $conf['rss_type']
141                ),
142        $_REQUEST
143    );
144    switch($type) {
145        case 'rss':
146            $opt['feed_type'] = 'RSS0.91';
147            $opt['mime_type'] = 'text/xml';
148            break;
149        case 'rss2':
150            $opt['feed_type'] = 'RSS2.0';
151            $opt['mime_type'] = 'text/xml';
152            break;
153        case 'atom':
154            $opt['feed_type'] = 'ATOM0.3';
155            $opt['mime_type'] = 'application/xml';
156            break;
157        case 'atom1':
158            $opt['feed_type'] = 'ATOM1.0';
159            $opt['mime_type'] = 'application/atom+xml';
160            break;
161        default:
162            $opt['feed_type'] = 'RSS1.0';
163            $opt['mime_type'] = 'application/xml';
164    }
165
166    $eventData = array(
167        'opt' => &$opt,
168    );
169    trigger_event('FEED_OPTS_POSTPROCESS', $eventData);
170    return $opt;
171}
172
173/**
174 * Add recent changed pages to a feed object
175 *
176 * @author Andreas Gohr <andi@splitbrain.org>
177 * @param  FeedCreator $rss the FeedCreator Object
178 * @param  array       $data the items to add
179 * @param  array       $opt  the feed options
180 */
181function rss_buildItems(&$rss, &$data, $opt) {
182    global $conf;
183    global $lang;
184    /* @var DokuWiki_Auth_Plugin $auth */
185    global $auth;
186
187    $eventData = array(
188        'rss'  => &$rss,
189        'data' => &$data,
190        'opt'  => &$opt,
191    );
192    $event     = new Doku_Event('FEED_DATA_PROCESS', $eventData);
193    if($event->advise_before(false)) {
194        foreach($data as $ditem) {
195            if(!is_array($ditem)) {
196                // not an array? then only a list of IDs was given
197                $ditem = array('id' => $ditem);
198            }
199
200            $item = new FeedItem();
201            $id   = $ditem['id'];
202            if(!$ditem['media']) {
203                $meta = p_get_metadata($id);
204            } else {
205                $meta = array();
206            }
207
208            // add date
209            if($ditem['date']) {
210                $date = $ditem['date'];
211            } elseif ($ditem['media']) {
212                $date = @filemtime(mediaFN($id));
213            } elseif (@file_exists(wikiFN($id))) {
214                $date = @filemtime(wikiFN($id));
215            } elseif($meta['date']['modified']) {
216                $date = $meta['date']['modified'];
217            } else {
218                $date = 0;
219            }
220            if($date) $item->date = date('r', $date);
221
222            // add title
223            if($conf['useheading'] && $meta['title']) {
224                $item->title = $meta['title'];
225            } else {
226                $item->title = $ditem['id'];
227            }
228            if($conf['rss_show_summary'] && !empty($ditem['sum'])) {
229                $item->title .= ' - '.strip_tags($ditem['sum']);
230            }
231
232            // add item link
233            switch($opt['link_to']) {
234                case 'page':
235                    if($ditem['media']) {
236                        $item->link = media_managerURL(
237                            array(
238                                 'image' => $id,
239                                 'ns'    => getNS($id),
240                                 'rev'   => $date
241                            ), '&', true
242                        );
243                    } else {
244                        $item->link = wl($id, 'rev='.$date, true, '&');
245                    }
246                    break;
247                case 'rev':
248                    if($ditem['media']) {
249                        $item->link = media_managerURL(
250                            array(
251                                 'image'       => $id,
252                                 'ns'          => getNS($id),
253                                 'rev'         => $date,
254                                 'tab_details' => 'history'
255                            ), '&', true
256                        );
257                    } else {
258                        $item->link = wl($id, 'do=revisions&rev='.$date, true, '&');
259                    }
260                    break;
261                case 'current':
262                    if($ditem['media']) {
263                        $item->link = media_managerURL(
264                            array(
265                                 'image' => $id,
266                                 'ns'    => getNS($id)
267                            ), '&', true
268                        );
269                    } else {
270                        $item->link = wl($id, '', true, '&');
271                    }
272                    break;
273                case 'diff':
274                default:
275                    if($ditem['media']) {
276                        $item->link = media_managerURL(
277                            array(
278                                 'image'       => $id,
279                                 'ns'          => getNS($id),
280                                 'rev'         => $date,
281                                 'tab_details' => 'history',
282                                 'mediado'     => 'diff'
283                            ), '&', true
284                        );
285                    } else {
286                        $item->link = wl($id, 'rev='.$date.'&do=diff', true, '&');
287                    }
288            }
289
290            // add item content
291            switch($opt['item_content']) {
292                case 'diff':
293                case 'htmldiff':
294                    if($ditem['media']) {
295                        $revs  = getRevisions($id, 0, 1, 8192, true);
296                        $rev   = $revs[0];
297                        $src_r = '';
298                        $src_l = '';
299
300                        if($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)), 300)) {
301                            $more  = 'w='.$size[0].'&h='.$size[1].'&t='.@filemtime(mediaFN($id));
302                            $src_r = ml($id, $more, true, '&amp;', true);
303                        }
304                        if($rev && $size = media_image_preview_size($id, $rev, new JpegMeta(mediaFN($id, $rev)), 300)) {
305                            $more  = 'rev='.$rev.'&w='.$size[0].'&h='.$size[1];
306                            $src_l = ml($id, $more, true, '&amp;', true);
307                        }
308                        $content = '';
309                        if($src_r) {
310                            $content = '<table>';
311                            $content .= '<tr><th width="50%">'.$rev.'</th>';
312                            $content .= '<th width="50%">'.$lang['current'].'</th></tr>';
313                            $content .= '<tr align="center"><td><img src="'.$src_l.'" alt="" /></td><td>';
314                            $content .= '<img src="'.$src_r.'" alt="'.$id.'" /></td></tr>';
315                            $content .= '</table>';
316                        }
317
318                    } else {
319                        require_once(DOKU_INC.'inc/DifferenceEngine.php');
320                        $revs = getRevisions($id, 0, 1);
321                        $rev  = $revs[0];
322
323                        if($rev) {
324                            $df = new Diff(explode("\n", rawWiki($id, $rev)),
325                                           explode("\n", rawWiki($id, '')));
326                        } else {
327                            $df = new Diff(array(''),
328                                           explode("\n", rawWiki($id, '')));
329                        }
330
331                        if($opt['item_content'] == 'htmldiff') {
332                            // note: no need to escape diff output, TableDiffFormatter provides 'safe' html
333                            $tdf     = new TableDiffFormatter();
334                            $content = '<table>';
335                            $content .= '<tr><th colspan="2" width="50%">'.$rev.'</th>';
336                            $content .= '<th colspan="2" width="50%">'.$lang['current'].'</th></tr>';
337                            $content .= $tdf->format($df);
338                            $content .= '</table>';
339                        } else {
340                            // note: diff output must be escaped, UnifiedDiffFormatter provides plain text
341                            $udf     = new UnifiedDiffFormatter();
342                            $content = "<pre>\n".hsc($udf->format($df))."\n</pre>";
343                        }
344                    }
345                    break;
346                case 'html':
347                    if($ditem['media']) {
348                        if($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)))) {
349                            $more    = 'w='.$size[0].'&h='.$size[1].'&t='.@filemtime(mediaFN($id));
350                            $src     = ml($id, $more, true, '&amp;', true);
351                            $content = '<img src="'.$src.'" alt="'.$id.'" />';
352                        } else {
353                            $content = '';
354                        }
355                    } else {
356                        if (@filemtime(wikiFN($id)) === $date) {
357                            $content = p_wiki_xhtml($id, '', false);
358                        } else {
359                            $content = p_wiki_xhtml($id, $date, false);
360                        }
361                        // no TOC in feeds
362                        $content = preg_replace('/(<!-- TOC START -->).*(<!-- TOC END -->)/s', '', $content);
363
364                        // add alignment for images
365                        $content = preg_replace('/(<img .*?class="medialeft")/s', '\\1 align="left"', $content);
366                        $content = preg_replace('/(<img .*?class="mediaright")/s', '\\1 align="right"', $content);
367
368                        // make URLs work when canonical is not set, regexp instead of rerendering!
369                        if(!$conf['canonical']) {
370                            $base    = preg_quote(DOKU_REL, '/');
371                            $content = preg_replace('/(<a href|<img src)="('.$base.')/s', '$1="'.DOKU_URL, $content);
372                        }
373                    }
374
375                    break;
376                case 'abstract':
377                default:
378                    if($ditem['media']) {
379                        if($size = media_image_preview_size($id, false, new JpegMeta(mediaFN($id)))) {
380                            $more    = 'w='.$size[0].'&h='.$size[1].'&t='.@filemtime(mediaFN($id));
381                            $src     = ml($id, $more, true, '&amp;', true);
382                            $content = '<img src="'.$src.'" alt="'.$id.'" />';
383                        } else {
384                            $content = '';
385                        }
386                    } else {
387                        $content = $meta['description']['abstract'];
388                    }
389            }
390            $item->description = $content; //FIXME a plugin hook here could be senseful
391
392            // add user
393            # FIXME should the user be pulled from metadata as well?
394            $user         = @$ditem['user']; // the @ spares time repeating lookup
395            $item->author = '';
396            if($user && $conf['useacl'] && $auth) {
397                $userInfo = $auth->getUserData($user);
398                if($userInfo) {
399                    switch($conf['showuseras']) {
400                        case 'username':
401                            $item->author = $userInfo['name'];
402                            break;
403                        default:
404                            $item->author = $user;
405                            break;
406                    }
407                } else {
408                    $item->author = $user;
409                }
410                if($userInfo && !$opt['guardmail']) {
411                    $item->authorEmail = $userInfo['mail'];
412                } else {
413                    //cannot obfuscate because some RSS readers may check validity
414                    $item->authorEmail = $user.'@'.$ditem['ip'];
415                }
416            } elseif($user) {
417                // this happens when no ACL but some Apache auth is used
418                $item->author      = $user;
419                $item->authorEmail = $user.'@'.$ditem['ip'];
420            } else {
421                $item->authorEmail = 'anonymous@'.$ditem['ip'];
422            }
423
424            // add category
425            if(isset($meta['subject'])) {
426                $item->category = $meta['subject'];
427            } else {
428                $cat = getNS($id);
429                if($cat) $item->category = $cat;
430            }
431
432            // finally add the item to the feed object, after handing it to registered plugins
433            $evdata = array(
434                'item'  => &$item,
435                'opt'   => &$opt,
436                'ditem' => &$ditem,
437                'rss'   => &$rss
438            );
439            $evt    = new Doku_Event('FEED_ITEM_ADD', $evdata);
440            if($evt->advise_before()) {
441                $rss->addItem($item);
442            }
443            $evt->advise_after(); // for completeness
444        }
445    }
446    $event->advise_after();
447}
448
449/**
450 * Add recent changed pages to the feed object
451 *
452 * @author Andreas Gohr <andi@splitbrain.org>
453 */
454function rssRecentChanges($opt) {
455    global $conf;
456    $flags = RECENTS_SKIP_DELETED;
457    if(!$opt['show_minor']) $flags += RECENTS_SKIP_MINORS;
458    if($opt['content_type'] == 'media' && $conf['mediarevisions']) $flags += RECENTS_MEDIA_CHANGES;
459    if($opt['content_type'] == 'both' && $conf['mediarevisions']) $flags += RECENTS_MEDIA_PAGES_MIXED;
460
461    $recents = getRecents(0, $opt['items'], $opt['namespace'], $flags);
462    return $recents;
463}
464
465/**
466 * Add all pages of a namespace to the feed object
467 *
468 * @author Andreas Gohr <andi@splitbrain.org>
469 */
470function rssListNamespace($opt) {
471    require_once(DOKU_INC.'inc/search.php');
472    global $conf;
473
474    $ns = ':'.cleanID($opt['namespace']);
475    $ns = str_replace(':', '/', $ns);
476
477    $data = array();
478    $search_opts = array(
479        'depth' => 1,
480        'pagesonly' => true,
481        'listfiles' => true
482    );
483    search($data, $conf['datadir'], 'search_universal', $search_opts, $ns);
484
485    return $data;
486}
487
488/**
489 * Add the result of a full text search to the feed object
490 *
491 * @author Andreas Gohr <andi@splitbrain.org>
492 */
493function rssSearch($opt) {
494    if(!$opt['search_query']) return array();
495
496    require_once(DOKU_INC.'inc/fulltext.php');
497    $data = ft_pageSearch($opt['search_query'], $poswords);
498    $data = array_keys($data);
499
500    return $data;
501}
502
503//Setup VIM: ex: et ts=4 :
504