xref: /dokuwiki/inc/Remote/ApiCore.php (revision 3f4a342befbede62946481d36e02a2a7b211c309)
1<?php
2
3namespace dokuwiki\Remote;
4use dokuwiki\Search\PageIndex;
5
6use Doku_Renderer_xhtml;
7use dokuwiki\ChangeLog\MediaChangeLog;
8use dokuwiki\ChangeLog\PageChangeLog;
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
313        $Indexer = PageIndex::getInstance();
314        $pages = $Indexer->getPages();
315        $pages = array_filter(array_filter($pages, 'isVisiblePage'), 'page_exists');
316
317        foreach (array_keys($pages) as $idx) {
318            $perm = auth_quickaclcheck($pages[$idx]);
319            if ($perm < AUTH_READ) {
320                continue;
321            }
322            $page = array();
323            $page['id'] = trim($pages[$idx]);
324            $page['perms'] = $perm;
325            $page['size'] = @filesize(wikiFN($pages[$idx]));
326            $page['lastModified'] = $this->api->toDate(@filemtime(wikiFN($pages[$idx])));
327            $list[] = $page;
328        }
329
330        return $list;
331    }
332
333    /**
334     * List all pages in the given namespace (and below)
335     *
336     * @param string $ns
337     * @param array $opts
338     *    $opts['depth']   recursion level, 0 for all
339     *    $opts['hash']    do md5 sum of content?
340     * @return array
341     */
342    public function readNamespace($ns, $opts)
343    {
344        global $conf;
345
346        if (!is_array($opts)) $opts = array();
347
348        $ns = cleanID($ns);
349        $dir = utf8_encodeFN(str_replace(':', '/', $ns));
350        $data = array();
351        $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
352        search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
353        return $data;
354    }
355
356    /**
357     * List all pages in the given namespace (and below)
358     *
359     * @param string $query
360     * @return array
361     */
362    public function search($query)
363    {
364        $regex = array();
365        $data = ft_pageSearch($query, $regex);
366        $pages = array();
367
368        // prepare additional data
369        $idx = 0;
370        foreach ($data as $id => $score) {
371            $file = wikiFN($id);
372
373            if ($idx < FT_SNIPPET_NUMBER) {
374                $snippet = ft_snippet($id, $regex);
375                $idx++;
376            } else {
377                $snippet = '';
378            }
379
380            $pages[] = array(
381                'id' => $id,
382                'score' => intval($score),
383                'rev' => filemtime($file),
384                'mtime' => filemtime($file),
385                'size' => filesize($file),
386                'snippet' => $snippet,
387                'title' => useHeading('navigation') ? p_get_first_heading($id) : $id
388            );
389        }
390        return $pages;
391    }
392
393    /**
394     * Returns the wiki title.
395     *
396     * @return string
397     */
398    public function getTitle()
399    {
400        global $conf;
401        return $conf['title'];
402    }
403
404    /**
405     * List all media files.
406     *
407     * Available options are 'recursive' for also including the subnamespaces
408     * in the listing, and 'pattern' for filtering the returned files against
409     * a regular expression matching their name.
410     *
411     * @author Gina Haeussge <osd@foosel.net>
412     *
413     * @param string $ns
414     * @param array $options
415     *   $options['depth']     recursion level, 0 for all
416     *   $options['showmsg']   shows message if invalid media id is used
417     *   $options['pattern']   check given pattern
418     *   $options['hash']      add hashes to result list
419     * @return array
420     * @throws AccessDeniedException no access to the media files
421     */
422    public function listAttachments($ns, $options = array())
423    {
424        global $conf;
425
426        $ns = cleanID($ns);
427
428        if (!is_array($options)) $options = array();
429        $options['skipacl'] = 0; // no ACL skipping for XMLRPC
430
431        if (auth_quickaclcheck($ns . ':*') >= AUTH_READ) {
432            $dir = utf8_encodeFN(str_replace(':', '/', $ns));
433
434            $data = array();
435            search($data, $conf['mediadir'], 'search_media', $options, $dir);
436            $len = count($data);
437            if (!$len) return array();
438
439            for ($i = 0; $i < $len; $i++) {
440                unset($data[$i]['meta']);
441                $data[$i]['perms'] = $data[$i]['perm'];
442                unset($data[$i]['perm']);
443                $data[$i]['lastModified'] = $this->api->toDate($data[$i]['mtime']);
444            }
445            return $data;
446        } else {
447            throw new AccessDeniedException('You are not allowed to list media files.', 215);
448        }
449    }
450
451    /**
452     * Return a list of backlinks
453     *
454     * @param string $id page id
455     * @return array
456     */
457    public function listBackLinks($id)
458    {
459        return ft_backlinks($this->resolvePageId($id));
460    }
461
462    /**
463     * Return some basic data about a page
464     *
465     * @param string $id page id
466     * @param string|int $rev revision timestamp or empty string
467     * @return array
468     * @throws AccessDeniedException no access for page
469     * @throws RemoteException page not exist
470     */
471    public function pageInfo($id, $rev = '')
472    {
473        $id = $this->resolvePageId($id);
474        if (auth_quickaclcheck($id) < AUTH_READ) {
475            throw new AccessDeniedException('You are not allowed to read this page', 111);
476        }
477        $file = wikiFN($id, $rev);
478        $time = @filemtime($file);
479        if (!$time) {
480            throw new RemoteException('The requested page does not exist', 121);
481        }
482
483        // set revision to current version if empty, use revision otherwise
484        // as the timestamps of old files are not necessarily correct
485        if ($rev === '') {
486            $rev = $time;
487        }
488
489        $pagelog = new PageChangeLog($id, 1024);
490        $info = $pagelog->getRevisionInfo($rev);
491
492        $data = array(
493            'name' => $id,
494            'lastModified' => $this->api->toDate($rev),
495            'author' => (($info['user']) ? $info['user'] : $info['ip']),
496            'version' => $rev
497        );
498
499        return ($data);
500    }
501
502    /**
503     * Save a wiki page
504     *
505     * @author Michael Klier <chi@chimeric.de>
506     *
507     * @param string $id page id
508     * @param string $text wiki text
509     * @param array $params parameters: summary, minor edit
510     * @return bool
511     * @throws AccessDeniedException no write access for page
512     * @throws RemoteException no id, empty new page or locked
513     */
514    public function putPage($id, $text, $params)
515    {
516        global $TEXT;
517        global $lang;
518
519        $id = $this->resolvePageId($id);
520        $TEXT = cleanText($text);
521        $sum = $params['sum'];
522        $minor = $params['minor'];
523
524        if (empty($id)) {
525            throw new RemoteException('Empty page ID', 131);
526        }
527
528        if (!page_exists($id) && trim($TEXT) == '') {
529            throw new RemoteException('Refusing to write an empty new wiki page', 132);
530        }
531
532        if (auth_quickaclcheck($id) < AUTH_EDIT) {
533            throw new AccessDeniedException('You are not allowed to edit this page', 112);
534        }
535
536        // Check, if page is locked
537        if (checklock($id)) {
538            throw new RemoteException('The page is currently locked', 133);
539        }
540
541        // SPAM check
542        if (checkwordblock()) {
543            throw new RemoteException('Positive wordblock check', 134);
544        }
545
546        // autoset summary on new pages
547        if (!page_exists($id) && empty($sum)) {
548            $sum = $lang['created'];
549        }
550
551        // autoset summary on deleted pages
552        if (page_exists($id) && empty($TEXT) && empty($sum)) {
553            $sum = $lang['deleted'];
554        }
555
556        lock($id);
557
558        saveWikiText($id, $TEXT, $sum, $minor);
559
560        unlock($id);
561
562        // run the indexer if page wasn't indexed yet
563        idx_addPage($id);
564
565        return true;
566    }
567
568    /**
569     * Appends text to a wiki page.
570     *
571     * @param string $id page id
572     * @param string $text wiki text
573     * @param array $params such as summary,minor
574     * @return bool|string
575     * @throws RemoteException
576     */
577    public function appendPage($id, $text, $params)
578    {
579        $currentpage = $this->rawPage($id);
580        if (!is_string($currentpage)) {
581            return $currentpage;
582        }
583        return $this->putPage($id, $currentpage . $text, $params);
584    }
585
586    /**
587     * Remove one or more users from the list of registered users
588     *
589     * @param string[] $usernames List of usernames to remove
590     *
591     * @return bool
592     *
593     * @throws AccessDeniedException
594     */
595    public function deleteUsers($usernames)
596    {
597        if (!auth_isadmin()) {
598            throw new AccessDeniedException('Only admins are allowed to delete users', 114);
599        }
600        /** @var \dokuwiki\Extension\AuthPlugin $auth */
601        global $auth;
602        return (bool)$auth->triggerUserMod('delete', array($usernames));
603    }
604
605    /**
606     * Uploads a file to the wiki.
607     *
608     * Michael Klier <chi@chimeric.de>
609     *
610     * @param string $id page id
611     * @param string $file
612     * @param array $params such as overwrite
613     * @return false|string
614     * @throws RemoteException
615     */
616    public function putAttachment($id, $file, $params)
617    {
618        $id = cleanID($id);
619        $auth = auth_quickaclcheck(getNS($id) . ':*');
620
621        if (!isset($id)) {
622            throw new RemoteException('Filename not given.', 231);
623        }
624
625        global $conf;
626
627        $ftmp = $conf['tmpdir'] . '/' . md5($id . clientIP());
628
629        // save temporary file
630        @unlink($ftmp);
631        io_saveFile($ftmp, $file);
632
633        $res = media_save(array('name' => $ftmp), $id, $params['ow'], $auth, 'rename');
634        if (is_array($res)) {
635            throw new RemoteException($res[0], -$res[1]);
636        } else {
637            return $res;
638        }
639    }
640
641    /**
642     * Deletes a file from the wiki.
643     *
644     * @author Gina Haeussge <osd@foosel.net>
645     *
646     * @param string $id page id
647     * @return int
648     * @throws AccessDeniedException no permissions
649     * @throws RemoteException file in use or not deleted
650     */
651    public function deleteAttachment($id)
652    {
653        $id = cleanID($id);
654        $auth = auth_quickaclcheck(getNS($id) . ':*');
655        $res = media_delete($id, $auth);
656        if ($res & DOKU_MEDIA_DELETED) {
657            return 0;
658        } elseif ($res & DOKU_MEDIA_NOT_AUTH) {
659            throw new AccessDeniedException('You don\'t have permissions to delete files.', 212);
660        } elseif ($res & DOKU_MEDIA_INUSE) {
661            throw new RemoteException('File is still referenced', 232);
662        } else {
663            throw new RemoteException('Could not delete file', 233);
664        }
665    }
666
667    /**
668     * Returns the permissions of a given wiki page for the current user or another user
669     *
670     * @param string $id page id
671     * @param string|null $user username
672     * @param array|null $groups array of groups
673     * @return int permission level
674     */
675    public function aclCheck($id, $user = null, $groups = null)
676    {
677        /** @var \dokuwiki\Extension\AuthPlugin $auth */
678        global $auth;
679
680        $id = $this->resolvePageId($id);
681        if ($user === null) {
682            return auth_quickaclcheck($id);
683        } else {
684            if ($groups === null) {
685                $userinfo = $auth->getUserData($user);
686                if ($userinfo === false) {
687                    $groups = array();
688                } else {
689                    $groups = $userinfo['grps'];
690                }
691            }
692            return auth_aclcheck($id, $user, $groups);
693        }
694    }
695
696    /**
697     * Lists all links contained in a wiki page
698     *
699     * @author Michael Klier <chi@chimeric.de>
700     *
701     * @param string $id page id
702     * @return array
703     * @throws AccessDeniedException  no read access for page
704     */
705    public function listLinks($id)
706    {
707        $id = $this->resolvePageId($id);
708        if (auth_quickaclcheck($id) < AUTH_READ) {
709            throw new AccessDeniedException('You are not allowed to read this page', 111);
710        }
711        $links = array();
712
713        // resolve page instructions
714        $ins = p_cached_instructions(wikiFN($id));
715
716        // instantiate new Renderer - needed for interwiki links
717        $Renderer = new Doku_Renderer_xhtml();
718        $Renderer->interwiki = getInterwiki();
719
720        // parse parse instructions
721        foreach ($ins as $in) {
722            $link = array();
723            switch ($in[0]) {
724                case 'internallink':
725                    $link['type'] = 'local';
726                    $link['page'] = $in[1][0];
727                    $link['href'] = wl($in[1][0]);
728                    array_push($links, $link);
729                    break;
730                case 'externallink':
731                    $link['type'] = 'extern';
732                    $link['page'] = $in[1][0];
733                    $link['href'] = $in[1][0];
734                    array_push($links, $link);
735                    break;
736                case 'interwikilink':
737                    $url = $Renderer->_resolveInterWiki($in[1][2], $in[1][3]);
738                    $link['type'] = 'extern';
739                    $link['page'] = $url;
740                    $link['href'] = $url;
741                    array_push($links, $link);
742                    break;
743            }
744        }
745
746        return ($links);
747    }
748
749    /**
750     * Returns a list of recent changes since give timestamp
751     *
752     * @author Michael Hamann <michael@content-space.de>
753     * @author Michael Klier <chi@chimeric.de>
754     *
755     * @param int $timestamp unix timestamp
756     * @return array
757     * @throws RemoteException no valid timestamp
758     */
759    public function getRecentChanges($timestamp)
760    {
761        if (strlen($timestamp) != 10) {
762            throw new RemoteException('The provided value is not a valid timestamp', 311);
763        }
764
765        $recents = getRecentsSince($timestamp);
766
767        $changes = array();
768
769        foreach ($recents as $recent) {
770            $change = array();
771            $change['name'] = $recent['id'];
772            $change['lastModified'] = $this->api->toDate($recent['date']);
773            $change['author'] = $recent['user'];
774            $change['version'] = $recent['date'];
775            $change['perms'] = $recent['perms'];
776            $change['size'] = @filesize(wikiFN($recent['id']));
777            array_push($changes, $change);
778        }
779
780        if (!empty($changes)) {
781            return $changes;
782        } else {
783            // in case we still have nothing at this point
784            throw new RemoteException('There are no changes in the specified timeframe', 321);
785        }
786    }
787
788    /**
789     * Returns a list of recent media changes since give timestamp
790     *
791     * @author Michael Hamann <michael@content-space.de>
792     * @author Michael Klier <chi@chimeric.de>
793     *
794     * @param int $timestamp unix timestamp
795     * @return array
796     * @throws RemoteException no valid timestamp
797     */
798    public function getRecentMediaChanges($timestamp)
799    {
800        if (strlen($timestamp) != 10)
801            throw new RemoteException('The provided value is not a valid timestamp', 311);
802
803        $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES);
804
805        $changes = array();
806
807        foreach ($recents as $recent) {
808            $change = array();
809            $change['name'] = $recent['id'];
810            $change['lastModified'] = $this->api->toDate($recent['date']);
811            $change['author'] = $recent['user'];
812            $change['version'] = $recent['date'];
813            $change['perms'] = $recent['perms'];
814            $change['size'] = @filesize(mediaFN($recent['id']));
815            array_push($changes, $change);
816        }
817
818        if (!empty($changes)) {
819            return $changes;
820        } else {
821            // in case we still have nothing at this point
822            throw new RemoteException('There are no changes in the specified timeframe', 321);
823        }
824    }
825
826    /**
827     * Returns a list of available revisions of a given wiki page
828     * Number of returned pages is set by $conf['recent']
829     * However not accessible pages are skipped, so less than $conf['recent'] could be returned
830     *
831     * @author Michael Klier <chi@chimeric.de>
832     *
833     * @param string $id page id
834     * @param int $first skip the first n changelog lines
835     *                      0 = from current(if exists)
836     *                      1 = from 1st old rev
837     *                      2 = from 2nd old rev, etc
838     * @return array
839     * @throws AccessDeniedException no read access for page
840     * @throws RemoteException empty id
841     */
842    public function pageVersions($id, $first)
843    {
844        $id = $this->resolvePageId($id);
845        if (auth_quickaclcheck($id) < AUTH_READ) {
846            throw new AccessDeniedException('You are not allowed to read this page', 111);
847        }
848        global $conf;
849
850        $versions = array();
851
852        if (empty($id)) {
853            throw new RemoteException('Empty page ID', 131);
854        }
855
856        $first = (int) $first;
857        $first_rev = $first - 1;
858        $first_rev = $first_rev < 0 ? 0 : $first_rev;
859        $pagelog = new PageChangeLog($id);
860        $revisions = $pagelog->getRevisions($first_rev, $conf['recent']);
861
862        if ($first == 0) {
863            array_unshift($revisions, '');  // include current revision
864            if (count($revisions) > $conf['recent']) {
865                array_pop($revisions);          // remove extra log entry
866            }
867        }
868
869        if (!empty($revisions)) {
870            foreach ($revisions as $rev) {
871                $file = wikiFN($id, $rev);
872                $time = @filemtime($file);
873                // we check if the page actually exists, if this is not the
874                // case this can lead to less pages being returned than
875                // specified via $conf['recent']
876                if ($time) {
877                    $pagelog->setChunkSize(1024);
878                    $info = $pagelog->getRevisionInfo($rev ? $rev : $time);
879                    if (!empty($info)) {
880                        $data = array();
881                        $data['user'] = $info['user'];
882                        $data['ip'] = $info['ip'];
883                        $data['type'] = $info['type'];
884                        $data['sum'] = $info['sum'];
885                        $data['modified'] = $this->api->toDate($info['date']);
886                        $data['version'] = $info['date'];
887                        array_push($versions, $data);
888                    }
889                }
890            }
891            return $versions;
892        } else {
893            return array();
894        }
895    }
896
897    /**
898     * The version of Wiki RPC API supported
899     */
900    public function wikiRpcVersion()
901    {
902        return 2;
903    }
904
905    /**
906     * Locks or unlocks a given batch of pages
907     *
908     * Give an associative array with two keys: lock and unlock. Both should contain a
909     * list of pages to lock or unlock
910     *
911     * Returns an associative array with the keys locked, lockfail, unlocked and
912     * unlockfail, each containing lists of pages.
913     *
914     * @param array[] $set list pages with array('lock' => array, 'unlock' => array)
915     * @return array
916     */
917    public function setLocks($set)
918    {
919        $locked = array();
920        $lockfail = array();
921        $unlocked = array();
922        $unlockfail = array();
923
924        foreach ((array) $set['lock'] as $id) {
925            $id = $this->resolvePageId($id);
926            if (auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)) {
927                $lockfail[] = $id;
928            } else {
929                lock($id);
930                $locked[] = $id;
931            }
932        }
933
934        foreach ((array) $set['unlock'] as $id) {
935            $id = $this->resolvePageId($id);
936            if (auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)) {
937                $unlockfail[] = $id;
938            } else {
939                $unlocked[] = $id;
940            }
941        }
942
943        return array(
944            'locked' => $locked,
945            'lockfail' => $lockfail,
946            'unlocked' => $unlocked,
947            'unlockfail' => $unlockfail,
948        );
949    }
950
951    /**
952     * Return API version
953     *
954     * @return int
955     */
956    public function getAPIVersion()
957    {
958        return self::API_VERSION;
959    }
960
961    /**
962     * Login
963     *
964     * @param string $user
965     * @param string $pass
966     * @return int
967     */
968    public function login($user, $pass)
969    {
970        global $conf;
971        /** @var \dokuwiki\Extension\AuthPlugin $auth */
972        global $auth;
973
974        if (!$conf['useacl']) return 0;
975        if (!$auth) return 0;
976
977        @session_start(); // reopen session for login
978        if ($auth->canDo('external')) {
979            $ok = $auth->trustExternal($user, $pass, false);
980        } else {
981            $evdata = array(
982                'user' => $user,
983                'password' => $pass,
984                'sticky' => false,
985                'silent' => true,
986            );
987            $ok = Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
988        }
989        session_write_close(); // we're done with the session
990
991        return $ok;
992    }
993
994    /**
995     * Log off
996     *
997     * @return int
998     */
999    public function logoff()
1000    {
1001        global $conf;
1002        global $auth;
1003        if (!$conf['useacl']) return 0;
1004        if (!$auth) return 0;
1005
1006        auth_logoff();
1007
1008        return 1;
1009    }
1010
1011    /**
1012     * Resolve page id
1013     *
1014     * @param string $id page id
1015     * @return string
1016     */
1017    private function resolvePageId($id)
1018    {
1019        $id = cleanID($id);
1020        if (empty($id)) {
1021            global $conf;
1022            $id = cleanID($conf['start']);
1023        }
1024        return $id;
1025    }
1026}
1027