xref: /dokuwiki/lib/exe/xmlrpc.php (revision b77df6012df39de023b5ebb0b60f2427a465c25f)
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/**
8 * Increased whenever the API is changed
9 */
10define('DOKU_XMLRPC_API_VERSION',3);
11
12require_once(DOKU_INC.'inc/init.php');
13require_once(DOKU_INC.'inc/common.php');
14require_once(DOKU_INC.'inc/auth.php');
15session_write_close();  //close session
16
17if(!$conf['xmlrpc']) die('XML-RPC server not enabled.');
18
19require_once(DOKU_INC.'inc/IXR_Library.php');
20
21
22/**
23 * Contains needed wrapper functions and registers all available
24 * XMLRPC functions.
25 */
26class dokuwiki_xmlrpc_server extends IXR_IntrospectionServer {
27    var $methods       = array();
28    var $public_methods = array();
29
30    /**
31     * Checks if the current user is allowed to execute non anonymous methods
32     */
33    function checkAuth(){
34        global $conf;
35        global $USERINFO;
36
37        if(!$conf['useacl']) return true; //no ACL - then no checks
38
39        $allowed = explode(',',$conf['xmlrpcuser']);
40        $allowed = array_map('trim', $allowed);
41        $allowed = array_unique($allowed);
42        $allowed = array_filter($allowed);
43
44        if(!count($allowed)) return true; //no restrictions
45
46        $user   = $_SERVER['REMOTE_USER'];
47        $groups = (array) $USERINFO['grps'];
48
49        if(in_array($user,$allowed)) return true; //user explicitly mentioned
50
51        //check group memberships
52        foreach($groups as $group){
53            if(in_array('@'.$group,$allowed)) return true;
54        }
55
56        //still here? no access!
57        return false;
58    }
59
60    /**
61     * Adds a callback, extends parent method
62     *
63     * add another parameter to define if anonymous access to
64     * this method should be granted.
65     */
66    function addCallback($method, $callback, $args, $help, $public=false){
67        if($public) $this->public_methods[] = $method;
68        return parent::addCallback($method, $callback, $args, $help);
69    }
70
71    /**
72     * Execute a call, extends parent method
73     *
74     * Checks for authentication first
75     */
76    function call($methodname, $args){
77        if(!in_array($methodname,$this->public_methods) && !$this->checkAuth()){
78            return new IXR_Error(-32603, 'server error. not authorized to call method "'.$methodname.'".');
79        }
80        return parent::call($methodname, $args);
81    }
82
83    /**
84     * Constructor. Register methods and run Server
85     */
86    function dokuwiki_xmlrpc_server(){
87        $this->IXR_IntrospectionServer();
88
89        /* DokuWiki's own methods */
90        $this->addCallback(
91            'dokuwiki.getXMLRPCAPIVersion',
92            'this:getAPIVersion',
93            array('integer'),
94            'Returns the XMLRPC API version.',
95            true
96        );
97
98        $this->addCallback(
99            'dokuwiki.getVersion',
100            'getVersion',
101            array('string'),
102            'Returns the running DokuWiki version.',
103            true
104        );
105
106        $this->addCallback(
107            'dokuwiki.login',
108            'this:login',
109            array('integer','string','string'),
110            'Tries to login with the given credentials and sets auth cookies.',
111            true
112        );
113
114        $this->addCallback(
115            'dokuwiki.getPagelist',
116            'this:readNamespace',
117            array('struct','string','struct'),
118            'List all pages within the given namespace.'
119        );
120
121        $this->addCallback(
122            'dokuwiki.search',
123            'this:search',
124            array('struct','string'),
125            'Perform a fulltext search and return a list of matching pages'
126        );
127
128        $this->addCallback(
129            'dokuwiki.getTime',
130            'time',
131            array('int'),
132            'Return the current time at the wiki server.'
133        );
134
135        $this->addCallback(
136            'dokuwiki.setLocks',
137            'this:setLocks',
138            array('struct','struct'),
139            'Lock or unlock pages.'
140        );
141
142        /* Wiki API v2 http://www.jspwiki.org/wiki/WikiRPCInterface2 */
143        $this->addCallback(
144            'wiki.getRPCVersionSupported',
145            'this:wiki_RPCVersion',
146            array('int'),
147            'Returns 2 with the supported RPC API version.',
148            true
149        );
150        $this->addCallback(
151            'wiki.getPage',
152            'this:rawPage',
153            array('string','string'),
154            'Get the raw Wiki text of page, latest version.'
155        );
156        $this->addCallback(
157            'wiki.getPageVersion',
158            'this:rawPage',
159            array('string','string','int'),
160            'Get the raw Wiki text of page.'
161        );
162        $this->addCallback(
163            'wiki.getPageHTML',
164            'this:htmlPage',
165            array('string','string'),
166            'Return page in rendered HTML, latest version.'
167        );
168        $this->addCallback(
169            'wiki.getPageHTMLVersion',
170            'this:htmlPage',
171            array('string','string','int'),
172            'Return page in rendered HTML.'
173        );
174        $this->addCallback(
175            'wiki.getAllPages',
176            'this:listPages',
177            array('struct'),
178            'Returns a list of all pages. The result is an array of utf8 pagenames.'
179        );
180        $this->addCallback(
181            'wiki.getAttachments',
182            'this:listAttachments',
183            array('struct', 'string', 'struct'),
184            'Returns a list of all media files.'
185        );
186        $this->addCallback(
187            'wiki.getBackLinks',
188            'this:listBackLinks',
189            array('struct','string'),
190            'Returns the pages that link to this page.'
191        );
192        $this->addCallback(
193            'wiki.getPageInfo',
194            'this:pageInfo',
195            array('struct','string'),
196            'Returns a struct with infos about the page.'
197        );
198        $this->addCallback(
199            'wiki.getPageInfoVersion',
200            'this:pageInfo',
201            array('struct','string','int'),
202            'Returns a struct with infos about the page.'
203        );
204        $this->addCallback(
205            'wiki.getPageVersions',
206            'this:pageVersions',
207            array('struct','string','int'),
208            'Returns the available revisions of the page.'
209        );
210        $this->addCallback(
211            'wiki.putPage',
212            'this:putPage',
213            array('int', 'string', 'string', 'struct'),
214            'Saves a wiki page.'
215        );
216        $this->addCallback(
217            'wiki.listLinks',
218            'this:listLinks',
219            array('struct','string'),
220            'Lists all links contained in a wiki page.'
221        );
222        $this->addCallback(
223            'wiki.getRecentChanges',
224            'this:getRecentChanges',
225            array('struct','int'),
226            'Returns a struct about all recent changes since given timestamp.'
227        );
228        $this->addCallback(
229            'wiki.getRecentMediaChanges',
230            'this:getRecentMediaChanges',
231            array('struct','int'),
232            'Returns a struct about all recent media changes since given timestamp.'
233        );
234        $this->addCallback(
235            'wiki.aclCheck',
236            'this:aclCheck',
237            array('int', 'string'),
238            'Returns the permissions of a given wiki page.'
239        );
240        $this->addCallback(
241            'wiki.putAttachment',
242            'this:putAttachment',
243            array('struct', 'string', 'base64', 'struct'),
244            'Upload a file to the wiki.'
245        );
246        $this->addCallback(
247            'wiki.deleteAttachment',
248            'this:deleteAttachment',
249            array('int', 'string'),
250            'Delete a file from the wiki.'
251        );
252        $this->addCallback(
253            'wiki.getAttachment',
254            'this:getAttachment',
255            array('base64', 'string'),
256            'Download a file from the wiki.'
257        );
258        $this->addCallback(
259            'wiki.getAttachmentInfo',
260            'this:getAttachmentInfo',
261            array('struct', 'string'),
262            'Returns a struct with infos about the attachment.'
263        );
264
265        /**
266         * Trigger XMLRPC_CALLBACK_REGISTER, action plugins can use this event
267         * to extend the XMLRPC interface and register their own callbacks.
268         *
269         * Event data:
270         *  The XMLRPC server object:
271         *
272         *  $event->data->addCallback() - register a callback, the second
273         *  paramter has to be of the form "plugin:<pluginname>:<plugin
274         *  method>"
275         *
276         *  $event->data->callbacks - an array which holds all awaylable
277         *  callbacks
278         */
279        trigger_event('XMLRPC_CALLBACK_REGISTER', $this);
280
281        $this->serve();
282    }
283
284    /**
285     * Return a raw wiki page
286     */
287    function rawPage($id,$rev=''){
288        if(auth_quickaclcheck($id) < AUTH_READ){
289            return new IXR_Error(1, 'You are not allowed to read this page');
290        }
291        $text = rawWiki($id,$rev);
292        if(!$text) {
293            return pageTemplate($id);
294        } else {
295            return $text;
296        }
297    }
298
299    /**
300     * Return a media file encoded in base64
301     *
302     * @author Gina Haeussge <osd@foosel.net>
303     */
304    function getAttachment($id){
305        $id = cleanID($id);
306        if (auth_quickaclcheck(getNS($id).':*') < AUTH_READ)
307            return new IXR_Error(1, 'You are not allowed to read this file');
308
309        $file = mediaFN($id);
310        if (!@ file_exists($file))
311            return new IXR_Error(1, 'The requested file does not exist');
312
313        $data = io_readFile($file, false);
314        $base64 = base64_encode($data);
315        return $base64;
316    }
317
318    /**
319     * Return info about a media file
320     *
321     * @author Gina Haeussge <osd@foosel.net>
322     */
323    function getAttachmentInfo($id){
324        $id = cleanID($id);
325        $info = array(
326            'lastModified' => 0,
327            'size' => 0,
328        );
329
330        $file = mediaFN($id);
331        if ((auth_quickaclcheck(getNS($id).':*') >= AUTH_READ) && file_exists($file)){
332            $info['lastModified'] = new IXR_Date(filemtime($file));
333            $info['size'] = filesize($file);
334        }
335
336        return $info;
337    }
338
339    /**
340     * Return a wiki page rendered to html
341     */
342    function htmlPage($id,$rev=''){
343        if(auth_quickaclcheck($id) < AUTH_READ){
344            return new IXR_Error(1, 'You are not allowed to read this page');
345        }
346        return p_wiki_xhtml($id,$rev,false);
347    }
348
349    /**
350     * List all pages - we use the indexer list here
351     */
352    function listPages(){
353        global $conf;
354
355        $list  = array();
356        $pages = file($conf['indexdir'] . '/page.idx');
357        $pages = array_filter($pages, 'isVisiblePage');
358
359        foreach(array_keys($pages) as $idx) {
360            if(page_exists($pages[$idx])) {
361                $perm = auth_quickaclcheck($pages[$idx]);
362                if($perm >= AUTH_READ) {
363                    $page = array();
364                    $page['id'] = trim($pages[$idx]);
365                    $page['perms'] = $perm;
366                    $page['size'] = @filesize(wikiFN($pages[$idx]));
367                    $page['lastModified'] = new IXR_Date(@filemtime(wikiFN($pages[$idx])));
368                    $list[] = $page;
369                }
370            }
371        }
372
373        return $list;
374    }
375
376    /**
377     * List all pages in the given namespace (and below)
378     */
379    function readNamespace($ns,$opts){
380        global $conf;
381
382        if(!is_array($opts)) $opts=array();
383
384        $ns = cleanID($ns);
385        $dir = utf8_encodeFN(str_replace(':', '/', $ns));
386        $data = array();
387        require_once(DOKU_INC.'inc/search.php');
388        $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
389        search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
390        return $data;
391    }
392
393    /**
394     * List all pages in the given namespace (and below)
395     */
396    function search($query){
397        require_once(DOKU_INC.'inc/fulltext.php');
398
399        $regex = '';
400        $data  = ft_pageSearch($query,$regex);
401        $pages = array();
402
403        // prepare additional data
404        $idx = 0;
405        foreach($data as $id => $score){
406            $file = wikiFN($id);
407
408            if($idx < FT_SNIPPET_NUMBER){
409                $snippet = ft_snippet($id,$regex);
410                $idx++;
411            }else{
412                $snippet = '';
413            }
414
415            $pages[] = array(
416                'id'      => $id,
417                'score'   => $score,
418                'rev'     => filemtime($file),
419                'mtime'   => filemtime($file),
420                'size'    => filesize($file),
421                'snippet' => $snippet,
422            );
423        }
424        return $data;
425    }
426
427
428    /**
429     * List all media files.
430     *
431     * Available options are 'recursive' for also including the subnamespaces
432     * in the listing, and 'pattern' for filtering the returned files against
433     * a regular expression matching their name.
434     *
435     * @author Gina Haeussge <osd@foosel.net>
436     */
437    function listAttachments($ns, $options = array()) {
438        global $conf;
439        global $lang;
440
441        $ns = cleanID($ns);
442
443        if (!is_array($options)) $options = array();
444        $options['skipacl'] = 0; // no ACL skipping for XMLRPC
445
446
447        if(auth_quickaclcheck($ns.':*') >= AUTH_READ) {
448            $dir = utf8_encodeFN(str_replace(':', '/', $ns));
449
450            $data = array();
451            require_once(DOKU_INC.'inc/search.php');
452            search($data, $conf['mediadir'], 'search_media', $options, $dir);
453            $len = count($data);
454            if(!$len) return array();
455
456            for($i=0; $i<$len; $i++) {
457                unset($data[$i]['meta']);
458                $data[$i]['lastModified'] = new IXR_Date($data[$i]['mtime']);
459            }
460            return $data;
461        } else {
462            return new IXR_Error(1, 'You are not allowed to list media files.');
463        }
464    }
465
466    /**
467     * Return a list of backlinks
468     */
469    function listBackLinks($id){
470        require_once(DOKU_INC.'inc/fulltext.php');
471        return ft_backlinks($id);
472    }
473
474    /**
475     * Return some basic data about a page
476     */
477    function pageInfo($id,$rev=''){
478        if(auth_quickaclcheck($id) < AUTH_READ){
479            return new IXR_Error(1, 'You are not allowed to read this page');
480        }
481        $file = wikiFN($id,$rev);
482        $time = @filemtime($file);
483        if(!$time){
484            return new IXR_Error(10, 'The requested page does not exist');
485        }
486
487        $info = getRevisionInfo($id, $time, 1024);
488
489        $data = array(
490            'name'         => $id,
491            'lastModified' => new IXR_Date($time),
492            'author'       => (($info['user']) ? $info['user'] : $info['ip']),
493            'version'      => $time
494        );
495
496        return ($data);
497    }
498
499    /**
500     * Save a wiki page
501     *
502     * @author Michael Klier <chi@chimeric.de>
503     */
504    function putPage($id, $text, $params) {
505        global $TEXT;
506        global $lang;
507        global $conf;
508
509        $id    = cleanID($id);
510        $TEXT  = cleanText($text);
511        $sum   = $params['sum'];
512        $minor = $params['minor'];
513
514        if(empty($id))
515            return new IXR_Error(1, 'Empty page ID');
516
517        if(!page_exists($id) && trim($TEXT) == '' ) {
518            return new IXR_ERROR(1, 'Refusing to write an empty new wiki page');
519        }
520
521        if(auth_quickaclcheck($id) < AUTH_EDIT)
522            return new IXR_Error(1, 'You are not allowed to edit this page');
523
524        // Check, if page is locked
525        if(checklock($id))
526            return new IXR_Error(1, 'The page is currently locked');
527
528        // SPAM check
529        if(checkwordblock())
530            return new IXR_Error(1, 'Positive wordblock check');
531
532        // autoset summary on new pages
533        if(!page_exists($id) && empty($sum)) {
534            $sum = $lang['created'];
535        }
536
537        // autoset summary on deleted pages
538        if(page_exists($id) && empty($TEXT) && empty($sum)) {
539            $sum = $lang['deleted'];
540        }
541
542        lock($id);
543
544        saveWikiText($id,$TEXT,$sum,$minor);
545
546        unlock($id);
547
548        // run the indexer if page wasn't indexed yet
549        if(!@file_exists(metaFN($id, '.indexed'))) {
550            // try to aquire a lock
551            $lock = $conf['lockdir'].'/_indexer.lock';
552            while(!@mkdir($lock,$conf['dmode'])){
553                usleep(50);
554                if(time()-@filemtime($lock) > 60*5){
555                    // looks like a stale lock - remove it
556                    @rmdir($lock);
557                }else{
558                    return false;
559                }
560            }
561            if($conf['dperm']) chmod($lock, $conf['dperm']);
562
563            require_once(DOKU_INC.'inc/indexer.php');
564
565            // do the work
566            idx_addPage($id);
567
568            // we're finished - save and free lock
569            io_saveFile(metaFN($id,'.indexed'),INDEXER_VERSION);
570            @rmdir($lock);
571        }
572
573        return 0;
574    }
575
576    /**
577     * Uploads a file to the wiki.
578     *
579     * Michael Klier <chi@chimeric.de>
580     */
581    function putAttachment($id, $file, $params) {
582        global $conf;
583        global $lang;
584
585        $auth = auth_quickaclcheck(getNS($id).':*');
586        if($auth >= AUTH_UPLOAD) {
587            if(!isset($id)) {
588                return new IXR_ERROR(1, 'Filename not given.');
589            }
590
591            $ftmp = $conf['tmpdir'] . '/' . $id;
592
593            // save temporary file
594            @unlink($ftmp);
595            $buff = base64_decode($file);
596            io_saveFile($ftmp, $buff);
597
598            // get filename
599            list($iext, $imime,$dl) = mimetype($id);
600            $id = cleanID($id);
601            $fn = mediaFN($id);
602
603            // get filetype regexp
604            $types = array_keys(getMimeTypes());
605            $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
606            $regex = join('|',$types);
607
608            // because a temp file was created already
609            if(preg_match('/\.('.$regex.')$/i',$fn)) {
610                //check for overwrite
611                $overwrite = @file_exists($fn);
612                if($overwrite && (!$params['ow'] || $auth < AUTH_DELETE)) {
613                    return new IXR_ERROR(1, $lang['uploadexist'].'1');
614                }
615                // check for valid content
616                @require_once(DOKU_INC.'inc/media.php');
617                $ok = media_contentcheck($ftmp, $imime);
618                if($ok == -1) {
619                    return new IXR_ERROR(1, sprintf($lang['uploadexist'].'2', ".$iext"));
620                } elseif($ok == -2) {
621                    return new IXR_ERROR(1, $lang['uploadspam']);
622                } elseif($ok == -3) {
623                    return new IXR_ERROR(1, $lang['uploadxss']);
624                }
625
626                // prepare event data
627                $data[0] = $ftmp;
628                $data[1] = $fn;
629                $data[2] = $id;
630                $data[3] = $imime;
631                $data[4] = $overwrite;
632
633                // trigger event
634                require_once(DOKU_INC.'inc/events.php');
635                return trigger_event('MEDIA_UPLOAD_FINISH', $data, array($this, '_media_upload_action'), true);
636
637            } else {
638                return new IXR_ERROR(1, $lang['uploadwrong']);
639            }
640        } else {
641            return new IXR_ERROR(1, "You don't have permissions to upload files.");
642        }
643    }
644
645    /**
646     * Deletes a file from the wiki.
647     *
648     * @author Gina Haeussge <osd@foosel.net>
649     */
650    function deleteAttachment($id){
651        $auth = auth_quickaclcheck(getNS($id).':*');
652        if($auth < AUTH_DELETE) return new IXR_ERROR(1, "You don't have permissions to delete files.");
653        global $conf;
654        global $lang;
655
656        // check for references if needed
657        $mediareferences = array();
658        if($conf['refcheck']){
659            require_once(DOKU_INC.'inc/fulltext.php');
660            $mediareferences = ft_mediause($id,$conf['refshow']);
661        }
662
663        if(!count($mediareferences)){
664            $file = mediaFN($id);
665            if(@unlink($file)){
666                require_once(DOKU_INC.'inc/changelog.php');
667                addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE);
668                io_sweepNS($id,'mediadir');
669                return 0;
670            }
671            //something went wrong
672               return new IXR_ERROR(1, 'Could not delete file');
673        } else {
674            return new IXR_ERROR(1, 'File is still referenced');
675        }
676    }
677
678    /**
679     * Moves the temporary file to its final destination.
680     *
681     * Michael Klier <chi@chimeric.de>
682     */
683    function _media_upload_action($data) {
684        global $conf;
685
686        if(is_array($data) && count($data)===5) {
687            io_createNamespace($data[2], 'media');
688            if(rename($data[0], $data[1])) {
689                chmod($data[1], $conf['fmode']);
690                media_notify($data[2], $data[1], $data[3]);
691                // add a log entry to the media changelog
692                require_once(DOKU_INC.'inc/changelog.php');
693                if ($data[4]) {
694                    addMediaLogEntry(time(), $data[2], DOKU_CHANGE_TYPE_EDIT);
695                } else {
696                    addMediaLogEntry(time(), $data[2], DOKU_CHANGE_TYPE_CREATE);
697                }
698                return $data[2];
699            } else {
700                return new IXR_ERROR(1, 'Upload failed.');
701            }
702        } else {
703            return new IXR_ERROR(1, 'Upload failed.');
704        }
705    }
706
707    /**
708    * Returns the permissions of a given wiki page
709    */
710    function aclCheck($id) {
711        return auth_quickaclcheck($id);
712    }
713
714    /**
715     * Lists all links contained in a wiki page
716     *
717     * @author Michael Klier <chi@chimeric.de>
718     */
719    function listLinks($id) {
720        if(auth_quickaclcheck($id) < AUTH_READ){
721            return new IXR_Error(1, 'You are not allowed to read this page');
722        }
723        $links = array();
724
725        // resolve page instructions
726        $ins   = p_cached_instructions(wikiFN(cleanID($id)));
727
728        // instantiate new Renderer - needed for interwiki links
729        include(DOKU_INC.'inc/parser/xhtml.php');
730        $Renderer = new Doku_Renderer_xhtml();
731        $Renderer->interwiki = getInterwiki();
732
733        // parse parse instructions
734        foreach($ins as $in) {
735            $link = array();
736            switch($in[0]) {
737                case 'internallink':
738                    $link['type'] = 'local';
739                    $link['page'] = $in[1][0];
740                    $link['href'] = wl($in[1][0]);
741                    array_push($links,$link);
742                    break;
743                case 'externallink':
744                    $link['type'] = 'extern';
745                    $link['page'] = $in[1][0];
746                    $link['href'] = $in[1][0];
747                    array_push($links,$link);
748                    break;
749                case 'interwikilink':
750                    $url = $Renderer->_resolveInterWiki($in[1][2],$in[1][3]);
751                    $link['type'] = 'extern';
752                    $link['page'] = $url;
753                    $link['href'] = $url;
754                    array_push($links,$link);
755                    break;
756            }
757        }
758
759        return ($links);
760    }
761
762    /**
763     * Returns a list of recent changes since give timestamp
764     *
765     * @author Michael Hamann <michael@content-space.de>
766     * @author Michael Klier <chi@chimeric.de>
767     */
768    function getRecentChanges($timestamp) {
769        if(strlen($timestamp) != 10)
770            return new IXR_Error(20, 'The provided value is not a valid timestamp');
771
772        require_once(DOKU_INC.'inc/changelog.php');
773        require_once(DOKU_INC.'inc/pageutils.php');
774
775        $recents = getRecentsSince($timestamp);
776
777        $changes = array();
778
779        foreach ($recents as $recent) {
780            $change = array();
781            $change['name']         = $recent['id'];
782            $change['lastModified'] = new IXR_Date($recent['date']);
783            $change['author']       = $recent['user'];
784            $change['version']      = $recent['date'];
785            $change['perms']        = $recent['perms'];
786            $change['size']         = @filesize(wikiFN($recent['id']));
787            array_push($changes, $change);
788        }
789
790        if (!empty($changes)) {
791            return $changes;
792        } else {
793            // in case we still have nothing at this point
794            return new IXR_Error(30, 'There are no changes in the specified timeframe');
795        }
796    }
797
798    /**
799     * Returns a list of recent media changes since give timestamp
800     *
801     * @author Michael Hamann <michael@content-space.de>
802     * @author Michael Klier <chi@chimeric.de>
803     */
804    function getRecentMediaChanges($timestamp) {
805        if(strlen($timestamp) != 10)
806            return new IXR_Error(20, 'The provided value is not a valid timestamp');
807
808        require_once(DOKU_INC.'inc/changelog.php');
809        require_once(DOKU_INC.'inc/pageutils.php');
810
811        $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES);
812
813        $changes = array();
814
815        foreach ($recents as $recent) {
816            $change = array();
817            $change['name']         = $recent['id'];
818            $change['lastModified'] = new IXR_Date($recent['date']);
819            $change['author']       = $recent['user'];
820            $change['version']      = $recent['date'];
821            $change['perms']        = $recent['perms'];
822            $change['size']         = @filesize(mediaFN($recent['id']));
823            array_push($changes, $change);
824        }
825
826        if (!empty($changes)) {
827            return $changes;
828        } else {
829            // in case we still have nothing at this point
830            return new IXR_Error(30, 'There are no changes in the specified timeframe');
831        }
832    }
833
834    /**
835     * Returns a list of available revisions of a given wiki page
836     *
837     * @author Michael Klier <chi@chimeric.de>
838     */
839    function pageVersions($id, $first) {
840        global $conf;
841
842        $versions = array();
843
844        if(empty($id))
845            return new IXR_Error(1, 'Empty page ID');
846
847        require_once(DOKU_INC.'inc/changelog.php');
848
849        $revisions = getRevisions($id, $first, $conf['recent']+1);
850
851        if(count($revisions)==0 && $first!=0) {
852            $first=0;
853            $revisions = getRevisions($id, $first, $conf['recent']+1);
854        }
855
856        if(count($revisions)>0 && $first==0) {
857            array_unshift($revisions, '');  // include current revision
858            array_pop($revisions);          // remove extra log entry
859        }
860
861        $hasNext = false;
862        if(count($revisions)>$conf['recent']) {
863            $hasNext = true;
864            array_pop($revisions); // remove extra log entry
865        }
866
867        if(!empty($revisions)) {
868            foreach($revisions as $rev) {
869                $file = wikiFN($id,$rev);
870                $time = @filemtime($file);
871                // we check if the page actually exists, if this is not the
872                // case this can lead to less pages being returned than
873                // specified via $conf['recent']
874                if($time){
875                    $info = getRevisionInfo($id, $time, 1024);
876                    if(!empty($info)) {
877                        $data['user'] = $info['user'];
878                        $data['ip']   = $info['ip'];
879                        $data['type'] = $info['type'];
880                        $data['sum']  = $info['sum'];
881                        $data['modified'] = new IXR_Date($info['date']);
882                        $data['version'] = $info['date'];
883                        array_push($versions, $data);
884                    }
885                }
886            }
887            return $versions;
888        } else {
889            return array();
890        }
891    }
892
893    /**
894     * The version of Wiki RPC API supported
895     */
896    function wiki_RPCVersion(){
897        return 2;
898    }
899
900
901    /**
902     * Locks or unlocks a given batch of pages
903     *
904     * Give an associative array with two keys: lock and unlock. Both should contain a
905     * list of pages to lock or unlock
906     *
907     * Returns an associative array with the keys locked, lockfail, unlocked and
908     * unlockfail, each containing lists of pages.
909     */
910    function setLocks($set){
911        $locked     = array();
912        $lockfail   = array();
913        $unlocked   = array();
914        $unlockfail = array();
915
916        foreach((array) $set['lock'] as $id){
917            if(checklock($id)){
918                $lockfail[] = $id;
919            }else{
920                lock($id);
921                $locked[] = $id;
922            }
923        }
924
925        foreach((array) $set['unlock'] as $id){
926            if(unlock($id)){
927                $unlocked[] = $id;
928            }else{
929                $unlockfail[] = $id;
930            }
931        }
932
933        return array(
934            'locked'     => $locked,
935            'lockfail'   => $lockfail,
936            'unlocked'   => $unlocked,
937            'unlockfail' => $unlockfail,
938        );
939    }
940
941    function getAPIVersion(){
942        return DOKU_XMLRPC_API_VERSION;
943    }
944
945    function login($user,$pass){
946        global $conf;
947        global $auth;
948        if(!$conf['useacl']) return 0;
949        if(!$auth) return 0;
950        if($auth->canDo('external')){
951            return $auth->trustExternal($user,$pass,false);
952        }else{
953            return auth_login($user,$pass,false,true);
954        }
955    }
956
957
958}
959
960$server = new dokuwiki_xmlrpc_server();
961
962// vim:ts=4:sw=4:et:enc=utf-8:
963