Improve debug messages when running on command line
[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 array $params array of parameters to be passed to the method (xmlrpcval 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 $meth 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 $par
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 messge.
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 axmlrpc 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         /// @todo when in CLI mode, do not html-encode the output
302         if ($this->debug && count($this->httpResponse['headers'])) {
303             print "</PRE>\n";
304             foreach ($this->httpResponse['headers'] as $header => $value) {
305                 print htmlentities("HEADER: $header: $value\n");
306             }
307             foreach ($this->httpResponse['cookies'] as $header => $value) {
308                 print htmlentities("COOKIE: $header={$value['value']}\n");
309             }
310             print "</PRE>\n";
311         }
312
313         // if CURL was used for the call, http headers have been processed,
314         // and dechunking + reinflating have been carried out
315         if (!$headers_processed) {
316             // Decode chunked encoding sent by http 1.1 servers
317             if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') {
318                 if (!$data = Http::decode_chunked($data)) {
319                     error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
320                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']);
321
322                     return $r;
323                 }
324             }
325
326             // Decode gzip-compressed stuff
327             // code shamelessly inspired from nusoap library by Dietrich Ayala
328             if (isset($this->httpResponse['headers']['content-encoding'])) {
329                 $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']);
330                 if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') {
331                     // if decoding works, use it. else assume data wasn't gzencoded
332                     if (function_exists('gzinflate')) {
333                         if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
334                             $data = $degzdata;
335                             if ($this->debug) {
336                                 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
337                             }
338                         } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
339                             $data = $degzdata;
340                             if ($this->debug) {
341                                 $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
342                             }
343                         } else {
344                             error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
345                             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']);
346
347                             return $r;
348                         }
349                     } else {
350                         error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
351                         $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']);
352
353                         return $r;
354                     }
355                 }
356             }
357         } // end of 'if needed, de-chunk, re-inflate response'
358
359         return;
360     }
361
362     /**
363      * Parse the xmlrpc response contained in the string $data and return a Response object.
364      *
365      * @param string $data the xmlrpc response, eventually including http headers
366      * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
367      * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
368      *
369      * @return Response
370      */
371     public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals')
372     {
373         if ($this->debug) {
374             // by maHo, replaced htmlspecialchars with htmlentities
375             $this->debugMessage("---GOT---\n$data\n---END---");
376         }
377
378         $this->httpResponse = array();
379         $this->httpResponse['raw_data'] = $data;
380         $this->httpResponse['headers'] = array();
381         $this->httpResponse['cookies'] = array();
382
383         if ($data == '') {
384             error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
385             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
386
387             return $r;
388         }
389
390         // parse the HTTP headers of the response, if present, and separate them from data
391         if (substr($data, 0, 4) == 'HTTP') {
392             $r = $this->parseResponseHeaders($data, $headers_processed);
393             if ($r) {
394                 // failed processing of HTTP response headers
395                 // save into response obj the full payload received, for debugging
396                 $r->raw_data = $data;
397
398                 return $r;
399             }
400         }
401
402         if ($this->debug) {
403             $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
404             if ($start) {
405                 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
406                 $end = strpos($data, '-->', $start);
407                 $comments = substr($data, $start, $end - $start);
408                 $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n</PRE>";
409             }
410         }
411
412         // be tolerant of extra whitespace in response body
413         $data = trim($data);
414
415         /// @todo return an error msg if $data=='' ?
416
417         // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
418         // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
419         $pos = strrpos($data, '</methodResponse>');
420         if ($pos !== false) {
421             $data = substr($data, 0, $pos + 17);
422         }
423
424         // if user wants back raw xml, give it to him
425         if ($return_type == 'xml') {
426             $r = new Response($data, 0, '', 'xml');
427             $r->hdrs = $this->httpResponse['headers'];
428             $r->_cookies = $this->httpResponse['cookies'];
429             $r->raw_data = $this->httpResponse['raw_data'];
430
431             return $r;
432         }
433
434         // try to 'guestimate' the character encoding of the received response
435         $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data);
436
437         // if response charset encoding is not known / supported, try to use
438         // the default encoding and parse the xml anyway, but log a warning...
439         if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
440             // the following code might be better for mb_string enabled installs, but
441             // makes the lib about 200% slower...
442             //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
443
444             error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding);
445             $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding;
446         }
447         $parser = xml_parser_create($resp_encoding);
448         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
449         // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
450         // the xml parser to give us back data in the expected charset.
451         // What if internal encoding is not in one of the 3 allowed?
452         // we use the broadest one, ie. utf8
453         // This allows to send data which is native in various charset,
454         // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
455         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
456             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
457         } else {
458             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
459         }
460
461         $xmlRpcParser = new XMLParser();
462         xml_set_object($parser, $xmlRpcParser);
463
464         if ($return_type == 'phpvals') {
465             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
466         } else {
467             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
468         }
469
470         xml_set_character_data_handler($parser, 'xmlrpc_cd');
471         xml_set_default_handler($parser, 'xmlrpc_dh');
472
473         // first error check: xml not well formed
474         if (!xml_parse($parser, $data, count($data))) {
475             // thanks to Peter Kocks <peter.kocks@baygate.com>
476             if ((xml_get_current_line_number($parser)) == 1) {
477                 $errstr = 'XML error at line 1, check URL';
478             } else {
479                 $errstr = sprintf('XML error: %s at line %d, column %d',
480                     xml_error_string(xml_get_error_code($parser)),
481                     xml_get_current_line_number($parser), xml_get_current_column_number($parser));
482             }
483             error_log($errstr);
484             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')');
485             xml_parser_free($parser);
486             if ($this->debug) {
487                 print $errstr;
488             }
489             $r->hdrs = $this->httpResponse['headers'];
490             $r->_cookies = $this->httpResponse['cookies'];
491             $r->raw_data = $this->httpResponse['raw_data'];
492
493             return $r;
494         }
495         xml_parser_free($parser);
496         // second error check: xml well formed but not xml-rpc compliant
497         if ($xmlRpcParser->_xh['isf'] > 1) {
498             if ($this->debug) {
499                 /// @todo echo something for user?
500             }
501
502             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
503                 PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
504         }
505         // third error check: parsing of the response has somehow gone boink.
506         // NB: shall we omit this check, since we trust the parsing code?
507         elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
508             // something odd has happened
509             // and it's time to generate a client side error
510             // indicating something odd went on
511             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
512                 PhpXmlRpc::$xmlrpcstr['invalid_return']);
513         } else {
514             if ($this->debug) {
515                 $this->debugMessage(
516                     "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false
517                 );
518             }
519
520             // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
521             $v = &$xmlRpcParser->_xh['value'];
522
523             if ($xmlRpcParser->_xh['isf']) {
524                 /// @todo we should test here if server sent an int and a string,
525                 /// and/or coerce them into such...
526                 if ($return_type == 'xmlrpcvals') {
527                     $errno_v = $v->structmem('faultCode');
528                     $errstr_v = $v->structmem('faultString');
529                     $errno = $errno_v->scalarval();
530                     $errstr = $errstr_v->scalarval();
531                 } else {
532                     $errno = $v['faultCode'];
533                     $errstr = $v['faultString'];
534                 }
535
536                 if ($errno == 0) {
537                     // FAULT returned, errno needs to reflect that
538                     $errno = -1;
539                 }
540
541                 $r = new Response(0, $errno, $errstr);
542             } else {
543                 $r = new Response($v, 0, '', $return_type);
544             }
545         }
546
547         $r->hdrs = $this->httpResponse['headers'];
548         $r->_cookies = $this->httpResponse['cookies'];
549         $r->raw_data = $this->httpResponse['raw_data'];
550
551         return $r;
552     }
553
554     /**
555      * Echoes a debug message, taking care of escaping it when not in console mode
556      *
557      * @param string $message
558      */
559     protected function debugMessage($message, $encodeEntities = true)
560     {
561         if (PHP_SAPI != 'cli') {
562             if ($encodeEntities)
563                 print "<PRE>\n".htmlentities($message)."\n</PRE>";
564             else
565                 print "<PRE>\n".htmlspecialchars($message)."\n</PRE>";
566         }
567         else {
568             print "\n$message\n";
569         }
570         // let the client see this now in case http times out...
571         flush();
572     }
573 }