xref: /dokuwiki/inc/Remote/ApiCore.php (revision 7fcedc39d164da3013a88e9ad6660009940e851b)
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;
12use dokuwiki\Utf8\Sort;
13
14use const dokuwiki\Search\FT_SNIPPET_NUMBER;
15
16define('DOKU_API_VERSION', 10);
17
18/**
19 * Provides the core methods for the remote API.
20 * The methods are ordered in 'wiki.<method>' and 'dokuwiki.<method>' namespaces
21 */
22class ApiCore
23{
24    /** @var int Increased whenever the API is changed */
25    const API_VERSION = 10;
26
27
28    /** @var Api */
29    private $api;
30
31    /**
32     * @param Api $api
33     */
34    public function __construct(Api $api)
35    {
36        $this->api = $api;
37    }
38
39    /**
40     * Returns details about the core methods
41     *
42     * @return array
43     */
44    public function getRemoteInfo()
45    {
46        return array(
47            'dokuwiki.getVersion' => array(
48                'args' => array(),
49                'return' => 'string',
50                'doc' => 'Returns the running DokuWiki version.'
51            ), 'dokuwiki.login' => array(
52                'args' => array('string', 'string'),
53                'return' => 'int',
54                'doc' => 'Tries to login with the given credentials and sets auth cookies.',
55                'public' => '1'
56            ), 'dokuwiki.logoff' => array(
57                'args' => array(),
58                'return' => 'int',
59                'doc' => 'Tries to logoff by expiring auth cookies and the associated PHP session.'
60            ), 'dokuwiki.getPagelist' => array(
61                'args' => array('string', 'array'),
62                'return' => 'array',
63                'doc' => 'List all pages within the given namespace.',
64                'name' => 'readNamespace'
65            ), 'dokuwiki.search' => array(
66                'args' => array('string'),
67                'return' => 'array',
68                'doc' => 'Perform a fulltext search and return a list of matching pages'
69            ), 'dokuwiki.getTime' => array(
70                'args' => array(),
71                'return' => 'int',
72                'doc' => 'Returns the current time at the remote wiki server as Unix timestamp.',
73            ), 'dokuwiki.setLocks' => array(
74                'args' => array('array'),
75                'return' => 'array',
76                'doc' => 'Lock or unlock pages.'
77            ), 'dokuwiki.getTitle' => array(
78                'args' => array(),
79                'return' => 'string',
80                'doc' => 'Returns the wiki title.',
81                'public' => '1'
82            ), 'dokuwiki.appendPage' => array(
83                'args' => array('string', 'string', 'array'),
84                'return' => 'bool',
85                'doc' => 'Append text to a wiki page.'
86            ), 'dokuwiki.deleteUsers' => array(
87                'args' => array('array'),
88                'return' => 'bool',
89                'doc' => 'Remove one or more users from the list of registered users.'
90            ),  'wiki.getPage' => array(
91                'args' => array('string'),
92                'return' => 'string',
93                'doc' => 'Get the raw Wiki text of page, latest version.',
94                'name' => 'rawPage',
95            ), 'wiki.getPageVersion' => array(
96                'args' => array('string', 'int'),
97                'name' => 'rawPage',
98                'return' => 'string',
99                'doc' => 'Return a raw wiki page'
100            ), 'wiki.getPageHTML' => array(
101                'args' => array('string'),
102                'return' => 'string',
103                'doc' => 'Return page in rendered HTML, latest version.',
104                'name' => 'htmlPage'
105            ), 'wiki.getPageHTMLVersion' => array(
106                'args' => array('string', 'int'),
107                'return' => 'string',
108                'doc' => 'Return page in rendered HTML.',
109                'name' => 'htmlPage'
110            ), 'wiki.getAllPages' => array(
111                'args' => array(),
112                'return' => 'array',
113                'doc' => 'Returns a list of all pages. The result is an array of utf8 pagenames.',
114                'name' => 'listPages'
115            ), 'wiki.getAttachments' => array(
116                'args' => array('string', 'array'),
117                'return' => 'array',
118                'doc' => 'Returns a list of all media files.',
119                'name' => 'listAttachments'
120            ), 'wiki.getBackLinks' => array(
121                'args' => array('string'),
122                'return' => 'array',
123                'doc' => 'Returns the pages that link to this page.',
124                'name' => 'listBackLinks'
125            ), 'wiki.getPageInfo' => array(
126                'args' => array('string'),
127                'return' => 'array',
128                'doc' => 'Returns a struct with info about the page, latest version.',
129                'name' => 'pageInfo'
130            ), 'wiki.getPageInfoVersion' => array(
131                'args' => array('string', 'int'),
132                'return' => 'array',
133                'doc' => 'Returns a struct with info about the page.',
134                'name' => 'pageInfo'
135            ), 'wiki.getPageVersions' => array(
136                'args' => array('string', 'int'),
137                'return' => 'array',
138                'doc' => 'Returns the available revisions of the page.',
139                'name' => 'pageVersions'
140            ), 'wiki.putPage' => array(
141                'args' => array('string', 'string', 'array'),
142                'return' => 'bool',
143                'doc' => 'Saves a wiki page.'
144            ), 'wiki.listLinks' => array(
145                'args' => array('string'),
146                'return' => 'array',
147                'doc' => 'Lists all links contained in a wiki page.'
148            ), 'wiki.getRecentChanges' => array(
149                'args' => array('int'),
150                'return' => 'array',
151                'doc' => 'Returns a struct about all recent changes since given timestamp.'
152            ), 'wiki.getRecentMediaChanges' => array(
153                'args' => array('int'),
154                'return' => 'array',
155                'doc' => 'Returns a struct about all recent media changes since given timestamp.'
156            ), 'wiki.aclCheck' => array(
157                'args' => array('string', 'string', 'array'),
158                'return' => 'int',
159                'doc' => 'Returns the permissions of a given wiki page. By default, for current user/groups'
160            ), 'wiki.putAttachment' => array(
161                'args' => array('string', 'file', 'array'),
162                'return' => 'array',
163                'doc' => 'Upload a file to the wiki.'
164            ), 'wiki.deleteAttachment' => array(
165                'args' => array('string'),
166                'return' => 'int',
167                'doc' => 'Delete a file from the wiki.'
168            ), 'wiki.getAttachment' => array(
169                'args' => array('string'),
170                'doc' => 'Return a media file',
171                'return' => 'file',
172                'name' => 'getAttachment',
173            ), 'wiki.getAttachmentInfo' => array(
174                'args' => array('string'),
175                'return' => 'array',
176                'doc' => 'Returns a struct with info about the attachment.'
177            ), 'dokuwiki.getXMLRPCAPIVersion' => array(
178                'args' => array(),
179                'name' => 'getAPIVersion',
180                'return' => 'int',
181                'doc' => 'Returns the XMLRPC API version.',
182                'public' => '1',
183            ), 'wiki.getRPCVersionSupported' => array(
184                'args' => array(),
185                'name' => 'wikiRpcVersion',
186                'return' => 'int',
187                'doc' => 'Returns 2 with the supported RPC API version.',
188                'public' => '1'
189            ),
190
191        );
192    }
193
194    /**
195     * @return string
196     */
197    public function getVersion()
198    {
199        return getVersion();
200    }
201
202    /**
203     * @return int unix timestamp
204     */
205    public function getTime()
206    {
207        return time();
208    }
209
210    /**
211     * Return a raw wiki page
212     *
213     * @param string $id wiki page id
214     * @param int|string $rev revision timestamp of the page or empty string
215     * @return string page text.
216     * @throws AccessDeniedException if no permission for page
217     */
218    public function rawPage($id, $rev = '')
219    {
220        $id = $this->resolvePageId($id);
221        if (auth_quickaclcheck($id) < AUTH_READ) {
222            throw new AccessDeniedException('You are not allowed to read this file', 111);
223        }
224        $text = rawWiki($id, $rev);
225        if (!$text) {
226            return pageTemplate($id);
227        } else {
228            return $text;
229        }
230    }
231
232    /**
233     * Return a media file
234     *
235     * @author Gina Haeussge <osd@foosel.net>
236     *
237     * @param string $id file id
238     * @return mixed media file
239     * @throws AccessDeniedException no permission for media
240     * @throws RemoteException not exist
241     */
242    public function getAttachment($id)
243    {
244        $id = cleanID($id);
245        if (auth_quickaclcheck(getNS($id) . ':*') < AUTH_READ) {
246            throw new AccessDeniedException('You are not allowed to read this file', 211);
247        }
248
249        $file = mediaFN($id);
250        if (!@ file_exists($file)) {
251            throw new RemoteException('The requested file does not exist', 221);
252        }
253
254        $data = io_readFile($file, false);
255        return $this->api->toFile($data);
256    }
257
258    /**
259     * Return info about a media file
260     *
261     * @author Gina Haeussge <osd@foosel.net>
262     *
263     * @param string $id page id
264     * @return array
265     */
266    public function getAttachmentInfo($id)
267    {
268        $id = cleanID($id);
269        $info = array(
270            'lastModified' => $this->api->toDate(0),
271            'size' => 0,
272        );
273
274        $file = mediaFN($id);
275        if (auth_quickaclcheck(getNS($id) . ':*') >= AUTH_READ) {
276            if (file_exists($file)) {
277                $info['lastModified'] = $this->api->toDate(filemtime($file));
278                $info['size'] = filesize($file);
279            } else {
280                //Is it deleted media with changelog?
281                $medialog = new MediaChangeLog($id);
282                $revisions = $medialog->getRevisions(0, 1);
283                if (!empty($revisions)) {
284                    $info['lastModified'] = $this->api->toDate($revisions[0]);
285                }
286            }
287        }
288
289        return $info;
290    }
291
292    /**
293     * Return a wiki page rendered to html
294     *
295     * @param string $id page id
296     * @param string|int $rev revision timestamp or empty string
297     * @return null|string html
298     * @throws AccessDeniedException no access to page
299     */
300    public function htmlPage($id, $rev = '')
301    {
302        $id = $this->resolvePageId($id);
303        if (auth_quickaclcheck($id) < AUTH_READ) {
304            throw new AccessDeniedException('You are not allowed to read this page', 111);
305        }
306        return p_wiki_xhtml($id, $rev, false);
307    }
308
309    /**
310     * List all pages - we use the indexer list here
311     *
312     * @return array
313     */
314    public function listPages()
315    {
316        $list = array();
317
318        $pages = (new Indexer())->getPages();
319        $pages = array_filter(array_filter($pages, 'isVisiblePage'), 'page_exists');
320        Sort::ksort($pages);
321
322        foreach (array_keys($pages) as $idx) {
323            $perm = auth_quickaclcheck($pages[$idx]);
324            if ($perm < AUTH_READ) {
325                continue;
326            }
327            $page = array();
328            $page['id'] = trim($pages[$idx]);
329            $page['perms'] = $perm;
330            $page['size'] = @filesize(wikiFN($pages[$idx]));
331            $page['lastModified'] = $this->api->toDate(@filemtime(wikiFN($pages[$idx])));
332            $list[] = $page;
333        }
334
335        return $list;
336    }
337
338    /**
339     * List all pages in the given namespace (and below)
340     *
341     * @param string $ns
342     * @param array $opts
343     *    $opts['depth']   recursion level, 0 for all
344     *    $opts['hash']    do md5 sum of content?
345     * @return array
346     */
347    public function readNamespace($ns, $opts = array())
348    {
349        global $conf;
350
351        if (!is_array($opts)) $opts = array();
352
353        $ns = cleanID($ns);
354        $dir = utf8_encodeFN(str_replace(':', '/', $ns));
355        $data = array();
356        $opts['skipacl'] = 0; // no ACL skipping for XMLRPC
357        search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
358        return $data;
359    }
360
361    /**
362     * List all pages in the given namespace (and below)
363     *
364     * @param string $query
365     * @return array
366     */
367    public function search($query)
368    {
369        $regex = array();
370        $FulltextSearch = new FulltextSearch();
371        $data = $FulltextSearch->pageSearch($query, $regex);
372        $pages = array();
373
374        // prepare additional data
375        $idx = 0;
376        foreach ($data as $id => $score) {
377            $file = wikiFN($id);
378
379            if ($idx < FT_SNIPPET_NUMBER) {
380                $snippet = $FulltextSearch->snippet($id, $regex);
381                $idx++;
382            } else {
383                $snippet = '';
384            }
385
386            $pages[] = array(
387                'id' => $id,
388                'score' => intval($score),
389                'rev' => filemtime($file),
390                'mtime' => filemtime($file),
391                'size' => filesize($file),
392                'snippet' => $snippet,
393                'title' => useHeading('navigation') ? p_get_first_heading($id) : $id
394            );
395        }
396        return $pages;
397    }
398
399    /**
400     * Returns the wiki title.
401     *
402     * @return string
403     */
404    public function getTitle()
405    {
406        global $conf;
407        return $conf['title'];
408    }
409
410    /**
411     * List all media files.
412     *
413     * Available options are 'recursive' for also including the subnamespaces
414     * in the listing, and 'pattern' for filtering the returned files against
415     * a regular expression matching their name.
416     *
417     * @author Gina Haeussge <osd@foosel.net>
418     *
419     * @param string $ns
420     * @param array $options
421     *   $options['depth']     recursion level, 0 for all
422     *   $options['showmsg']   shows message if invalid media id is used
423     *   $options['pattern']   check given pattern
424     *   $options['hash']      add hashes to result list
425     * @return array
426     * @throws AccessDeniedException no access to the media files
427     */
428    public function listAttachments($ns, $options = array())
429    {
430        global $conf;
431
432        $ns = cleanID($ns);
433
434        if (!is_array($options)) $options = array();
435        $options['skipacl'] = 0; // no ACL skipping for XMLRPC
436
437        if (auth_quickaclcheck($ns . ':*') >= AUTH_READ) {
438            $dir = utf8_encodeFN(str_replace(':', '/', $ns));
439
440            $data = array();
441            search($data, $conf['mediadir'], 'search_media', $options, $dir);
442            $len = count($data);
443            if (!$len) return array();
444
445            for ($i = 0; $i < $len; $i++) {
446                unset($data[$i]['meta']);
447                $data[$i]['perms'] = $data[$i]['perm'];
448                unset($data[$i]['perm']);
449                $data[$i]['lastModified'] = $this->api->toDate($data[$i]['mtime']);
450            }
451            return $data;
452        } else {
453            throw new AccessDeniedException('You are not allowed to list media files.', 215);
454        }
455    }
456
457    /**
458     * Return a list of backlinks
459     *
460     * @param string $id page id
461     * @return array
462     */
463    public function listBackLinks($id)
464    {
465        return (new MetadataIndex())->backlinks($this->resolvePageId($id));
466    }
467
468    /**
469     * Return some basic data about a page
470     *
471     * @param string $id page id
472     * @param string|int $rev revision timestamp or empty string
473     * @return array
474     * @throws AccessDeniedException no access for page
475     * @throws RemoteException page not exist
476     */
477    public function pageInfo($id, $rev = '')
478    {
479        $id = $this->resolvePageId($id);
480        if (auth_quickaclcheck($id) < AUTH_READ) {
481            throw new AccessDeniedException('You are not allowed to read this page', 111);
482        }
483        $file = wikiFN($id, $rev);
484        $time = @filemtime($file);
485        if (!$time) {
486            throw new RemoteException('The requested page does not exist', 121);
487        }
488
489        // set revision to current version if empty, use revision otherwise
490        // as the timestamps of old files are not necessarily correct
491        if ($rev === '') {
492            $rev = $time;
493        }
494
495        $pagelog = new PageChangeLog($id, 1024);
496        $info = $pagelog->getRevisionInfo($rev);
497
498        $data = array(
499            'name' => $id,
500            'lastModified' => $this->api->toDate($rev),
501            'author' => is_array($info) ? (($info['user']) ? $info['user'] : $info['ip']) : null,
502            'version' => $rev
503        );
504
505        return ($data);
506    }
507
508    /**
509     * Save a wiki page
510     *
511     * @author Michael Klier <chi@chimeric.de>
512     *
513     * @param string $id page id
514     * @param string $text wiki text
515     * @param array $params parameters: summary, minor edit
516     * @return bool
517     * @throws AccessDeniedException no write access for page
518     * @throws RemoteException no id, empty new page or locked
519     */
520    public function putPage($id, $text, $params = array())
521    {
522        global $TEXT;
523        global $lang;
524
525        $id = $this->resolvePageId($id);
526        $TEXT = cleanText($text);
527        $sum = $params['sum'];
528        $minor = $params['minor'];
529
530        if (empty($id)) {
531            throw new RemoteException('Empty page ID', 131);
532        }
533
534        if (!page_exists($id) && trim($TEXT) == '') {
535            throw new RemoteException('Refusing to write an empty new wiki page', 132);
536        }
537
538        if (auth_quickaclcheck($id) < AUTH_EDIT) {
539            throw new AccessDeniedException('You are not allowed to edit this page', 112);
540        }
541
542        // Check, if page is locked
543        if (checklock($id)) {
544            throw new RemoteException('The page is currently locked', 133);
545        }
546
547        // SPAM check
548        if (checkwordblock()) {
549            throw new RemoteException('Positive wordblock check', 134);
550        }
551
552        // autoset summary on new pages
553        if (!page_exists($id) && empty($sum)) {
554            $sum = $lang['created'];
555        }
556
557        // autoset summary on deleted pages
558        if (page_exists($id) && empty($TEXT) && empty($sum)) {
559            $sum = $lang['deleted'];
560        }
561
562        lock($id);
563
564        saveWikiText($id, $TEXT, $sum, $minor);
565
566        unlock($id);
567
568        // run the indexer if page wasn't indexed yet
569        (new Indexer($id))->addPage();
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 = array())
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 = array())
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 = 0)
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        $ok = null;
985        if ($auth->canDo('external')) {
986            $ok = $auth->trustExternal($user, $pass, false);
987        }
988        if ($ok === null){
989            $evdata = array(
990                'user' => $user,
991                'password' => $pass,
992                'sticky' => false,
993                'silent' => true,
994            );
995            $ok = Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
996        }
997        session_write_close(); // we're done with the session
998
999        return $ok;
1000    }
1001
1002    /**
1003     * Log off
1004     *
1005     * @return int
1006     */
1007    public function logoff()
1008    {
1009        global $conf;
1010        global $auth;
1011        if (!$conf['useacl']) return 0;
1012        if (!$auth) return 0;
1013
1014        auth_logoff();
1015
1016        return 1;
1017    }
1018
1019    /**
1020     * Resolve page id
1021     *
1022     * @param string $id page id
1023     * @return string
1024     */
1025    private function resolvePageId($id)
1026    {
1027        $id = cleanID($id);
1028        if (empty($id)) {
1029            global $conf;
1030            $id = cleanID($conf['start']);
1031        }
1032        return $id;
1033    }
1034}
1035