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