7 * Client for querying zhdaemon
12 var $mHost, $mPort, $mFP, $mConnected;
19 function ZhClient($host, $port) {
22 $this->mConnected
= $this->connect();
26 * Check if connection to zhdaemon is successful
30 function isconnected() {
31 return $this->mConnected
;
35 * Establish conncetion
41 $errno = $errstr = '';
42 $this->mFP
= fsockopen($this->mHost
, $this->mPort
, $errno, $errstr, 30);
51 * Query the daemon and return the result
55 function query($request) {
56 if(!$this->mConnected
)
59 fwrite($this->mFP
, $request);
61 $result=fgets($this->mFP
, 1024);
63 list($status, $len) = explode(" ", $result);
64 if($status == 'ERROR') {
65 //$len is actually the error code...
66 print "zhdaemon error $len<br />\n";
71 while(!feof($this->mFP
) && $bytesread<$len) {
72 $str= fread($this->mFP
, $len-$bytesread);
73 $bytesread +
= strlen($str);
76 //data should be of length $len. otherwise something is wrong
77 if(strlen($data) != $len)
83 * Convert the input to a different language variant
85 * @param string $text input text
86 * @param string $tolang language variant
87 * @return string the converted text
90 function convert($text, $tolang) {
92 $q = "CONV $tolang $len\n$text";
93 $result = $this->query($q);
100 * Convert the input to all possible variants
102 * @param string $text input text
103 * @return array langcode => converted_string
106 function convertToAllVariants($text) {
107 $len = strlen($text);
108 $q = "CONV ALL $len\n$text";
109 $result = $this->query($q);
112 list($infoline, $data) = explode('|', $result, 2);
113 $info = explode(";", $infoline);
116 foreach($info as $variant) {
117 list($code, $len) = explode(' ', $variant);
118 $ret[strtolower($code)] = substr($data, $i, $len);
124 * Perform word segmentation
126 * @param string $text input text
127 * @return string segmented text
130 function segment($text) {
131 $len = strlen($text);
132 $q = "SEG $len\n$text";
133 $result = $this->query($q);
134 if(!$result) {// fallback to character based segmentation
135 $result = ZhClientFake
::segment($text);
141 * Close the connection