xref: /dokuwiki/feed.php (revision 92062b79cfc90c269b95398132c98f32ac7027ff)
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
9if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/');
10require_once(DOKU_INC.'inc/init.php');
11
12//close session
13session_write_close();
14
15// get params
16$opt = rss_parseOptions();
17
18// the feed is dynamic - we need a cache for each combo
19// (but most people just use the default feed so it's still effective)
20$cache = getCacheName(join('',array_values($opt)).$_SERVER['REMOTE_USER'],'.feed');
21$key   = join('', array_values($opt)) . $_SERVER['REMOTE_USER'];
22$cache = new cache($key, '.feed');
23
24// prepare cache depends
25$depends['files'] = getConfigFiles('main');
26$depends['age']   = $conf['rss_update'];
27$depends['purge'] = ($_REQUEST['purge']) ? true : false;
28
29// check cacheage and deliver if nothing has changed since last
30// time or the update interval has not passed, also handles conditional requests
31header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
32header('Pragma: public');
33header('Content-Type: application/xml; charset=utf-8');
34header('X-Robots-Tag: noindex');
35if($cache->useCache($depends)) {
36    http_conditionalRequest($cache->_time);
37    if($conf['allowdebug']) header("X-CacheUsed: $cache->cache");
38    print $cache->retrieveCache();
39    exit;
40} else {
41    http_conditionalRequest(time());
42 }
43
44// create new feed
45$rss = new DokuWikiFeedCreator();
46$rss->title = $conf['title'].(($opt['namespace']) ? ' '.$opt['namespace'] : '');
47$rss->link  = DOKU_URL;
48$rss->syndicationURL = DOKU_URL.'feed.php';
49$rss->cssStyleSheet  = DOKU_URL.'lib/exe/css.php?s=feed';
50
51$image = new FeedImage();
52$image->title = $conf['title'];
53$image->url = DOKU_URL."lib/images/favicon.ico";
54$image->link = DOKU_URL;
55$rss->image = $image;
56
57$data = null;
58if($opt['feed_mode'] == 'list'){
59    $data = rssListNamespace($opt);
60}elseif($opt['feed_mode'] == 'search'){
61    $data = rssSearch($opt);
62}else{
63    $eventData = array(
64        'opt'  => &$opt,
65        'data' => &$data,
66    );
67    $event = new Doku_Event('FEED_MODE_UNKNOWN', $eventData);
68    if ($event->advise_before(true)) {
69        $data = rssRecentChanges($opt);
70    }
71    $event->advise_after();
72}
73
74rss_buildItems($rss, $data, $opt);
75$feed = $rss->createFeed($opt['feed_type'],'utf-8');
76
77// save cachefile
78$cache->storeCache($feed);
79
80// finally deliver
81print $feed;
82
83// ---------------------------------------------------------------- //
84
85/**
86 * Get URL parameters and config options and return a initialized option array
87 *
88 * @author Andreas Gohr <andi@splitbrain.org>
89 */
90function rss_parseOptions(){
91    global $conf;
92
93    $opt['items']        = (int) $_REQUEST['num'];
94    $opt['feed_type']    = $_REQUEST['type'];
95    $opt['feed_mode']    = $_REQUEST['mode'];
96    $opt['show_minor']   = $_REQUEST['minor'];
97    $opt['namespace']    = $_REQUEST['ns'];
98    $opt['link_to']      = $_REQUEST['linkto'];
99    $opt['item_content'] = $_REQUEST['content'];
100    $opt['search_query'] = $_REQUEST['q'];
101
102    if(!$opt['feed_type'])    $opt['feed_type']    = $conf['rss_type'];
103    if(!$opt['item_content']) $opt['item_content'] = $conf['rss_content'];
104    if(!$opt['link_to'])      $opt['link_to']      = $conf['rss_linkto'];
105    if(!$opt['items'])        $opt['items']        = $conf['recent'];
106    $opt['guardmail']  = ($conf['mailguard'] != '' && $conf['mailguard'] != 'none');
107
108    switch ($opt['feed_type']){
109        case 'rss':
110            $opt['feed_type'] = 'RSS0.91';
111            $opt['mime_type'] = 'text/xml';
112            break;
113        case 'rss2':
114            $opt['feed_type'] = 'RSS2.0';
115            $opt['mime_type'] = 'text/xml';
116            break;
117        case 'atom':
118            $opt['feed_type'] = 'ATOM0.3';
119            $opt['mime_type'] = 'application/xml';
120            break;
121        case 'atom1':
122            $opt['feed_type'] = 'ATOM1.0';
123            $opt['mime_type'] = 'application/atom+xml';
124            break;
125        default:
126            $opt['feed_type'] = 'RSS1.0';
127            $opt['mime_type'] = 'application/xml';
128    }
129
130    $eventData = array(
131        'opt' => &$opt,
132    );
133    trigger_event('FEED_OPTS_POSTPROCESS', $eventData);
134    return $opt;
135}
136
137/**
138 * Add recent changed pages to a feed object
139 *
140 * @author Andreas Gohr <andi@splitbrain.org>
141 * @param  object $rss - the FeedCreator Object
142 * @param  array $data - the items to add
143 * @param  array $opt  - the feed options
144 */
145function rss_buildItems(&$rss,&$data,$opt){
146    global $conf;
147    global $lang;
148    global $auth;
149
150    $eventData = array(
151        'rss' => &$rss,
152        'data' => &$data,
153        'opt' => &$opt,
154    );
155    $event = new Doku_Event('FEED_DATA_PROCESS', $eventData);
156    if ($event->advise_before(false)){
157        foreach($data as $ditem){
158            if(!is_array($ditem)){
159                // not an array? then only a list of IDs was given
160                $ditem = array( 'id' => $ditem );
161            }
162
163            $item = new FeedItem();
164            $id   = $ditem['id'];
165            $meta = p_get_metadata($id);
166
167            // add date
168            if($ditem['date']){
169                $date = $ditem['date'];
170            }elseif($meta['date']['modified']){
171                $date = $meta['date']['modified'];
172            }else{
173                $date = @filemtime(wikiFN($id));
174            }
175            if($date) $item->date = date('r',$date);
176
177            // add title
178            if($conf['useheading'] && $meta['title']){
179                $item->title = $meta['title'];
180            }else{
181                $item->title = $ditem['id'];
182            }
183            if($conf['rss_show_summary'] && !empty($ditem['sum'])){
184                $item->title .= ' - '.strip_tags($ditem['sum']);
185            }
186
187            // add item link
188            switch ($opt['link_to']){
189                case 'page':
190                    $item->link = wl($id,'rev='.$date,true,'&');
191                    break;
192                case 'rev':
193                    $item->link = wl($id,'do=revisions&rev='.$date,true,'&');
194                    break;
195                case 'current':
196                    $item->link = wl($id, '', true,'&');
197                    break;
198                case 'diff':
199                default:
200                    $item->link = wl($id,'rev='.$date.'&do=diff',true,'&');
201            }
202
203            // add item content
204            switch ($opt['item_content']){
205                case 'diff':
206                case 'htmldiff':
207                    require_once(DOKU_INC.'inc/DifferenceEngine.php');
208                    $revs = getRevisions($id, 0, 1);
209                    $rev = $revs[0];
210
211                    if($rev){
212                        $df  = new Diff(explode("\n",htmlspecialchars(rawWiki($id,$rev))),
213                                        explode("\n",htmlspecialchars(rawWiki($id,''))));
214                    }else{
215                        $df  = new Diff(array(''),
216                                        explode("\n",htmlspecialchars(rawWiki($id,''))));
217                    }
218
219                    if($opt['item_content'] == 'htmldiff'){
220                        $tdf = new TableDiffFormatter();
221                        $content  = '<table>';
222                        $content .= '<tr><th colspan="2" width="50%">'.$rev.'</th>';
223                        $content .= '<th colspan="2" width="50%">'.$lang['current'].'</th></tr>';
224                        $content .= $tdf->format($df);
225                        $content .= '</table>';
226                    }else{
227                        $udf = new UnifiedDiffFormatter();
228                        $content = "<pre>\n".$udf->format($df)."\n</pre>";
229                    }
230                    break;
231                case 'html':
232                    $content = p_wiki_xhtml($id,$date,false);
233                    // no TOC in feeds
234                    $content = preg_replace('/(<!-- TOC START -->).*(<!-- TOC END -->)/s','',$content);
235
236                    // make URLs work when canonical is not set, regexp instead of rerendering!
237                    if(!$conf['canonical']){
238                        $base = preg_quote(DOKU_REL,'/');
239                        $content = preg_replace('/(<a href|<img src)="('.$base.')/s','$1="'.DOKU_URL,$content);
240                    }
241
242                    break;
243                case 'abstract':
244                default:
245                    $content = $meta['description']['abstract'];
246            }
247            $item->description = $content; //FIXME a plugin hook here could be senseful
248
249            // add user
250            # FIXME should the user be pulled from metadata as well?
251            $user = @$ditem['user']; // the @ spares time repeating lookup
252            $item->author = '';
253            if($user && $conf['useacl'] && $auth){
254                $userInfo = $auth->getUserData($user);
255                if ($userInfo){
256                    switch ($conf['showuseras']){
257                        case 'username':
258                            $item->author = $userInfo['name'];
259                            break;
260                        default:
261                            $item->author = $user;
262                            break;
263                    }
264                } else {
265                    $item->author = $user;
266                }
267                if($userInfo && !$opt['guardmail']){
268                    $item->authorEmail = $userInfo['mail'];
269                }else{
270                    //cannot obfuscate because some RSS readers may check validity
271                    $item->authorEmail = $user.'@'.$ditem['ip'];
272                }
273            }elseif($user){
274                // this happens when no ACL but some Apache auth is used
275                $item->author      = $user;
276                $item->authorEmail = $user.'@'.$ditem['ip'];
277            }else{
278                $item->authorEmail = 'anonymous@'.$ditem['ip'];
279            }
280
281            // add category
282            if($meta['subject']){
283                $item->category = $meta['subject'];
284            }else{
285                $cat = getNS($id);
286                if($cat) $item->category = $cat;
287            }
288
289            // finally add the item to the feed object, after handing it to registered plugins
290            $evdata = array('item'  => &$item,
291                            'opt'   => &$opt,
292                            'ditem' => &$ditem,
293                            'rss'   => &$rss);
294            $evt = new Doku_Event('FEED_ITEM_ADD', $evdata);
295            if ($evt->advise_before()){
296                $rss->addItem($item);
297            }
298            $evt->advise_after(); // for completeness
299        }
300    }
301    $event->advise_after();
302}
303
304
305/**
306 * Add recent changed pages to the feed object
307 *
308 * @author Andreas Gohr <andi@splitbrain.org>
309 */
310function rssRecentChanges($opt){
311    $flags = RECENTS_SKIP_DELETED;
312    if(!$opt['show_minor']) $flags += RECENTS_SKIP_MINORS;
313
314    $recents = getRecents(0,$opt['items'],$opt['namespace'],$flags);
315    return $recents;
316}
317
318/**
319 * Add all pages of a namespace to the feed object
320 *
321 * @author Andreas Gohr <andi@splitbrain.org>
322 */
323function rssListNamespace($opt){
324    require_once(DOKU_INC.'inc/search.php');
325    global $conf;
326
327    $ns=':'.cleanID($opt['namespace']);
328    $ns=str_replace(':','/',$ns);
329
330    $data = array();
331    sort($data);
332    search($data,$conf['datadir'],'search_list','',$ns);
333
334    return $data;
335}
336
337/**
338 * Add the result of a full text search to the feed object
339 *
340 * @author Andreas Gohr <andi@splitbrain.org>
341 */
342function rssSearch($opt){
343    if(!$opt['search_query']) return;
344
345    require_once(DOKU_INC.'inc/fulltext.php');
346    $data = ft_pageSearch($opt['search_query'],$poswords);
347    $data = array_keys($data);
348
349    return $data;
350}
351
352//Setup VIM: ex: et ts=4 enc=utf-8 :
353