2 // by Edd Dumbill (C) 1999-2002
4 // $Original: xmlrpc.inc,v 1.158 2007/03/01 21:21:02 ggiunta Exp $
6 // $NucleusJP: xmlrpc.inc.php,v 1.6.2.2 2007/09/07 07:04:24 kimitake Exp $
9 // Copyright (c) 1999,2000,2002 Edd Dumbill.
10 // All rights reserved.
12 // Redistribution and use in source and binary forms, with or without
13 // modification, are permitted provided that the following conditions
16 // * Redistributions of source code must retain the above copyright
17 // notice, this list of conditions and the following disclaimer.
19 // * Redistributions in binary form must reproduce the above
20 // copyright notice, this list of conditions and the following
21 // disclaimer in the documentation and/or other materials provided
22 // with the distribution.
24 // * Neither the name of the "XML-RPC for PHP" nor the names of its
25 // contributors may be used to endorse or promote products derived
26 // from this software without specific prior written permission.
28 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
31 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
32 // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
33 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39 // OF THE POSSIBILITY OF SUCH DAMAGE.
41 if(!function_exists('xml_parser_create'))
43 // For PHP 4 onward, XML functionality is always compiled-in on windows:
44 // no more need to dl-open it. It might have been compiled out on *nix...
45 //if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
46 $phpver = phpversion();
47 if (!extension_loaded('xml') && version_compare($phpver,'5.3.0','<'))
53 // Try to be backward compat with php < 4.2 (are we not being nice ?)
54 $phpversion = phpversion();
55 if($phpversion[0] == '4' && $phpversion[2] < 2)
57 // give an opportunity to user to specify where to include other files from
58 if(!defined('PHP_XMLRPC_COMPAT_DIR'))
60 define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
62 if($phpversion[2] == '0')
64 if($phpversion[4] < 6)
66 include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
68 include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
69 include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
70 include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
72 include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
73 include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
76 // G. Giunta 2005/01/29: declare global these variables,
77 // so that xmlrpc.inc will work even if included from within a function
78 // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
79 $GLOBALS['xmlrpcI4']='i4';
80 $GLOBALS['xmlrpcInt']='int';
81 $GLOBALS['xmlrpcBoolean']='boolean';
82 $GLOBALS['xmlrpcDouble']='double';
83 $GLOBALS['xmlrpcString']='string';
84 $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
85 $GLOBALS['xmlrpcBase64']='base64';
86 $GLOBALS['xmlrpcArray']='array';
87 $GLOBALS['xmlrpcStruct']='struct';
88 $GLOBALS['xmlrpcValue']='undefined';
90 $GLOBALS['xmlrpcTypes']=array(
91 $GLOBALS['xmlrpcI4'] => 1,
92 $GLOBALS['xmlrpcInt'] => 1,
93 $GLOBALS['xmlrpcBoolean'] => 1,
94 $GLOBALS['xmlrpcString'] => 1,
95 $GLOBALS['xmlrpcDouble'] => 1,
96 $GLOBALS['xmlrpcDateTime'] => 1,
97 $GLOBALS['xmlrpcBase64'] => 1,
98 $GLOBALS['xmlrpcArray'] => 2,
99 $GLOBALS['xmlrpcStruct'] => 3
102 $GLOBALS['xmlrpc_valid_parents'] = array(
103 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
104 'BOOLEAN' => array('VALUE'),
105 'I4' => array('VALUE'),
106 'INT' => array('VALUE'),
107 'STRING' => array('VALUE'),
108 'DOUBLE' => array('VALUE'),
109 'DATETIME.ISO8601' => array('VALUE'),
110 'BASE64' => array('VALUE'),
111 'MEMBER' => array('STRUCT'),
112 'NAME' => array('MEMBER'),
113 'DATA' => array('ARRAY'),
114 'ARRAY' => array('VALUE'),
115 'STRUCT' => array('VALUE'),
116 'PARAM' => array('PARAMS'),
117 'METHODNAME' => array('METHODCALL'),
118 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
119 'FAULT' => array('METHODRESPONSE'),
120 'NIL' => array('VALUE') // only used when extension activated
123 // define extra types for supporting NULL (useful for json or <NIL/>)
124 $GLOBALS['xmlrpcNull']='null';
125 $GLOBALS['xmlrpcTypes']['null']=1;
127 // Not in use anymore since 2.0. Shall we remove it?
129 $GLOBALS['xmlEntities']=array(
137 // tables used for transcoding different charsets into us-ascii xml
139 $GLOBALS['xml_iso88591_Entities']=array();
140 $GLOBALS['xml_iso88591_Entities']['in'] = array();
141 $GLOBALS['xml_iso88591_Entities']['out'] = array();
142 for ($i = 0; $i < 32; $i++)
144 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
145 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
147 for ($i = 160; $i < 256; $i++)
149 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
150 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
153 /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159.
154 /// These will NOT be present in true ISO-8859-1, but will save the unwary
155 /// windows user from sending junk.
159 '\x80'=>'€', '\x81'=>'?', '\x82'=>'‚', '\x83'=>'ƒ',
160 '\x84'=>'„', '\x85'=>'…', '\x86'=>'†', \x87'=>'‡',
161 '\x88'=>'ˆ', '\x89'=>'‰', '\x8A'=>'Š', '\x8B'=>'‹',
162 '\x8C'=>'Œ', '\x8D'=>'?', '\x8E'=>'Ž', '\x8F'=>'?',
163 '\x90'=>'?', '\x91'=>'‘', '\x92'=>'’', '\x93'=>'“',
164 '\x94'=>'”', '\x95'=>'•', '\x96'=>'–', '\x97'=>'—',
165 '\x98'=>'˜', '\x99'=>'™', '\x9A'=>'š', '\x9B'=>'›',
166 '\x9C'=>'œ', '\x9D'=>'?', '\x9E'=>'ž', '\x9F'=>'Ÿ'
170 $GLOBALS['xmlrpcerr']['unknown_method']=1;
171 $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method';
172 $GLOBALS['xmlrpcerr']['invalid_return']=2;
173 $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload';
174 $GLOBALS['xmlrpcerr']['incorrect_params']=3;
175 $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method';
176 $GLOBALS['xmlrpcerr']['introspect_unknown']=4;
177 $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown";
178 $GLOBALS['xmlrpcerr']['http_error']=5;
179 $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server.";
180 $GLOBALS['xmlrpcerr']['no_data']=6;
181 $GLOBALS['xmlrpcstr']['no_data']='No data received from server.';
182 $GLOBALS['xmlrpcerr']['no_ssl']=7;
183 $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.';
184 $GLOBALS['xmlrpcerr']['curl_fail']=8;
185 $GLOBALS['xmlrpcstr']['curl_fail']='CURL error';
186 $GLOBALS['xmlrpcerr']['invalid_request']=15;
187 $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload';
188 $GLOBALS['xmlrpcerr']['no_curl']=16;
189 $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.';
190 $GLOBALS['xmlrpcerr']['server_error']=17;
191 $GLOBALS['xmlrpcstr']['server_error']='Internal server error';
192 $GLOBALS['xmlrpcerr']['multicall_error']=18;
193 $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response';
195 $GLOBALS['xmlrpcerr']['multicall_notstruct'] = 9;
196 $GLOBALS['xmlrpcstr']['multicall_notstruct'] = 'system.multicall expected struct';
197 $GLOBALS['xmlrpcerr']['multicall_nomethod'] = 10;
198 $GLOBALS['xmlrpcstr']['multicall_nomethod'] = 'missing methodName';
199 $GLOBALS['xmlrpcerr']['multicall_notstring'] = 11;
200 $GLOBALS['xmlrpcstr']['multicall_notstring'] = 'methodName is not a string';
201 $GLOBALS['xmlrpcerr']['multicall_recursion'] = 12;
202 $GLOBALS['xmlrpcstr']['multicall_recursion'] = 'recursive system.multicall forbidden';
203 $GLOBALS['xmlrpcerr']['multicall_noparams'] = 13;
204 $GLOBALS['xmlrpcstr']['multicall_noparams'] = 'missing params';
205 $GLOBALS['xmlrpcerr']['multicall_notarray'] = 14;
206 $GLOBALS['xmlrpcstr']['multicall_notarray'] = 'params is not an array';
208 $GLOBALS['xmlrpcerr']['cannot_decompress']=103;
209 $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress';
210 $GLOBALS['xmlrpcerr']['decompress_fail']=104;
211 $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP';
212 $GLOBALS['xmlrpcerr']['dechunk_fail']=105;
213 $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP';
214 $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106;
215 $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress';
216 $GLOBALS['xmlrpcerr']['server_decompress_fail']=107;
217 $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request';
219 // The charset encoding used by the server for received messages and
220 // by the client for received responses when received charset cannot be determined
221 // or is not supported
222 $GLOBALS['xmlrpc_defencoding']='UTF-8';
224 // The encoding used internally by PHP.
225 // String values received as xml will be converted to this, and php strings will be converted to xml
226 // as if having been coded with this
227 $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
229 $GLOBALS['xmlrpcName']='XML-RPC for PHP';
230 $GLOBALS['xmlrpcVersion']='2.2';
232 // let user errors start at 800
233 $GLOBALS['xmlrpcerruser']=800;
234 // let XML parse errors start at 100
235 $GLOBALS['xmlrpcerrxml']=100;
237 // formulate backslashes for escaping regexp
238 // Not in use anymore since 2.0. Shall we remove it?
240 $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
242 // set to TRUE to enable correct decoding of <NIL/> values
243 $GLOBALS['xmlrpc_null_extension']=false;
245 // used to store state during parsing
246 // quick explanation of components:
247 // ac - used to accumulate values
248 // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
249 // isf_reason - used for storing xmlrpcresp fault string
250 // lv - used to indicate "looking for a value": implements
251 // the logic to allow values with no types to be strings
252 // params - used to store parameters in method calls
253 // method - used to store method name
254 // stack - array with genealogy of xml elements names:
255 // used to validate nesting of xmlrpc elements
256 $GLOBALS['_xh']=null;
259 * Convert a string to the correct XML representation in a target charset
260 * To help correct communication of non-ascii chars inside strings, regardless
261 * of the charset used when sending requests, parsing them, sending responses
262 * and parsing responses, an option is to convert all non-ascii chars present in the message
263 * into their equivalent 'charset entity'. Charset entities enumerated this way
264 * are independent of the charset encoding used to transmit them, and all XML
265 * parsers are bound to understand them.
266 * Note that in the std case we are not sending a charset encoding mime type
267 * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
269 * @todo do a bit of basic benchmarking (strtr vs. str_replace)
270 * @todo make usage of iconv() or recode_string() or mb_string() where available
272 function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
274 if ($src_encoding == '')
276 // lame, but we know no better...
277 $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
280 switch(strtoupper($src_encoding.'_'.$dest_encoding))
283 case 'ISO-8859-1_US-ASCII':
284 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
285 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
287 case 'ISO-8859-1_UTF-8':
288 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
289 $escaped_data = utf8_encode($escaped_data);
291 case 'ISO-8859-1_ISO-8859-1':
292 case 'US-ASCII_US-ASCII':
293 case 'US-ASCII_UTF-8':
295 case 'US-ASCII_ISO-8859-1':
297 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
300 case 'UTF-8_US-ASCII':
301 case 'UTF-8_ISO-8859-1':
302 // NB: this will choke on invalid UTF-8, going most likely beyond EOF
304 // be kind to users creating string xmlrpcvals out of different php types
305 $data = (string) $data;
306 $ns = strlen ($data);
307 for ($nn = 0; $nn < $ns; $nn++)
314 /// @todo shall we replace this with a (supposedly) faster str_replace?
317 $escaped_data .= '"';
320 $escaped_data .= '&';
323 $escaped_data .= ''';
326 $escaped_data .= '<';
329 $escaped_data .= '>';
332 $escaped_data .= $ch;
335 //2 11 110bbbbb 10bbbbbb (2047)
336 else if ($ii>>5 == 6)
339 $ii = ord($data[$nn+1]);
341 $ii = ($b1 * 64) + $b2;
342 $ent = sprintf ('&#%d;', $ii);
343 $escaped_data .= $ent;
346 //3 16 1110bbbb 10bbbbbb 10bbbbbb
347 else if ($ii>>4 == 14)
350 $ii = ord($data[$nn+1]);
352 $ii = ord($data[$nn+2]);
354 $ii = ((($b1 * 64) + $b2) * 64) + $b3;
355 $ent = sprintf ('&#%d;', $ii);
356 $escaped_data .= $ent;
359 //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
360 else if ($ii>>3 == 30)
363 $ii = ord($data[$nn+1]);
365 $ii = ord($data[$nn+2]);
367 $ii = ord($data[$nn+3]);
369 $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
370 $ent = sprintf ('&#%d;', $ii);
371 $escaped_data .= $ent;
378 error_log("Converting from $src_encoding to $dest_encoding: not supported...");
380 return $escaped_data;
383 /// xml parser handler function for opening element tags
384 function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
386 // if invalid xmlrpc already detected, skip all processing
387 if ($GLOBALS['_xh']['isf'] < 2)
389 // check for correct element nesting
390 // top level element can only be of 2 types
391 /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
392 /// there is only a single top level element in xml anyway
393 if (count($GLOBALS['_xh']['stack']) == 0)
395 if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
396 $name != 'VALUE' && !$accept_single_vals))
398 $GLOBALS['_xh']['isf'] = 2;
399 $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
404 $GLOBALS['_xh']['rt'] = strtolower($name);
409 // not top level element: see if parent is OK
410 $parent = end($GLOBALS['_xh']['stack']);
411 if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
413 $GLOBALS['_xh']['isf'] = 2;
414 $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
421 // optimize for speed switch cases: most common cases first
423 /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
424 $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
425 $GLOBALS['_xh']['ac']='';
426 $GLOBALS['_xh']['lv']=1;
427 $GLOBALS['_xh']['php_class']=null;
434 case 'DATETIME.ISO8601':
436 if ($GLOBALS['_xh']['vt']!='value')
438 //two data elements inside a value: an error occurred!
439 $GLOBALS['_xh']['isf'] = 2;
440 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
443 $GLOBALS['_xh']['ac']=''; // reset the accumulator
447 if ($GLOBALS['_xh']['vt']!='value')
449 //two data elements inside a value: an error occurred!
450 $GLOBALS['_xh']['isf'] = 2;
451 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
454 // create an empty array to hold child values, and push it onto appropriate stack
456 $cur_val['values'] = array();
457 $cur_val['type'] = $name;
458 // check for out-of-band information to rebuild php objs
459 // and in case it is found, save it
460 if (@isset($attrs['PHP_CLASS']))
462 $cur_val['php_class'] = $attrs['PHP_CLASS'];
464 $GLOBALS['_xh']['valuestack'][] = $cur_val;
465 $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
468 if ($GLOBALS['_xh']['vt']!='data')
470 //two data elements inside a value: an error occurred!
471 $GLOBALS['_xh']['isf'] = 2;
472 $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
476 case 'METHODRESPONSE':
478 // valid elements that add little to processing
482 /// @todo we could check for 2 NAME elements inside a MEMBER element
483 $GLOBALS['_xh']['ac']='';
486 $GLOBALS['_xh']['isf']=1;
489 $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on
490 //$GLOBALS['_xh']['ac']='';
491 // Drop trough intentionally
493 // clear value type, so we can check later if no value has been passed for this param/member
494 $GLOBALS['_xh']['vt']=null;
497 if ($GLOBALS['xmlrpc_null_extension'])
499 if ($GLOBALS['_xh']['vt']!='value')
501 //two data elements inside a value: an error occurred!
502 $GLOBALS['_xh']['isf'] = 2;
503 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
506 $GLOBALS['_xh']['ac']=''; // reset the accumulator
509 // we do not support the <NIL/> extension, so
510 // drop through intentionally
512 /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
513 $GLOBALS['_xh']['isf'] = 2;
514 $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";
518 // Save current element name to stack, to validate nesting
519 $GLOBALS['_xh']['stack'][] = $name;
521 /// @todo optimization creep: move this inside the big switch() above
524 $GLOBALS['_xh']['lv']=0;
529 /// Used in decoding xml chunks that might represent single xmlrpc values
530 function xmlrpc_se_any($parser, $name, $attrs)
532 xmlrpc_se($parser, $name, $attrs, true);
535 /// xml parser handler function for close element tags
536 function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)
538 if ($GLOBALS['_xh']['isf'] < 2)
540 // push this element name from stack
541 // NB: if XML validates, correct opening/closing is guaranteed and
542 // we do not have to check for $name == $curr_elem.
543 // we also checked for proper nesting at start of elements...
544 $curr_elem = array_pop($GLOBALS['_xh']['stack']);
549 // This if() detects if no scalar was inside <VALUE></VALUE>
550 if ($GLOBALS['_xh']['vt']=='value')
552 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
553 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
556 if ($rebuild_xmlrpcvals)
558 // build the xmlrpc val out of the data received, and substitute it
559 $temp = new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);
560 // in case we got info about underlying php class, save it
561 // in the object we're rebuilding
562 if (isset($GLOBALS['_xh']['php_class']))
563 $temp->_php_class = $GLOBALS['_xh']['php_class'];
564 // check if we are inside an array or struct:
565 // if value just built is inside an array, let's move it into array on the stack
566 $vscount = count($GLOBALS['_xh']['valuestack']);
567 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
569 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;
573 $GLOBALS['_xh']['value'] = $temp;
578 /// @todo this needs to treat correctly php-serialized objects,
579 /// since std deserializing is done by php_xmlrpc_decode,
580 /// which we will not be calling...
581 if (isset($GLOBALS['_xh']['php_class']))
585 // check if we are inside an array or struct:
586 // if value just built is inside an array, let's move it into array on the stack
587 $vscount = count($GLOBALS['_xh']['valuestack']);
588 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
590 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];
599 case 'DATETIME.ISO8601':
601 $GLOBALS['_xh']['vt']=strtolower($name);
602 /// @todo: optimization creep - remove the if/elseif cycle below
603 /// since the case() in which we are already did that
606 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
608 elseif ($name=='DATETIME.ISO8601')
610 if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))
612 error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);
614 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];
615 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
617 elseif ($name=='BASE64')
619 /// @todo check for failure of base64 decoding / catch warnings
620 $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);
622 elseif ($name=='BOOLEAN')
624 // special case here: we translate boolean 1 or 0 into PHP
625 // constants true or false.
626 // Strings 'true' and 'false' are accepted, even though the
627 // spec never mentions them (see eg. Blogger api docs)
628 // NB: this simple checks helps a lot sanitizing input, ie no
629 // security problems around here
630 if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)
632 $GLOBALS['_xh']['value']=true;
636 // log if receiveing something strange, even though we set the value to false anyway
637 if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($_xh[$parser]['ac'], 'false') != 0)
638 error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);
639 $GLOBALS['_xh']['value']=false;
642 elseif ($name=='DOUBLE')
645 // we must check that only 0123456789-.<space> are characters here
646 if (!preg_match('/^[+-]?[eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))
648 /// @todo: find a better way of throwing an error
650 error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);
651 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
655 // it's ok, add it on
656 $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];
662 // we must check that only 0123456789-<space> are characters here
663 if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))
665 /// @todo find a better way of throwing an error
667 error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);
668 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
672 // it's ok, add it on
673 $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];
676 //$GLOBALS['_xh']['ac']=''; // is this necessary?
677 $GLOBALS['_xh']['lv']=3; // indicate we've found a value
680 $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];
683 //$GLOBALS['_xh']['ac']=''; // is this necessary?
684 // add to array in the stack the last element built,
685 // unless no VALUE was found
686 if ($GLOBALS['_xh']['vt'])
688 $vscount = count($GLOBALS['_xh']['valuestack']);
689 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];
691 error_log('XML-RPC: missing VALUE inside STRUCT in received xml');
694 //$GLOBALS['_xh']['ac']=''; // is this necessary?
695 $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty
699 // fetch out of stack array of values, and promote it to current value
700 $curr_val = array_pop($GLOBALS['_xh']['valuestack']);
701 $GLOBALS['_xh']['value'] = $curr_val['values'];
702 $GLOBALS['_xh']['vt']=strtolower($name);
703 if (isset($curr_val['php_class']))
705 $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];
709 // add to array of params the current value,
710 // unless no VALUE was found
711 if ($GLOBALS['_xh']['vt'])
713 $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];
714 $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];
717 error_log('XML-RPC: missing VALUE inside PARAM in received xml');
720 $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);
723 if ($GLOBALS['xmlrpc_null_extension'])
725 $GLOBALS['_xh']['vt']='null';
726 $GLOBALS['_xh']['value']=null;
727 $GLOBALS['_xh']['lv']=3;
730 // drop through intentionally if nil extension not enabled
734 case 'METHORESPONSE':
737 // End of INVALID ELEMENT!
738 // shall we add an assert here for unreachable code???
744 /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values
745 function xmlrpc_ee_fast($parser, $name)
747 xmlrpc_ee($parser, $name, false);
750 /// xml parser handler function for character data
751 function xmlrpc_cd($parser, $data)
753 // skip processing if xml fault already detected
754 if ($GLOBALS['_xh']['isf'] < 2)
756 // "lookforvalue==3" means that we've found an entire value
757 // and should discard any further character data
758 if($GLOBALS['_xh']['lv']!=3)
760 // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2
761 //if($GLOBALS['_xh']['lv']==1)
763 // if we've found text and we're just in a <value> then
764 // say we've found a value
765 //$GLOBALS['_xh']['lv']=2;
767 // we always initialize the accumulator before starting parsing, anyway...
768 //if(!@isset($GLOBALS['_xh']['ac']))
770 // $GLOBALS['_xh']['ac'] = '';
772 $GLOBALS['_xh']['ac'].=$data;
777 /// xml parser handler function for 'other stuff', ie. not char data or
778 /// element start/end tag. In fact it only gets called on unknown entities...
779 function xmlrpc_dh($parser, $data)
781 // skip processing if xml fault already detected
782 if ($GLOBALS['_xh']['isf'] < 2)
784 if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')
786 // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2
787 //if($GLOBALS['_xh']['lv']==1)
789 // $GLOBALS['_xh']['lv']=2;
791 $GLOBALS['_xh']['ac'].=$data;
815 var $verifypeer=true;
817 var $no_multicall=false;
822 var $proxy_authtype=1;
823 var $cookies=array();
825 * List of http compression methods accepted by the client for responses.
826 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
828 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
829 * in those cases it will be up to CURL to decide the compression methods
830 * it supports. You might check for the presence of 'zlib' in the output of
831 * curl_version() to determine wheter compression is supported or not
833 var $accepted_compression = array();
835 * Name of compression scheme to be used for sending requests.
836 * Either null, gzip or deflate
838 var $request_compression = '';
840 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
841 * http://curl.haxx.se/docs/faq.html#7.3)
843 var $xmlrpc_curl_handle = null;
844 /// Wheter to use persistent connections for http 1.1 and https
845 var $keepalive = false;
846 /// Charset encodings that can be decoded without problems by the client
847 var $accepted_charset_encodings = array();
848 /// Charset encoding to be used in serializing request. NULL = use ASCII
849 var $request_charset_encoding = '';
851 * Decides the content of xmlrpcresp objects returned by calls to send()
852 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
854 var $return_type = 'xmlrpcvals';
857 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
858 * @param string $server the server name / ip address
859 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
860 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
862 function xmlrpc_client($path, $server='', $port='', $method='')
864 // allow user to specify all params in $path
865 if($server == '' and $port == '' and $method == '')
867 $parts = parse_url($path);
868 $server = $parts['host'];
869 $path = $parts['path'];
870 if(isset($parts['query']))
872 $path .= '?'.$parts['query'];
874 if(isset($parts['fragment']))
876 $path .= '#'.$parts['fragment'];
878 if(isset($parts['port']))
880 $port = $parts['port'];
882 if(isset($parts['scheme']))
884 $method = $parts['scheme'];
886 if(isset($parts['user']))
888 $this->username = $parts['user'];
890 if(isset($parts['pass']))
892 $this->password = $parts['pass'];
895 if($path == '' || $path[0] != '/')
897 $this->path='/'.$path;
903 $this->server=$server;
910 $this->method=$method;
913 // if ZLIB is enabled, let the client by default accept compressed responses
914 if(function_exists('gzinflate') || (
915 function_exists('curl_init') && (($info = curl_version()) &&
916 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
919 $this->accepted_compression = array('gzip', 'deflate');
922 // keepalives: enabled by default ONLY for PHP >= 4.3.8
923 // (see http://curl.haxx.se/docs/faq.html#7.3)
924 if(version_compare(phpversion(), '4.3.8') >= 0)
926 $this->keepalive = true;
929 // by default the xml parser can support these 3 charset encodings
930 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
934 * Enables/disables the echoing to screen of the xmlrpc responses received
935 * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
938 function setDebug($in)
944 * Add some http BASIC AUTH credentials, used by the client to authenticate
945 * @param string $u username
946 * @param string $p password
947 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
950 function setCredentials($u, $p, $t=1)
958 * Add a client-side https certificate
959 * @param string $cert
960 * @param string $certpass
963 function setCertificate($cert, $certpass)
966 $this->certpass = $certpass;
970 * Add a CA certificate to verify server with (see man page about
971 * CURLOPT_CAINFO for more details
972 * @param string $cacert certificate file name (or dir holding certificates)
973 * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false
976 function setCaCertificate($cacert, $is_dir=false)
980 $this->cacert = $cacert;
984 $this->cacertdir = $cacert;
989 * Set attributes for SSL communication: private SSL key
990 * @param string $key The name of a file containing a private SSL key
991 * @param string $keypass The secret password needed to use the private SSL key
993 * NB: does not work in older php/curl installs
994 * Thanks to Daniel Convissor
996 function setKey($key, $keypass)
999 $this->keypass = $keypass;
1003 * Set attributes for SSL communication: verify server certificate
1004 * @param bool $i enable/disable verification of peer certificate
1007 function setSSLVerifyPeer($i)
1009 $this->verifypeer = $i;
1013 * Set attributes for SSL communication: verify match of server cert w. hostname
1017 function setSSLVerifyHost($i)
1019 $this->verifyhost = $i;
1024 * @param string $proxyhost
1025 * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS
1026 * @param string $proxyusername Leave blank if proxy has public access
1027 * @param string $proxypassword Leave blank if proxy has public access
1028 * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy
1031 function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)
1033 $this->proxy = $proxyhost;
1034 $this->proxyport = $proxyport;
1035 $this->proxy_user = $proxyusername;
1036 $this->proxy_pass = $proxypassword;
1037 $this->proxy_authtype = $proxyauthtype;
1041 * Enables/disables reception of compressed xmlrpc responses.
1042 * Note that enabling reception of compressed responses merely adds some standard
1043 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
1044 * compressed responses when receiving such requests.
1045 * @param string $compmethod either 'gzip', 'deflate', 'any' or ''
1048 function setAcceptedCompression($compmethod)
1050 if ($compmethod == 'any')
1051 $this->accepted_compression = array('gzip', 'deflate');
1053 $this->accepted_compression = array($compmethod);
1057 * Enables/disables http compression of xmlrpc request.
1058 * Take care when sending compressed requests: servers might not support them
1059 * (and automatic fallback to uncompressed requests is not yet implemented)
1060 * @param string $compmethod either 'gzip', 'deflate' or ''
1063 function setRequestCompression($compmethod)
1065 $this->request_compression = $compmethod;
1069 * Adds a cookie to list of cookies that will be sent to server.
1070 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
1071 * do not do it unless you know what you are doing
1072 * @param string $name
1073 * @param string $value
1074 * @param string $path
1075 * @param string $domain
1079 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
1081 function setCookie($name, $value='', $path='', $domain='', $port=null)
1083 $this->cookies[$name]['value'] = urlencode($value);
1084 if ($path || $domain || $port)
1086 $this->cookies[$name]['path'] = $path;
1087 $this->cookies[$name]['domain'] = $domain;
1088 $this->cookies[$name]['port'] = $port;
1089 $this->cookies[$name]['version'] = 1;
1093 $this->cookies[$name]['version'] = 0;
1098 * Send an xmlrpc request
1099 * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request
1100 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
1101 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
1102 * @return xmlrpcresp
1105 function& send($msg, $timeout=0, $method='')
1107 // if user deos not specify http protocol, use native method of this client
1108 // (i.e. method set during call to constructor)
1111 $method = $this->method;
1116 // $msg is an array of xmlrpcmsg's
1117 $r = $this->multicall($msg, $timeout, $method);
1120 elseif(is_string($msg))
1122 $n = new xmlrpcmsg('');
1127 // where msg is an xmlrpcmsg
1128 $msg->debug=$this->debug;
1130 if($method == 'https')
1132 $r =& $this->sendPayloadHTTPS(
1148 $this->proxy_authtype,
1154 elseif($method == 'http11')
1156 $r =& $this->sendPayloadCURL(
1172 $this->proxy_authtype,
1179 $r =& $this->sendPayloadHTTP10(
1191 $this->proxy_authtype
1201 function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,
1202 $username='', $password='', $authtype=1, $proxyhost='',
1203 $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)
1210 // Only create the payload if it was not created previously
1211 if(empty($msg->payload))
1213 $msg->createPayload($this->request_charset_encoding);
1216 $payload = $msg->payload;
1217 // Deflate request body and set appropriate request headers
1218 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
1220 if($this->request_compression == 'gzip')
1222 $a = @gzencode($payload);
1226 $encoding_hdr = "Content-Encoding: gzip\r\n";
1231 $a = @gzcompress($payload);
1235 $encoding_hdr = "Content-Encoding: deflate\r\n";
1244 // thanks to Grant Rauscher <grant7@firstworld.net> for this
1248 $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
1251 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');
1255 $accepted_encoding = '';
1256 if(is_array($this->accepted_compression) && count($this->accepted_compression))
1258 $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
1261 $proxy_credentials = '';
1268 $connectserver = $proxyhost;
1269 $connectport = $proxyport;
1270 $uri = 'http://'.$server.':'.$port.$this->path;
1271 if($proxyusername != '')
1273 if ($proxyauthtype != 1)
1275 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');
1277 $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";
1282 $connectserver = $server;
1283 $connectport = $port;
1287 // Cookie generation, as per rfc2965 (version 1 cookies) or
1288 // netscape's rules (version 0 cookies)
1290 foreach ($this->cookies as $name => $cookie)
1292 if ($cookie['version'])
1294 $cookieheader .= 'Cookie: $Version="' . $cookie['version'] . '"; ';
1295 $cookieheader .= $name . '="' . $cookie['value'] . '";';
1296 if ($cookie['path'])
1297 $cookieheader .= ' $Path="' . $cookie['path'] . '";';
1298 if ($cookie['domain'])
1299 $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';
1300 if ($cookie['port'])
1301 $cookieheader .= ' $Port="' . $cookie['domain'] . '";';
1302 $cookieheader = substr($cookieheader, 0, -1) . "\r\n";
1306 $cookieheader .= 'Cookie: ' . $name . '=' . $cookie['value'] . "\r\n";
1310 $op= 'POST ' . $uri. " HTTP/1.0\r\n" .
1311 'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" .
1312 'Host: '. $server . ':' . $port . "\r\n" .
1314 $proxy_credentials .
1315 $accepted_encoding .
1317 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
1319 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .
1320 strlen($payload) . "\r\n\r\n" .
1323 if($this->debug > 1)
1325 print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";
1326 // let the client see this now in case http times out...
1332 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);
1336 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);
1340 if($timeout>0 && function_exists('stream_set_timeout'))
1342 stream_set_timeout($fp, $timeout);
1347 $this->errstr='Connect error: '.$this->errstr;
1348 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');
1352 if(!fputs($fp, $op, strlen($op)))
1354 $this->errstr='Write error';
1355 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);
1360 // reset errno and errstr on succesful socket connection
1363 // G. Giunta 2005/10/24: close socket before parsing.
1364 // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
1366 while($data=fread($fp, 32768))
1368 // shall we check for $data === FALSE?
1369 // as per the manual, it signals an error
1373 $r =& $msg->parseResponse($ipd, false, $this->return_type);
1381 function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
1382 $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
1383 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
1384 $keepalive=false, $key='', $keypass='')
1386 $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
1387 $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
1388 $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
1393 * Contributed by Justin Miller <justin@voxel.net>
1394 * Requires curl to be built into PHP
1395 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
1398 function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
1399 $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
1400 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
1401 $keepalive=false, $key='', $keypass='')
1403 if(!function_exists('curl_init'))
1405 $this->errstr='CURL unavailable on this install';
1406 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);
1409 if($method == 'https')
1411 if(($info = curl_version()) &&
1412 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
1414 $this->errstr='SSL unavailable on this install';
1415 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);
1422 if($method == 'http')
1432 // Only create the payload if it was not created previously
1433 if(empty($msg->payload))
1435 $msg->createPayload($this->request_charset_encoding);
1438 // Deflate request body and set appropriate request headers
1439 $payload = $msg->payload;
1440 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
1442 if($this->request_compression == 'gzip')
1444 $a = @gzencode($payload);
1448 $encoding_hdr = 'Content-Encoding: gzip';
1453 $a = @gzcompress($payload);
1457 $encoding_hdr = 'Content-Encoding: deflate';
1466 if($this->debug > 1)
1468 print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
1469 // let the client see this now in case http times out...
1473 if(!$keepalive || !$this->xmlrpc_curl_handle)
1475 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
1478 $this->xmlrpc_curl_handle = $curl;
1483 $curl = $this->xmlrpc_curl_handle;
1486 // results into variable
1487 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
1491 curl_setopt($curl, CURLOPT_VERBOSE, 1);
1493 curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);
1494 // required for XMLRPC: post the data
1495 curl_setopt($curl, CURLOPT_POST, 1);
1497 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
1499 // return the header too
1500 curl_setopt($curl, CURLOPT_HEADER, 1);
1502 // will only work with PHP >= 5.0
1503 // NB: if we set an empty string, CURL will add http header indicating
1504 // ALL methods it is supporting. This is possibly a better option than
1505 // letting the user tell what curl can / cannot do...
1506 if(is_array($this->accepted_compression) && count($this->accepted_compression))
1508 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
1509 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1510 if (count($this->accepted_compression) == 1)
1512 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
1515 curl_setopt($curl, CURLOPT_ENCODING, '');
1518 $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
1519 // if no keepalive is wanted, let the server know it in advance
1522 $headers[] = 'Connection: close';
1524 // request compression header
1527 $headers[] = $encoding_hdr;
1530 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
1531 // timeout is borked
1534 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
1537 if($username && $password)
1539 curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
1540 if (defined('CURLOPT_HTTPAUTH'))
1542 curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
1544 else if ($authtype != 1)
1546 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');
1550 if($method == 'https')
1555 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
1557 // set cert password
1560 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
1562 // whether to verify remote host's cert
1563 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
1564 // set ca certificates file/dir
1567 curl_setopt($curl, CURLOPT_CAINFO, $cacert);
1571 curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
1573 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1576 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1578 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1581 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
1583 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used
1584 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1592 $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
1594 curl_setopt($curl, CURLOPT_PROXY,$proxyhost.':'.$proxyport);
1595 //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
1598 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
1599 if (defined('CURLOPT_PROXYAUTH'))
1601 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
1603 else if ($proxyauthtype != 1)
1605 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1610 // NB: should we build cookie http headers by hand rather than let CURL do it?
1611 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
1612 // set to clint obj the the user...
1613 if (count($this->cookies))
1616 foreach ($this->cookies as $name => $cookie)
1618 $cookieheader .= $name . '=' . $cookie['value'] . ', ';
1620 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
1623 $result = curl_exec($curl);
1627 $this->errstr='no response';
1628 $resp= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));
1640 $resp =& $msg->parseResponse($result, true, $this->return_type);
1646 * Send an array of request messages and return an array of responses.
1647 * Unless $this->no_multicall has been set to true, it will try first
1648 * to use one single xmlrpc call to server method system.multicall, and
1649 * revert to sending many successive calls in case of failure.
1650 * This failure is also stored in $this->no_multicall for subsequent calls.
1651 * Unfortunately, there is no server error code universally used to denote
1652 * the fact that multicall is unsupported, so there is no way to reliably
1653 * distinguish between that and a temporary failure.
1654 * If you are sure that server supports multicall and do not want to
1655 * fallback to using many single calls, set the fourth parameter to FALSE.
1657 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1658 * in pretty much convoluted code...
1660 * @param array $msgs an array of xmlrpcmsg objects
1661 * @param integer $timeout connection timeout (in seconds)
1662 * @param string $method the http protocol variant to be used
1663 * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted
1667 function multicall($msgs, $timeout=0, $method='', $fallback=true)
1671 $method = $this->method;
1673 if(!$this->no_multicall)
1675 $results = $this->_try_multicall($msgs, $timeout, $method);
1676 if(is_array($results))
1678 // System.multicall succeeded
1683 // either system.multicall is unsupported by server,
1684 // or call failed for some other reason.
1687 // Don't try it next time...
1688 $this->no_multicall = true;
1692 if (is_a($results, 'xmlrpcresp'))
1698 $result = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);
1705 // override fallback, in case careless user tries to do two
1706 // opposite things at the same time
1713 // system.multicall is (probably) unsupported by server:
1714 // emulate multicall via multiple requests
1715 foreach($msgs as $msg)
1717 $results[] =& $this->send($msg, $timeout, $method);
1722 // user does NOT want to fallback on many single calls:
1723 // since we should always return an array of responses,
1724 // return an array with the same error repeated n times
1725 foreach($msgs as $msg)
1727 $results[] = $result;
1734 * Attempt to boxcar $msgs via system.multicall.
1735 * Returns either an array of xmlrpcreponses, an xmlrpc error response
1736 * or false (when received response does not respect valid multicall syntax)
1739 function _try_multicall($msgs, $timeout, $method)
1741 // Construct multicall message
1743 foreach($msgs as $msg)
1745 $call['methodName'] = new xmlrpcval($msg->method(),'string');
1746 $numParams = $msg->getNumParams();
1748 for($i = 0; $i < $numParams; $i++)
1750 $params[$i] = $msg->getParam($i);
1752 $call['params'] = new xmlrpcval($params, 'array');
1753 $calls[] = new xmlrpcval($call, 'struct');
1755 $multicall = new xmlrpcmsg('system.multicall');
1756 $multicall->addParam(new xmlrpcval($calls, 'array'));
1759 $result =& $this->send($multicall, $timeout, $method);
1761 if($result->faultCode() != 0)
1763 // call to system.multicall failed
1767 // Unpack responses.
1768 $rets = $result->value();
1770 if ($this->return_type == 'xml')
1774 else if ($this->return_type == 'phpvals')
1776 ///@todo test this code branch...
1777 $rets = $result->value();
1778 if(!is_array($rets))
1780 return false; // bad return type from system.multicall
1782 $numRets = count($rets);
1783 if($numRets != count($msgs))
1785 return false; // wrong number of return values.
1788 $response = array();
1789 for($i = 0; $i < $numRets; $i++)
1792 if (!is_array($val)) {
1800 return false; // Bad value
1802 // Normal return value
1803 $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');
1806 /// @todo remove usage of @: it is apparently quite slow
1807 $code = @$val['faultCode'];
1812 $str = @$val['faultString'];
1813 if(!is_string($str))
1817 $response[$i] = new xmlrpcresp(0, $code, $str);
1825 else // return type == 'xmlrpcvals'
1827 $rets = $result->value();
1828 if($rets->kindOf() != 'array')
1830 return false; // bad return type from system.multicall
1832 $numRets = $rets->arraysize();
1833 if($numRets != count($msgs))
1835 return false; // wrong number of return values.
1838 $response = array();
1839 for($i = 0; $i < $numRets; $i++)
1841 $val = $rets->arraymem($i);
1842 switch($val->kindOf())
1845 if($val->arraysize() != 1)
1847 return false; // Bad value
1849 // Normal return value
1850 $response[$i] = new xmlrpcresp($val->arraymem(0));
1853 $code = $val->structmem('faultCode');
1854 if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
1858 $str = $val->structmem('faultString');
1859 if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
1863 $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
1872 } // end class xmlrpc_client
1881 var $hdrs = array();
1882 var $_cookies = array();
1883 var $content_type = 'text/xml';
1887 * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
1888 * @param integer $fcode set it to anything but 0 to create an error response
1889 * @param string $fstr the error string, in case of an error response
1890 * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
1892 * @todo add check that $val / $fcode / $fstr is of correct type???
1893 * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
1894 * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
1896 function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')
1901 $this->errno = $fcode;
1902 $this->errstr = $fstr;
1903 //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
1907 // successful response
1911 // user did not declare type of response value: try to guess it
1912 if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))
1914 $this->valtyp = 'xmlrpcvals';
1916 else if (is_string($this->val))
1918 $this->valtyp = 'xml';
1923 $this->valtyp = 'phpvals';
1928 // user declares type of resp value: believe him
1929 $this->valtyp = $valtyp;
1935 * Returns the error code of the response.
1936 * @return integer the error code of this response (0 for not-error responses)
1939 function faultCode()
1941 return $this->errno;
1945 * Returns the error code of the response.
1946 * @return string the error string of this response ('' for not-error responses)
1949 function faultString()
1951 return $this->errstr;
1955 * Returns the value received by the server.
1956 * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects
1965 * Returns an array with the cookies received from the server.
1966 * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
1967 * with attributes being e.g. 'expires', 'path', domain'.
1968 * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
1969 * are still present in the array. It is up to the user-defined code to decide
1970 * how to use the received cookies, and wheter they have to be sent back with the next
1971 * request to the server (using xmlrpc_client::setCookie) or not
1972 * @return array array of cookies received from the server
1977 return $this->_cookies;
1981 * Returns xml representation of the response. XML prologue not included
1982 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
1983 * @return string the xml representation of the response
1986 function serialize($charset_encoding='')
1988 if ($charset_encoding != '')
1989 $this->content_type = 'text/xml; charset=' . $charset_encoding;
1991 $this->content_type = 'text/xml';
1992 $result = "<methodResponse>\n";
1995 // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
1996 // by xml-encoding non ascii chars
1997 $result .= "<fault>\n" .
1998 "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
1999 "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
2000 xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
2001 "</struct>\n</value>\n</fault>";
2005 if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
2007 if (is_string($this->val) && $this->valtyp == 'xml')
2009 $result .= "<params>\n<param>\n" .
2011 "</param>\n</params>";
2015 /// @todo try to build something serializable?
2016 die('cannot serialize xmlrpcresp objects whose content is native php values');
2021 $result .= "<params>\n<param>\n" .
2022 $this->val->serialize($charset_encoding) .
2023 "</param>\n</params>";
2026 $result .= "\n</methodResponse>";
2027 $this->payload = $result;
2036 var $params=array();
2038 var $content_type = 'text/xml';
2041 * @param string $meth the name of the method to invoke
2042 * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)
2044 function xmlrpcmsg($meth, $pars=0)
2046 $this->methodname=$meth;
2047 if(is_array($pars) && count($pars)>0)
2049 for($i=0; $i<count($pars); $i++)
2051 $this->addParam($pars[$i]);
2059 function xml_header($charset_encoding='')
2061 if ($charset_encoding != '')
2063 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
2067 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
2074 function xml_footer()
2076 return '</methodCall>';
2090 function createPayload($charset_encoding='')
2092 if ($charset_encoding != '')
2093 $this->content_type = 'text/xml; charset=' . $charset_encoding;
2095 $this->content_type = 'text/xml';
2096 $this->payload=$this->xml_header($charset_encoding);
2097 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
2098 $this->payload.="<params>\n";
2099 for($i=0; $i<count($this->params); $i++)
2101 $p=$this->params[$i];
2102 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
2105 $this->payload.="</params>\n";
2106 $this->payload.=$this->xml_footer();
2110 * Gets/sets the xmlrpc method to be invoked
2111 * @param string $meth the method to be set (leave empty not to set it)
2112 * @return string the method that will be invoked
2115 function method($meth='')
2119 $this->methodname=$meth;
2121 return $this->methodname;
2125 * Returns xml representation of the message. XML prologue included
2126 * @return string the xml representation of the message, xml prologue included
2129 function serialize($charset_encoding='')
2131 $this->createPayload($charset_encoding);
2132 return $this->payload;
2136 * Add a parameter to the list of parameters to be used upon method invocation
2137 * @param xmlrpcval $par
2138 * @return boolean false on failure
2141 function addParam($par)
2143 // add check: do not add to self params which are not xmlrpcvals
2144 if(is_object($par) && is_a($par, 'xmlrpcval'))
2146 $this->params[]=$par;
2156 * Returns the nth parameter in the message. The index zero-based.
2157 * @param integer $i the index of the parameter to fetch (zero based)
2158 * @return xmlrpcval the i-th parameter
2161 function getParam($i) { return $this->params[$i]; }
2164 * Returns the number of parameters in the messge.
2165 * @return integer the number of parameters currently set
2168 function getNumParams() { return count($this->params); }
2171 * Given an open file handle, read all data available and parse it as axmlrpc response.
2172 * NB: the file handle is not closed by this function.
2174 * @return xmlrpcresp
2175 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
2177 function &parseResponseFile($fp)
2180 while($data=fread($fp, 32768))
2185 $r =& $this->parseResponse($ipd);
2190 * Parses HTTP headers and separates them from data.
2193 function &parseResponseHeaders(&$data, $headers_processed=false)
2195 // Support "web-proxy-tunelling" connections for https through proxies
2196 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
2198 // Look for CR/LF or simple LF as line separator,
2199 // (even though it is not valid http)
2200 $pos = strpos($data,"\r\n\r\n");
2201 if($pos || is_int($pos))
2207 $pos = strpos($data,"\n\n");
2208 if($pos || is_int($pos))
2214 // No separation between response headers and body: fault?
2220 // this filters out all http headers from proxy.
2221 // maybe we could take them into account, too?
2222 $data = substr($data, $bd);
2226 error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed');
2227 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
2232 // Strip HTTP 1.1 100 Continue header if present
2233 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
2235 $pos = strpos($data, 'HTTP', 12);
2236 // server sent a Continue header without any (valid) content following...
2237 // give the client a chance to know it
2238 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
2242 $data = substr($data, $pos);
2244 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
2246 $errstr= substr($data, 0, strpos($data, "\n")-1);
2247 error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);
2248 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
2252 $GLOBALS['_xh']['headers'] = array();
2253 $GLOBALS['_xh']['cookies'] = array();
2255 // be tolerant to usage of \n instead of \r\n to separate headers and data
2256 // (even though it is not valid http)
2257 $pos = strpos($data,"\r\n\r\n");
2258 if($pos || is_int($pos))
2264 $pos = strpos($data,"\n\n");
2265 if($pos || is_int($pos))
2271 // No separation between response headers and body: fault?
2272 // we could take some action here instead of going on...
2276 // be tolerant to line endings, and extra empty lines
2277 //$ar = split("\r?\n", trim(substr($data, 0, $pos))); //split() is deprecated
2278 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
2279 while(list(,$line) = @each($ar))
2281 // take care of multi-line headers and cookies
2282 $arr = explode(':',$line,2);
2285 $header_name = strtolower(trim($arr[0]));
2286 /// @todo some other headers (the ones that allow a CSV list of values)
2287 /// do allow many values to be passed using multiple header lines.
2288 /// We should add content to $GLOBALS['_xh']['headers'][$header_name]
2289 /// instead of replacing it for those...
2290 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
2292 if ($header_name == 'set-cookie2')
2294 // version 2 cookies:
2295 // there could be many cookies on one line, comma separated
2296 $cookies = explode(',', $arr[1]);
2300 $cookies = array($arr[1]);
2302 foreach ($cookies as $cookie)
2304 // glue together all received cookies, using a comma to separate them
2305 // (same as php does with getallheaders())
2306 if (isset($GLOBALS['_xh']['headers'][$header_name]))
2307 $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
2309 $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
2310 // parse cookie attributes, in case user wants to correctly honour them
2311 // feature creep: only allow rfc-compliant cookie attributes?
2312 $cookie = explode(';', $cookie);
2313 foreach ($cookie as $pos => $val)
2315 $val = explode('=', $val, 2);
2316 $tag = trim($val[0]);
2317 $val = trim(@$val[1]);
2318 /// @todo with version 1 cookies, we should strip leading and trailing " chars
2322 $GLOBALS['_xh']['cookies'][$tag] = array();
2323 $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
2327 $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
2334 $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
2337 elseif(isset($header_name))
2339 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
2340 $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
2344 $data = substr($data, $bd);
2346 if($this->debug && count($GLOBALS['_xh']['headers']))
2349 foreach($GLOBALS['_xh']['headers'] as $header => $value)
2351 print htmlentities("HEADER: $header: $value\n");
2353 foreach($GLOBALS['_xh']['cookies'] as $header => $value)
2355 print htmlentities("COOKIE: $header={$value['value']}\n");
2360 // if CURL was used for the call, http headers have been processed,
2361 // and dechunking + reinflating have been carried out
2362 if(!$headers_processed)
2364 // Decode chunked encoding sent by http 1.1 servers
2365 if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
2367 if(!$data = decode_chunked($data))
2369 error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');
2370 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
2375 // Decode gzip-compressed stuff
2376 // code shamelessly inspired from nusoap library by Dietrich Ayala
2377 if(isset($GLOBALS['_xh']['headers']['content-encoding']))
2379 $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
2380 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
2382 // if decoding works, use it. else assume data wasn't gzencoded
2383 if(function_exists('gzinflate'))
2385 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
2389 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
2391 elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
2395 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
2399 error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');
2400 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
2406 error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
2407 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
2412 } // end of 'if needed, de-chunk, re-inflate response'
2414 // real stupid hack to avoid PHP 4 complaining about returning NULL by ref
2421 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
2422 * @param string $data the xmlrpc response, eventually including http headers
2423 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
2424 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
2425 * @return xmlrpcresp
2428 function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
2432 //by maHo, replaced htmlspecialchars with htmlentities
2433 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
2438 error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');
2439 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);
2443 $GLOBALS['_xh']=array();
2446 // parse the HTTP headers of the response, if present, and separate them from data
2447 if(substr($data, 0, 4) == 'HTTP')
2449 $r =& $this->parseResponseHeaders($data, $headers_processed);
2452 // failed processing of HTTP response headers
2453 // save into response obj the full payload received, for debugging
2454 $r->raw_data = $data;
2460 $GLOBALS['_xh']['headers'] = array();
2461 $GLOBALS['_xh']['cookies'] = array();
2466 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
2469 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
2470 $end = strpos($data, '-->', $start);
2471 $comments = substr($data, $start, $end-$start);
2472 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
2476 // be tolerant of extra whitespace in response body
2477 $data = trim($data);
2479 /// @todo return an error msg if $data=='' ?
2481 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
2482 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
2484 // Poor man's version of strrpos for php 4...
2485 $pos = strpos($data, '</methodResponse>');
2486 while($pos || is_int($pos))
2489 $pos = strpos($data, '</methodResponse>', $bd);
2493 $data = substr($data, 0, $bd);
2496 // if user wants back raw xml, give it to him
2497 if ($return_type == 'xml')
2499 $r = new xmlrpcresp($data, 0, '', 'xml');
2500 $r->hdrs = $GLOBALS['_xh']['headers'];
2501 $r->_cookies = $GLOBALS['_xh']['cookies'];
2502 $r->raw_data = $raw_data;
2506 // try to 'guestimate' the character encoding of the received response
2507 $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);
2509 $GLOBALS['_xh']['ac']='';
2510 //$GLOBALS['_xh']['qt']=''; //unused...
2511 $GLOBALS['_xh']['stack'] = array();
2512 $GLOBALS['_xh']['valuestack'] = array();
2513 $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
2514 $GLOBALS['_xh']['isf_reason']='';
2515 $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'
2517 // if response charset encoding is not known / supported, try to use
2518 // the default encoding and parse the xml anyway, but log a warning...
2519 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
2520 // the following code might be better for mb_string enabled installs, but
2521 // makes the lib about 200% slower...
2522 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
2524 error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);
2525 $resp_encoding = $GLOBALS['xmlrpc_defencoding'];
2527 $parser = xml_parser_create($resp_encoding);
2528 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
2529 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
2530 // the xml parser to give us back data in the expected charset
2531 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
2533 if ($return_type == 'phpvals')
2535 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
2539 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
2542 xml_set_character_data_handler($parser, 'xmlrpc_cd');
2543 xml_set_default_handler($parser, 'xmlrpc_dh');
2545 // first error check: xml not well formed
2546 if(!xml_parse($parser, $data, count($data)))
2548 // thanks to Peter Kocks <peter.kocks@baygate.com>
2549 if((xml_get_current_line_number($parser)) == 1)
2551 $errstr = 'XML error at line 1, check URL';
2555 $errstr = sprintf('XML error: %s at line %d, column %d',
2556 xml_error_string(xml_get_error_code($parser)),
2557 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
2560 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');
2561 xml_parser_free($parser);
2566 $r->hdrs = $GLOBALS['_xh']['headers'];
2567 $r->_cookies = $GLOBALS['_xh']['cookies'];
2568 $r->raw_data = $raw_data;
2571 xml_parser_free($parser);
2572 // second error check: xml well formed but not xml-rpc compliant
2573 if ($GLOBALS['_xh']['isf'] > 1)
2577 /// @todo echo something for user?
2580 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
2581 $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);
2583 // third error check: parsing of the response has somehow gone boink.
2584 // NB: shall we omit this check, since we trust the parsing code?
2585 elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))
2587 // something odd has happened
2588 // and it's time to generate a client side error
2589 // indicating something odd went on
2590 $r= new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
2591 $GLOBALS['xmlrpcstr']['invalid_return']);
2597 print "<PRE>---PARSED---\n";
2598 // somehow htmlentities chokes on var_export, and some full html string...
2599 //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
2600 print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));
2601 print "\n---END---</PRE>";
2604 // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.
2605 $v =& $GLOBALS['_xh']['value'];
2607 if($GLOBALS['_xh']['isf'])
2609 /// @todo we should test here if server sent an int and a string,
2610 /// and/or coerce them into such...
2611 if ($return_type == 'xmlrpcvals')
2613 $errno_v = $v->structmem('faultCode');
2614 $errstr_v = $v->structmem('faultString');
2615 $errno = $errno_v->scalarval();
2616 $errstr = $errstr_v->scalarval();
2620 $errno = $v['faultCode'];
2621 $errstr = $v['faultString'];
2626 // FAULT returned, errno needs to reflect that
2630 $r = new xmlrpcresp(0, $errno, $errstr);
2634 $r= new xmlrpcresp($v, 0, '', $return_type);
2638 $r->hdrs = $GLOBALS['_xh']['headers'];
2639 $r->_cookies = $GLOBALS['_xh']['cookies'];
2640 $r->raw_data = $raw_data;
2649 var $_php_class=null;
2653 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
2655 function xmlrpcval($val=-1, $type='')
2657 /// @todo: optimization creep - do not call addXX, do it all inline.
2658 /// downside: booleans will not be coerced anymore
2659 if($val!==-1 || $type!='')
2661 // optimization creep: inlined all work done by constructor
2666 $this->me['string']=$val;
2673 case 'dateTime.iso8601':
2677 $this->me[$type]=$val;
2681 $this->me['array']=$val;
2685 $this->me['struct']=$val;
2688 error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");
2694 if($GLOBALS['xmlrpcTypes'][$type]==1)
2696 $this->addScalar($val,$type);
2698 elseif($GLOBALS['xmlrpcTypes'][$type]==2)
2700 $this->addArray($val);
2702 elseif($GLOBALS['xmlrpcTypes'][$type]==3)
2704 $this->addStruct($val);
2710 * Add a single php value to an (unitialized) xmlrpcval
2712 * @param string $type
2713 * @return int 1 or 0 on failure
2715 function addScalar($val, $type='string')
2717 $typeof=@$GLOBALS['xmlrpcTypes'][$type];
2720 error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");
2724 // coerce booleans into correct values
2725 // NB: we should iether do it for datetimes, integers and doubles, too,
2726 // or just plain remove this check, implemnted on booleans only...
2727 if($type==$GLOBALS['xmlrpcBoolean'])
2729 if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))
2739 switch($this->mytype)
2742 error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');
2745 error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');
2748 // we're adding a scalar value to an array here
2749 //$ar=$this->me['array'];
2750 //$ar[]= new xmlrpcval($val, $type);
2751 //$this->me['array']=$ar;
2752 // Faster (?) avoid all the costly array-copy-by-val done here...
2753 $this->me['array'][]= new xmlrpcval($val, $type);
2756 // a scalar, so set the value and remember we're scalar
2757 $this->me[$type]=$val;
2758 $this->mytype=$typeof;
2764 * Add an array of xmlrpcval objects to an xmlrpcval
2765 * @param array $vals
2766 * @return int 1 or 0 on failure
2769 * @todo add some checking for $vals to be an array of xmlrpcvals?
2771 function addArray($vals)
2773 if($this->mytype==0)
2775 $this->mytype=$GLOBALS['xmlrpcTypes']['array'];
2776 $this->me['array']=$vals;
2779 elseif($this->mytype==2)
2781 // we're adding to an array here
2782 $this->me['array'] = array_merge($this->me['array'], $vals);
2787 error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']');
2793 * Add an array of named xmlrpcval objects to an xmlrpcval
2794 * @param array $vals
2795 * @return int 1 or 0 on failure
2798 * @todo add some checking for $vals to be an array?
2800 function addStruct($vals)
2802 if($this->mytype==0)
2804 $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];
2805 $this->me['struct']=$vals;
2808 elseif($this->mytype==3)
2810 // we're adding to a struct here
2811 $this->me['struct'] = array_merge($this->me['struct'], $vals);
2816 error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']');
2821 // poor man's version of print_r ???
2825 foreach($ar as $key => $val)
2827 echo "$key => $val<br />";
2830 while(list($key2, $val2) = each($val))
2832 echo "-- $key2 => $val2<br />";
2839 * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
2845 switch($this->mytype)
2864 function serializedata($typ, $val, $charset_encoding='')
2867 switch(@$GLOBALS['xmlrpcTypes'][$typ])
2872 case $GLOBALS['xmlrpcBase64']:
2873 $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";
2875 case $GLOBALS['xmlrpcBoolean']:
2876 $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
2878 case $GLOBALS['xmlrpcString']:
2879 // G. Giunta 2005/2/13: do NOT use htmlentities, since
2880 // it will produce named html entities, which are invalid xml
2881 $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";
2883 case $GLOBALS['xmlrpcInt']:
2884 case $GLOBALS['xmlrpcI4']:
2885 $rs.="<${typ}>".(int)$val."</${typ}>";
2887 case $GLOBALS['xmlrpcDouble']:
2888 $rs.="<${typ}>".(double)$val."</${typ}>";
2890 case $GLOBALS['xmlrpcNull']:
2894 // no standard type value should arrive here, but provide a possibility
2895 // for xmlrpcvals of unknown type...
2896 $rs.="<${typ}>${val}</${typ}>";
2901 if ($this->_php_class)
2903 $rs.='<struct php_class="' . $this->_php_class . "\">\n";
2909 foreach($val as $key2 => $val2)
2911 $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";
2912 //$rs.=$this->serializeval($val2);
2913 $rs.=$val2->serialize($charset_encoding);
2920 $rs.="<array>\n<data>\n";
2921 for($i=0; $i<count($val); $i++)
2923 //$rs.=$this->serializeval($val[$i]);
2924 $rs.=$val[$i]->serialize($charset_encoding);
2926 $rs.="</data>\n</array>";
2935 * Returns xml representation of the value. XML prologue not included
2936 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
2940 function serialize($charset_encoding='')
2942 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
2943 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
2946 list($typ, $val) = each($this->me);
2947 return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";
2952 function serializeval($o)
2954 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
2955 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
2959 list($typ, $val) = each($ar);
2960 return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
2965 * Checks wheter a struct member with a given name is present.
2966 * Works only on xmlrpcvals of type struct.
2967 * @param string $m the name of the struct member to be looked up
2971 function structmemexists($m)
2973 return array_key_exists($m, $this->me['struct']);
2977 * Returns the value of a given struct member (an xmlrpcval object in itself).
2978 * Will raise a php warning if struct member of given name does not exist
2979 * @param string $m the name of the struct member to be looked up
2983 function structmem($m)
2985 return $this->me['struct'][$m];
2989 * Reset internal pointer for xmlrpcvals of type struct.
2992 function structreset()
2994 reset($this->me['struct']);
2998 * Return next member element for xmlrpcvals of type struct.
3002 function structeach()
3004 return each($this->me['struct']);
3007 // DEPRECATED! this code looks like it is very fragile and has not been fixed
3008 // for a long long time. Shall we remove it for 2.0?
3013 list($a,$b)=each($this->me);
3014 // contributed by I Sofer, 2001-03-24
3015 // add support for nested arrays to scalarval
3016 // i've created a new method here, so as to
3017 // preserve back compatibility
3022 while(list($id,$cont) = @each($b))
3024 $b[$id] = $cont->scalarval();
3028 // add support for structures directly encoding php objects
3031 $t = get_object_vars($b);
3033 while(list($id,$cont) = @each($t))
3035 $t[$id] = $cont->scalarval();
3038 while(list($id,$cont) = @each($t))
3048 * Returns the value of a scalar xmlrpcval
3052 function scalarval()
3055 list(,$b)=each($this->me);
3060 * Returns the type of the xmlrpcval.
3061 * For integers, 'int' is always returned in place of 'i4'
3065 function scalartyp()
3068 list($a,)=each($this->me);
3069 if($a==$GLOBALS['xmlrpcI4'])
3071 $a=$GLOBALS['xmlrpcInt'];
3077 * Returns the m-th member of an xmlrpcval of struct type
3078 * @param integer $m the index of the value to be retrieved (zero based)
3082 function arraymem($m)
3084 return $this->me['array'][$m];
3088 * Returns the number of members in an xmlrpcval of array type
3092 function arraysize()
3094 return count($this->me['array']);
3098 * Returns the number of members in an xmlrpcval of struct type
3102 function structsize()
3104 return count($this->me['struct']);
3112 * Given a timestamp, return the corresponding ISO8601 encoded string.
3114 * Really, timezones ought to be supported
3115 * but the XML-RPC spec says:
3117 * "Don't assume a timezone. It should be specified by the server in its
3118 * documentation what assumptions it makes about timezones."
3120 * These routines always assume localtime unless
3121 * $utc is set to 1, in which case UTC is assumed
3122 * and an adjustment for locale is made when encoding
3124 * @param int $timet (timestamp)
3125 * @param int $utc (0 or 1)
3128 function iso8601_encode($timet, $utc=0)
3132 $t=strftime("%Y%m%dT%H:%M:%S", $timet);
3136 if(function_exists('gmstrftime'))
3138 // gmstrftime doesn't exist in some versions
3140 $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);
3144 $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));
3151 * Given an ISO8601 date string, return a timet in the localtime, or UTC
3152 * @param string $idate
3153 * @param int $utc either 0 or 1
3154 * @return int (datetime)
3156 function iso8601_decode($idate, $utc=0)
3159 if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))
3163 $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
3167 $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
3174 * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.
3176 * Works with xmlrpc message objects as input, too.
3178 * Given proper options parameter, can rebuild generic php object instances
3179 * (provided those have been encoded to xmlrpc format using a corresponding
3180 * option in php_xmlrpc_encode())
3181 * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
3182 * This means that the remote communication end can decide which php code will
3183 * get executed on your server, leaving the door possibly open to 'php-injection'
3184 * style of attacks (provided you have some classes defined on your server that
3185 * might wreak havoc if instances are built outside an appropriate context).
3186 * Make sure you trust the remote server/client before eanbling this!
3188 * @author Dan Libby (dan@libby.com)
3190 * @param xmlrpcval $xmlrpc_val
3191 * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects
3194 function php_xmlrpc_decode($xmlrpc_val, $options=array())
3196 switch($xmlrpc_val->kindOf())
3199 if (in_array('extension_api', $options))
3201 reset($xmlrpc_val->me);
3202 list($typ,$val) = each($xmlrpc_val->me);
3205 case 'dateTime.iso8601':
3206 $xmlrpc_val->scalar = $val;
3207 $xmlrpc_val->xmlrpc_type = 'datetime';
3208 $xmlrpc_val->timestamp = iso8601_decode($val);
3211 $xmlrpc_val->scalar = $val;
3212 $xmlrpc_val->type = $typ;
3215 return $xmlrpc_val->scalarval();
3218 return $xmlrpc_val->scalarval();
3220 $size = $xmlrpc_val->arraysize();
3222 for($i = 0; $i < $size; $i++)
3224 $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);
3228 $xmlrpc_val->structreset();
3229 // If user said so, try to rebuild php objects for specific struct vals.
3230 /// @todo should we raise a warning for class not found?
3231 // shall we check for proper subclass of xmlrpcval instead of
3232 // presence of _php_class to detect what we can do?
3233 if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''
3234 && class_exists($xmlrpc_val->_php_class))
3236 $obj = @new $xmlrpc_val->_php_class;
3237 while(list($key,$value)=$xmlrpc_val->structeach())
3239 $obj->$key = php_xmlrpc_decode($value, $options);
3246 while(list($key,$value)=$xmlrpc_val->structeach())
3248 $arr[$key] = php_xmlrpc_decode($value, $options);
3253 $paramcount = $xmlrpc_val->getNumParams();
3255 for($i = 0; $i < $paramcount; $i++)
3257 $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));
3263 // This constant left here only for historical reasons...
3264 // it was used to decide if we have to define xmlrpc_encode on our own, but
3265 // we do not do it anymore
3266 if(function_exists('xmlrpc_decode'))
3268 define('XMLRPC_EPI_ENABLED','1');
3272 define('XMLRPC_EPI_ENABLED','0');
3276 * Takes native php types and encodes them into xmlrpc PHP object format.
3277 * It will not re-encode xmlrpcval objects.
3279 * Feature creep -- could support more types via optional type argument
3280 * (string => datetime support has been added, ??? => base64 not yet)
3282 * If given a proper options parameter, php object instances will be encoded
3283 * into 'special' xmlrpc values, that can later be decoded into php objects
3284 * by calling php_xmlrpc_decode() with a corresponding option
3286 * @author Dan Libby (dan@libby.com)
3288 * @param mixed $php_val the value to be converted into an xmlrpcval object
3289 * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
3292 function &php_xmlrpc_encode($php_val, $options=array())
3294 $type = gettype($php_val);
3298 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))
3299 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);
3301 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);
3304 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);
3307 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);
3309 // <G_Giunta_2001-02-29>
3310 // Add support for encoding/decoding of booleans, since they are supported in PHP
3312 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);
3314 // </G_Giunta_2001-02-29>
3316 // PHP arrays can be encoded to either xmlrpc structs or arrays,
3317 // depending on wheter they are hashes or plain 0..n integer indexed
3318 // A shorter one-liner would be
3319 // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
3320 // but execution time skyrockets!
3324 foreach($php_val as $key => $val)
3326 $arr[$key] =& php_xmlrpc_encode($val, $options);
3327 if(!$ko && $key !== $j)
3335 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
3339 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);
3343 if(is_a($php_val, 'xmlrpcval'))
3345 $xmlrpc_val = $php_val;
3350 while(list($k,$v) = each($php_val))
3352 $arr[$k] = php_xmlrpc_encode($v, $options);
3354 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
3355 if (in_array('encode_php_objs', $options))
3357 // let's save original class name into xmlrpcval:
3358 // might be useful later on...
3359 $xmlrpc_val->_php_class = get_class($php_val);
3364 if (in_array('extension_api', $options))
3366 $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcString']);
3368 if (in_array('null_extension', $options))
3370 $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcNull']);
3374 $xmlrpc_val = new xmlrpcval();
3378 if (in_array('extension_api', $options))
3380 $xmlrpc_val = new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);
3384 $xmlrpc_val = new xmlrpcval();
3386 // catch "user function", "unknown type"
3388 // giancarlo pinerolo <ping@alt.it>
3390 // an empty object in case, not a boolean.
3391 $xmlrpc_val = new xmlrpcval();
3398 * Convert the xml representation of a method response, method request or single
3399 * xmlrpc value into the appropriate object (a.k.a. deserialize)
3400 * @param string $xml_val
3401 * @param array $options
3402 * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp
3404 function php_xmlrpc_decode_xml($xml_val, $options=array())
3406 $GLOBALS['_xh'] = array();
3407 $GLOBALS['_xh']['ac'] = '';
3408 $GLOBALS['_xh']['stack'] = array();
3409 $GLOBALS['_xh']['valuestack'] = array();
3410 $GLOBALS['_xh']['params'] = array();
3411 $GLOBALS['_xh']['pt'] = array();
3412 $GLOBALS['_xh']['isf'] = 0;
3413 $GLOBALS['_xh']['isf_reason'] = '';
3414 $GLOBALS['_xh']['method'] = false;
3415 $GLOBALS['_xh']['rt'] = '';
3416 /// @todo 'guestimate' encoding
3417 $parser = xml_parser_create();
3418 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
3419 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
3420 xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
3421 xml_set_character_data_handler($parser, 'xmlrpc_cd');
3422 xml_set_default_handler($parser, 'xmlrpc_dh');
3423 if(!xml_parse($parser, $xml_val, 1))
3425 $errstr = sprintf('XML error: %s at line %d, column %d',
3426 xml_error_string(xml_get_error_code($parser)),
3427 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
3429 xml_parser_free($parser);
3432 xml_parser_free($parser);
3433 if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???
3435 error_log($GLOBALS['_xh']['isf_reason']);
3438 switch ($GLOBALS['_xh']['rt'])
3440 case 'methodresponse':
3441 $v =& $GLOBALS['_xh']['value'];
3442 if ($GLOBALS['_xh']['isf'] == 1)
3444 $vc = $v->structmem('faultCode');
3445 $vs = $v->structmem('faultString');
3446 $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());
3450 $r = new xmlrpcresp($v);
3454 $m = new xmlrpcmsg($GLOBALS['_xh']['method']);
3455 for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)
3457 $m->addParam($GLOBALS['_xh']['params'][$i]);
3461 return $GLOBALS['_xh']['value'];
3468 * decode a string that is encoded w/ "chunked" transfer encoding
3469 * as defined in rfc2068 par. 19.4.6
3470 * code shamelessly stolen from nusoap library by Dietrich Ayala
3472 * @param string $buffer the string to be decoded
3475 function decode_chunked($buffer)
3481 // read chunk-size, chunk-extension (if any) and crlf
3482 // get the position of the linebreak
3483 $chunkend = strpos($buffer,"\r\n") + 2;
3484 $temp = substr($buffer,0,$chunkend);
3485 $chunk_size = hexdec( trim($temp) );
3486 $chunkstart = $chunkend;
3487 while($chunk_size > 0)
3489 $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);
3491 // just in case we got a broken connection
3492 if($chunkend == false)
3494 $chunk = substr($buffer,$chunkstart);
3495 // append chunk-data to entity-body
3497 $length += strlen($chunk);
3501 // read chunk-data and crlf
3502 $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
3503 // append chunk-data to entity-body
3505 // length := length + chunk-size
3506 $length += strlen($chunk);
3507 // read chunk-size and crlf
3508 $chunkstart = $chunkend + 2;
3510 $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;
3511 if($chunkend == false)
3513 break; //just in case we got a broken connection
3515 $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
3516 $chunk_size = hexdec( trim($temp) );
3517 $chunkstart = $chunkend;
3523 * xml charset encoding guessing helper function.
3524 * Tries to determine the charset encoding of an XML chunk
3525 * received over HTTP.
3526 * NB: according to the spec (RFC 3023, if text/xml content-type is received over HTTP without a content-type,
3527 * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
3528 * which will be most probably using UTF-8 anyway...
3530 * @param string $httpheaders the http Content-type header
3531 * @param string $xmlchunk xml content buffer
3532 * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)
3534 * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
3536 function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)
3538 // discussion: see http://www.yale.edu/pclt/encoding/
3539 // 1 - test if encoding is specified in HTTP HEADERS
3542 // LWS: (\13\10)?( |\t)+
3543 // token: (any char but excluded stuff)+
3544 // header: Content-type = ...; charset=value(; ...)*
3545 // where value is of type token, no LWS allowed between 'charset' and value
3546 // Note: we do not check for invalid chars in VALUE:
3547 // this had better be done using pure ereg as below
3549 /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
3551 if(preg_match('/;\s*charset=([^;]+)/i', $httpheader, $matches))
3553 return strtoupper(trim($matches[1]));
3556 // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
3557 // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
3558 // NOTE: actually, according to the spec, even if we find the BOM and determine
3559 // an encoding, we should check if there is an encoding specified
3560 // in the xml declaration, and verify if they match.
3561 /// @todo implement check as described above?
3562 /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
3563 if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))
3567 elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))
3571 elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))
3576 // 3 - test if encoding is specified in the xml declaration
3578 // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
3579 // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
3580 if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".
3581 '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
3582 $xmlchunk, $matches))
3584 return strtoupper(substr($matches[2], 1, -1));
3587 // 4 - if mbstring is available, let it do the guesswork
3588 // NB: we favour finding an encoding that is compatible with what we can process
3589 if(extension_loaded('mbstring'))
3593 $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);
3597 $enc = mb_detect_encoding($xmlchunk);
3599 // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
3600 // IANA also likes better US-ASCII, so go with it
3609 // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
3610 // Both RFC 2616 (HTTP 1.1) and 1945(http 1.0) clearly state that for text/xxx content types
3611 // this should be the standard. And we should be getting text/xml as request and response.
3612 // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
3613 return $GLOBALS['xmlrpc_defencoding'];
3618 * Checks if a given charset encoding is present in a list of encodings or
3619 * if it is a valid subset of any encoding in the list
3620 * @param string $encoding charset to be tested
3621 * @param mixed $validlist comma separated list of valid charsets (or array of charsets)
3623 function is_valid_charset($encoding, $validlist)
3625 $charset_supersets = array(
3626 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
3627 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
3628 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
3629 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
3630 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')
3632 if (is_string($validlist))
3633 $validlist = explode(',', $validlist);
3634 if (@in_array(strtoupper($encoding), $validlist))
3638 if (array_key_exists($encoding, $charset_supersets))
3639 foreach ($validlist as $allowed)
3640 if (in_array($allowed, $charset_supersets[$encoding]))