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