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