4 * Client for querying zhdaemon
7 var $mHost, $mPort, $mFP, $mConnected;
14 function __construct( $host, $port ) {
17 $this->mConnected
= $this->connect();
21 * Check if connection to zhdaemon is successful
23 function isconnected() {
24 return $this->mConnected
;
28 * Establish conncetion
34 $errno = $errstr = '';
35 $this->mFP
= fsockopen( $this->mHost
, $this->mPort
, $errno, $errstr, 30 );
44 * Query the daemon and return the result
48 function query( $request ) {
49 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 ) {
78 * Convert the input to a different language variant
80 * @param $text String: input text
81 * @param $tolang String: language variant
82 * @return string the converted text
84 function convert( $text, $tolang ) {
85 $len = strlen( $text );
86 $q = "CONV $tolang $len\n$text";
87 $result = $this->query( $q );
95 * Convert the input to all possible variants
97 * @param $text String: input text
98 * @return array langcode => converted_string
100 function convertToAllVariants( $text ) {
101 $len = strlen( $text );
102 $q = "CONV ALL $len\n$text";
103 $result = $this->query( $q );
107 list( $infoline, $data ) = explode( '|', $result, 2 );
108 $info = explode( ';', $infoline );
111 foreach( $info as $variant ) {
112 list( $code, $len ) = explode( ' ', $variant );
113 $ret[strtolower( $code )] = substr( $data, $i, $len );
119 * Perform word segmentation
121 * @param $text String: input text
122 * @return string segmented text
124 function segment( $text ) {
125 $len = strlen( $text );
126 $q = "SEG $len\n$text";
127 $result = $this->query( $q );
128 if ( !$result ) { // fallback to character based segmentation
129 $result = $this->segment( $text );
135 * Close the connection
138 fclose( $this->mFP
);