4 * Client for querying zhdaemon
8 var $mHost, $mPort, $mFP, $mConnected;
15 function ZhClient($host, $port) {
18 $this->mConnected
= $this->connect();
22 * Check if connection to zhdaemon is successful
24 function isconnected() {
25 return $this->mConnected
;
29 * Establish conncetion
35 $errno = $errstr = '';
36 $this->mFP
= fsockopen($this->mHost
, $this->mPort
, $errno, $errstr, 30);
45 * Query the daemon and return the result
49 function query($request) {
50 if(!$this->mConnected
)
53 fwrite($this->mFP
, $request);
55 $result=fgets($this->mFP
, 1024);
57 list($status, $len) = explode(" ", $result);
58 if($status == 'ERROR') {
59 //$len is actually the error code...
60 print "zhdaemon error $len<br />\n";
65 while(!feof($this->mFP
) && $bytesread<$len) {
66 $str= fread($this->mFP
, $len-$bytesread);
67 $bytesread +
= strlen($str);
70 //data should be of length $len. otherwise something is wrong
71 if(strlen($data) != $len)
77 * Convert the input to a different language variant
79 * @param $text string: input text
80 * @param $tolang string: language variant
81 * @return string the converted text
83 function convert($text, $tolang) {
85 $q = "CONV $tolang $len\n$text";
86 $result = $this->query($q);
93 * Convert the input to all possible variants
95 * @param $text string: input text
96 * @return array langcode => converted_string
98 function convertToAllVariants($text) {
100 $q = "CONV ALL $len\n$text";
101 $result = $this->query($q);
104 list($infoline, $data) = explode('|', $result, 2);
105 $info = explode(";", $infoline);
108 foreach($info as $variant) {
109 list($code, $len) = explode(' ', $variant);
110 $ret[strtolower($code)] = substr($data, $i, $len);
116 * Perform word segmentation
118 * @param $text string: input text
119 * @return string segmented text
121 function segment($text) {
122 $len = strlen($text);
123 $q = "SEG $len\n$text";
124 $result = $this->query($q);
125 if(!$result) {// fallback to character based segmentation
126 $result = ZhClientFake
::segment($text);
132 * Close the connection