7807319e9214cb95f6548f8c1281c1e75cc02dcf
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
25 function isconnected() {
26 return $this->mConnected
;
30 * Establish conncetion
38 $errno = $errstr = '';
39 $this->mFP
= fsockopen( $this->mHost
, $this->mPort
, $errno, $errstr, 30 );
48 * Query the daemon and return the result
52 function query( $request ) {
53 if ( !$this->mConnected
) {
57 fwrite( $this->mFP
, $request );
59 $result = fgets( $this->mFP
, 1024 );
61 list( $status, $len ) = explode( ' ', $result );
62 if( $status == 'ERROR' ) {
63 // $len is actually the error code...
64 print "zhdaemon error $len<br />\n";
69 while( !feof( $this->mFP
) && $bytesread < $len ) {
70 $str = fread( $this->mFP
, $len - $bytesread );
71 $bytesread +
= strlen( $str );
74 // data should be of length $len. otherwise something is wrong
75 if ( strlen( $data ) != $len ) {
82 * Convert the input to a different language variant
84 * @param $text String: input text
85 * @param $tolang String: language variant
86 * @return string the converted text
88 function convert( $text, $tolang ) {
89 $len = strlen( $text );
90 $q = "CONV $tolang $len\n$text";
91 $result = $this->query( $q );
99 * Convert the input to all possible variants
101 * @param $text String: input text
102 * @return array langcode => converted_string
104 function convertToAllVariants( $text ) {
105 $len = strlen( $text );
106 $q = "CONV ALL $len\n$text";
107 $result = $this->query( $q );
111 list( $infoline, $data ) = explode( '|', $result, 2 );
112 $info = explode( ';', $infoline );
115 foreach( $info as $variant ) {
116 list( $code, $len ) = explode( ' ', $variant );
117 $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
);