Doc tweaks:
[mediawiki.git] / includes / ZhClient.php
blobfe965f651f46295936198a3421a7ed03b5eddc96
1 <?php
2 /**
3 */
5 /**
6 * Client for querying zhdaemon
8 */
9 class ZhClient {
10 var $mHost, $mPort, $mFP, $mConnected;
12 /**
13 * Constructor
15 * @access private
17 function ZhClient($host, $port) {
18 $this->mHost = $host;
19 $this->mPort = $port;
20 $this->mConnected = $this->connect();
23 /**
24 * Check if connection to zhdaemon is successful
26 * @access public
28 function isconnected() {
29 return $this->mConnected;
32 /**
33 * Establish conncetion
35 * @access private
37 function connect() {
38 wfSuppressWarnings();
39 $errno = $errstr = '';
40 $this->mFP = fsockopen($this->mHost, $this->mPort, $errno, $errstr, 30);
41 wfRestoreWarnings();
42 if(!$this->mFP) {
43 return false;
45 return true;
48 /**
49 * Query the daemon and return the result
51 * @access private
53 function query($request) {
54 if(!$this->mConnected)
55 return false;
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";
65 return false;
67 $bytesread=0;
68 $data='';
69 while(!feof($this->mFP) && $bytesread<$len) {
70 $str= fread($this->mFP, $len-$bytesread);
71 $bytesread += strlen($str);
72 $data .= $str;
74 //data should be of length $len. otherwise something is wrong
75 if(strlen($data) != $len)
76 return false;
77 return $data;
80 /**
81 * Convert the input to a different language variant
83 * @param string $text input text
84 * @param string $tolang language variant
85 * @return string the converted text
86 * @access public
88 function convert($text, $tolang) {
89 $len = strlen($text);
90 $q = "CONV $tolang $len\n$text";
91 $result = $this->query($q);
92 if(!$result)
93 $result = $text;
94 return $result;
97 /**
98 * Convert the input to all possible variants
100 * @param string $text input text
101 * @return array langcode => converted_string
102 * @access public
104 function convertToAllVariants($text) {
105 $len = strlen($text);
106 $q = "CONV ALL $len\n$text";
107 $result = $this->query($q);
108 if(!$result)
109 return false;
110 list($infoline, $data) = explode('|', $result, 2);
111 $info = explode(";", $infoline);
112 $ret = array();
113 $i=0;
114 foreach($info as $variant) {
115 list($code, $len) = explode(' ', $variant);
116 $ret[strtolower($code)] = substr($data, $i, $len);
117 $i+=$len;
119 return $ret;
122 * Perform word segmentation
124 * @param string $text input text
125 * @return string segmented text
126 * @access public
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 = ZhClientFake::segment($text);
135 return $result;
139 * Close the connection
141 * @access public
143 function close() {
144 fclose($this->mFP);