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 );
48 * Query the daemon and return the result
54 function query( $request ) {
55 if ( !$this->mConnected
) {
59 fwrite( $this->mFP
, $request );
61 $result = fgets( $this->mFP
, 1024 );
63 list( $status, $len ) = explode( ' ', $result );
64 if( $status == 'ERROR' ) {
65 // $len is actually the error code...
66 print "zhdaemon error $len<br />\n";
71 while( !feof( $this->mFP
) && $bytesread < $len ) {
72 $str = fread( $this->mFP
, $len - $bytesread );
73 $bytesread +
= strlen( $str );
76 // data should be of length $len. otherwise something is wrong
77 return strlen( $data ) == $len;
81 * Convert the input to a different language variant
83 * @param $text String: input text
84 * @param $tolang String: language variant
85 * @return string the converted text
87 function convert( $text, $tolang ) {
88 $len = strlen( $text );
89 $q = "CONV $tolang $len\n$text";
90 $result = $this->query( $q );
98 * Convert the input to all possible variants
100 * @param $text String: input text
101 * @return array langcode => converted_string
103 function convertToAllVariants( $text ) {
104 $len = strlen( $text );
105 $q = "CONV ALL $len\n$text";
106 $result = $this->query( $q );
110 list( $infoline, $data ) = explode( '|', $result, 2 );
111 $info = explode( ';', $infoline );
114 foreach( $info as $variant ) {
115 list( $code, $len ) = explode( ' ', $variant );
116 $ret[strtolower( $code )] = substr( $data, $i, $len );
123 * Perform word segmentation
125 * @param $text String: input text
126 * @return string segmented text
128 function segment( $text ) {
129 $len = strlen( $text );
130 $q = "SEG $len\n$text";
131 $result = $this->query( $q );
132 if ( !$result ) { // fallback to character based segmentation
133 $result = $this->segment( $text );
139 * Close the connection
142 fclose( $this->mFP
);