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