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