xref: /plugin/aichat/action.php (revision 0337f47f2dd6cc31bdbfd81a2499e687ce633b47)
1<?php
2
3/**
4 * DokuWiki Plugin aichat (Action Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Andreas Gohr <gohr@cosmocode.de>
8 */
9class action_plugin_aichat extends \dokuwiki\Extension\ActionPlugin
10{
11
12    /** @inheritDoc */
13    public function register(Doku_Event_Handler $controller)
14    {
15        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleQuestion');
16
17    }
18
19
20    /**
21     * Event handler for AJAX_CALL_UNKNOWN event
22     *
23     * @see https://www.dokuwiki.org/devel:events:ajax_call_unknown
24     * @param Doku_Event $event Event object
25     * @param mixed $param optional parameter passed when event was registered
26     * @return void
27     */
28    public function handleQuestion(Doku_Event $event, $param)
29    {
30        if ($event->data !== 'aichat') return;
31        $event->preventDefault();
32        $event->stopPropagation();
33        global $INPUT;
34
35        $question = $INPUT->post->str('question');
36        $history = json_decode($INPUT->post->str('history'));
37
38        /** @var helper_plugin_aichat $helper */
39        $helper = plugin_load('helper', 'aichat');
40
41        $result = $helper->askChatQuestion($question, $history);
42
43        $sources = [];
44        foreach ($result['sources'] as $source) {
45            $sources[wl($source['meta']['pageid'])] = p_get_first_heading($source['meta']['pageid']) ?:
46                $source['meta']['pageid'];
47        }
48
49        header('Content-Type: application/json');
50        echo json_encode([
51            'question' => $result['question'],
52            'answer' => $result['answer'],
53            'sources' => $sources,
54        ]);
55    }
56
57}
58
59