about summary refs log tree commit diff stats
path: root/classes/Handler/DefineHandler.php
blob: 3da21dac52d88587865885cb461b94f037bab8d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php

namespace Handler;

use AuthRequired;
use Config;
use Request;
use RequestHandlerInterface;
use Response;

class DefineHandler implements RequestHandlerInterface, AuthRequired
{
    /** @return array<string> */
    private function parseDictReply(string $reply): array
    {
        $tmp = [];

        foreach (explode("\n", $reply) as $line) {
            list($code, $message) = explode(" ", $line, 2);

            if (!$code && $message) {
                array_push($tmp, $message);
            }
        }

        return $tmp;
    }

    public function handle(Request $request): Response
    {
        if (!Config::get(Config::DICT_SERVER)) {
            return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]]));
        }

        $word = strip_tags(str_replace("­", "", $request->getString('word')));
        $origWord = $word;
        $result = [];

        for ($i = 0; $i < 3; $i++) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $dictReply = curl_exec($ch);

            if ($dictReply) {
                $retParsed = $this->parseDictReply($dictReply);

                if (count($retParsed) > 0) {
                    array_push($result, "<strong>" . htmlspecialchars($word, ENT_QUOTES, 'UTF-8') . "</strong>");
                    $result = array_merge($result, $retParsed);
                    break;
                } else {
                    $word = mb_substr($word, 0, mb_strlen($word) - 1);
                }
            } else {
                $curlErr = curl_error($ch);
                if ($curlErr) {
                    user_error("dictd define lookup failed for '$word': $curlErr", E_USER_WARNING);
                }
                array_push($result, "Dictionary lookup failed. Please try again later.");
            }

            curl_close($ch);
        }

        if (count($result) == 0) {
            array_push($result, "No results for: <b>" . htmlspecialchars($origWord, ENT_QUOTES, 'UTF-8') . "</b>");
        }

        return (new Response())->withBody(json_encode(["result" => $result]));
    }
}