xref: /plugin/annotations/action.php (revision f58805fb9cf627da9470aa65cb6297e32c24dbdf)
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 $INFO;
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    = (string) ($_SERVER['REMOTE_USER'] ?? '');
141        $isAdmin = !empty($INFO['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            $jsonToken = isset($payload['sectok']) ? (string) $payload['sectok'] : '';
206            if ($jsonToken !== '' && !isset($_REQUEST['sectok'])) {
207                $_POST['sectok']    = $jsonToken;
208                $_REQUEST['sectok'] = $jsonToken;
209            }
210            if (!checkSecurityToken()) {
211                $this->sendError('Invalid security token.');
212                return;
213            }
214        }
215        $id = isset($payload['id']) ? cleanID((string) $payload['id']) : '';
216
217        if ($action === '' || $id === '') {
218            $this->sendError('Missing action or page id.');
219            return;
220        }
221
222        /** @var helper_plugin_annotations $helper */
223        $helper = $this->loadHelper('annotations', false);
224        if (!$helper) {
225            $this->sendError('Annotations helper unavailable.');
226            return;
227        }
228
229        // Gather facts once; pass them to the helper's permission methods.
230        global $USERINFO;
231        $user    = (string) ($_SERVER['REMOTE_USER'] ?? '');
232        $isAdmin = (bool) ($USERINFO['grps'] ?? false)
233            ? in_array('admin', (array) ($USERINFO['grps'] ?? []), true)
234            : false;
235        // also honour DokuWiki's own admin flag
236        if (!$isAdmin) {
237            global $INFO;
238            $isAdmin = !empty($INFO['isadmin']);
239        }
240        $aclLevel = auth_quickaclcheck($id);
241
242        // Route to the correct handler method.
243        switch ($action) {
244            case 'load':
245                $this->actionLoad($helper, $id, $aclLevel);
246                break;
247            case 'create':
248                $this->actionCreate($helper, $id, $payload, $user, $aclLevel);
249                break;
250            case 'reply':
251                $this->actionReply($helper, $id, $payload, $user, $aclLevel);
252                break;
253            case 'edit_annotation':
254                $this->actionEditAnnotation($helper, $id, $payload, $user, $isAdmin);
255                break;
256            case 'edit_reply':
257                $this->actionEditReply($helper, $id, $payload, $user, $isAdmin);
258                break;
259            case 'delete_annotation':
260                $this->actionDeleteAnnotation($helper, $id, $payload, $user, $isAdmin);
261                break;
262            case 'delete_reply':
263                $this->actionDeleteReply($helper, $id, $payload, $user, $isAdmin);
264                break;
265            case 'resolve':
266                $this->actionResolve($helper, $id, $payload, $user, $aclLevel);
267                break;
268            case 'clear_resolved':
269                $this->actionClearResolved($helper, $id, $isAdmin);
270                break;
271            case 'clear_orphaned':
272                $this->actionClearOrphaned($helper, $id, $isAdmin);
273                break;
274            default:
275                $this->sendError('Unknown action: ' . hsc($action));
276        }
277    }
278
279    // ------------------------------------------------------------------
280    //  Action handlers (one per supported action)
281    // ------------------------------------------------------------------
282
283    /**
284     * Create a new annotation.
285     *
286     * Payload: { action, id, anchor:{exact,prefix,suffix,start}, body }
287     *
288     * @param helper_plugin_annotations $helper
289     * @param string                    $id
290     * @param array                     $payload
291     * @param string                    $user
292     * @param int                       $aclLevel
293     */
294    protected function actionCreate($helper, $id, array $payload, $user, $aclLevel)
295    {
296        if (!$helper->canAnnotate($user, $aclLevel)) {
297            $this->sendError('Permission denied.');
298            return;
299        }
300        $anchor = isset($payload['anchor']) && is_array($payload['anchor'])
301            ? $payload['anchor']
302            : [];
303        $body = isset($payload['body']) ? (string) $payload['body'] : '';
304
305        $result = $helper->createAnnotation($id, $anchor, $user, $body);
306        if ($result === false) {
307            $this->sendError('Invalid annotation data.');
308            return;
309        }
310        $this->sendSuccess(['annotation' => $result]);
311    }
312
313    /**
314     * Add a reply to an existing annotation.
315     *
316     * Payload: { action, id, annId, body }
317     *
318     * @param helper_plugin_annotations $helper
319     * @param string                    $id
320     * @param array                     $payload
321     * @param string                    $user
322     * @param int                       $aclLevel
323     */
324    protected function actionReply($helper, $id, array $payload, $user, $aclLevel)
325    {
326        if (!$helper->canAnnotate($user, $aclLevel)) {
327            $this->sendError('Permission denied.');
328            return;
329        }
330        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
331        $body  = isset($payload['body'])  ? (string) $payload['body']  : '';
332
333        if ($annId === '') {
334            $this->sendError('Missing annId.');
335            return;
336        }
337        $result = $helper->addReply($id, $annId, $user, $body);
338        if ($result === false) {
339            $this->sendError('Invalid reply data or annotation not found.');
340            return;
341        }
342        $this->sendSuccess(['reply' => $result]);
343    }
344
345    /**
346     * Edit an annotation's body text.
347     *
348     * Payload: { action, id, annId, body }
349     *
350     * @param helper_plugin_annotations $helper
351     * @param string                    $id
352     * @param array                     $payload
353     * @param string                    $user
354     * @param bool                      $isAdmin
355     */
356    protected function actionEditAnnotation($helper, $id, array $payload, $user, $isAdmin)
357    {
358        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
359        $body  = isset($payload['body'])  ? (string) $payload['body']  : '';
360
361        if ($annId === '') {
362            $this->sendError('Missing annId.');
363            return;
364        }
365        $annotation = $helper->getAnnotation($id, $annId);
366        if ($annotation === null) {
367            $this->sendError('Annotation not found.');
368            return;
369        }
370        if (!$helper->canEditAnnotation($annotation, $user, $isAdmin)) {
371            $this->sendError('Permission denied.');
372            return;
373        }
374        $ok = $helper->updateAnnotationBody($id, $annId, $body);
375        if (!$ok) {
376            $this->sendError('Invalid body or annotation not found.');
377            return;
378        }
379        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
380    }
381
382    /**
383     * Edit a reply's body text.
384     *
385     * Payload: { action, id, annId, replyId, body }
386     *
387     * @param helper_plugin_annotations $helper
388     * @param string                    $id
389     * @param array                     $payload
390     * @param string                    $user
391     * @param bool                      $isAdmin
392     */
393    protected function actionEditReply($helper, $id, array $payload, $user, $isAdmin)
394    {
395        $annId   = isset($payload['annId'])   ? (string) $payload['annId']   : '';
396        $replyId = isset($payload['replyId']) ? (string) $payload['replyId'] : '';
397        $body    = isset($payload['body'])    ? (string) $payload['body']    : '';
398
399        if ($annId === '' || $replyId === '') {
400            $this->sendError('Missing annId or replyId.');
401            return;
402        }
403        $annotation = $helper->getAnnotation($id, $annId);
404        if ($annotation === null) {
405            $this->sendError('Annotation not found.');
406            return;
407        }
408        // Find the reply to permission-check its author.
409        $reply = null;
410        foreach (($annotation['replies'] ?? []) as $r) {
411            if (($r['id'] ?? '') === $replyId) {
412                $reply = $r;
413                break;
414            }
415        }
416        if ($reply === null) {
417            $this->sendError('Reply not found.');
418            return;
419        }
420        if (!$helper->canEditReply($reply, $user, $isAdmin)) {
421            $this->sendError('Permission denied.');
422            return;
423        }
424        $ok = $helper->updateReply($id, $annId, $replyId, $body);
425        if (!$ok) {
426            $this->sendError('Invalid body or reply not found.');
427            return;
428        }
429        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
430    }
431
432    /**
433     * Delete an annotation and all its replies.
434     *
435     * Payload: { action, id, annId }
436     *
437     * @param helper_plugin_annotations $helper
438     * @param string                    $id
439     * @param array                     $payload
440     * @param string                    $user
441     * @param bool                      $isAdmin
442     */
443    protected function actionDeleteAnnotation($helper, $id, array $payload, $user, $isAdmin)
444    {
445        $annId = isset($payload['annId']) ? (string) $payload['annId'] : '';
446
447        if ($annId === '') {
448            $this->sendError('Missing annId.');
449            return;
450        }
451        $annotation = $helper->getAnnotation($id, $annId);
452        if ($annotation === null) {
453            $this->sendError('Annotation not found.');
454            return;
455        }
456        if (!$helper->canEditAnnotation($annotation, $user, $isAdmin)) {
457            $this->sendError('Permission denied.');
458            return;
459        }
460        $ok = $helper->deleteAnnotation($id, $annId);
461        if (!$ok) {
462            $this->sendError('Delete failed.');
463            return;
464        }
465        $this->sendSuccess(['stats' => $helper->getStats($id)]);
466    }
467
468    /**
469     * Delete a reply.
470     *
471     * Payload: { action, id, annId, replyId }
472     *
473     * @param helper_plugin_annotations $helper
474     * @param string                    $id
475     * @param array                     $payload
476     * @param string                    $user
477     * @param bool                      $isAdmin
478     */
479    protected function actionDeleteReply($helper, $id, array $payload, $user, $isAdmin)
480    {
481        $annId   = isset($payload['annId'])   ? (string) $payload['annId']   : '';
482        $replyId = isset($payload['replyId']) ? (string) $payload['replyId'] : '';
483
484        if ($annId === '' || $replyId === '') {
485            $this->sendError('Missing annId or replyId.');
486            return;
487        }
488        $annotation = $helper->getAnnotation($id, $annId);
489        if ($annotation === null) {
490            $this->sendError('Annotation not found.');
491            return;
492        }
493        $reply = null;
494        foreach (($annotation['replies'] ?? []) as $r) {
495            if (($r['id'] ?? '') === $replyId) {
496                $reply = $r;
497                break;
498            }
499        }
500        if ($reply === null) {
501            $this->sendError('Reply not found.');
502            return;
503        }
504        if (!$helper->canEditReply($reply, $user, $isAdmin)) {
505            $this->sendError('Permission denied.');
506            return;
507        }
508        $ok = $helper->deleteReply($id, $annId, $replyId);
509        if (!$ok) {
510            $this->sendError('Delete failed.');
511            return;
512        }
513        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
514    }
515
516    /**
517     * Resolve or reopen an annotation.
518     *
519     * Payload: { action, id, annId, status:"open"|"resolved" }
520     *
521     * @param helper_plugin_annotations $helper
522     * @param string                    $id
523     * @param array                     $payload
524     * @param string                    $user
525     * @param int                       $aclLevel
526     */
527    protected function actionResolve($helper, $id, array $payload, $user, $aclLevel)
528    {
529        if (!$helper->canAnnotate($user, $aclLevel)) {
530            $this->sendError('Permission denied.');
531            return;
532        }
533        $annId  = isset($payload['annId'])  ? (string) $payload['annId']  : '';
534        $status = isset($payload['status']) ? (string) $payload['status'] : '';
535
536        if ($annId === '') {
537            $this->sendError('Missing annId.');
538            return;
539        }
540        $ok = $helper->setStatus($id, $annId, $status, $user);
541        if (!$ok) {
542            $this->sendError('Invalid status or annotation not found.');
543            return;
544        }
545        $this->sendSuccess(['annotation' => $helper->getAnnotation($id, $annId)]);
546    }
547
548    /**
549     * Remove all resolved annotations on the page. Admin only.
550     *
551     * Payload: { action, id }
552     *
553     * @param helper_plugin_annotations $helper
554     * @param string                    $id
555     * @param bool                      $isAdmin
556     */
557    protected function actionClearResolved($helper, $id, $isAdmin)
558    {
559        if (!$helper->canClear($isAdmin)) {
560            $this->sendError('Permission denied.');
561            return;
562        }
563        $count = $helper->clearResolved($id);
564        if ($count === false) {
565            $this->sendError('Clear failed.');
566            return;
567        }
568        $this->sendSuccess(['removed' => $count, 'stats' => $helper->getStats($id)]);
569    }
570
571    /**
572     * Remove all orphaned annotations on the page. Admin only.
573     *
574     * Payload: { action, id }
575     *
576     * @param helper_plugin_annotations $helper
577     * @param string                    $id
578     * @param bool                      $isAdmin
579     */
580    protected function actionClearOrphaned($helper, $id, $isAdmin)
581    {
582        if (!$helper->canClear($isAdmin)) {
583            $this->sendError('Permission denied.');
584            return;
585        }
586        $count = $helper->clearOrphaned($id);
587        if ($count === false) {
588            $this->sendError('Clear failed.');
589            return;
590        }
591        $this->sendSuccess(['removed' => $count, 'stats' => $helper->getStats($id)]);
592    }
593
594    // ------------------------------------------------------------------
595    //  Utilities
596    // ------------------------------------------------------------------
597
598    /**
599     * Whether the current user has the annotations_enabled preference on.
600     *
601     * If the usersettings plugin is absent the feature defaults to enabled.
602     * Public so templates and tests can call it directly.
603     *
604     * @return bool
605     */
606    public function isEnabledForUser()
607    {
608        /** @var helper_plugin_usersettings|null $us */
609        $us = plugin_load('helper', 'usersettings');
610        if (!$us) {
611            return true; // usersettings not installed — default on
612        }
613        $value = $us->getPreference('annotations_enabled');
614        // getPreference returns null when the toggle is not registered yet
615        // (e.g. very first page load before the event has fired).
616        return ($value === null) ? true : (bool) $value;
617    }
618
619    /**
620     * Parse the request body as JSON; also accepts form-encoded POSTs for
621     * simpler test scripts.
622     *
623     * @return array|null
624     */
625    protected function readPayload()
626    {
627        $ct = $_SERVER['CONTENT_TYPE'] ?? '';
628        if (strpos($ct, 'application/json') !== false) {
629            $raw  = file_get_contents('php://input');
630            $data = json_decode($raw, true);
631            return is_array($data) ? $data : null;
632        }
633        // For GET requests (load action), read from query string.
634        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
635            return $_GET ? (array) $_GET : [];
636        }
637        // Fall back to form-encoded POST (useful for simple curl tests).
638        return $_POST ? (array) $_POST : [];
639    }
640
641    /**
642     * Return all annotations for a page (read-only, no token required).
643     *
644     * The ACL check is still enforced: only users with at least AUTH_READ
645     * on the page can read its annotations.
646     *
647     * @param helper_plugin_annotations $helper
648     * @param string                    $id
649     * @param int                       $aclLevel
650     */
651    protected function actionLoad($helper, $id, $aclLevel)
652    {
653        if ($aclLevel < AUTH_READ) {
654            $this->sendError('Permission denied.');
655            return;
656        }
657        $annotations = $helper->getAnnotations($id);
658        $this->sendSuccess(['annotations' => $annotations]);
659    }
660
661        /**
662     * Emit a JSON success response and exit.
663     *
664     * @param array $extra additional fields merged into the response
665     */
666    protected function sendSuccess(array $extra = [])
667    {
668        echo json_encode(array_merge(['success' => true], $extra), JSON_PRETTY_PRINT);
669    }
670
671    /**
672     * Emit a JSON error response and exit.
673     *
674     * @param string $message human-readable error
675     */
676    protected function sendError($message)
677    {
678        echo json_encode(['success' => false, 'error' => $message], JSON_PRETTY_PRINT);
679    }
680}
681