Mereged updates from DokuWiki 38
[sudaraka-org:dokuwiki-mods.git] / inc / RemoteAPICore.php
1 <?php
2
3 /**
4  * Increased whenever the API is changed
5  */
6 define('DOKU_API_VERSION', 7);
7
8 class RemoteAPICore {
9
10     private $api;
11
12     public function __construct(RemoteAPI $api) {
13         $this->api = $api;
14     }
15
16     function __getRemoteInfo() {
17         return array(
18             'dokuwiki.getVersion' => array(
19                 'args' => array(),
20                 'return' => 'string',
21                 'doc' => 'Returns the running DokuWiki version.'
22             ), 'dokuwiki.login' => array(
23                 'args' => array('string', 'string'),
24                 'return' => 'int',
25                 'doc' => 'Tries to login with the given credentials and sets auth cookies.',
26                 'public' => '1'
27             ), 'dokuwiki.getPagelist' => array(
28                 'args' => array('string', 'array'),
29                 'return' => 'array',
30                 'doc' => 'List all pages within the given namespace.',
31                 'name' => 'readNamespace'
32             ), 'dokuwiki.search' => array(
33                 'args' => array('string'),
34                 'return' => 'array',
35                 'doc' => 'Perform a fulltext search and return a list of matching pages'
36             ), 'dokuwiki.getTime' => array(
37                 'args' => array(),
38                 'return' => 'int',
39                 'doc' =>  'Returns the current time at the remote wiki server as Unix timestamp.',
40             ), 'dokuwiki.setLocks' => array(
41                 'args' => array('array'),
42                 'return' => 'array',
43                 'doc' => 'Lock or unlock pages.'
44             ), 'dokuwiki.getTitle' => array(
45                 'args' => array(),
46                 'return' => 'string',
47                 'doc' => 'Returns the wiki title.',
48                 'public' => '1'
49             ), 'dokuwiki.appendPage' => array(
50                 'args' => array('string', 'string', 'array'),
51                 'return' => 'int',
52                 'doc' => 'Append text to a wiki page.'
53             ),  'wiki.getPage' => array(
54                 'args' => array('string'),
55                 'return' => 'string',
56                 'doc' => 'Get the raw Wiki text of page, latest version.',
57                 'name' => 'rawPage',
58             ), 'wiki.getPageVersion' => array(
59                 'args' => array('string', 'int'),
60                 'name' => 'rawPage',
61                 'return' => 'string',
62                 'doc' => 'Return a raw wiki page'
63             ), 'wiki.getPageHTML' => array(
64                 'args' => array('string'),
65                 'return' => 'string',
66                 'doc' => 'Return page in rendered HTML, latest version.',
67                 'name' => 'htmlPage'
68             ), 'wiki.getPageHTMLVersion' => array(
69                 'args' => array('string', 'int'),
70                 'return' => 'string',
71                 'doc' => 'Return page in rendered HTML.',
72                 'name' => 'htmlPage'
73             ), 'wiki.getAllPages' => array(
74                 'args' => array(),
75                 'return' => 'array',
76                 'doc' => 'Returns a list of all pages. The result is an array of utf8 pagenames.',
77                 'name' => 'listPages'
78             ), 'wiki.getAttachments' => array(
79                 'args' => array('string', 'array'),
80                 'return' => 'array',
81                 'doc' => 'Returns a list of all media files.',
82                 'name' => 'listAttachments'
83             ), 'wiki.getBackLinks' => array(
84                 'args' => array('string'),
85                 'return' => 'array',
86                 'doc' => 'Returns the pages that link to this page.',
87                 'name' => 'listBackLinks'
88             ), 'wiki.getPageInfo' => array(
89                 'args' => array('string'),
90                 'return' => 'array',
91                 'doc' => 'Returns a struct with infos about the page.',
92                 'name' => 'pageInfo'
93             ), 'wiki.getPageInfoVersion' => array(
94                 'args' => array('string', 'int'),
95                 'return' => 'array',
96                 'doc' => 'Returns a struct with infos about the page.',
97                 'name' => 'pageInfo'
98             ), 'wiki.getPageVersions' => array(
99                 'args' => array('string', 'int'),
100                 'return' => 'array',
101                 'doc' => 'Returns the available revisions of the page.',
102                 'name' => 'pageVersions'
103             ), 'wiki.putPage' => array(
104                 'args' => array('string', 'string', 'array'),
105                 'return' => 'int',
106                 'doc' => 'Saves a wiki page.'
107             ), 'wiki.listLinks' => array(
108                 'args' => array('string'),
109                 'return' => 'array',
110                 'doc' => 'Lists all links contained in a wiki page.'
111             ), 'wiki.getRecentChanges' => array(
112                 'args' => array('int'),
113                 'return' => 'array',
114                 'Returns a struct about all recent changes since given timestamp.'
115             ), 'wiki.getRecentMediaChanges' => array(
116                 'args' => array('int'),
117                 'return' => 'array',
118                 'Returns a struct about all recent media changes since given timestamp.'
119             ), 'wiki.aclCheck' => array(
120                 'args' => array('string'),
121                 'return' => 'int',
122                 'doc' => 'Returns the permissions of a given wiki page.'
123             ), 'wiki.putAttachment' => array(
124                 'args' => array('string', 'file', 'array'),
125                 'return' => 'array',
126                 'doc' => 'Upload a file to the wiki.'
127             ), 'wiki.deleteAttachment' => array(
128                 'args' => array('string'),
129                 'return' => 'int',
130                 'doc' => 'Delete a file from the wiki.'
131             ), 'wiki.getAttachment' => array(
132                 'args' => array('string'),
133                 'doc' => 'Return a media file',
134                 'return' => 'file',
135                 'name' => 'getAttachment',
136             ), 'wiki.getAttachmentInfo' => array(
137                 'args' => array('string'),
138                 'return' => 'array',
139                 'doc' => 'Returns a struct with infos about the attachment.'
140             ), 'dokuwiki.getXMLRPCAPIVersion' => array(
141                 'args' => array(),
142                 'name' => 'getAPIVersion',
143                 'return' => 'int',
144                 'doc' => 'Returns the XMLRPC API version.',
145                 'public' => '1',
146             ), 'wiki.getRPCVersionSupported' => array(
147                 'args' => array(),
148                 'name' => 'wiki_RPCVersion',
149                 'return' => 'int',
150                 'doc' => 'Returns 2 with the supported RPC API version.',
151                 'public' => '1'
152             ),
153
154         );
155     }
156
157     function getVersion() {
158         return getVersion();
159     }
160
161     function getTime() {
162         return time();
163     }
164
165     /**
166      * Return a raw wiki page
167      * @param string $id wiki page id
168      * @param string $rev revision number of the page
169      * @return page text.
170      */
171     function rawPage($id,$rev=''){
172         $id = $this->resolvePageId($id);
173         if(auth_quickaclcheck($id) < AUTH_READ){
174             throw new RemoteAccessDeniedException('You are not allowed to read this file', 111);
175         }
176         $text = rawWiki($id,$rev);
177         if(!$text) {
178             return pageTemplate($id);
179         } else {
180             return $text;
181         }
182     }
183
184     /**
185      * Return a media file
186      *
187      * @author Gina Haeussge <osd@foosel.net>
188      * @param string $id file id
189      * @return media file
190      */
191     function getAttachment($id){
192         $id = cleanID($id);
193         if (auth_quickaclcheck(getNS($id).':*') < AUTH_READ) {
194             throw new RemoteAccessDeniedException('You are not allowed to read this file', 211);
195         }
196
197         $file = mediaFN($id);
198         if (!@ file_exists($file)) {
199             throw new RemoteException('The requested file does not exist', 221);
200         }
201
202         $data = io_readFile($file, false);
203         return $this->api->toFile($data);
204     }
205
206     /**
207      * Return info about a media file
208      *
209      * @author Gina Haeussge <osd@foosel.net>
210      */
211     function getAttachmentInfo($id){
212         $id = cleanID($id);
213         $info = array(
214             'lastModified' => $this->api->toDate(0),
215             'size' => 0,
216         );
217
218         $file = mediaFN($id);
219         if ((auth_quickaclcheck(getNS($id).':*') >= AUTH_READ) && file_exists($file)){
220             $info['lastModified'] = $this->api->toDate(filemtime($file));
221             $info['size'] = filesize($file);
222         }
223
224         return $info;
225     }
226
227     /**
228      * Return a wiki page rendered to html
229      */
230     function htmlPage($id,$rev=''){
231         $id = $this->resolvePageId($id);
232         if(auth_quickaclcheck($id) < AUTH_READ){
233             throw new RemoteAccessDeniedException('You are not allowed to read this page', 111);
234         }
235         return p_wiki_xhtml($id,$rev,false);
236     }
237
238     /**
239      * List all pages - we use the indexer list here
240      */
241     function listPages(){
242         $list  = array();
243         $pages = idx_get_indexer()->getPages();
244         $pages = array_filter(array_filter($pages,'isVisiblePage'),'page_exists');
245
246         foreach(array_keys($pages) as $idx) {
247             $perm = auth_quickaclcheck($pages[$idx]);
248             if($perm < AUTH_READ) {
249                 continue;
250             }
251             $page = array();
252             $page['id'] = trim($pages[$idx]);
253             $page['perms'] = $perm;
254             $page['size'] = @filesize(wikiFN($pages[$idx]));
255             $page['lastModified'] = $this->api->toDate(@filemtime(wikiFN($pages[$idx])));
256             $list[] = $page;
257         }
258
259         return $list;
260     }
261
262     /**
263      * List all pages in the given namespace (and below)
264      */
265     function readNamespace($ns,$opts){
266         global $conf;
267
268         if(!is_array($opts)) $opts=array();
269
270         $ns = cleanID($ns);
271         $dir = utf8_encodeFN(str_replace(':', '/', $ns));
272         $data = array();
273         $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
274         search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
275         return $data;
276     }
277
278     /**
279      * List all pages in the given namespace (and below)
280      */
281     function search($query){
282         $regex = '';
283         $data  = ft_pageSearch($query,$regex);
284         $pages = array();
285
286         // prepare additional data
287         $idx = 0;
288         foreach($data as $id => $score){
289             $file = wikiFN($id);
290
291             if($idx < FT_SNIPPET_NUMBER){
292                 $snippet = ft_snippet($id,$regex);
293                 $idx++;
294             }else{
295                 $snippet = '';
296             }
297
298             $pages[] = array(
299                 'id'      => $id,
300                 'score'   => intval($score),
301                 'rev'     => filemtime($file),
302                 'mtime'   => filemtime($file),
303                 'size'    => filesize($file),
304                 'snippet' => $snippet,
305                 'title' => useHeading('navigation') ? p_get_first_heading($id) : $id
306             );
307         }
308         return $pages;
309     }
310
311     /**
312      * Returns the wiki title.
313      */
314     function getTitle(){
315         global $conf;
316         return $conf['title'];
317     }
318
319     /**
320      * List all media files.
321      *
322      * Available options are 'recursive' for also including the subnamespaces
323      * in the listing, and 'pattern' for filtering the returned files against
324      * a regular expression matching their name.
325      *
326      * @author Gina Haeussge <osd@foosel.net>
327      */
328     function listAttachments($ns, $options = array()) {
329         global $conf;
330
331         $ns = cleanID($ns);
332
333         if (!is_array($options)) $options = array();
334         $options['skipacl'] = 0; // no ACL skipping for XMLRPC
335
336
337         if(auth_quickaclcheck($ns.':*') >= AUTH_READ) {
338             $dir = utf8_encodeFN(str_replace(':', '/', $ns));
339
340             $data = array();
341             search($data, $conf['mediadir'], 'search_media', $options, $dir);
342             $len = count($data);
343             if(!$len) return array();
344
345             for($i=0; $i<$len; $i++) {
346                 unset($data[$i]['meta']);
347                 $data[$i]['lastModified'] = $this->api->toDate($data[$i]['mtime']);
348             }
349             return $data;
350         } else {
351             throw new RemoteAccessDeniedException('You are not allowed to list media files.', 215);
352         }
353     }
354
355     /**
356      * Return a list of backlinks
357      */
358     function listBackLinks($id){
359         return ft_backlinks($this->resolvePageId($id));
360     }
361
362     /**
363      * Return some basic data about a page
364      */
365     function pageInfo($id,$rev=''){
366         $id = $this->resolvePageId($id);
367         if(auth_quickaclcheck($id) < AUTH_READ){
368             throw new RemoteAccessDeniedException('You are not allowed to read this page', 111);
369         }
370         $file = wikiFN($id,$rev);
371         $time = @filemtime($file);
372         if(!$time){
373             throw new RemoteException(10, 'The requested page does not exist', 121);
374         }
375
376         $info = getRevisionInfo($id, $time, 1024);
377
378         $data = array(
379             'name'         => $id,
380             'lastModified' => $this->api->toDate($time),
381             'author'       => (($info['user']) ? $info['user'] : $info['ip']),
382             'version'      => $time
383         );
384
385         return ($data);
386     }
387
388     /**
389      * Save a wiki page
390      *
391      * @author Michael Klier <chi@chimeric.de>
392      */
393     function putPage($id, $text, $params) {
394         global $TEXT;
395         global $lang;
396
397         $id    = $this->resolvePageId($id);
398         $TEXT  = cleanText($text);
399         $sum   = $params['sum'];
400         $minor = $params['minor'];
401
402         if(empty($id)) {
403             throw new RemoteException('Empty page ID', 131);
404         }
405
406         if(!page_exists($id) && trim($TEXT) == '' ) {
407             throw new RemoteException('Refusing to write an empty new wiki page', 132);
408         }
409
410         if(auth_quickaclcheck($id) < AUTH_EDIT) {
411             throw new RemoteAccessDeniedException('You are not allowed to edit this page', 112);
412         }
413
414         // Check, if page is locked
415         if(checklock($id)) {
416             throw new RemoteException('The page is currently locked', 133);
417         }
418
419         // SPAM check
420         if(checkwordblock()) {
421             throw new RemoteException('Positive wordblock check', 134);
422         }
423
424         // autoset summary on new pages
425         if(!page_exists($id) && empty($sum)) {
426             $sum = $lang['created'];
427         }
428
429         // autoset summary on deleted pages
430         if(page_exists($id) && empty($TEXT) && empty($sum)) {
431             $sum = $lang['deleted'];
432         }
433
434         lock($id);
435
436         saveWikiText($id,$TEXT,$sum,$minor);
437
438         unlock($id);
439
440         // run the indexer if page wasn't indexed yet
441         idx_addPage($id);
442
443         return 0;
444     }
445
446     /**
447      * Appends text to a wiki page.
448      */
449     function appendPage($id, $text, $params) {
450         $currentpage = $this->rawPage($id);
451         if (!is_string($currentpage)) {
452             return $currentpage;
453         }
454         return $this->putPage($id, $currentpage.$text, $params);
455     }
456
457     /**
458      * Uploads a file to the wiki.
459      *
460      * Michael Klier <chi@chimeric.de>
461      */
462     function putAttachment($id, $file, $params) {
463         $id = cleanID($id);
464         $auth = auth_quickaclcheck(getNS($id).':*');
465
466         if(!isset($id)) {
467             throw new RemoteException('Filename not given.', 231);
468         }
469
470         global $conf;
471
472         $ftmp = $conf['tmpdir'] . '/' . md5($id.clientIP());
473
474         // save temporary file
475         @unlink($ftmp);
476         io_saveFile($ftmp, $file);
477
478         $res = media_save(array('name' => $ftmp), $id, $params['ow'], $auth, 'rename');
479         if (is_array($res)) {
480             throw new RemoteException($res[0], -$res[1]);
481         } else {
482             return $res;
483         }
484     }
485
486     /**
487      * Deletes a file from the wiki.
488      *
489      * @author Gina Haeussge <osd@foosel.net>
490      */
491     function deleteAttachment($id){
492         $id = cleanID($id);
493         $auth = auth_quickaclcheck(getNS($id).':*');
494         $res = media_delete($id, $auth);
495         if ($res & DOKU_MEDIA_DELETED) {
496             return 0;
497         } elseif ($res & DOKU_MEDIA_NOT_AUTH) {
498             throw new RemoteAccessDeniedException('You don\'t have permissions to delete files.', 212);
499         } elseif ($res & DOKU_MEDIA_INUSE) {
500             throw new RemoteException('File is still referenced', 232);
501         } else {
502             throw new RemoteException('Could not delete file', 233);
503         }
504     }
505
506     /**
507     * Returns the permissions of a given wiki page
508     */
509     function aclCheck($id) {
510         $id = $this->resolvePageId($id);
511         return auth_quickaclcheck($id);
512     }
513
514     /**
515      * Lists all links contained in a wiki page
516      *
517      * @author Michael Klier <chi@chimeric.de>
518      */
519     function listLinks($id) {
520         $id = $this->resolvePageId($id);
521         if(auth_quickaclcheck($id) < AUTH_READ){
522             throw new RemoteAccessDeniedException('You are not allowed to read this page', 111);
523         }
524         $links = array();
525
526         // resolve page instructions
527         $ins   = p_cached_instructions(wikiFN($id));
528
529         // instantiate new Renderer - needed for interwiki links
530         include(DOKU_INC.'inc/parser/xhtml.php');
531         $Renderer = new Doku_Renderer_xhtml();
532         $Renderer->interwiki = getInterwiki();
533
534         // parse parse instructions
535         foreach($ins as $in) {
536             $link = array();
537             switch($in[0]) {
538                 case 'internallink':
539                     $link['type'] = 'local';
540                     $link['page'] = $in[1][0];
541                     $link['href'] = wl($in[1][0]);
542                     array_push($links,$link);
543                     break;
544                 case 'externallink':
545                     $link['type'] = 'extern';
546                     $link['page'] = $in[1][0];
547                     $link['href'] = $in[1][0];
548                     array_push($links,$link);
549                     break;
550                 case 'interwikilink':
551                     $url = $Renderer->_resolveInterWiki($in[1][2],$in[1][3]);
552                     $link['type'] = 'extern';
553                     $link['page'] = $url;
554                     $link['href'] = $url;
555                     array_push($links,$link);
556                     break;
557             }
558         }
559
560         return ($links);
561     }
562
563     /**
564      * Returns a list of recent changes since give timestamp
565      *
566      * @author Michael Hamann <michael@content-space.de>
567      * @author Michael Klier <chi@chimeric.de>
568      */
569     function getRecentChanges($timestamp) {
570         if(strlen($timestamp) != 10) {
571             throw new RemoteException('The provided value is not a valid timestamp', 311);
572         }
573
574         $recents = getRecentsSince($timestamp);
575
576         $changes = array();
577
578         foreach ($recents as $recent) {
579             $change = array();
580             $change['name']         = $recent['id'];
581             $change['lastModified'] = $this->api->toDate($recent['date']);
582             $change['author']       = $recent['user'];
583             $change['version']      = $recent['date'];
584             $change['perms']        = $recent['perms'];
585             $change['size']         = @filesize(wikiFN($recent['id']));
586             array_push($changes, $change);
587         }
588
589         if (!empty($changes)) {
590             return $changes;
591         } else {
592             // in case we still have nothing at this point
593             return new RemoteException('There are no changes in the specified timeframe', 321);
594         }
595     }
596
597     /**
598      * Returns a list of recent media changes since give timestamp
599      *
600      * @author Michael Hamann <michael@content-space.de>
601      * @author Michael Klier <chi@chimeric.de>
602      */
603     function getRecentMediaChanges($timestamp) {
604         if(strlen($timestamp) != 10)
605             throw new RemoteException('The provided value is not a valid timestamp', 311);
606
607         $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES);
608
609         $changes = array();
610
611         foreach ($recents as $recent) {
612             $change = array();
613             $change['name']         = $recent['id'];
614             $change['lastModified'] = $this->api->toDate($recent['date']);
615             $change['author']       = $recent['user'];
616             $change['version']      = $recent['date'];
617             $change['perms']        = $recent['perms'];
618             $change['size']         = @filesize(mediaFN($recent['id']));
619             array_push($changes, $change);
620         }
621
622         if (!empty($changes)) {
623             return $changes;
624         } else {
625             // in case we still have nothing at this point
626             throw new RemoteException('There are no changes in the specified timeframe', 321);
627         }
628     }
629
630     /**
631      * Returns a list of available revisions of a given wiki page
632      *
633      * @author Michael Klier <chi@chimeric.de>
634      */
635     function pageVersions($id, $first) {
636         $id = $this->resolvePageId($id);
637         if(auth_quickaclcheck($id) < AUTH_READ) {
638             throw new RemoteAccessDeniedException('You are not allowed to read this page', 111);
639         }
640         global $conf;
641
642         $versions = array();
643
644         if(empty($id)) {
645             throw new RemoteException('Empty page ID', 131);
646         }
647
648         $revisions = getRevisions($id, $first, $conf['recent']+1);
649
650         if(count($revisions)==0 && $first!=0) {
651             $first=0;
652             $revisions = getRevisions($id, $first, $conf['recent']+1);
653         }
654
655         if(count($revisions)>0 && $first==0) {
656             array_unshift($revisions, '');  // include current revision
657             array_pop($revisions);          // remove extra log entry
658         }
659
660         if(count($revisions) > $conf['recent']) {
661             array_pop($revisions); // remove extra log entry
662         }
663
664         if(!empty($revisions)) {
665             foreach($revisions as $rev) {
666                 $file = wikiFN($id,$rev);
667                 $time = @filemtime($file);
668                 // we check if the page actually exists, if this is not the
669                 // case this can lead to less pages being returned than
670                 // specified via $conf['recent']
671                 if($time){
672                     $info = getRevisionInfo($id, $time, 1024);
673                     if(!empty($info)) {
674                         $data['user'] = $info['user'];
675                         $data['ip']   = $info['ip'];
676                         $data['type'] = $info['type'];
677                         $data['sum']  = $info['sum'];
678                         $data['modified'] = $this->api->toDate($info['date']);
679                         $data['version'] = $info['date'];
680                         array_push($versions, $data);
681                     }
682                 }
683             }
684             return $versions;
685         } else {
686             return array();
687         }
688     }
689
690     /**
691      * The version of Wiki RPC API supported
692      */
693     function wiki_RPCVersion(){
694         return 2;
695     }
696
697
698     /**
699      * Locks or unlocks a given batch of pages
700      *
701      * Give an associative array with two keys: lock and unlock. Both should contain a
702      * list of pages to lock or unlock
703      *
704      * Returns an associative array with the keys locked, lockfail, unlocked and
705      * unlockfail, each containing lists of pages.
706      */
707     function setLocks($set){
708         $locked     = array();
709         $lockfail   = array();
710         $unlocked   = array();
711         $unlockfail = array();
712
713         foreach((array) $set['lock'] as $id){
714             $id = $this->resolvePageId($id);
715             if(auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)){
716                 $lockfail[] = $id;
717             }else{
718                 lock($id);
719                 $locked[] = $id;
720             }
721         }
722
723         foreach((array) $set['unlock'] as $id){
724             $id = $this->resolvePageId($id);
725             if(auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)){
726                 $unlockfail[] = $id;
727             }else{
728                 $unlocked[] = $id;
729             }
730         }
731
732         return array(
733             'locked'     => $locked,
734             'lockfail'   => $lockfail,
735             'unlocked'   => $unlocked,
736             'unlockfail' => $unlockfail,
737         );
738     }
739
740     function getAPIVersion(){
741         return DOKU_API_VERSION;
742     }
743
744     function login($user,$pass){
745         global $conf;
746         global $auth;
747         if(!$conf['useacl']) return 0;
748         if(!$auth) return 0;
749
750         @session_start(); // reopen session for login
751         if($auth->canDo('external')){
752             $ok = $auth->trustExternal($user,$pass,false);
753         }else{
754             $evdata = array(
755                 'user'     => $user,
756                 'password' => $pass,
757                 'sticky'   => false,
758                 'silent'   => true,
759             );
760             $ok = trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
761         }
762         session_write_close(); // we're done with the session
763
764         return $ok;
765     }
766
767     private function resolvePageId($id) {
768         $id = cleanID($id);
769         if(empty($id)) {
770             global $conf;
771             $id = cleanID($conf['start']);      
772         }
773         return $id;
774     }
775
776 }
777