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