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