Move deprecated methods into the compatibility classes, out of the main library classes
[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 xmlrpcvals
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         //fclose($fp);
157         return $this->parseResponse($ipd);
158     }
159
160     /**
161      * Parses HTTP headers and separates them from data.
162      *
163      * @return null|Response null on success, or a Response on error
164      */
165     private function parseResponseHeaders(&$data, $headers_processed = false)
166     {
167         $this->httpResponse['headers'] = array();
168         $this->httpResponse['cookies'] = array();
169
170         // Support "web-proxy-tunelling" connections for https through proxies
171         if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
172             // Look for CR/LF or simple LF as line separator,
173             // (even though it is not valid http)
174             $pos = strpos($data, "\r\n\r\n");
175             if ($pos || is_int($pos)) {
176                 $bd = $pos + 4;
177             } else {
178                 $pos = strpos($data, "\n\n");
179                 if ($pos || is_int($pos)) {
180                     $bd = $pos + 2;
181                 } else {
182                     // No separation between response headers and body: fault?
183                     $bd = 0;
184                 }
185             }
186             if ($bd) {
187                 // this filters out all http headers from proxy.
188                 // maybe we could take them into account, too?
189                 $data = substr($data, $bd);
190             } else {
191                 error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
192                 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)');
193
194                 return $r;
195             }
196         }
197
198         // Strip HTTP 1.1 100 Continue header if present
199         while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
200             $pos = strpos($data, 'HTTP', 12);
201             // server sent a Continue header without any (valid) content following...
202             // give the client a chance to know it
203             if (!$pos && !is_int($pos)) {
204                 // works fine in php 3, 4 and 5
205
206                 break;
207             }
208             $data = substr($data, $pos);
209         }
210         if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
211             $errstr = substr($data, 0, strpos($data, "\n") - 1);
212             error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
213             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')');
214
215             return $r;
216         }
217
218         // be tolerant to usage of \n instead of \r\n to separate headers and data
219         // (even though it is not valid http)
220         $pos = strpos($data, "\r\n\r\n");
221         if ($pos || is_int($pos)) {
222             $bd = $pos + 4;
223         } else {
224             $pos = strpos($data, "\n\n");
225             if ($pos || is_int($pos)) {
226                 $bd = $pos + 2;
227             } else {
228                 // No separation between response headers and body: fault?
229                 // we could take some action here instead of going on...
230                 $bd = 0;
231             }
232         }
233         // be tolerant to line endings, and extra empty lines
234         $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
235         while (list(, $line) = @each($ar)) {
236             // take care of multi-line headers and cookies
237             $arr = explode(':', $line, 2);
238             if (count($arr) > 1) {
239                 $header_name = strtolower(trim($arr[0]));
240                 /// @todo some other headers (the ones that allow a CSV list of values)
241                 /// do allow many values to be passed using multiple header lines.
242                 /// We should add content to $xmlrpc->_xh['headers'][$header_name]
243                 /// instead of replacing it for those...
244                 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') {
245                     if ($header_name == 'set-cookie2') {
246                         // version 2 cookies:
247                         // there could be many cookies on one line, comma separated
248                         $cookies = explode(',', $arr[1]);
249                     } else {
250                         $cookies = array($arr[1]);
251                     }
252                     foreach ($cookies as $cookie) {
253                         // glue together all received cookies, using a comma to separate them
254                         // (same as php does with getallheaders())
255                         if (isset($this->httpResponse['headers'][$header_name])) {
256                             $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie);
257                         } else {
258                             $this->httpResponse['headers'][$header_name] = trim($cookie);
259                         }
260                         // parse cookie attributes, in case user wants to correctly honour them
261                         // feature creep: only allow rfc-compliant cookie attributes?
262                         // @todo support for server sending multiple time cookie with same name, but using different PATHs
263                         $cookie = explode(';', $cookie);
264                         foreach ($cookie as $pos => $val) {
265                             $val = explode('=', $val, 2);
266                             $tag = trim($val[0]);
267                             $val = trim(@$val[1]);
268                             /// @todo with version 1 cookies, we should strip leading and trailing " chars
269                             if ($pos == 0) {
270                                 $cookiename = $tag;
271                                 $this->httpResponse['cookies'][$tag] = array();
272                                 $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
273                             } else {
274                                 if ($tag != 'value') {
275                                     $this->httpResponse['cookies'][$cookiename][$tag] = $val;
276                                 }
277                             }
278                         }
279                     }
280                 } else {
281                     $this->httpResponse['headers'][$header_name] = trim($arr[1]);
282                 }
283             } elseif (isset($header_name)) {
284                 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
285                 $this->httpResponse['headers'][$header_name] .= ' ' . trim($line);
286             }
287         }
288
289         $data = substr($data, $bd);
290
291         if ($this->debug && count($this->httpResponse['headers'])) {
292             $msg = '';
293             foreach ($this->httpResponse['headers'] as $header => $value) {
294                 $msg .= "HEADER: $header: $value\n";
295             }
296             foreach ($this->httpResponse['cookies'] as $header => $value) {
297                 $msg .= "COOKIE: $header={$value['value']}\n";
298             }
299             $this->debugMessage($msg);
300         }
301
302         // if CURL was used for the call, http headers have been processed,
303         // and dechunking + reinflating have been carried out
304         if (!$headers_processed) {
305             // Decode chunked encoding sent by http 1.1 servers
306             if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') {
307                 if (!$data = Http::decode_chunked($data)) {
308                     error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
309                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
310
311                     return $r;
312                 }
313             }
314
315             // Decode gzip-compressed stuff
316             // code shamelessly inspired from nusoap library by Dietrich Ayala
317             if (isset($this->httpResponse['headers']['content-encoding'])) {
318                 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
319                 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') {
320                     // if decoding works, use it. else assume data wasn't gzencoded
321                     if (function_exists('gzinflate')) {
322                         if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
323                             $data = $degzdata;
324                             if ($this->debug) {
325                                 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
326                             }
327                         } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
328                             $data = $degzdata;
329                             if ($this->debug) {
330                                 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
331                             }
332                         } else {
333                             error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
334                             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
335
336                             return $r;
337                         }
338                     } else {
339                         error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
340                         $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
341
342                         return $r;
343                     }
344                 }
345             }
346         } // end of 'if needed, de-chunk, re-inflate response'
347
348         return;
349     }
350
351     /**
352      * Parse the xmlrpc response contained in the string $data and return a Response object.
353      *
354      * @param string $data the xmlrpc response, eventually including http headers
355      * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
356      * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
357      *
358      * @return Response
359      */
360     public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
361     {
362         if ($this->debug) {
363             // by maHo, replaced htmlspecialchars with htmlentities
364             $this->debugMessage("---GOT---\n$data\n---END---");
365         }
366
367         $this->httpResponse = array();
368         $this->httpResponse['raw_data'] = $data;
369         $this->httpResponse['headers'] = array();
370         $this->httpResponse['cookies'] = array();
371
372         if ($data == '') {
373             error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
374             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
375
376             return $r;
377         }
378
379         // parse the HTTP headers of the response, if present, and separate them from data
380         if (substr($data, 0, 4) == 'HTTP') {
381             $r = $this->parseResponseHeaders($data, $headers_processed);
382             if ($r) {
383                 // failed processing of HTTP response headers
384                 // save into response obj the full payload received, for debugging
385                 $r->raw_data = $data;
386
387                 return $r;
388             }
389         }
390
391         if ($this->debug) {
392             $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
393             if ($start) {
394                 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
395                 $end = strpos($data, '-->', $start);
396                 $comments = substr($data, $start, $end - $start);
397                 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
398             }
399         }
400
401         // be tolerant of extra whitespace in response body
402         $data = trim($data);
403
404         /// @todo return an error msg if $data=='' ?
405
406         // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
407         // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
408         $pos = strrpos($data, '</methodResponse>');
409         if ($pos !== false) {
410             $data = substr($data, 0, $pos + 17);
411         }
412
413         // if user wants back raw xml, give it to him
414         if ($return_type == 'xml') {
415             $r = new Response($data, 0, '', 'xml');
416             $r->hdrs = $this->httpResponse['headers'];
417             $r->_cookies = $this->httpResponse['cookies'];
418             $r->raw_data = $this->httpResponse['raw_data'];
419
420             return $r;
421         }
422
423         // try to 'guestimate' the character encoding of the received response
424         $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
425
426         // if response charset encoding is not known / supported, try to use
427         // the default encoding and parse the xml anyway, but log a warning...
428         if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
429             // the following code might be better for mb_string enabled installs, but
430             // makes the lib about 200% slower...
431             //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
432
433             error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
434             $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
435         }
436         $parser = xml_parser_create($resp_encoding);
437         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
438         // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
439         // the xml parser to give us back data in the expected charset.
440         // What if internal encoding is not in one of the 3 allowed?
441         // we use the broadest one, ie. utf8
442         // This allows to send data which is native in various charset,
443         // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
444         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
445             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
446         } else {
447             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
448         }
449
450         $xmlRpcParser = new XMLParser();
451         xml_set_object($parser, $xmlRpcParser);
452
453         if ($return_type == 'phpvals') {
454             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
455         } else {
456             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
457         }
458
459         xml_set_character_data_handler($parser, 'xmlrpc_cd');
460         xml_set_default_handler($parser, 'xmlrpc_dh');
461
462         // first error check: xml not well formed
463         if (!xml_parse($parser, $data, count($data))) {
464             // thanks to Peter Kocks <peter.kocks@baygate.com>
465             if ((xml_get_current_line_number($parser)) == 1) {
466                 $errstr = 'XML error at line 1, check URL';
467             } else {
468                 $errstr = sprintf('XML error: %s at line %d, column %d',
469                     xml_error_string(xml_get_error_code($parser)),
470                     xml_get_current_line_number($parser), xml_get_current_column_number($parser));
471             }
472             error_log($errstr);
473             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
474             xml_parser_free($parser);
475             if ($this->debug) {
476                 print $errstr;
477             }
478             $r->hdrs = $this->httpResponse['headers'];
479             $r->_cookies = $this->httpResponse['cookies'];
480             $r->raw_data = $this->httpResponse['raw_data'];
481
482             return $r;
483         }
484         xml_parser_free($parser);
485         // second error check: xml well formed but not xml-rpc compliant
486         if ($xmlRpcParser->_xh['isf'] > 1) {
487             if ($this->debug) {
488                 /// @todo echo something for user?
489             }
490
491             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
492                 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
493         }
494         // third error check: parsing of the response has somehow gone boink.
495         // NB: shall we omit this check, since we trust the parsing code?
496         elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
497             // something odd has happened
498             // and it's time to generate a client side error
499             // indicating something odd went on
500             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
501                 PhpXmlRpc::$xmlrpcstr['invalid_return']);
502         } else {
503             if ($this->debug) {
504                 $this->debugMessage(
505                     "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
506                 );
507             }
508
509             // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
510             $v = &$xmlRpcParser->_xh['value'];
511
512             if ($xmlRpcParser->_xh['isf']) {
513                 /// @todo we should test here if server sent an int and a string,
514                 /// and/or coerce them into such...
515                 if ($return_type == 'xmlrpcvals') {
516                     $errno_v = $v->structmem('faultCode');
517                     $errstr_v = $v->structmem('faultString');
518                     $errno = $errno_v->scalarval();
519                     $errstr = $errstr_v->scalarval();
520                 } else {
521                     $errno = $v['faultCode'];
522                     $errstr = $v['faultString'];
523                 }
524
525                 if ($errno == 0) {
526                     // FAULT returned, errno needs to reflect that
527                     $errno = -1;
528                 }
529
530                 $r = new Response(0, $errno, $errstr);
531             } else {
532                 $r = new Response($v, 0, '', $return_type);
533             }
534         }
535
536         $r->hdrs = $this->httpResponse['headers'];
537         $r->_cookies = $this->httpResponse['cookies'];
538         $r->raw_data = $this->httpResponse['raw_data'];
539
540         return $r;
541     }
542
543     /**
544      * Echoes a debug message, taking care of escaping it when not in console mode
545      *
546      * @param string $message
547      */
548     protected function debugMessage($message, $encodeEntities = true)
549     {
550         if (PHP_SAPI != 'cli') {
551             if ($encodeEntities)
552                 print "<PRE>\n".htmlentities($message)."\n</PRE>";
553             else
554                 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
555         }
556         else {
557             print "\n$message\n";
558         }
559     }
560 }