about summary refs log tree commit diff stats
path: root/classes/Handler/DefineHandler.php
blob: 87fd3f927e9c05fc346e43b462849a06f91097c1 (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
<?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->getAttribute('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>$word</strong>");
					$result = array_merge($result, $retParsed);
					break;
				} else {
					$word = mb_substr($word, 0, mb_strlen($word) - 1);
				}
			} else {
				array_push($result, curl_error($ch));
			}

			curl_close($ch);
		}

		if (count($result) == 0) {
			array_push($result, "No results for: <b>$origWord</b>");
		}

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