4 * Client for querying zhdaemon
7 var $mHost, $mPort, $mFP, $mConnected;
17 function __construct( $host, $port ) {
20 $this->mConnected
= $this->connect();
24 * Check if connection to zhdaemon is successful
28 function isconnected() {
29 return $this->mConnected
;
33 * Establish conncetion
41 $errno = $errstr = '';
42 $this->mFP
= fsockopen( $this->mHost
, $this->mPort
, $errno, $errstr, 30 );
51 * Query the daemon and return the result
57 function query( $request ) {
58 if ( !$this->mConnected
) {
62 fwrite( $this->mFP
, $request );
64 $result = fgets( $this->mFP
, 1024 );
66 list( $status, $len ) = explode( ' ', $result );
67 if( $status == 'ERROR' ) {
68 // $len is actually the error code...
69 print "zhdaemon error $len<br />\n";
74 while( !feof( $this->mFP
) && $bytesread < $len ) {
75 $str = fread( $this->mFP
, $len - $bytesread );
76 $bytesread +
= strlen( $str );
79 // data should be of length $len. otherwise something is wrong
80 if ( strlen( $data ) != $len ) {
87 * Convert the input to a different language variant
89 * @param $text String: input text
90 * @param $tolang String: language variant
91 * @return string the converted text
93 function convert( $text, $tolang ) {
94 $len = strlen( $text );
95 $q = "CONV $tolang $len\n$text";
96 $result = $this->query( $q );
104 * Convert the input to all possible variants
106 * @param $text String: input text
107 * @return array langcode => converted_string
109 function convertToAllVariants( $text ) {
110 $len = strlen( $text );
111 $q = "CONV ALL $len\n$text";
112 $result = $this->query( $q );
116 list( $infoline, $data ) = explode( '|', $result, 2 );
117 $info = explode( ';', $infoline );
120 foreach( $info as $variant ) {
121 list( $code, $len ) = explode( ' ', $variant );
122 $ret[strtolower( $code )] = substr( $data, $i, $len );
128 * Perform word segmentation
130 * @param $text String: input text
131 * @return string segmented text
133 function segment( $text ) {
134 $len = strlen( $text );
135 $q = "SEG $len\n$text";
136 $result = $this->query( $q );
137 if ( !$result ) { // fallback to character based segmentation
138 $result = $this->segment( $text );
144 * Close the connection
147 fclose( $this->mFP
);