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 $this->mFP
= fsockopen($this->mHost
, $this->mPort
, $errno, $errstr, 30);
50 * Query the daemon and return the result
54 function query($request) {
55 if(!$this->mConnected
)
58 fwrite($this->mFP
, $request);
60 $result=fgets($this->mFP
, 1024);
62 list($status, $len) = explode(" ", $result);
63 if($status == 'ERROR') {
64 //$len is actually the error code...
65 print "zhdaemon error $len<br />\n";
70 while(!feof($this->mFP
) && $bytesread<$len) {
71 $str= fread($this->mFP
, $len-$bytesread);
72 $bytesread +
= strlen($str);
75 //data should be of length $len. otherwise something is wrong
76 if(strlen($data) != $len)
82 * Convert the input to a different language variant
84 * @param string $text input text
85 * @param string $tolang language variant
86 * @return string the converted text
89 function convert($text, $tolang) {
91 $q = "CONV $tolang $len\n$text";
92 $result = $this->query($q);
99 * Convert the input to all possible variants
101 * @param string $text input text
102 * @return array langcode => converted_string
105 function convertToAllVariants($text) {
106 $len = strlen($text);
107 $q = "CONV ALL $len\n$text";
108 $result = $this->query($q);
111 list($infoline, $data) = explode('|', $result, 2);
112 $info = explode(";", $infoline);
115 foreach($info as $variant) {
116 list($code, $len) = explode(' ', $variant);
117 $ret[strtolower($code)] = substr($data, $i, $len);
118 $r = $ret[strtolower($code)];
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