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