Browse Source

use curl for dictionary lookups instead of dictc

Andrew Dolgov 5 days ago
parent
commit
597e3ebdb5
1 changed files with 34 additions and 29 deletions
  1. 34 29
      backend.php

+ 34 - 29
backend.php

@@ -241,50 +241,55 @@
 
 		break;
 	case "define":
-
 		if (defined('DICT_ENABLED') && DICT_ENABLED) {
+			function parse_dict_reply($reply) {
+				$tmp = [];
 
-			/* strip hyphens */
-			$word = str_replace("­", "", $_REQUEST["word"]);
-
-			$word = escapeshellarg($word);
+				foreach (explode("\n", $reply) as $line) {
+					list ($code, $message) = explode(" ", $line, 2);
 
-			exec(DICT_CLIENT . " -h ". DICT_SERVER ." $word 2>&1", $output, $rc);
+					if (!$code && $message)
+						array_push($tmp, $message);
+				}
 
-			if ($rc == 0) {
-				print json_encode(["result" => $output]);
+				return $tmp;
+			}
 
-			} else if ($rc == 21) {
+			/* strip hyphens */
+			$word = strip_tags(str_replace("­", "", $_REQUEST["word"]));
+			$orig_word = $word;
 
-				$word_matches = [];
+			$result = [];
 
-				foreach ($output as $line) {
-					if (preg_match('/^[^ ]+: *(.*)/', $line, $match)) {
+			for ($i = 0; $i < 3; $i++) {
+				$ch = curl_init();
+				curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", DICT_SERVER, $word));
+				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+				$dict_reply = curl_exec($ch);
 
-						if ($match[1]) {
-							$word_matches = explode("  ", $match[1]);
-							break;
-						}
-					}
-				}
+				if ($dict_reply) {
+					$ret_parsed = parse_dict_reply($dict_reply);
 
-				$word_matches = implode(" ", array_map("escapeshellarg", $word_matches));
+					if (count($ret_parsed) > 0) {
+						array_push($result, "<strong>$word</strong>");
 
-				unset($output);
-				exec(DICT_CLIENT . " -h ". DICT_SERVER ." $word_matches 2>&1", $output, $rc);
+						$result = array_merge($result, $ret_parsed);
+						break;
+					} else {
+						$word = mb_substr($word, 0, mb_strlen($word)-1);
+					}
 
-				if ($rc == 0) {
-					print json_encode(["result" => $output]);
+				} else {
+					array_push($result, curl_error($ch));
 				}
-			} else if ($rc == 20) {
 
-				exec(DICT_CLIENT . " -s soundex -h ". DICT_SERVER ." $word 2>&1", $output, $rc);
+				curl_close($ch);
+			}
 
-				print json_encode(["result" => $output]);
+			if (count($result) == 0)
+				array_push($result, "No results for: <b>$orig_word</b>");
 
-			} else {
-				print json_encode(["result" => $output]);
-			}
+			print json_encode(["result" => $result]);
 		}
 
 		break;