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
26 function isconnected() {
27 return $this->mConnected
;
31 * Establish conncetion
37 $errno = $errstr = '';
38 $this->mFP
= fsockopen($this->mHost
, $this->mPort
, $errno, $errstr, 30);
47 * Query the daemon and return the result
51 function query($request) {
52 if(!$this->mConnected
)
55 fwrite($this->mFP
, $request);
57 $result=fgets($this->mFP
, 1024);
59 list($status, $len) = explode(" ", $result);
60 if($status == 'ERROR') {
61 //$len is actually the error code...
62 print "zhdaemon error $len<br />\n";
67 while(!feof($this->mFP
) && $bytesread<$len) {
68 $str= fread($this->mFP
, $len-$bytesread);
69 $bytesread +
= strlen($str);
72 //data should be of length $len. otherwise something is wrong
73 if(strlen($data) != $len)
79 * Convert the input to a different language variant
81 * @param string $text input text
82 * @param string $tolang language variant
83 * @return string the converted text
86 function convert($text, $tolang) {
88 $q = "CONV $tolang $len\n$text";
89 $result = $this->query($q);
96 * Convert the input to all possible variants
98 * @param string $text input text
99 * @return array langcode => converted_string
102 function convertToAllVariants($text) {
103 $len = strlen($text);
104 $q = "CONV ALL $len\n$text";
105 $result = $this->query($q);
108 list($infoline, $data) = explode('|', $result, 2);
109 $info = explode(";", $infoline);
112 foreach($info as $variant) {
113 list($code, $len) = explode(' ', $variant);
114 $ret[strtolower($code)] = substr($data, $i, $len);
120 * Perform word segmentation
122 * @param string $text input text
123 * @return string segmented text
126 function segment($text) {
127 $len = strlen($text);
128 $q = "SEG $len\n$text";
129 $result = $this->query($q);
130 if(!$result) {// fallback to character based segmentation
131 $result = ZhClientFake
::segment($text);
137 * Close the connection