Update code comments: remove old class names
[plcapi.git] / src / Request.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\Http;
6 use PhpXmlRpc\Helper\XMLParser;
7
8 class Request
9 {
10     /// @todo: do these need to be public?
11     public $payload;
12     public $methodname;
13     public $params = array();
14     public $debug = 0;
15     public $content_type = 'text/xml';
16
17     // holds data while parsing the response. NB: Not a full Response object
18     protected $httpResponse = array();
19
20     /**
21      * @param string $methodName the name of the method to invoke
22      * @param Value[] $params array of parameters to be passed to the method (Value objects)
23      */
24     public function __construct($methodName, $params = array())
25     {
26         $this->methodname = $methodName;
27         foreach ($params as $param) {
28             $this->addParam($param);
29         }
30     }
31
32     public function xml_header($charset_encoding = '')
33     {
34         if ($charset_encoding != '') {
35             return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
36         } else {
37             return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
38         }
39     }
40
41     public function xml_footer()
42     {
43         return '</methodCall>';
44     }
45
46     public function createPayload($charset_encoding = '')
47     {
48         if ($charset_encoding != '') {
49             $this->content_type = 'text/xml; charset=' . $charset_encoding;
50         } else {
51             $this->content_type = 'text/xml';
52         }
53         $this->payload = $this->xml_header($charset_encoding);
54         $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
55         $this->payload .= "<params>\n";
56         foreach ($this->params as $p) {
57             $this->payload .= "<param>\n" . $p->serialize($charset_encoding) .
58                 "</param>\n";
59         }
60         $this->payload .= "</params>\n";
61         $this->payload .= $this->xml_footer();
62     }
63
64     /**
65      * Gets/sets the xmlrpc method to be invoked.
66      *
67      * @param string $methodName the method to be set (leave empty not to set it)
68      *
69      * @return string the method that will be invoked
70      */
71     public function method($methodName = '')
72     {
73         if ($methodName != '') {
74             $this->methodname = $methodName;
75         }
76
77         return $this->methodname;
78     }
79
80     /**
81      * Returns xml representation of the message. XML prologue included.
82      *
83      * @param string $charset_encoding
84      *
85      * @return string the xml representation of the message, xml prologue included
86      */
87     public function serialize($charset_encoding = '')
88     {
89         $this->createPayload($charset_encoding);
90
91         return $this->payload;
92     }
93
94     /**
95      * Add a parameter to the list of parameters to be used upon method invocation.
96      *
97      * @param Value $param
98      *
99      * @return boolean false on failure
100      */
101     public function addParam($param)
102     {
103         // add check: do not add to self params which are not xmlrpc values
104         if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
105             $this->params[] = $param;
106
107             return true;
108         } else {
109             return false;
110         }
111     }
112
113     /**
114      * Returns the nth parameter in the request. The index zero-based.
115      *
116      * @param integer $i the index of the parameter to fetch (zero based)
117      *
118      * @return Value the i-th parameter
119      */
120     public function getParam($i)
121     {
122         return $this->params[$i];
123     }
124
125     /**
126      * Returns the number of parameters in the message.
127      *
128      * @return integer the number of parameters currently set
129      */
130     public function getNumParams()
131     {
132         return count($this->params);
133     }
134
135     /**
136      * Given an open file handle, read all data available and parse it as an xmlrpc response.
137      * NB: the file handle is not closed by this function.
138      * NNB: might have trouble in rare cases to work on network streams, as we
139      *      check for a read of 0 bytes instead of feof($fp).
140      *      But since checking for feof(null) returns false, we would risk an
141      *      infinite loop in that case, because we cannot trust the caller
142      *      to give us a valid pointer to an open file...
143      *
144      * @param resource $fp stream pointer
145      *
146      * @return Response
147      *
148      * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
149      */
150     public function parseResponseFile($fp)
151     {
152         $ipd = '';
153         while ($data = fread($fp, 32768)) {
154             $ipd .= $data;
155         }
156         return $this->parseResponse($ipd);
157     }
158
159     /**
160      * Parse the xmlrpc response contained in the string $data and return a Response object.
161      *
162      * @param string $data the xmlrpc response, eventually including http headers
163      * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
164      * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
165      *
166      * @return Response
167      */
168     public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
169     {
170         if ($this->debug) {
171             // by maHo, replaced htmlspecialchars with htmlentities
172             $this->debugMessage("---GOT---\n$data\n---END---");
173         }
174
175         $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
176
177         if ($data == '') {
178             error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
179             return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
180         }
181
182         // parse the HTTP headers of the response, if present, and separate them from data
183         if (substr($data, 0, 4) == 'HTTP') {
184             $httpParser = new Http();
185             try {
186                 $this->httpResponse = $httpParser->parseResponseHeaders($data, $headers_processed, $this->debug);
187             } catch(\Exception $e) {
188                 $r = new Response(0, $e->getCode(), $e->getMessage());
189                 // failed processing of HTTP response headers
190                 // save into response obj the full payload received, for debugging
191                 $r->raw_data = $data;
192
193                 return $r;
194             }
195         }
196
197         if ($this->debug) {
198             $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
199             if ($start) {
200                 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
201                 $end = strpos($data, '-->', $start);
202                 $comments = substr($data, $start, $end - $start);
203                 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
204             }
205         }
206
207         // be tolerant of extra whitespace in response body
208         $data = trim($data);
209
210         /// @todo return an error msg if $data=='' ?
211
212         // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
213         // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
214         $pos = strrpos($data, '</methodResponse>');
215         if ($pos !== false) {
216             $data = substr($data, 0, $pos + 17);
217         }
218
219         // if user wants back raw xml, give it to him
220         if ($return_type == 'xml') {
221             $r = new Response($data, 0, '', 'xml');
222             $r->hdrs = $this->httpResponse['headers'];
223             $r->_cookies = $this->httpResponse['cookies'];
224             $r->raw_data = $this->httpResponse['raw_data'];
225
226             return $r;
227         }
228
229         // try to 'guestimate' the character encoding of the received response
230         $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
231
232         // if response charset encoding is not known / supported, try to use
233         // the default encoding and parse the xml anyway, but log a warning...
234         if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
235             // the following code might be better for mb_string enabled installs, but
236             // makes the lib about 200% slower...
237             //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
238
239             error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
240             $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
241         }
242         $parser = xml_parser_create($resp_encoding);
243         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
244         // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
245         // the xml parser to give us back data in the expected charset.
246         // What if internal encoding is not in one of the 3 allowed?
247         // we use the broadest one, ie. utf8
248         // This allows to send data which is native in various charset,
249         // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
250         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
251             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
252         } else {
253             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
254         }
255
256         $xmlRpcParser = new XMLParser();
257         xml_set_object($parser, $xmlRpcParser);
258
259         if ($return_type == 'phpvals') {
260             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
261         } else {
262             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
263         }
264
265         xml_set_character_data_handler($parser, 'xmlrpc_cd');
266         xml_set_default_handler($parser, 'xmlrpc_dh');
267
268         // first error check: xml not well formed
269         if (!xml_parse($parser, $data, count($data))) {
270             // thanks to Peter Kocks <peter.kocks@baygate.com>
271             if ((xml_get_current_line_number($parser)) == 1) {
272                 $errstr = 'XML error at line 1, check URL';
273             } else {
274                 $errstr = sprintf('XML error: %s at line %d, column %d',
275                     xml_error_string(xml_get_error_code($parser)),
276                     xml_get_current_line_number($parser), xml_get_current_column_number($parser));
277             }
278             error_log($errstr);
279             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
280             xml_parser_free($parser);
281             if ($this->debug) {
282                 print $errstr;
283             }
284             $r->hdrs = $this->httpResponse['headers'];
285             $r->_cookies = $this->httpResponse['cookies'];
286             $r->raw_data = $this->httpResponse['raw_data'];
287
288             return $r;
289         }
290         xml_parser_free($parser);
291         // second error check: xml well formed but not xml-rpc compliant
292         if ($xmlRpcParser->_xh['isf'] > 1) {
293             if ($this->debug) {
294                 /// @todo echo something for user?
295             }
296
297             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
298                 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
299         }
300         // third error check: parsing of the response has somehow gone boink.
301         // NB: shall we omit this check, since we trust the parsing code?
302         elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
303             // something odd has happened
304             // and it's time to generate a client side error
305             // indicating something odd went on
306             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
307                 PhpXmlRpc::$xmlrpcstr['invalid_return']);
308         } else {
309             if ($this->debug) {
310                 $this->debugMessage(
311                     "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
312                 );
313             }
314
315             // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
316             $v = &$xmlRpcParser->_xh['value'];
317
318             if ($xmlRpcParser->_xh['isf']) {
319                 /// @todo we should test here if server sent an int and a string,
320                 /// and/or coerce them into such...
321                 if ($return_type == 'xmlrpcvals') {
322                     $errno_v = $v->structmem('faultCode');
323                     $errstr_v = $v->structmem('faultString');
324                     $errno = $errno_v->scalarval();
325                     $errstr = $errstr_v->scalarval();
326                 } else {
327                     $errno = $v['faultCode'];
328                     $errstr = $v['faultString'];
329                 }
330
331                 if ($errno == 0) {
332                     // FAULT returned, errno needs to reflect that
333                     $errno = -1;
334                 }
335
336                 $r = new Response(0, $errno, $errstr);
337             } else {
338                 $r = new Response($v, 0, '', $return_type);
339             }
340         }
341
342         $r->hdrs = $this->httpResponse['headers'];
343         $r->_cookies = $this->httpResponse['cookies'];
344         $r->raw_data = $this->httpResponse['raw_data'];
345
346         return $r;
347     }
348
349     /**
350      * Echoes a debug message, taking care of escaping it when not in console mode
351      *
352      * @param string $message
353      */
354     protected function debugMessage($message, $encodeEntities = true)
355     {
356         if (PHP_SAPI != 'cli') {
357             if ($encodeEntities)
358                 print "<PRE>\n".htmlentities($message)."\n</PRE>";
359             else
360                 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
361         }
362         else {
363             print "\n$message\n";
364         }
365     }
366 }