xref: /dokuwiki/lib/exe/xmlrpc.php (revision dfd13e55ad5658529ad92eb78ba4481a3a8ffc58)
1<?php
2if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
3
4// fix when '<?xml' isn't on the very first line
5if(isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
6
7
8require_once(DOKU_INC.'inc/init.php');
9require_once(DOKU_INC.'inc/common.php');
10require_once(DOKU_INC.'inc/auth.php');
11session_write_close();  //close session
12
13if(!$conf['xmlrpc']) {
14    die('XML-RPC server not enabled.');
15    // FIXME check for groups allowed
16}
17
18require_once(DOKU_INC.'inc/IXR_Library.php');
19
20
21/**
22 * Contains needed wrapper functions and registers all available
23 * XMLRPC functions.
24 */
25class dokuwiki_xmlrpc_server extends IXR_IntrospectionServer {
26    var $methods = array();
27
28    /**
29     * Constructor. Register methods and run Server
30     */
31    function dokuwiki_xmlrpc_server(){
32        $this->IXR_IntrospectionServer();
33
34        /* DokuWiki's own methods */
35        $this->addCallback(
36            'dokuwiki.getVersion',
37            'getVersion',
38            array('string'),
39            'Returns the running DokuWiki version.'
40        );
41
42        /* Wiki API v2 http://www.jspwiki.org/wiki/WikiRPCInterface2 */
43        $this->addCallback(
44            'wiki.getRPCVersionSupported',
45            'this:wiki_RPCVersion',
46            array('int'),
47            'Returns 2 with the supported RPC API version.'
48        );
49        $this->addCallback(
50            'wiki.getPage',
51            'this:rawPage',
52            array('string','string'),
53            'Get the raw Wiki text of page, latest version.'
54        );
55        $this->addCallback(
56            'wiki.getPageVersion',
57            'this:rawPage',
58            array('string','string','int'),
59            'Get the raw Wiki text of page.'
60        );
61        $this->addCallback(
62            'wiki.getPageHTML',
63            'this:htmlPage',
64            array('string','string'),
65            'Return page in rendered HTML, latest version.'
66        );
67        $this->addCallback(
68            'wiki.getPageHTMLVersion',
69            'this:htmlPage',
70            array('string','string','int'),
71            'Return page in rendered HTML.'
72        );
73        $this->addCallback(
74            'wiki.getAllPages',
75            'this:listPages',
76            array('struct'),
77            'Returns a list of all pages. The result is an array of utf8 pagenames.'
78        );
79        $this->addCallback(
80            'wiki.getAttachments',
81            'this:listAttachments',
82            array('struct', 'string', 'struct'),
83            'Returns a list of all media files.'
84        );
85        $this->addCallback(
86            'wiki.getBackLinks',
87            'this:listBackLinks',
88            array('struct','string'),
89            'Returns the pages that link to this page.'
90        );
91        $this->addCallback(
92            'wiki.getPageInfo',
93            'this:pageInfo',
94            array('struct','string'),
95            'Returns a struct with infos about the page.'
96        );
97        $this->addCallback(
98            'wiki.getPageInfoVersion',
99            'this:pageInfo',
100            array('struct','string','int'),
101            'Returns a struct with infos about the page.'
102        );
103        $this->addCallback(
104            'wiki.getPageVersions',
105            'this:pageVersions',
106            array('struct','string','int'),
107            'Returns the available revisions of the page.'
108        );
109        $this->addCallback(
110            'wiki.putPage',
111            'this:putPage',
112            array('int', 'string', 'string', 'struct'),
113            'Saves a wiki page.'
114        );
115        $this->addCallback(
116            'wiki.listLinks',
117            'this:listLinks',
118            array('struct','string'),
119            'Lists all links contained in a wiki page.'
120        );
121        $this->addCallback(
122            'wiki.getRecentChanges',
123            'this:getRecentChanges',
124            array('struct','int'),
125            'Returns a strukt about all recent changes since given timestamp.'
126        );
127        $this->addCallback(
128            'wiki.aclCheck',
129            'this:aclCheck',
130            array('int', 'string'),
131            'Returns the permissions of a given wiki page.'
132        );
133        $this->addCallback(
134            'wiki.putAttachment',
135            'this:putAttachment',
136            array('struct', 'string', 'base64', 'struct'),
137            'Upload a file to the wiki.'
138        );
139        $this->addCallback(
140            'wiki.getAttachment',
141            'this:getAttachment',
142            array('base64', 'string'),
143            'Download a file from the wiki.'
144        );
145        $this->addCallback(
146            'wiki.getAttachmentInfo',
147            'this:getAttachmentInfo',
148            array('struct', 'string'),
149            'Returns a struct with infos about the attachment.'
150        );
151
152        $this->serve();
153    }
154
155    /**
156     * Return a raw wiki page
157     */
158    function rawPage($id,$rev=''){
159        if(auth_quickaclcheck($id) < AUTH_READ){
160            return new IXR_Error(1, 'You are not allowed to read this page');
161        }
162        $text = rawWiki($id,$rev);
163        if(!$text) {
164            $data = array($id);
165            return trigger_event('HTML_PAGE_FROMTEMPLATE',$data,'pageTemplate',true);
166        } else {
167            return $text;
168        }
169    }
170
171    /**
172     * Return a media file encoded in base64
173     *
174     * @author Gina Haeussge <osd@foosel.net>
175     */
176    function getAttachment($id){
177    	$id = cleanID($id);
178    	if (auth_quickaclcheck(getNS($id).':*') < AUTH_READ)
179    		return new IXR_Error(1, 'You are not allowed to read this file');
180
181		$file = mediaFN($id);
182		if (!@ file_exists($file))
183			return new IXR_Error(1, 'The requested file does not exist');
184
185		$data = io_readFile($file, false);
186		$base64 = base64_encode($data);
187		return $base64;
188    }
189
190    /**
191     * Return info about a media file
192     *
193     * @author Gina Haeussge <osd@foosel.net>
194     */
195    function getAttachmentInfo($id){
196    	$id = cleanID($id);
197		$info = array(
198			'lastModified' => 0,
199			'size' => 0,
200		);
201
202		$file = mediaFN($id);
203		if ((auth_quickaclcheck(getNS($id).':*') >= AUTH_READ) && file_exists($file)){
204			$info['lastModified'] = new IXR_Date(filemtime($file));
205			$info['size'] = filesize($file);
206		}
207
208    	return $info;
209    }
210
211    /**
212     * Return a wiki page rendered to html
213     */
214    function htmlPage($id,$rev=''){
215        if(auth_quickaclcheck($id) < AUTH_READ){
216            return new IXR_Error(1, 'You are not allowed to read this page');
217        }
218        return p_wiki_xhtml($id,$rev,false);
219    }
220
221    /**
222     * List all pages - we use the indexer list here
223     */
224    function listPages(){
225        global $conf;
226
227        $list  = array();
228        $pages = file($conf['indexdir'] . '/page.idx');
229        $pages = array_filter($pages, 'isVisiblePage');
230
231        foreach(array_keys($pages) as $idx) {
232            if(page_exists($pages[$idx])) {
233                $perm = auth_quickaclcheck($pages[$idx]);
234                if($perm >= AUTH_READ) {
235                    $page = array();
236                    $page['id'] = trim($pages[$idx]);
237                    $page['perms'] = $perm;
238                    $page['size'] = @filesize(wikiFN($pages[$idx]));
239                    $page['lastModified'] = new IXR_Date(@filemtime($pages[$idx]));
240                    $list[] = $page;
241                }
242            }
243        }
244
245        return $list;
246    }
247
248    /**
249     * List all media files.
250     *
251     * Available options are 'recursive' for also including the subnamespaces
252     * in the listing, and 'pattern' for filtering the returned files against
253     * a regular expression matching their name.
254     *
255     * @author Gina Haeussge <osd@foosel.net>
256     */
257    function listAttachments($ns, $options = array()) {
258        global $conf;
259        global $lang;
260
261        $ns = cleanID($ns);
262
263		if (!is_array($options))
264			$options = array();
265
266		if (!isset($options['recursive'])) $options['recursive'] = false;
267
268        if(auth_quickaclcheck($ns.':*') >= AUTH_READ) {
269            $dir = utf8_encodeFN(str_replace(':', '/', $ns));
270
271            $data = array();
272            require_once(DOKU_INC.'inc/search.php');
273            search($data, $conf['mediadir'], 'search_media', array('recursive' => $options['recursive']), $dir);
274
275            if(!count($data)) {
276                return array();
277            }
278
279            $files = array();
280            foreach($data as $item) {
281            	if (isset($options['pattern']) && !@preg_match($options['pattern'], $item['id']))
282            		continue;
283                $file = array();
284                $file['id']       = $item['id'];
285                $file['size']     = $item['size'];
286                $file['lastModified']    = $item['mtime'];
287                $file['isimg']    = $item['isimg'];
288                $file['writable'] = $item['writeable'];
289                $file['perms'] = auth_quickaclcheck(getNS($item['id']).':*');
290                array_push($files, $file);
291            }
292
293            return $files;
294
295        } else {
296            return new IXR_Error(1, 'You are not allowed to list media files.');
297        }
298    }
299
300    /**
301     * Return a list of backlinks
302     */
303    function listBackLinks($id){
304        require_once(DOKU_INC.'inc/fulltext.php');
305        return ft_backlinks($id);
306    }
307
308    /**
309     * Return some basic data about a page
310     */
311    function pageInfo($id,$rev=''){
312        if(auth_quickaclcheck($id) < AUTH_READ){
313            return new IXR_Error(1, 'You are not allowed to read this page');
314        }
315        $file = wikiFN($id,$rev);
316        $time = @filemtime($file);
317        if(!$time){
318            return new IXR_Error(10, 'The requested page does not exist');
319        }
320
321        $info = getRevisionInfo($id, $time, 1024);
322
323        $data = array(
324            'name'         => $id,
325            'lastModified' => new IXR_Date($time),
326            'author'       => (($info['user']) ? $info['user'] : $info['ip']),
327            'version'      => $time
328        );
329
330        return ($data);
331    }
332
333    /**
334     * Save a wiki page
335     *
336     * @author Michael Klier <chi@chimeric.de>
337     */
338    function putPage($id, $text, $params) {
339        global $TEXT;
340        global $lang;
341        global $conf;
342
343        $id    = cleanID($id);
344        $TEXT  = trim($text);
345        $sum   = $params['sum'];
346        $minor = $params['minor'];
347
348        if(empty($id))
349            return new IXR_Error(1, 'Empty page ID');
350
351        if(!page_exists($id) && empty($TEXT)) {
352            return new IXR_ERROR(1, 'Refusing to write an empty new wiki page');
353        }
354
355        if(auth_quickaclcheck($id) < AUTH_EDIT)
356            return new IXR_Error(1, 'You are not allowed to edit this page');
357
358        // Check, if page is locked
359        if(checklock($id))
360            return new IXR_Error(1, 'The page is currently locked');
361
362        // SPAM check
363        if(checkwordblock())
364            return new IXR_Error(1, 'Positive wordblock check');
365
366        // autoset summary on new pages
367        if(!page_exists($id) && empty($sum)) {
368            $sum = $lang['created'];
369        }
370
371        // autoset summary on deleted pages
372        if(page_exists($id) && empty($TEXT) && empty($sum)) {
373            $sum = $lang['deleted'];
374        }
375
376        lock($id);
377
378        saveWikiText($id,$TEXT,$sum,$minor);
379
380        unlock($id);
381
382        // run the indexer if page wasn't indexed yet
383        if(!@file_exists(metaFN($id, '.indexed'))) {
384            // try to aquire a lock
385            $lock = $conf['lockdir'].'/_indexer.lock';
386            while(!@mkdir($lock,$conf['dmode'])){
387                usleep(50);
388                if(time()-@filemtime($lock) > 60*5){
389                    // looks like a stale lock - remove it
390                    @rmdir($lock);
391                }else{
392                    return false;
393                }
394            }
395            if($conf['dperm']) chmod($lock, $conf['dperm']);
396
397            require_once(DOKU_INC.'inc/indexer.php');
398
399            // do the work
400            idx_addPage($id);
401
402            // we're finished - save and free lock
403            io_saveFile(metaFN($id,'.indexed'),INDEXER_VERSION);
404            @rmdir($lock);
405        }
406
407        return 0;
408    }
409
410    /**
411     * Uploads a file to the wiki.
412     *
413     * Michael Klier <chi@chimeric.de>
414     */
415    function putAttachment($ns, $file, $params) {
416        global $conf;
417        global $lang;
418
419        $auth = auth_quickaclcheck($ns.':*');
420        if($auth >= AUTH_UPLOAD) {
421            if(!isset($params['name'])) {
422                return new IXR_ERROR(1, 'Filename not given.');
423            }
424
425            $ftmp = $conf['tmpdir'] . '/' . $params['name'];
426            $name = $params['name'];
427
428            // save temporary file
429            @unlink($ftmp);
430            $buff = base64_decode($file);
431            io_saveFile($ftmp, $buff);
432
433            // get filename
434            list($iext, $imime) = mimetype($name);
435            $id = cleanID($ns.':'.$name);
436            $fn = mediaFN($id);
437
438            // get filetype regexp
439            $types = array_keys(getMimeTypes());
440            $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
441            $regex = join('|',$types);
442
443            // because a temp file was created already
444            if(preg_match('/\.('.$regex.')$/i',$fn)) {
445                //check for overwrite
446                if(@file_exists($fn) && (!$params['ow'] || $auth < AUTH_DELETE)) {
447                    return new IXR_ERROR(1, $lang['uploadexist']);
448                }
449                // check for valid content
450                @require_once(DOKU_INC.'inc/media.php');
451                $ok = media_contentcheck($ftmp, $imime);
452                if($ok == -1) {
453                    return new IXR_ERROR(1, sprintf($lang['uploadexist'], ".$iext"));
454                } elseif($ok == -2) {
455                    return new IXR_ERROR(1, $lang['uploadspam']);
456                } elseif($ok == -3) {
457                    return new IXR_ERROR(1, $lang['uploadxss']);
458                }
459
460                // prepare event data
461                $data[0] = $ftmp;
462                $data[1] = $fn;
463                $data[2] = $id;
464                $data[3] = $imime;
465
466                // trigger event
467                require_once(DOKU_INC.'inc/events.php');
468                return trigger_event('MEDIA_UPLOAD_FINISH', $data, array($this, '_media_upload_action'), true);
469
470            } else {
471                return new IXR_ERROR(1, $lang['uploadwrong']);
472            }
473        } else {
474            return new IXR_ERROR(1, "You don't have permissions to upload files.");
475        }
476    }
477
478    /**
479     * Moves the temporary file to its final destination.
480     *
481     * Michael Klier <chi@chimeric.de>
482     */
483    function _media_upload_action($data) {
484        global $conf;
485
486        if(is_array($data) && count($data)===4) {
487            io_createNamespace($data[2], 'media');
488            if(rename($data[0], $data[1])) {
489                chmod($data[1], $conf['fmode']);
490                media_notify($data[2], $data[1], $data[3]);
491                return $data[2];
492            } else {
493                return new IXR_ERROR(1, 'Upload failed.');
494            }
495        } else {
496            return new IXR_ERROR(1, 'Upload failed.');
497        }
498    }
499
500    /**
501    * Returns the permissions of a given wiki page
502    */
503    function aclCheck($id) {
504        return auth_quickaclcheck($id);
505    }
506
507    /**
508     * Lists all links contained in a wiki page
509     *
510     * @author Michael Klier <chi@chimeric.de>
511     */
512    function listLinks($id) {
513        if(auth_quickaclcheck($id) < AUTH_READ){
514            return new IXR_Error(1, 'You are not allowed to read this page');
515        }
516        $links = array();
517
518        // resolve page instructions
519        $ins   = p_cached_instructions(wikiFN(cleanID($id)));
520
521        // instantiate new Renderer - needed for interwiki links
522        include(DOKU_INC.'inc/parser/xhtml.php');
523        $Renderer = new Doku_Renderer_xhtml();
524        $Renderer->interwiki = getInterwiki();
525
526        // parse parse instructions
527        foreach($ins as $in) {
528            $link = array();
529            switch($in[0]) {
530                case 'internallink':
531                    $link['type'] = 'local';
532                    $link['page'] = $in[1][0];
533                    $link['href'] = wl($in[1][0]);
534                    array_push($links,$link);
535                    break;
536                case 'externallink':
537                    $link['type'] = 'extern';
538                    $link['page'] = $in[1][0];
539                    $link['href'] = $in[1][0];
540                    array_push($links,$link);
541                    break;
542                case 'interwikilink':
543                    $url = $Renderer->_resolveInterWiki($in[1][2],$in[1][3]);
544                    $link['type'] = 'extern';
545                    $link['page'] = $url;
546                    $link['href'] = $url;
547                    array_push($links,$link);
548                    break;
549            }
550        }
551
552        return ($links);
553    }
554
555    /**
556     * Returns a list of recent changes since give timestamp
557     *
558     * @author Michael Klier <chi@chimeric.de>
559     */
560    function getRecentChanges($timestamp) {
561        global $conf;
562
563        if(strlen($timestamp) != 10)
564            return new IXR_Error(20, 'The provided value is not a valid timestamp');
565
566        $changes = array();
567
568        require_once(DOKU_INC.'inc/changelog.php');
569        require_once(DOKU_INC.'inc/pageutils.php');
570
571        // read changes
572        $lines = @file($conf['changelog']);
573
574        if(empty($lines))
575            return new IXR_Error(10, 'The changelog could not be read');
576
577        // we start searching at the end of the list
578        $lines = array_reverse($lines);
579
580        // cache seen pages and skip them
581        $seen = array();
582
583        foreach($lines as $line) {
584
585            if(empty($line)) continue; // skip empty lines
586
587            $logline = parseChangelogLine($line);
588
589            if($logline === false) continue;
590
591            // skip seen ones
592            if(isset($seen[$logline['id']])) continue;
593
594            // skip minors
595            if($logline['type'] === DOKU_CHANGE_TYPE_MINOR_EDIT && ($flags & RECENTS_SKIP_MINORS)) continue;
596
597            // remember in seen to skip additional sights
598            $seen[$logline['id']] = 1;
599
600            // check if it's a hidden page
601            if(isHiddenPage($logline['id'])) continue;
602
603            // check ACL
604            if(auth_quickaclcheck($logline['id']) < AUTH_READ) continue;
605
606            // check existance
607            if((!@file_exists(wikiFN($logline['id']))) && ($flags & RECENTS_SKIP_DELETED)) continue;
608
609            // check if logline is still in the queried time frame
610            if($logline['date'] >= $timestamp) {
611                $change['name']         = $logline['id'];
612                $change['lastModified'] = new IXR_Date($logline['date']);
613                $change['author']       = $logline['user'];
614                $change['version']      = $logline['date'];
615                array_push($changes, $change);
616            } else {
617                $changes = array_reverse($changes);
618                return ($changes);
619            }
620        }
621        // in case we still have nothing at this point
622        return new IXR_Error(30, 'There are no changes in the specified timeframe');
623    }
624
625    /**
626     * Returns a list of available revisions of a given wiki page
627     *
628     * @author Michael Klier <chi@chimeric.de>
629     */
630    function pageVersions($id, $first) {
631        global $conf;
632
633        $versions = array();
634
635        if(empty($id))
636            return new IXR_Error(1, 'Empty page ID');
637
638        require_once(DOKU_INC.'inc/changelog.php');
639
640        $revisions = getRevisions($id, $first, $conf['recent']+1);
641
642        if(count($revisions)==0 && $first!=0) {
643            $first=0;
644            $revisions = getRevisions($id, $first, $conf['recent']+1);
645        }
646
647        if(count($revisions)>0 && $first==0) {
648            array_unshift($revisions, '');  // include current revision
649            array_pop($revisions);          // remove extra log entry
650        }
651
652        $hasNext = false;
653        if(count($revisions)>$conf['recent']) {
654            $hasNext = true;
655            array_pop($revisions); // remove extra log entry
656        }
657
658        if(!empty($revisions)) {
659            foreach($revisions as $rev) {
660                $file = wikiFN($id,$rev);
661                $time = @filemtime($file);
662                // we check if the page actually exists, if this is not the
663                // case this can lead to less pages being returned than
664                // specified via $conf['recent']
665                if($time){
666                    $info = getRevisionInfo($id, $time, 1024);
667                    if(!empty($info)) {
668                        $data['user'] = $info['user'];
669                        $data['ip']   = $info['ip'];
670                        $data['type'] = $info['type'];
671                        $data['sum']  = $info['sum'];
672                        $data['modified'] = new IXR_Date($info['date']);
673                        $data['version'] = $info['date'];
674                        array_push($versions, $data);
675                    }
676                }
677            }
678            return $versions;
679        } else {
680            return array();
681        }
682    }
683
684    /**
685     * The version of Wiki RPC API supported
686     */
687    function wiki_RPCVersion(){
688        return 2;
689    }
690}
691
692$server = new dokuwiki_xmlrpc_server();
693
694// vim:ts=4:sw=4:et:enc=utf-8:
695