xref: /dokuwiki/inc/Remote/ApiCore.php (revision cbb44eabe033d70affb048ec0daf4e579e09dd20)
1<?php
2
3namespace dokuwiki\Remote;
4
5use Doku_Renderer_xhtml;
6use dokuwiki\ChangeLog\MediaChangeLog;
7use dokuwiki\ChangeLog\PageChangeLog;
8use dokuwiki\Extension\AuthPlugin;
9use dokuwiki\Extension\Event;
10
11define('DOKU_API_VERSION', 10);
12
13/**
14 * Provides the core methods for the remote API.
15 * The methods are ordered in 'wiki.<method>' and 'dokuwiki.<method>' namespaces
16 */
17class ApiCore
18{
19    /** @var int Increased whenever the API is changed */
20    const API_VERSION = 10;
21
22
23    /** @var Api */
24    private $api;
25
26    /**
27     * @param Api $api
28     */
29    public function __construct(Api $api)
30    {
31        $this->api = $api;
32    }
33
34    /**
35     * Returns details about the core methods
36     *
37     * @return array
38     */
39    public function __getRemoteInfo()
40    {
41        return array(
42            'dokuwiki.getVersion' => array(
43                'args' => array(),
44                'return' => 'string',
45                'doc' => 'Returns the running DokuWiki version.'
46            ), 'dokuwiki.login' => array(
47                'args' => array('string', 'string'),
48                'return' => 'int',
49                'doc' => 'Tries to login with the given credentials and sets auth cookies.',
50                'public' => '1'
51            ), 'dokuwiki.logoff' => array(
52                'args' => array(),
53                'return' => 'int',
54                'doc' => 'Tries to logoff by expiring auth cookies and the associated PHP session.'
55            ), 'dokuwiki.getPagelist' => array(
56                'args' => array('string', 'array'),
57                'return' => 'array',
58                'doc' => 'List all pages within the given namespace.',
59                'name' => 'readNamespace'
60            ), 'dokuwiki.search' => array(
61                'args' => array('string'),
62                'return' => 'array',
63                'doc' => 'Perform a fulltext search and return a list of matching pages'
64            ), 'dokuwiki.getTime' => array(
65                'args' => array(),
66                'return' => 'int',
67                'doc' => 'Returns the current time at the remote wiki server as Unix timestamp.',
68            ), 'dokuwiki.setLocks' => array(
69                'args' => array('array'),
70                'return' => 'array',
71                'doc' => 'Lock or unlock pages.'
72            ), 'dokuwiki.getTitle' => array(
73                'args' => array(),
74                'return' => 'string',
75                'doc' => 'Returns the wiki title.',
76                'public' => '1'
77            ), 'dokuwiki.appendPage' => array(
78                'args' => array('string', 'string', 'array'),
79                'return' => 'bool',
80                'doc' => 'Append text to a wiki page.'
81            ), 'dokuwiki.deleteUsers' => array(
82                'args' => array('array'),
83                'return' => 'bool',
84                'doc' => 'Remove one or more users from the list of registered users.'
85            ),  'wiki.getPage' => array(
86                'args' => array('string'),
87                'return' => 'string',
88                'doc' => 'Get the raw Wiki text of page, latest version.',
89                'name' => 'rawPage',
90            ), 'wiki.getPageVersion' => array(
91                'args' => array('string', 'int'),
92                'name' => 'rawPage',
93                'return' => 'string',
94                'doc' => 'Return a raw wiki page'
95            ), 'wiki.getPageHTML' => array(
96                'args' => array('string'),
97                'return' => 'string',
98                'doc' => 'Return page in rendered HTML, latest version.',
99                'name' => 'htmlPage'
100            ), 'wiki.getPageHTMLVersion' => array(
101                'args' => array('string', 'int'),
102                'return' => 'string',
103                'doc' => 'Return page in rendered HTML.',
104                'name' => 'htmlPage'
105            ), 'wiki.getAllPages' => array(
106                'args' => array(),
107                'return' => 'array',
108                'doc' => 'Returns a list of all pages. The result is an array of utf8 pagenames.',
109                'name' => 'listPages'
110            ), 'wiki.getAttachments' => array(
111                'args' => array('string', 'array'),
112                'return' => 'array',
113                'doc' => 'Returns a list of all media files.',
114                'name' => 'listAttachments'
115            ), 'wiki.getBackLinks' => array(
116                'args' => array('string'),
117                'return' => 'array',
118                'doc' => 'Returns the pages that link to this page.',
119                'name' => 'listBackLinks'
120            ), 'wiki.getPageInfo' => array(
121                'args' => array('string'),
122                'return' => 'array',
123                'doc' => 'Returns a struct with info about the page, latest version.',
124                'name' => 'pageInfo'
125            ), 'wiki.getPageInfoVersion' => array(
126                'args' => array('string', 'int'),
127                'return' => 'array',
128                'doc' => 'Returns a struct with info about the page.',
129                'name' => 'pageInfo'
130            ), 'wiki.getPageVersions' => array(
131                'args' => array('string', 'int'),
132                'return' => 'array',
133                'doc' => 'Returns the available revisions of the page.',
134                'name' => 'pageVersions'
135            ), 'wiki.putPage' => array(
136                'args' => array('string', 'string', 'array'),
137                'return' => 'bool',
138                'doc' => 'Saves a wiki page.'
139            ), 'wiki.listLinks' => array(
140                'args' => array('string'),
141                'return' => 'array',
142                'doc' => 'Lists all links contained in a wiki page.'
143            ), 'wiki.getRecentChanges' => array(
144                'args' => array('int'),
145                'return' => 'array',
146                'Returns a struct about all recent changes since given timestamp.'
147            ), 'wiki.getRecentMediaChanges' => array(
148                'args' => array('int'),
149                'return' => 'array',
150                'Returns a struct about all recent media changes since given timestamp.'
151            ), 'wiki.aclCheck' => array(
152                'args' => array('string', 'string', 'array'),
153                'return' => 'int',
154                'doc' => 'Returns the permissions of a given wiki page. By default, for current user/groups'
155            ), 'wiki.putAttachment' => array(
156                'args' => array('string', 'file', 'array'),
157                'return' => 'array',
158                'doc' => 'Upload a file to the wiki.'
159            ), 'wiki.deleteAttachment' => array(
160                'args' => array('string'),
161                'return' => 'int',
162                'doc' => 'Delete a file from the wiki.'
163            ), 'wiki.getAttachment' => array(
164                'args' => array('string'),
165                'doc' => 'Return a media file',
166                'return' => 'file',
167                'name' => 'getAttachment',
168            ), 'wiki.getAttachmentInfo' => array(
169                'args' => array('string'),
170                'return' => 'array',
171                'doc' => 'Returns a struct with info about the attachment.'
172            ), 'dokuwiki.getXMLRPCAPIVersion' => array(
173                'args' => array(),
174                'name' => 'getAPIVersion',
175                'return' => 'int',
176                'doc' => 'Returns the XMLRPC API version.',
177                'public' => '1',
178            ), 'wiki.getRPCVersionSupported' => array(
179                'args' => array(),
180                'name' => 'wikiRpcVersion',
181                'return' => 'int',
182                'doc' => 'Returns 2 with the supported RPC API version.',
183                'public' => '1'
184            ),
185
186        );
187    }
188
189    /**
190     * @return string
191     */
192    public function getVersion()
193    {
194        return getVersion();
195    }
196
197    /**
198     * @return int unix timestamp
199     */
200    public function getTime()
201    {
202        return time();
203    }
204
205    /**
206     * Return a raw wiki page
207     *
208     * @param string $id wiki page id
209     * @param int|string $rev revision timestamp of the page or empty string
210     * @return string page text.
211     * @throws AccessDeniedException if no permission for page
212     */
213    public function rawPage($id, $rev = '')
214    {
215        $id = $this->resolvePageId($id);
216        if (auth_quickaclcheck($id) < AUTH_READ) {
217            throw new AccessDeniedException('You are not allowed to read this file', 111);
218        }
219        $text = rawWiki($id, $rev);
220        if (!$text) {
221            return pageTemplate($id);
222        } else {
223            return $text;
224        }
225    }
226
227    /**
228     * Return a media file
229     *
230     * @author Gina Haeussge <osd@foosel.net>
231     *
232     * @param string $id file id
233     * @return mixed media file
234     * @throws AccessDeniedException no permission for media
235     * @throws RemoteException not exist
236     */
237    public function getAttachment($id)
238    {
239        $id = cleanID($id);
240        if (auth_quickaclcheck(getNS($id) . ':*') < AUTH_READ) {
241            throw new AccessDeniedException('You are not allowed to read this file', 211);
242        }
243
244        $file = mediaFN($id);
245        if (!@ file_exists($file)) {
246            throw new RemoteException('The requested file does not exist', 221);
247        }
248
249        $data = io_readFile($file, false);
250        return $this->api->toFile($data);
251    }
252
253    /**
254     * Return info about a media file
255     *
256     * @author Gina Haeussge <osd@foosel.net>
257     *
258     * @param string $id page id
259     * @return array
260     */
261    public function getAttachmentInfo($id)
262    {
263        $id = cleanID($id);
264        $info = array(
265            'lastModified' => $this->api->toDate(0),
266            'size' => 0,
267        );
268
269        $file = mediaFN($id);
270        if (auth_quickaclcheck(getNS($id) . ':*') >= AUTH_READ) {
271            if (file_exists($file)) {
272                $info['lastModified'] = $this->api->toDate(filemtime($file));
273                $info['size'] = filesize($file);
274            } else {
275                //Is it deleted media with changelog?
276                $medialog = new MediaChangeLog($id);
277                $revisions = $medialog->getRevisions(0, 1);
278                if (!empty($revisions)) {
279                    $info['lastModified'] = $this->api->toDate($revisions[0]);
280                }
281            }
282        }
283
284        return $info;
285    }
286
287    /**
288     * Return a wiki page rendered to html
289     *
290     * @param string $id page id
291     * @param string|int $rev revision timestamp or empty string
292     * @return null|string html
293     * @throws AccessDeniedException no access to page
294     */
295    public function htmlPage($id, $rev = '')
296    {
297        $id = $this->resolvePageId($id);
298        if (auth_quickaclcheck($id) < AUTH_READ) {
299            throw new AccessDeniedException('You are not allowed to read this page', 111);
300        }
301        return p_wiki_xhtml($id, $rev, false);
302    }
303
304    /**
305     * List all pages - we use the indexer list here
306     *
307     * @return array
308     */
309    public function listPages()
310    {
311        $list = array();
312        $pages = idx_get_indexer()->getPages();
313        $pages = array_filter(array_filter($pages, 'isVisiblePage'), 'page_exists');
314
315        foreach (array_keys($pages) as $idx) {
316            $perm = auth_quickaclcheck($pages[$idx]);
317            if ($perm < AUTH_READ) {
318                continue;
319            }
320            $page = array();
321            $page['id'] = trim($pages[$idx]);
322            $page['perms'] = $perm;
323            $page['size'] = @filesize(wikiFN($pages[$idx]));
324            $page['lastModified'] = $this->api->toDate(@filemtime(wikiFN($pages[$idx])));
325            $list[] = $page;
326        }
327
328        return $list;
329    }
330
331    /**
332     * List all pages in the given namespace (and below)
333     *
334     * @param string $ns
335     * @param array $opts
336     *    $opts['depth']   recursion level, 0 for all
337     *    $opts['hash']    do md5 sum of content?
338     * @return array
339     */
340    public function readNamespace($ns, $opts)
341    {
342        global $conf;
343
344        if (!is_array($opts)) $opts = array();
345
346        $ns = cleanID($ns);
347        $dir = utf8_encodeFN(str_replace(':', '/', $ns));
348        $data = array();
349        $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
350        search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
351        return $data;
352    }
353
354    /**
355     * List all pages in the given namespace (and below)
356     *
357     * @param string $query
358     * @return array
359     */
360    public function search($query)
361    {
362        $regex = array();
363        $data = ft_pageSearch($query, $regex);
364        $pages = array();
365
366        // prepare additional data
367        $idx = 0;
368        foreach ($data as $id => $score) {
369            $file = wikiFN($id);
370
371            if ($idx < FT_SNIPPET_NUMBER) {
372                $snippet = ft_snippet($id, $regex);
373                $idx++;
374            } else {
375                $snippet = '';
376            }
377
378            $pages[] = array(
379                'id' => $id,
380                'score' => intval($score),
381                'rev' => filemtime($file),
382                'mtime' => filemtime($file),
383                'size' => filesize($file),
384                'snippet' => $snippet,
385                'title' => useHeading('navigation') ? p_get_first_heading($id) : $id
386            );
387        }
388        return $pages;
389    }
390
391    /**
392     * Returns the wiki title.
393     *
394     * @return string
395     */
396    public function getTitle()
397    {
398        global $conf;
399        return $conf['title'];
400    }
401
402    /**
403     * List all media files.
404     *
405     * Available options are 'recursive' for also including the subnamespaces
406     * in the listing, and 'pattern' for filtering the returned files against
407     * a regular expression matching their name.
408     *
409     * @author Gina Haeussge <osd@foosel.net>
410     *
411     * @param string $ns
412     * @param array $options
413     *   $options['depth']     recursion level, 0 for all
414     *   $options['showmsg']   shows message if invalid media id is used
415     *   $options['pattern']   check given pattern
416     *   $options['hash']      add hashes to result list
417     * @return array
418     * @throws AccessDeniedException no access to the media files
419     */
420    public function listAttachments($ns, $options = array())
421    {
422        global $conf;
423
424        $ns = cleanID($ns);
425
426        if (!is_array($options)) $options = array();
427        $options['skipacl'] = 0; // no ACL skipping for XMLRPC
428
429        if (auth_quickaclcheck($ns . ':*') >= AUTH_READ) {
430            $dir = utf8_encodeFN(str_replace(':', '/', $ns));
431
432            $data = array();
433            search($data, $conf['mediadir'], 'search_media', $options, $dir);
434            $len = count($data);
435            if (!$len) return array();
436
437            for ($i = 0; $i < $len; $i++) {
438                unset($data[$i]['meta']);
439                $data[$i]['perms'] = $data[$i]['perm'];
440                unset($data[$i]['perm']);
441                $data[$i]['lastModified'] = $this->api->toDate($data[$i]['mtime']);
442            }
443            return $data;
444        } else {
445            throw new AccessDeniedException('You are not allowed to list media files.', 215);
446        }
447    }
448
449    /**
450     * Return a list of backlinks
451     *
452     * @param string $id page id
453     * @return array
454     */
455    public function listBackLinks($id)
456    {
457        return ft_backlinks($this->resolvePageId($id));
458    }
459
460    /**
461     * Return some basic data about a page
462     *
463     * @param string $id page id
464     * @param string|int $rev revision timestamp or empty string
465     * @return array
466     * @throws AccessDeniedException no access for page
467     * @throws RemoteException page not exist
468     */
469    public function pageInfo($id, $rev = '')
470    {
471        $id = $this->resolvePageId($id);
472        if (auth_quickaclcheck($id) < AUTH_READ) {
473            throw new AccessDeniedException('You are not allowed to read this page', 111);
474        }
475        $file = wikiFN($id, $rev);
476        $time = @filemtime($file);
477        if (!$time) {
478            throw new RemoteException('The requested page does not exist', 121);
479        }
480
481        // set revision to current version if empty, use revision otherwise
482        // as the timestamps of old files are not necessarily correct
483        if ($rev === '') {
484            $rev = $time;
485        }
486
487        $pagelog = new PageChangeLog($id, 1024);
488        $info = $pagelog->getRevisionInfo($rev);
489
490        $data = array(
491            'name' => $id,
492            'lastModified' => $this->api->toDate($rev),
493            'author' => (($info['user']) ? $info['user'] : $info['ip']),
494            'version' => $rev
495        );
496
497        return ($data);
498    }
499
500    /**
501     * Save a wiki page
502     *
503     * @author Michael Klier <chi@chimeric.de>
504     *
505     * @param string $id page id
506     * @param string $text wiki text
507     * @param array $params parameters: summary, minor edit
508     * @return bool
509     * @throws AccessDeniedException no write access for page
510     * @throws RemoteException no id, empty new page or locked
511     */
512    public function putPage($id, $text, $params)
513    {
514        global $TEXT;
515        global $lang;
516
517        $id = $this->resolvePageId($id);
518        $TEXT = cleanText($text);
519        $sum = $params['sum'];
520        $minor = $params['minor'];
521
522        if (empty($id)) {
523            throw new RemoteException('Empty page ID', 131);
524        }
525
526        if (!page_exists($id) && trim($TEXT) == '') {
527            throw new RemoteException('Refusing to write an empty new wiki page', 132);
528        }
529
530        if (auth_quickaclcheck($id) < AUTH_EDIT) {
531            throw new AccessDeniedException('You are not allowed to edit this page', 112);
532        }
533
534        // Check, if page is locked
535        if (checklock($id)) {
536            throw new RemoteException('The page is currently locked', 133);
537        }
538
539        // SPAM check
540        if (checkwordblock()) {
541            throw new RemoteException('Positive wordblock check', 134);
542        }
543
544        // autoset summary on new pages
545        if (!page_exists($id) && empty($sum)) {
546            $sum = $lang['created'];
547        }
548
549        // autoset summary on deleted pages
550        if (page_exists($id) && empty($TEXT) && empty($sum)) {
551            $sum = $lang['deleted'];
552        }
553
554        lock($id);
555
556        saveWikiText($id, $TEXT, $sum, $minor);
557
558        unlock($id);
559
560        // run the indexer if page wasn't indexed yet
561        idx_addPage($id);
562
563        return true;
564    }
565
566    /**
567     * Appends text to a wiki page.
568     *
569     * @param string $id page id
570     * @param string $text wiki text
571     * @param array $params such as summary,minor
572     * @return bool|string
573     * @throws RemoteException
574     */
575    public function appendPage($id, $text, $params)
576    {
577        $currentpage = $this->rawPage($id);
578        if (!is_string($currentpage)) {
579            return $currentpage;
580        }
581        return $this->putPage($id, $currentpage . $text, $params);
582    }
583
584    /**
585     * Remove one or more users from the list of registered users
586     *
587     * @param string[] $usernames List of usernames to remove
588     *
589     * @return bool
590     *
591     * @throws AccessDeniedException
592     */
593    public function deleteUsers($usernames)
594    {
595        if (!auth_isadmin()) {
596            throw new AccessDeniedException('Only admins are allowed to delete users', 114);
597        }
598        /** @var \dokuwiki\Plugin\\dokuwiki\Extension\AuthPlugin $auth */
599        global $auth;
600        return (bool)$auth->triggerUserMod('delete', array($usernames));
601    }
602
603    /**
604     * Uploads a file to the wiki.
605     *
606     * Michael Klier <chi@chimeric.de>
607     *
608     * @param string $id page id
609     * @param string $file
610     * @param array $params such as overwrite
611     * @return false|string
612     * @throws RemoteException
613     */
614    public function putAttachment($id, $file, $params)
615    {
616        $id = cleanID($id);
617        $auth = auth_quickaclcheck(getNS($id) . ':*');
618
619        if (!isset($id)) {
620            throw new RemoteException('Filename not given.', 231);
621        }
622
623        global $conf;
624
625        $ftmp = $conf['tmpdir'] . '/' . md5($id . clientIP());
626
627        // save temporary file
628        @unlink($ftmp);
629        io_saveFile($ftmp, $file);
630
631        $res = media_save(array('name' => $ftmp), $id, $params['ow'], $auth, 'rename');
632        if (is_array($res)) {
633            throw new RemoteException($res[0], -$res[1]);
634        } else {
635            return $res;
636        }
637    }
638
639    /**
640     * Deletes a file from the wiki.
641     *
642     * @author Gina Haeussge <osd@foosel.net>
643     *
644     * @param string $id page id
645     * @return int
646     * @throws AccessDeniedException no permissions
647     * @throws RemoteException file in use or not deleted
648     */
649    public function deleteAttachment($id)
650    {
651        $id = cleanID($id);
652        $auth = auth_quickaclcheck(getNS($id) . ':*');
653        $res = media_delete($id, $auth);
654        if ($res & DOKU_MEDIA_DELETED) {
655            return 0;
656        } elseif ($res & DOKU_MEDIA_NOT_AUTH) {
657            throw new AccessDeniedException('You don\'t have permissions to delete files.', 212);
658        } elseif ($res & DOKU_MEDIA_INUSE) {
659            throw new RemoteException('File is still referenced', 232);
660        } else {
661            throw new RemoteException('Could not delete file', 233);
662        }
663    }
664
665    /**
666     * Returns the permissions of a given wiki page for the current user or another user
667     *
668     * @param string $id page id
669     * @param string|null $user username
670     * @param array|null $groups array of groups
671     * @return int permission level
672     */
673    public function aclCheck($id, $user = null, $groups = null)
674    {
675        /** @var \dokuwiki\Plugin\\dokuwiki\Extension\AuthPlugin $auth */
676        global $auth;
677
678        $id = $this->resolvePageId($id);
679        if ($user === null) {
680            return auth_quickaclcheck($id);
681        } else {
682            if ($groups === null) {
683                $userinfo = $auth->getUserData($user);
684                if ($userinfo === false) {
685                    $groups = array();
686                } else {
687                    $groups = $userinfo['grps'];
688                }
689            }
690            return auth_aclcheck($id, $user, $groups);
691        }
692    }
693
694    /**
695     * Lists all links contained in a wiki page
696     *
697     * @author Michael Klier <chi@chimeric.de>
698     *
699     * @param string $id page id
700     * @return array
701     * @throws AccessDeniedException  no read access for page
702     */
703    public function listLinks($id)
704    {
705        $id = $this->resolvePageId($id);
706        if (auth_quickaclcheck($id) < AUTH_READ) {
707            throw new AccessDeniedException('You are not allowed to read this page', 111);
708        }
709        $links = array();
710
711        // resolve page instructions
712        $ins = p_cached_instructions(wikiFN($id));
713
714        // instantiate new Renderer - needed for interwiki links
715        $Renderer = new Doku_Renderer_xhtml();
716        $Renderer->interwiki = getInterwiki();
717
718        // parse parse instructions
719        foreach ($ins as $in) {
720            $link = array();
721            switch ($in[0]) {
722                case 'internallink':
723                    $link['type'] = 'local';
724                    $link['page'] = $in[1][0];
725                    $link['href'] = wl($in[1][0]);
726                    array_push($links, $link);
727                    break;
728                case 'externallink':
729                    $link['type'] = 'extern';
730                    $link['page'] = $in[1][0];
731                    $link['href'] = $in[1][0];
732                    array_push($links, $link);
733                    break;
734                case 'interwikilink':
735                    $url = $Renderer->_resolveInterWiki($in[1][2], $in[1][3]);
736                    $link['type'] = 'extern';
737                    $link['page'] = $url;
738                    $link['href'] = $url;
739                    array_push($links, $link);
740                    break;
741            }
742        }
743
744        return ($links);
745    }
746
747    /**
748     * Returns a list of recent changes since give timestamp
749     *
750     * @author Michael Hamann <michael@content-space.de>
751     * @author Michael Klier <chi@chimeric.de>
752     *
753     * @param int $timestamp unix timestamp
754     * @return array
755     * @throws RemoteException no valid timestamp
756     */
757    public function getRecentChanges($timestamp)
758    {
759        if (strlen($timestamp) != 10) {
760            throw new RemoteException('The provided value is not a valid timestamp', 311);
761        }
762
763        $recents = getRecentsSince($timestamp);
764
765        $changes = array();
766
767        foreach ($recents as $recent) {
768            $change = array();
769            $change['name'] = $recent['id'];
770            $change['lastModified'] = $this->api->toDate($recent['date']);
771            $change['author'] = $recent['user'];
772            $change['version'] = $recent['date'];
773            $change['perms'] = $recent['perms'];
774            $change['size'] = @filesize(wikiFN($recent['id']));
775            array_push($changes, $change);
776        }
777
778        if (!empty($changes)) {
779            return $changes;
780        } else {
781            // in case we still have nothing at this point
782            throw new RemoteException('There are no changes in the specified timeframe', 321);
783        }
784    }
785
786    /**
787     * Returns a list of recent media changes since give timestamp
788     *
789     * @author Michael Hamann <michael@content-space.de>
790     * @author Michael Klier <chi@chimeric.de>
791     *
792     * @param int $timestamp unix timestamp
793     * @return array
794     * @throws RemoteException no valid timestamp
795     */
796    public function getRecentMediaChanges($timestamp)
797    {
798        if (strlen($timestamp) != 10)
799            throw new RemoteException('The provided value is not a valid timestamp', 311);
800
801        $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES);
802
803        $changes = array();
804
805        foreach ($recents as $recent) {
806            $change = array();
807            $change['name'] = $recent['id'];
808            $change['lastModified'] = $this->api->toDate($recent['date']);
809            $change['author'] = $recent['user'];
810            $change['version'] = $recent['date'];
811            $change['perms'] = $recent['perms'];
812            $change['size'] = @filesize(mediaFN($recent['id']));
813            array_push($changes, $change);
814        }
815
816        if (!empty($changes)) {
817            return $changes;
818        } else {
819            // in case we still have nothing at this point
820            throw new RemoteException('There are no changes in the specified timeframe', 321);
821        }
822    }
823
824    /**
825     * Returns a list of available revisions of a given wiki page
826     * Number of returned pages is set by $conf['recent']
827     * However not accessible pages are skipped, so less than $conf['recent'] could be returned
828     *
829     * @author Michael Klier <chi@chimeric.de>
830     *
831     * @param string $id page id
832     * @param int $first skip the first n changelog lines
833     *                      0 = from current(if exists)
834     *                      1 = from 1st old rev
835     *                      2 = from 2nd old rev, etc
836     * @return array
837     * @throws AccessDeniedException no read access for page
838     * @throws RemoteException empty id
839     */
840    public function pageVersions($id, $first)
841    {
842        $id = $this->resolvePageId($id);
843        if (auth_quickaclcheck($id) < AUTH_READ) {
844            throw new AccessDeniedException('You are not allowed to read this page', 111);
845        }
846        global $conf;
847
848        $versions = array();
849
850        if (empty($id)) {
851            throw new RemoteException('Empty page ID', 131);
852        }
853
854        $first = (int) $first;
855        $first_rev = $first - 1;
856        $first_rev = $first_rev < 0 ? 0 : $first_rev;
857        $pagelog = new PageChangeLog($id);
858        $revisions = $pagelog->getRevisions($first_rev, $conf['recent']);
859
860        if ($first == 0) {
861            array_unshift($revisions, '');  // include current revision
862            if (count($revisions) > $conf['recent']) {
863                array_pop($revisions);          // remove extra log entry
864            }
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                    $pagelog->setChunkSize(1024);
876                    $info = $pagelog->getRevisionInfo($rev ? $rev : $time);
877                    if (!empty($info)) {
878                        $data = array();
879                        $data['user'] = $info['user'];
880                        $data['ip'] = $info['ip'];
881                        $data['type'] = $info['type'];
882                        $data['sum'] = $info['sum'];
883                        $data['modified'] = $this->api->toDate($info['date']);
884                        $data['version'] = $info['date'];
885                        array_push($versions, $data);
886                    }
887                }
888            }
889            return $versions;
890        } else {
891            return array();
892        }
893    }
894
895    /**
896     * The version of Wiki RPC API supported
897     */
898    public function wikiRpcVersion()
899    {
900        return 2;
901    }
902
903    /**
904     * Locks or unlocks a given batch of pages
905     *
906     * Give an associative array with two keys: lock and unlock. Both should contain a
907     * list of pages to lock or unlock
908     *
909     * Returns an associative array with the keys locked, lockfail, unlocked and
910     * unlockfail, each containing lists of pages.
911     *
912     * @param array[] $set list pages with array('lock' => array, 'unlock' => array)
913     * @return array
914     */
915    public function setLocks($set)
916    {
917        $locked = array();
918        $lockfail = array();
919        $unlocked = array();
920        $unlockfail = array();
921
922        foreach ((array) $set['lock'] as $id) {
923            $id = $this->resolvePageId($id);
924            if (auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)) {
925                $lockfail[] = $id;
926            } else {
927                lock($id);
928                $locked[] = $id;
929            }
930        }
931
932        foreach ((array) $set['unlock'] as $id) {
933            $id = $this->resolvePageId($id);
934            if (auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)) {
935                $unlockfail[] = $id;
936            } else {
937                $unlocked[] = $id;
938            }
939        }
940
941        return array(
942            'locked' => $locked,
943            'lockfail' => $lockfail,
944            'unlocked' => $unlocked,
945            'unlockfail' => $unlockfail,
946        );
947    }
948
949    /**
950     * Return API version
951     *
952     * @return int
953     */
954    public function getAPIVersion()
955    {
956        return self::API_VERSION;
957    }
958
959    /**
960     * Login
961     *
962     * @param string $user
963     * @param string $pass
964     * @return int
965     */
966    public function login($user, $pass)
967    {
968        global $conf;
969        /** @var \dokuwiki\Plugin\\dokuwiki\Extension\AuthPlugin $auth */
970        global $auth;
971
972        if (!$conf['useacl']) return 0;
973        if (!$auth) return 0;
974
975        @session_start(); // reopen session for login
976        if ($auth->canDo('external')) {
977            $ok = $auth->trustExternal($user, $pass, false);
978        } else {
979            $evdata = array(
980                'user' => $user,
981                'password' => $pass,
982                'sticky' => false,
983                'silent' => true,
984            );
985            $ok = Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
986        }
987        session_write_close(); // we're done with the session
988
989        return $ok;
990    }
991
992    /**
993     * Log off
994     *
995     * @return int
996     */
997    public function logoff()
998    {
999        global $conf;
1000        global $auth;
1001        if (!$conf['useacl']) return 0;
1002        if (!$auth) return 0;
1003
1004        auth_logoff();
1005
1006        return 1;
1007    }
1008
1009    /**
1010     * Resolve page id
1011     *
1012     * @param string $id page id
1013     * @return string
1014     */
1015    private function resolvePageId($id)
1016    {
1017        $id = cleanID($id);
1018        if (empty($id)) {
1019            global $conf;
1020            $id = cleanID($conf['start']);
1021        }
1022        return $id;
1023    }
1024}
1025