xref: /plugin/annotations/action.php (revision da56206cc13612db0df36be97c0f01d8f3c5e9f4)
1<?php
2
3/**
4 * Annotations plugin — event registration and AJAX endpoint.
5 *
6 * Responsibilities:
7 *
8 *   1. Register a per-user "annotations_enabled" toggle via the usersettings
9 *      plugin's PLUGIN_USERSETTINGS_REGISTER event (BEFORE, so it fires when
10 *      the usersettings helper calls getRegisteredToggles()).
11 *
12 *   2. Push the current user's preference and the page's annotation stats
13 *      into JSINFO on every normal page view, so script.js can gate itself
14 *      and seed the counter without an extra round-trip.
15 *
16 *   3. Serve the AJAX endpoint at:
17 *        /lib/exe/ajax.php?call=annotations
18 *      POST body (application/json) carries { action, id, ... }.
19 *      All state-changing actions require a valid DokuWiki security token.
20 *      Every response is JSON: { success:true, ... } or { success:false, error:"..." }.
21 *
22 * Supported actions (all POST):
23 *   create          — body, anchor (object)
24 *   reply           — annId, body
25 *   edit_annotation — annId, body
26 *   edit_reply      — annId, replyId, body
27 *   delete_annotation — annId
28 *   delete_reply    — annId, replyId
29 *   resolve         — annId, status ("open"|"resolved")
30 *   clear_resolved  — (no extra fields)
31 *   clear_orphaned  — (no extra fields)
32 *
33 * Permission enforcement is done here; the helper's permission methods are
34 * called with facts gathered from the DokuWiki global state.
35 */
36
37// must be run within DokuWiki
38if (!defined('DOKU_INC')) die();
39
40class action_plugin_annotations extends DokuWiki_Action_Plugin
41{
42    // ------------------------------------------------------------------
43    //  Event registration
44    // ------------------------------------------------------------------
45
46    /**
47     * @param Doku_Event_Handler $controller
48     */
49    public function register(Doku_Event_Handler $controller)
50    {
51        // Register our toggle with the usersettings plugin.
52        $controller->register_hook(
53            'PLUGIN_USERSETTINGS_REGISTER',
54            'BEFORE',
55            $this,
56            'handleSettingsRegister'
57        );
58
59        // Inject annotation stats + user preference into JSINFO.
60        $controller->register_hook(
61            'TPL_METAHEADER_OUTPUT',
62            'BEFORE',
63            $this,
64            'handleMetaHeader'
65        );
66
67        // Handle the AJAX call.
68        $controller->register_hook(
69            'AJAX_CALL_UNKNOWN',
70            'BEFORE',
71            $this,
72            'handleAjax'
73        );
74    }
75
76    // ------------------------------------------------------------------
77    //  1. usersettings toggle registration
78    // ------------------------------------------------------------------
79
80    /**
81     * Append the annotations_enabled toggle definition to the event data.
82     *
83     * The event data is an array that the usersettings helper fires with
84     * createAndTrigger(); every handler appends its definition(s).
85     *
86     * @param Doku_Event $event PLUGIN_USERSETTINGS_REGISTER
87     * @param mixed       $param
88     */
89    public function handleSettingsRegister(Doku_Event $event, $param)
90    {
91        $event->data[] = [
92            'key'     => 'annotations_enabled',
93            'label'   => $this->getLang('toggle_label'),
94            'desc'    => $this->getLang('toggle_desc'),
95            'type'    => 'checkbox',
96            'default' => true,
97            'plugin'  => 'annotations',
98        ];
99    }
100
101    // ------------------------------------------------------------------
102    //  2. Inject into JSINFO
103    // ------------------------------------------------------------------
104
105    /**
106     * Add annotation stats and the user preference to JSINFO so script.js
107     * does not need an extra round-trip on page load.
108     *
109     * IMPORTANT: tpl_metaheaders() calls jsinfo() and then immediately
110     * JSON-encodes $JSINFO into an inline <script> string BEFORE firing
111     * TPL_METAHEADER_OUTPUT. Writing to $JSINFO here is therefore too late.
112     * Instead we locate that inline script block in $event->data and append
113     * a JSINFO.annotations = {...}; statement so it runs in the same scope.
114     *
115     * @param Doku_Event $event TPL_METAHEADER_OUTPUT
116     * @param mixed       $param
117     */
118    public function handleMetaHeader(Doku_Event $event, $param)
119    {
120        global $ID, $ACT;
121
122        // Only inject on normal page-view actions.
123        if (!in_array(act_clean($ACT), ['show', 'export_xhtml'], true)) {
124            return;
125        }
126
127        /** @var helper_plugin_annotations $helper */
128        $helper = $this->loadHelper('annotations', false);
129        if (!$helper) {
130            return;
131        }
132
133        global $INPUT;
134
135        $enabled = $this->isEnabledForUser();
136        $stats   = $helper->getStats($ID);
137
138        // DokuWiki's jsinfo() does not expose user identity, so we inject it
139        // here. JS uses these to gate the selection tooltip and permission UI.
140        $user    = $INPUT->server->str('REMOTE_USER');
141        $isAdmin = auth_isadmin();
142
143        $payload = json_encode([
144            'enabled' => $enabled,
145            'pageId'  => $ID,
146            'stats'   => $stats,
147            'user'    => $user,
148            'isAdmin' => $isAdmin,
149            'token'   => getSecurityToken(),  // CSRF token for AJAX POSTs
150        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
151
152        // The inline script block containing "var JSINFO = ...;" is in
153        // $event->data['script']. Find it and append our assignment so it
154        // runs in the same scope after JSINFO is already declared.
155        if (!empty($event->data['script'])) {
156            foreach ($event->data['script'] as &$scriptTag) {
157                if (
158                    isset($scriptTag['_data']) &&
159                    strpos($scriptTag['_data'], 'var JSINFO') !== false
160                ) {
161                    $scriptTag['_data'] .= 'JSINFO.annotations=' . $payload . ';';
162                    break;
163                }
164            }
165            unset($scriptTag);
166        }
167    }
168
169    // ------------------------------------------------------------------
170    //  3. AJAX endpoint
171    // ------------------------------------------------------------------
172
173    /**
174     * Handle AJAX calls for the annotations plugin.
175     * Ignores calls not addressed to us.
176     *
177     * @param Doku_Event $event AJAX_CALL_UNKNOWN
178     * @param mixed       $param
179     */
180    public function handleAjax(Doku_Event $event, $param)
181    {
182        if ($event->data !== 'annotations') {
183            return;
184        }
185        $event->stopPropagation();
186        $event->preventDefault();
187
188        header('Content-Type: application/json; charset=utf-8');
189
190        // Parse JSON body; fall back to POST/GET fields for simple callers.
191        // The 'load' action is a GET request, so we accept query parameters too.
192        $payload = $this->readPayload();
193        if ($payload === null) {
194            $this->sendError('Invalid request body.');
195            return;
196        }
197
198        $action = isset($payload['action']) ? (string) $payload['action'] : '';
199        // For the read-only 'load' action, accept GET requests without a token.
200        // All state-changing actions require a valid DokuWiki security token.
201        // checkSecurityToken() reads from $_REQUEST (form fields), so when the
202        // request body is JSON we must inject the token from the parsed payload
203        // into $_POST / $_REQUEST before calling it.
204        if ($action !== 'load') {
205            // checkSecurityToken() accepts the token directly, so we hand it the
206            // value from the JSON body rather than poking it into $_REQUEST.
207            $jsonToken = isset($payload['sectok']) ? (string) $payload['sectok'] : '';
208            if (!checkSecurityToken($jsonToken)) {
209                $this->sendError('Invalid security token.');
210                return;
211            }
212        }
213        $id = isset($payload['id']) ? cleanID((string) $payload['id']) : '';
214
215        if ($action === '' || $id === '') {
216            $this->sendError('Missing action or page id.');
217            return;
218        }
219
220        /** @var helper_plugin_annotations $helper */
221        $helper = $this->loadHelper('annotations', false);
222        if (!$helper) {
223            $this->sendError('Annotations helper unavailable.');
224            return;
225        }
226
227        // Gather facts once; pass them to the helper's permission methods.
228        global $INPUT;
229        $user     = $INPUT->server->str('REMOTE_USER');
230        $isAdmin  = auth_isadmin();
231        $aclLevel = auth_quickaclcheck($id);
232
233        // Route to the correct handler method.
234        switch ($action) {
235            case 'load':
236                $this->actionLoad($helper, $id, $aclLevel);
237                break;
238            case 'create':
239                $this->actionCreate($helper, $id, $payload, $user, $aclLevel);
240                break;
241            case 'reply':
242                $this->actionReply($helper, $id, $payload, $user, $aclLevel);
243                break;
244            case 'edit_annotation':
245                $this->actionEditAnnotation($helper, $id, $payload, $user, $isAdmin);
246                break;
247            case 'edit_reply':
248                $this->actionEditReply($helper, $id, $payload, $user, $isAdmin);
249                break;
250            case 'delete_annotation':
251                $this->actionDeleteAnnotation($helper, $id, $payload, $user, $isAdmin);
252                break;
253            case 'delete_reply':
254                $this->actionDeleteReply($helper, $id, $payload, $user, $isAdmin);
255                break;
256            case 'resolve':
257                $this->actionResolve($helper, $id, $payload, $user, $aclLevel);
258                break;
259            case 'clear_resolved':
260                $this->actionClearResolved($helper, $id, $isAdmin);
261                break;
262            case 'clear_orphaned':
263                $this->actionClearOrphaned($helper, $id, $isAdmin);
264                break;
265            default:
266                $this->sendError('Unknown action: ' . hsc($action));
267        }
268    }
269
270    // ------------------------------------------------------------------
271    //  Action handlers (one per supported action)
272    // ------------------------------------------------------------------
273
274    /**
275     * Create a new annotation.
276     *
277     * Payload: { action, id, anchor:{exact,prefix,suffix,start}, body }
278     *
279     * @param helper_plugin_annotations $helper
280     * @param string                    $id
281     * @param array                     $payload
282     * @param string                    $user
283     * @param int                       $aclLevel
284     */
285    protected function actionCreate($helper, $id, array $payload, $user, $aclLevel)
286    {
287        if (!$helper->canAnnotate($user, $aclLevel)) {
288            $this->sendError('Permission denied.');
289            return;
290        }
291        $anchor = isset($payload['anchor']) && is_array($payload['anchor'])
292            ? $payload['anchor']
293            : [];
294        $body = isset($payload['body']) ? (string) $payload['body'] : '';
295
296        $result = $helper->createAnnotation($id, $anchor, $user, $body);
297        if ($result === false) {
298            $this->sendError('Invalid annotation data.');
299            return;
300        }
301        $this->sendSuccess(['annotation' => $result]);
302    }
303
304    /**
305     * Add a reply to an existing annotation.
306     *
307     * Payload: { action, id, annId, body }
308     *
309     * @param helper_plugin_annotations $helper
310     * @param string                    $id
311     * @param array                     $payload
312     * @param string                    $user
313     * @param int                       $aclLevel
314     */
315    protected function actionReply($helper, $id, array $payload, $user, $aclLevel)
316    {
317        if (!$helper->canAnnotate($user, $aclLevel)) {
318            $this->sendError('Permission denied.');
319            return;
320        }
321        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
322        $body  = isset($payload['body'])  ? (string) $payload['body']  : '';
323
324        if ($annId === '') {
325            $this->sendError('Missing annId.');
326            return;
327        }
328        $result = $helper->addReply($id, $annId, $user, $body);
329        if ($result === false) {
330            $this->sendError('Invalid reply data or annotation not found.');
331            return;
332        }
333        $this->sendSuccess(['reply' => $result]);
334    }
335
336    /**
337     * Edit an annotation's body text.
338     *
339     * Payload: { action, id, annId, body }
340     *
341     * @param helper_plugin_annotations $helper
342     * @param string                    $id
343     * @param array                     $payload
344     * @param string                    $user
345     * @param bool                      $isAdmin
346     */
347    protected function actionEditAnnotation($helper, $id, array $payload, $user, $isAdmin)
348    {
349        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
350        $body  = isset($payload['body'])  ? (string) $payload['body']  : '';
351
352        if ($annId === '') {
353            $this->sendError('Missing annId.');
354            return;
355        }
356        $annotation = $helper->getAnnotation($id, $annId);
357        if ($annotation === null) {
358            $this->sendError('Annotation not found.');
359            return;
360        }
361        if (!$helper->canEditAnnotation($annotation, $user, $isAdmin)) {
362            $this->sendError('Permission denied.');
363            return;
364        }
365        $ok = $helper->updateAnnotationBody($id, $annId, $body);
366        if (!$ok) {
367            $this->sendError('Invalid body or annotation not found.');
368            return;
369        }
370        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
371    }
372
373    /**
374     * Edit a reply's body text.
375     *
376     * Payload: { action, id, annId, replyId, body }
377     *
378     * @param helper_plugin_annotations $helper
379     * @param string                    $id
380     * @param array                     $payload
381     * @param string                    $user
382     * @param bool                      $isAdmin
383     */
384    protected function actionEditReply($helper, $id, array $payload, $user, $isAdmin)
385    {
386        $annId   = isset($payload['annId'])   ? (string) $payload['annId']   : '';
387        $replyId = isset($payload['replyId']) ? (string) $payload['replyId'] : '';
388        $body    = isset($payload['body'])    ? (string) $payload['body']    : '';
389
390        if ($annId === '' || $replyId === '') {
391            $this->sendError('Missing annId or replyId.');
392            return;
393        }
394        $annotation = $helper->getAnnotation($id, $annId);
395        if ($annotation === null) {
396            $this->sendError('Annotation not found.');
397            return;
398        }
399        // Find the reply to permission-check its author.
400        $reply = null;
401        foreach (($annotation['replies'] ?? []) as $r) {
402            if (($r['id'] ?? '') === $replyId) {
403                $reply = $r;
404                break;
405            }
406        }
407        if ($reply === null) {
408            $this->sendError('Reply not found.');
409            return;
410        }
411        if (!$helper->canEditReply($reply, $user, $isAdmin)) {
412            $this->sendError('Permission denied.');
413            return;
414        }
415        $ok = $helper->updateReply($id, $annId, $replyId, $body);
416        if (!$ok) {
417            $this->sendError('Invalid body or reply not found.');
418            return;
419        }
420        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
421    }
422
423    /**
424     * Delete an annotation and all its replies.
425     *
426     * Payload: { action, id, annId }
427     *
428     * @param helper_plugin_annotations $helper
429     * @param string                    $id
430     * @param array                     $payload
431     * @param string                    $user
432     * @param bool                      $isAdmin
433     */
434    protected function actionDeleteAnnotation($helper, $id, array $payload, $user, $isAdmin)
435    {
436        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
437
438        if ($annId === '') {
439            $this->sendError('Missing annId.');
440            return;
441        }
442        $annotation = $helper->getAnnotation($id, $annId);
443        if ($annotation === null) {
444            $this->sendError('Annotation not found.');
445            return;
446        }
447        if (!$helper->canEditAnnotation($annotation, $user, $isAdmin)) {
448            $this->sendError('Permission denied.');
449            return;
450        }
451        $ok = $helper->deleteAnnotation($id, $annId);
452        if (!$ok) {
453            $this->sendError('Delete failed.');
454            return;
455        }
456        $this->sendSuccess(['stats' => $helper->getStats($id)]);
457    }
458
459    /**
460     * Delete a reply.
461     *
462     * Payload: { action, id, annId, replyId }
463     *
464     * @param helper_plugin_annotations $helper
465     * @param string                    $id
466     * @param array                     $payload
467     * @param string                    $user
468     * @param bool                      $isAdmin
469     */
470    protected function actionDeleteReply($helper, $id, array $payload, $user, $isAdmin)
471    {
472        $annId   = isset($payload['annId'])   ? (string) $payload['annId']   : '';
473        $replyId = isset($payload['replyId']) ? (string) $payload['replyId'] : '';
474
475        if ($annId === '' || $replyId === '') {
476            $this->sendError('Missing annId or replyId.');
477            return;
478        }
479        $annotation = $helper->getAnnotation($id, $annId);
480        if ($annotation === null) {
481            $this->sendError('Annotation not found.');
482            return;
483        }
484        $reply = null;
485        foreach (($annotation['replies'] ?? []) as $r) {
486            if (($r['id'] ?? '') === $replyId) {
487                $reply = $r;
488                break;
489            }
490        }
491        if ($reply === null) {
492            $this->sendError('Reply not found.');
493            return;
494        }
495        if (!$helper->canEditReply($reply, $user, $isAdmin)) {
496            $this->sendError('Permission denied.');
497            return;
498        }
499        $ok = $helper->deleteReply($id, $annId, $replyId);
500        if (!$ok) {
501            $this->sendError('Delete failed.');
502            return;
503        }
504        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
505    }
506
507    /**
508     * Resolve or reopen an annotation.
509     *
510     * Payload: { action, id, annId, status:"open"|"resolved" }
511     *
512     * @param helper_plugin_annotations $helper
513     * @param string                    $id
514     * @param array                     $payload
515     * @param string                    $user
516     * @param int                       $aclLevel
517     */
518    protected function actionResolve($helper, $id, array $payload, $user, $aclLevel)
519    {
520        if (!$helper->canAnnotate($user, $aclLevel)) {
521            $this->sendError('Permission denied.');
522            return;
523        }
524        $annId  = isset($payload['annId'])  ? (string) $payload['annId']  : '';
525        $status = isset($payload['status']) ? (string) $payload['status'] : '';
526
527        if ($annId === '') {
528            $this->sendError('Missing annId.');
529            return;
530        }
531        $ok = $helper->setStatus($id, $annId, $status, $user);
532        if (!$ok) {
533            $this->sendError('Invalid status or annotation not found.');
534            return;
535        }
536        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
537    }
538
539    /**
540     * Remove all resolved annotations on the page. Admin only.
541     *
542     * Payload: { action, id }
543     *
544     * @param helper_plugin_annotations $helper
545     * @param string                    $id
546     * @param bool                      $isAdmin
547     */
548    protected function actionClearResolved($helper, $id, $isAdmin)
549    {
550        if (!$helper->canClear($isAdmin)) {
551            $this->sendError('Permission denied.');
552            return;
553        }
554        $count = $helper->clearResolved($id);
555        if ($count === false) {
556            $this->sendError('Clear failed.');
557            return;
558        }
559        $this->sendSuccess(['removed' => $count, 'stats' => $helper->getStats($id)]);
560    }
561
562    /**
563     * Remove all orphaned annotations on the page. Admin only.
564     *
565     * Payload: { action, id }
566     *
567     * @param helper_plugin_annotations $helper
568     * @param string                    $id
569     * @param bool                      $isAdmin
570     */
571    protected function actionClearOrphaned($helper, $id, $isAdmin)
572    {
573        if (!$helper->canClear($isAdmin)) {
574            $this->sendError('Permission denied.');
575            return;
576        }
577        $count = $helper->clearOrphaned($id);
578        if ($count === false) {
579            $this->sendError('Clear failed.');
580            return;
581        }
582        $this->sendSuccess(['removed' => $count, 'stats' => $helper->getStats($id)]);
583    }
584
585    // ------------------------------------------------------------------
586    //  Utilities
587    // ------------------------------------------------------------------
588
589    /**
590     * Whether the current user has the annotations_enabled preference on.
591     *
592     * If the usersettings plugin is absent the feature defaults to enabled.
593     * Public so templates and tests can call it directly.
594     *
595     * @return bool
596     */
597    public function isEnabledForUser()
598    {
599        /** @var helper_plugin_usersettings|null $us */
600        $us = plugin_load('helper', 'usersettings');
601        if (!$us) {
602            return true; // usersettings not installed — default on
603        }
604        $value = $us->getPreference('annotations_enabled');
605        // getPreference returns null when the toggle is not registered yet
606        // (e.g. very first page load before the event has fired).
607        return ($value === null) ? true : (bool) $value;
608    }
609
610    /**
611     * Parse the request body as JSON; also accepts form-encoded POSTs for
612     * simpler test scripts.
613     *
614     * @return array|null
615     */
616    protected function readPayload()
617    {
618        global $INPUT;
619        $ct = $INPUT->server->str('CONTENT_TYPE');
620        if (strpos($ct, 'application/json') !== false) {
621            $data = json_decode(file_get_contents('php://input'), true);
622            return is_array($data) ? $data : null;
623        }
624        // The read-only 'load' action is a GET carrying action + id only.
625        if ($INPUT->server->str('REQUEST_METHOD') === 'GET') {
626            return [
627                'action' => $INPUT->get->str('action'),
628                'id'     => $INPUT->get->str('id'),
629            ];
630        }
631        // Form-encoded POST fallback (handy for simple curl tests).
632        return [
633            'action'  => $INPUT->post->str('action'),
634            'id'      => $INPUT->post->str('id'),
635            'sectok'  => $INPUT->post->str('sectok'),
636            'annId'   => $INPUT->post->str('annId'),
637            'replyId' => $INPUT->post->str('replyId'),
638            'body'    => $INPUT->post->str('body'),
639            'status'  => $INPUT->post->str('status'),
640        ];
641    }
642
643    /**
644     * Return all annotations for a page (read-only, no token required).
645     *
646     * The ACL check is still enforced: only users with at least AUTH_READ
647     * on the page can read its annotations.
648     *
649     * @param helper_plugin_annotations $helper
650     * @param string                    $id
651     * @param int                       $aclLevel
652     */
653    protected function actionLoad($helper, $id, $aclLevel)
654    {
655        if ($aclLevel < AUTH_READ) {
656            $this->sendError('Permission denied.');
657            return;
658        }
659        $annotations = $helper->getAnnotations($id);
660        $this->sendSuccess(['annotations' => $annotations]);
661    }
662
663        /**
664     * Emit a JSON success response and exit.
665     *
666     * @param array $extra additional fields merged into the response
667     */
668    protected function sendSuccess(array $extra = [])
669    {
670        echo json_encode(array_merge(['success' => true], $extra), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
671    }
672
673    /**
674     * Emit a JSON error response and exit.
675     *
676     * @param string $message human-readable error
677     */
678    protected function sendError($message)
679    {
680        echo json_encode(['success' => false, 'error' => $message], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
681    }
682}
683