MediaWiki
REL1_19
|
00001 <?php 00002 00006 class ZhClient { 00007 var $mHost, $mPort, $mFP, $mConnected; 00008 00017 function __construct( $host, $port ) { 00018 $this->mHost = $host; 00019 $this->mPort = $port; 00020 $this->mConnected = $this->connect(); 00021 } 00022 00028 function isconnected() { 00029 return $this->mConnected; 00030 } 00031 00039 function connect() { 00040 wfSuppressWarnings(); 00041 $errno = $errstr = ''; 00042 $this->mFP = fsockopen( $this->mHost, $this->mPort, $errno, $errstr, 30 ); 00043 wfRestoreWarnings(); 00044 return !$this->mFP; 00045 } 00046 00054 function query( $request ) { 00055 if ( !$this->mConnected ) { 00056 return false; 00057 } 00058 00059 fwrite( $this->mFP, $request ); 00060 00061 $result = fgets( $this->mFP, 1024 ); 00062 00063 list( $status, $len ) = explode( ' ', $result ); 00064 if( $status == 'ERROR' ) { 00065 // $len is actually the error code... 00066 print "zhdaemon error $len<br />\n"; 00067 return false; 00068 } 00069 $bytesread = 0; 00070 $data = ''; 00071 while( !feof( $this->mFP ) && $bytesread < $len ) { 00072 $str = fread( $this->mFP, $len - $bytesread ); 00073 $bytesread += strlen( $str ); 00074 $data .= $str; 00075 } 00076 // data should be of length $len. otherwise something is wrong 00077 return strlen( $data ) == $len; 00078 } 00079 00087 function convert( $text, $tolang ) { 00088 $len = strlen( $text ); 00089 $q = "CONV $tolang $len\n$text"; 00090 $result = $this->query( $q ); 00091 if ( !$result ) { 00092 $result = $text; 00093 } 00094 return $result; 00095 } 00096 00103 function convertToAllVariants( $text ) { 00104 $len = strlen( $text ); 00105 $q = "CONV ALL $len\n$text"; 00106 $result = $this->query( $q ); 00107 if ( !$result ) { 00108 return false; 00109 } 00110 list( $infoline, $data ) = explode( '|', $result, 2 ); 00111 $info = explode( ';', $infoline ); 00112 $ret = array(); 00113 $i = 0; 00114 foreach( $info as $variant ) { 00115 list( $code, $len ) = explode( ' ', $variant ); 00116 $ret[strtolower( $code )] = substr( $data, $i, $len ); 00117 $i += $len; 00118 } 00119 return $ret; 00120 } 00121 00128 function segment( $text ) { 00129 $len = strlen( $text ); 00130 $q = "SEG $len\n$text"; 00131 $result = $this->query( $q ); 00132 if ( !$result ) { // fallback to character based segmentation 00133 $result = $this->segment( $text ); 00134 } 00135 return $result; 00136 } 00137 00141 function close() { 00142 fclose( $this->mFP ); 00143 } 00144 }