4 * Client for querying zhdaemon
8 var $mHost, $mPort, $mFP, $mConnected;
15 function __construct($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
) {
54 fwrite($this->mFP
, $request);
56 $result=fgets($this->mFP
, 1024);
58 list($status, $len) = explode(" ", $result);
59 if($status == 'ERROR') {
60 //$len is actually the error code...
61 print "zhdaemon error $len<br />\n";
66 while(!feof($this->mFP
) && $bytesread<$len) {
67 $str= fread($this->mFP
, $len-$bytesread);
68 $bytesread +
= strlen($str);
71 //data should be of length $len. otherwise something is wrong
72 if ( strlen($data) != $len ) {
79 * Convert the input to a different language variant
81 * @param $text string: input text
82 * @param $tolang string: language variant
83 * @return string the converted text
85 function convert($text, $tolang) {
87 $q = "CONV $tolang $len\n$text";
88 $result = $this->query($q);
96 * Convert the input to all possible variants
98 * @param $text string: input text
99 * @return array langcode => converted_string
101 function convertToAllVariants($text) {
102 $len = strlen($text);
103 $q = "CONV ALL $len\n$text";
104 $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 $text string: input text
123 * @return string segmented text
125 function segment($text) {
126 $len = strlen($text);
127 $q = "SEG $len\n$text";
128 $result = $this->query($q);
129 if ( !$result ) {// fallback to character based segmentation
130 $result = $this->segment($text);
136 * Close the connection