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