6 * Client for querying zhdaemon
10 var $mHost, $mPort, $mFP, $mConnected;
17 function ZhClient($host, $port) {
20 $this->mConnected
= $this->connect();
24 * Check if connection to zhdaemon is successful
28 function isconnected() {
29 return $this->mConnected
;
33 * Establish conncetion
39 $errno = $errstr = '';
40 $this->mFP
= fsockopen($this->mHost
, $this->mPort
, $errno, $errstr, 30);
49 * Query the daemon and return the result
53 function query($request) {
54 if(!$this->mConnected
)
57 fwrite($this->mFP
, $request);
59 $result=fgets($this->mFP
, 1024);
61 list($status, $len) = explode(" ", $result);
62 if($status == 'ERROR') {
63 //$len is actually the error code...
64 print "zhdaemon error $len<br />\n";
69 while(!feof($this->mFP
) && $bytesread<$len) {
70 $str= fread($this->mFP
, $len-$bytesread);
71 $bytesread +
= strlen($str);
74 //data should be of length $len. otherwise something is wrong
75 if(strlen($data) != $len)
81 * Convert the input to a different language variant
83 * @param string $text input text
84 * @param string $tolang language variant
85 * @return string the converted text
88 function convert($text, $tolang) {
90 $q = "CONV $tolang $len\n$text";
91 $result = $this->query($q);
98 * Convert the input to all possible variants
100 * @param string $text input text
101 * @return array langcode => converted_string
104 function convertToAllVariants($text) {
105 $len = strlen($text);
106 $q = "CONV ALL $len\n$text";
107 $result = $this->query($q);
110 list($infoline, $data) = explode('|', $result, 2);
111 $info = explode(";", $infoline);
114 foreach($info as $variant) {
115 list($code, $len) = explode(' ', $variant);
116 $ret[strtolower($code)] = substr($data, $i, $len);
122 * Perform word segmentation
124 * @param string $text input text
125 * @return string segmented text
128 function segment($text) {
129 $len = strlen($text);
130 $q = "SEG $len\n$text";
131 $result = $this->query($q);
132 if(!$result) {// fallback to character based segmentation
133 $result = ZhClientFake
::segment($text);
139 * Close the connection