2 // by Edd Dumbill (C) 1999-2002
\r
3 // <edd@usefulinc.com>
\r
5 // Copyright (c) 1999,2000,2002 Edd Dumbill.
\r
6 // All rights reserved.
\r
8 // Redistribution and use in source and binary forms, with or without
\r
9 // modification, are permitted provided that the following conditions
\r
12 // * Redistributions of source code must retain the above copyright
\r
13 // notice, this list of conditions and the following disclaimer.
\r
15 // * Redistributions in binary form must reproduce the above
\r
16 // copyright notice, this list of conditions and the following
\r
17 // disclaimer in the documentation and/or other materials provided
\r
18 // with the distribution.
\r
20 // * Neither the name of the "XML-RPC for PHP" nor the names of its
\r
21 // contributors may be used to endorse or promote products derived
\r
22 // from this software without specific prior written permission.
\r
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
\r
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
\r
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
\r
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
\r
28 // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
\r
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
\r
30 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
\r
31 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
\r
32 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
\r
33 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
\r
34 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
\r
35 // OF THE POSSIBILITY OF SUCH DAMAGE.
\r
37 // G. Giunta 2005/01/29: declare global these variables,
\r
38 // so that xmlrpc.inc will work even if included from within a function
\r
39 // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
\r
40 $GLOBALS['xmlrpcI4']='i4';
\r
41 $GLOBALS['xmlrpcInt']='int';
\r
42 $GLOBALS['xmlrpcBoolean']='boolean';
\r
43 $GLOBALS['xmlrpcDouble']='double';
\r
44 $GLOBALS['xmlrpcString']='string';
\r
45 $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
\r
46 $GLOBALS['xmlrpcBase64']='base64';
\r
47 $GLOBALS['xmlrpcArray']='array';
\r
48 $GLOBALS['xmlrpcStruct']='struct';
\r
49 $GLOBALS['xmlrpcValue']='undefined';
\r
51 $GLOBALS['xmlrpcTypes']=array(
\r
52 $GLOBALS['xmlrpcI4'] => 1,
\r
53 $GLOBALS['xmlrpcInt'] => 1,
\r
54 $GLOBALS['xmlrpcBoolean'] => 1,
\r
55 $GLOBALS['xmlrpcString'] => 1,
\r
56 $GLOBALS['xmlrpcDouble'] => 1,
\r
57 $GLOBALS['xmlrpcDateTime'] => 1,
\r
58 $GLOBALS['xmlrpcBase64'] => 1,
\r
59 $GLOBALS['xmlrpcArray'] => 2,
\r
60 $GLOBALS['xmlrpcStruct'] => 3
\r
63 $GLOBALS['xmlrpc_valid_parents'] = array(
\r
64 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
\r
65 'BOOLEAN' => array('VALUE'),
\r
66 'I4' => array('VALUE'),
\r
67 'INT' => array('VALUE'),
\r
68 'STRING' => array('VALUE'),
\r
69 'DOUBLE' => array('VALUE'),
\r
70 'DATETIME.ISO8601' => array('VALUE'),
\r
71 'BASE64' => array('VALUE'),
\r
72 'MEMBER' => array('STRUCT'),
\r
73 'NAME' => array('MEMBER'),
\r
74 'DATA' => array('ARRAY'),
\r
75 'ARRAY' => array('VALUE'),
\r
76 'STRUCT' => array('VALUE'),
\r
77 'PARAM' => array('PARAMS'),
\r
78 'METHODNAME' => array('METHODCALL'),
\r
79 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
\r
80 'FAULT' => array('METHODRESPONSE'),
\r
81 'NIL' => array('VALUE'), // only used when extension activated
\r
82 'EX:NIL' => array('VALUE') // only used when extension activated
\r
85 // define extra types for supporting NULL (useful for json or <NIL/>)
\r
86 $GLOBALS['xmlrpcNull']='null';
\r
87 $GLOBALS['xmlrpcTypes']['null']=1;
\r
89 // tables used for transcoding different charsets into us-ascii xml
\r
91 $GLOBALS['xml_iso88591_Entities']=array();
\r
92 $GLOBALS['xml_iso88591_Entities']['in'] = array();
\r
93 $GLOBALS['xml_iso88591_Entities']['out'] = array();
\r
94 for ($i = 0; $i < 32; $i++)
\r
96 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
\r
97 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
\r
99 for ($i = 160; $i < 256; $i++)
\r
101 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
\r
102 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
\r
105 /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
\r
106 /// These will NOT be present in true ISO-8859-1, but will save the unwary
\r
107 /// windows user from sending junk (though no luck when reciving them...)
\r
109 $GLOBALS['xml_cp1252_Entities']=array();
\r
110 for ($i = 128; $i < 160; $i++)
\r
112 $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i);
\r
114 $GLOBALS['xml_cp1252_Entities']['out'] = array(
\r
115 '€', '?', '‚', 'ƒ',
\r
116 '„', '…', '†', '‡',
\r
117 'ˆ', '‰', 'Š', '‹',
\r
118 'Œ', '?', 'Ž', '?',
\r
119 '?', '‘', '’', '“',
\r
120 '”', '•', '–', '—',
\r
121 '˜', '™', 'š', '›',
\r
122 'œ', '?', 'ž', 'Ÿ'
\r
126 $GLOBALS['xmlrpcerr'] = array(
\r
127 'unknown_method'=>1,
\r
128 'invalid_return'=>2,
\r
129 'incorrect_params'=>3,
\r
130 'introspect_unknown'=>4,
\r
135 'invalid_request'=>15,
\r
137 'server_error'=>17,
\r
138 'multicall_error'=>18,
\r
139 'multicall_notstruct'=>9,
\r
140 'multicall_nomethod'=>10,
\r
141 'multicall_notstring'=>11,
\r
142 'multicall_recursion'=>12,
\r
143 'multicall_noparams'=>13,
\r
144 'multicall_notarray'=>14,
\r
146 'cannot_decompress'=>103,
\r
147 'decompress_fail'=>104,
\r
148 'dechunk_fail'=>105,
\r
149 'server_cannot_decompress'=>106,
\r
150 'server_decompress_fail'=>107
\r
153 $GLOBALS['xmlrpcstr'] = array(
\r
154 'unknown_method'=>'Unknown method',
\r
155 'invalid_return'=>'Invalid return payload: enable debugging to examine incoming payload',
\r
156 'incorrect_params'=>'Incorrect parameters passed to method',
\r
157 'introspect_unknown'=>"Can't introspect: method unknown",
\r
158 'http_error'=>"Didn't receive 200 OK from remote server.",
\r
159 'no_data'=>'No data received from server.',
\r
160 'no_ssl'=>'No SSL support compiled in.',
\r
161 'curl_fail'=>'CURL error',
\r
162 'invalid_request'=>'Invalid request payload',
\r
163 'no_curl'=>'No CURL support compiled in.',
\r
164 'server_error'=>'Internal server error',
\r
165 'multicall_error'=>'Received from server invalid multicall response',
\r
166 'multicall_notstruct'=>'system.multicall expected struct',
\r
167 'multicall_nomethod'=>'missing methodName',
\r
168 'multicall_notstring'=>'methodName is not a string',
\r
169 'multicall_recursion'=>'recursive system.multicall forbidden',
\r
170 'multicall_noparams'=>'missing params',
\r
171 'multicall_notarray'=>'params is not an array',
\r
173 'cannot_decompress'=>'Received from server compressed HTTP and cannot decompress',
\r
174 'decompress_fail'=>'Received from server invalid compressed HTTP',
\r
175 'dechunk_fail'=>'Received from server invalid chunked HTTP',
\r
176 'server_cannot_decompress'=>'Received from client compressed HTTP request and cannot decompress',
\r
177 'server_decompress_fail'=>'Received from client invalid compressed HTTP request'
\r
180 // The charset encoding used by the server for received messages and
\r
181 // by the client for received responses when received charset cannot be determined
\r
182 // or is not supported
\r
183 $GLOBALS['xmlrpc_defencoding']='UTF-8';
\r
185 // The encoding used internally by PHP.
\r
186 // String values received as xml will be converted to this, and php strings will be converted to xml
\r
187 // as if having been coded with this
\r
188 $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
\r
190 $GLOBALS['xmlrpcName']='XML-RPC for PHP';
\r
191 $GLOBALS['xmlrpcVersion']='3.0.0.beta';
\r
193 // let user errors start at 800
\r
194 $GLOBALS['xmlrpcerruser']=800;
\r
195 // let XML parse errors start at 100
\r
196 $GLOBALS['xmlrpcerrxml']=100;
\r
198 // set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values
\r
199 $GLOBALS['xmlrpc_null_extension']=false;
\r
201 // set to TRUE to enable encoding of php NULL values to <EX:NIL/> instead of <NIL/>
\r
202 $GLOBALS['xmlrpc_null_apache_encoding']=false;
\r
203 $GLOBALS['xmlrpc_null_apache_encoding_ns']='http://ws.apache.org/xmlrpc/namespaces/extensions';
\r
205 // used to store state during parsing
\r
206 // quick explanation of components:
\r
207 // ac - used to accumulate values
\r
208 // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
\r
209 // isf_reason - used for storing xmlrpcresp fault string
\r
210 // lv - used to indicate "looking for a value": implements
\r
211 // the logic to allow values with no types to be strings
\r
212 // params - used to store parameters in method calls
\r
213 // method - used to store method name
\r
214 // stack - array with genealogy of xml elements names:
\r
215 // used to validate nesting of xmlrpc elements
\r
216 $GLOBALS['_xh']=null;
\r
219 * Convert a string to the correct XML representation in a target charset
\r
220 * To help correct communication of non-ascii chars inside strings, regardless
\r
221 * of the charset used when sending requests, parsing them, sending responses
\r
222 * and parsing responses, an option is to convert all non-ascii chars present in the message
\r
223 * into their equivalent 'charset entity'. Charset entities enumerated this way
\r
224 * are independent of the charset encoding used to transmit them, and all XML
\r
225 * parsers are bound to understand them.
\r
226 * Note that in the std case we are not sending a charset encoding mime type
\r
227 * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
\r
229 * @todo do a bit of basic benchmarking (strtr vs. str_replace)
\r
230 * @todo make usage of iconv() or recode_string() or mb_string() where available
\r
232 function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
\r
234 if ($src_encoding == '')
\r
236 // lame, but we know no better...
\r
237 $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
\r
240 switch(strtoupper($src_encoding.'_'.$dest_encoding))
\r
242 case 'ISO-8859-1_':
\r
243 case 'ISO-8859-1_US-ASCII':
\r
244 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
245 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
\r
247 case 'ISO-8859-1_UTF-8':
\r
248 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
249 $escaped_data = utf8_encode($escaped_data);
\r
251 case 'ISO-8859-1_ISO-8859-1':
\r
252 case 'US-ASCII_US-ASCII':
\r
253 case 'US-ASCII_UTF-8':
\r
255 case 'US-ASCII_ISO-8859-1':
\r
256 case 'UTF-8_UTF-8':
\r
257 //case 'CP1252_CP1252':
\r
258 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
261 case 'UTF-8_US-ASCII':
\r
262 case 'UTF-8_ISO-8859-1':
\r
263 // NB: this will choke on invalid UTF-8, going most likely beyond EOF
\r
264 $escaped_data = '';
\r
265 // be kind to users creating string xmlrpcvals out of different php types
\r
266 $data = (string) $data;
\r
267 $ns = strlen ($data);
\r
268 for ($nn = 0; $nn < $ns; $nn++)
\r
272 //1 7 0bbbbbbb (127)
\r
275 /// @todo shall we replace this with a (supposedly) faster str_replace?
\r
278 $escaped_data .= '"';
\r
281 $escaped_data .= '&';
\r
284 $escaped_data .= ''';
\r
287 $escaped_data .= '<';
\r
290 $escaped_data .= '>';
\r
293 $escaped_data .= $ch;
\r
296 //2 11 110bbbbb 10bbbbbb (2047)
\r
297 else if ($ii>>5 == 6)
\r
300 $ii = ord($data[$nn+1]);
\r
302 $ii = ($b1 * 64) + $b2;
\r
303 $ent = sprintf ('&#%d;', $ii);
\r
304 $escaped_data .= $ent;
\r
307 //3 16 1110bbbb 10bbbbbb 10bbbbbb
\r
308 else if ($ii>>4 == 14)
\r
311 $ii = ord($data[$nn+1]);
\r
313 $ii = ord($data[$nn+2]);
\r
315 $ii = ((($b1 * 64) + $b2) * 64) + $b3;
\r
316 $ent = sprintf ('&#%d;', $ii);
\r
317 $escaped_data .= $ent;
\r
320 //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
\r
321 else if ($ii>>3 == 30)
\r
324 $ii = ord($data[$nn+1]);
\r
326 $ii = ord($data[$nn+2]);
\r
328 $ii = ord($data[$nn+3]);
\r
330 $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
\r
331 $ent = sprintf ('&#%d;', $ii);
\r
332 $escaped_data .= $ent;
\r
339 case 'CP1252_US-ASCII':
\r
340 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
341 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
\r
342 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
\r
344 case 'CP1252_UTF-8':
\r
345 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
346 /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)
\r
347 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
\r
348 $escaped_data = utf8_encode($escaped_data);
\r
350 case 'CP1252_ISO-8859-1':
\r
351 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
\r
352 // we might as well replave all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...
\r
353 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
\r
357 $escaped_data = '';
\r
358 error_log("Converting from $src_encoding to $dest_encoding: not supported...");
\r
360 return $escaped_data;
\r
363 /// xml parser handler function for opening element tags
\r
364 function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
\r
366 // if invalid xmlrpc already detected, skip all processing
\r
367 if ($GLOBALS['_xh']['isf'] < 2)
\r
369 // check for correct element nesting
\r
370 // top level element can only be of 2 types
\r
371 /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
\r
372 /// there is only a single top level element in xml anyway
\r
373 if (count($GLOBALS['_xh']['stack']) == 0)
\r
375 if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
\r
376 $name != 'VALUE' && !$accept_single_vals))
\r
378 $GLOBALS['_xh']['isf'] = 2;
\r
379 $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
\r
384 $GLOBALS['_xh']['rt'] = strtolower($name);
\r
385 $GLOBALS['_xh']['rt'] = strtolower($name);
\r
390 // not top level element: see if parent is OK
\r
391 $parent = end($GLOBALS['_xh']['stack']);
\r
392 if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
\r
394 $GLOBALS['_xh']['isf'] = 2;
\r
395 $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
\r
402 // optimize for speed switch cases: most common cases first
\r
404 /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
\r
405 $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
\r
406 $GLOBALS['_xh']['ac']='';
\r
407 $GLOBALS['_xh']['lv']=1;
\r
408 $GLOBALS['_xh']['php_class']=null;
\r
415 case 'DATETIME.ISO8601':
\r
417 if ($GLOBALS['_xh']['vt']!='value')
\r
419 //two data elements inside a value: an error occurred!
\r
420 $GLOBALS['_xh']['isf'] = 2;
\r
421 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
\r
424 $GLOBALS['_xh']['ac']=''; // reset the accumulator
\r
428 if ($GLOBALS['_xh']['vt']!='value')
\r
430 //two data elements inside a value: an error occurred!
\r
431 $GLOBALS['_xh']['isf'] = 2;
\r
432 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
\r
435 // create an empty array to hold child values, and push it onto appropriate stack
\r
436 $cur_val = array();
\r
437 $cur_val['values'] = array();
\r
438 $cur_val['type'] = $name;
\r
439 // check for out-of-band information to rebuild php objs
\r
440 // and in case it is found, save it
\r
441 if (@isset($attrs['PHP_CLASS']))
\r
443 $cur_val['php_class'] = $attrs['PHP_CLASS'];
\r
445 $GLOBALS['_xh']['valuestack'][] = $cur_val;
\r
446 $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
\r
449 if ($GLOBALS['_xh']['vt']!='data')
\r
451 //two data elements inside a value: an error occurred!
\r
452 $GLOBALS['_xh']['isf'] = 2;
\r
453 $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
\r
457 case 'METHODRESPONSE':
\r
459 // valid elements that add little to processing
\r
463 /// @todo we could check for 2 NAME elements inside a MEMBER element
\r
464 $GLOBALS['_xh']['ac']='';
\r
467 $GLOBALS['_xh']['isf']=1;
\r
470 $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
\r
471 //$GLOBALS['_xh']['ac']='';
\r
472 // Drop trough intentionally
\r
474 // clear value type, so we can check later if no value has been passed for this param/member
\r
475 $GLOBALS['_xh']['vt']=null;
\r
479 if ($GLOBALS['xmlrpc_null_extension'])
\r
481 if ($GLOBALS['_xh']['vt']!='value')
\r
483 //two data elements inside a value: an error occurred!
\r
484 $GLOBALS['_xh']['isf'] = 2;
\r
485 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
\r
488 $GLOBALS['_xh']['ac']=''; // reset the accumulator
\r
491 // we do not support the <NIL/> extension, so
\r
492 // drop through intentionally
\r
494 /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
\r
495 $GLOBALS['_xh']['isf'] = 2;
\r
496 $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";
\r
500 // Save current element name to stack, to validate nesting
\r
501 $GLOBALS['_xh']['stack'][] = $name;
\r
503 /// @todo optimization creep: move this inside the big switch() above
\r
506 $GLOBALS['_xh']['lv']=0;
\r
511 /// Used in decoding xml chunks that might represent single xmlrpc values
\r
512 function xmlrpc_se_any($parser, $name, $attrs)
\r
514 xmlrpc_se($parser, $name, $attrs, true);
\r
517 /// xml parser handler function for close element tags
\r
518 function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)
\r
520 if ($GLOBALS['_xh']['isf'] < 2)
\r
522 // push this element name from stack
\r
523 // NB: if XML validates, correct opening/closing is guaranteed and
\r
524 // we do not have to check for $name == $curr_elem.
\r
525 // we also checked for proper nesting at start of elements...
\r
526 $curr_elem = array_pop($GLOBALS['_xh']['stack']);
\r
531 // This if() detects if no scalar was inside <VALUE></VALUE>
\r
532 if ($GLOBALS['_xh']['vt']=='value')
\r
534 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
\r
535 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
\r
538 if ($rebuild_xmlrpcvals)
\r
540 // build the xmlrpc val out of the data received, and substitute it
\r
541 $temp = new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);
\r
542 // in case we got info about underlying php class, save it
\r
543 // in the object we're rebuilding
\r
544 if (isset($GLOBALS['_xh']['php_class']))
\r
545 $temp->_php_class = $GLOBALS['_xh']['php_class'];
\r
546 // check if we are inside an array or struct:
\r
547 // if value just built is inside an array, let's move it into array on the stack
\r
548 $vscount = count($GLOBALS['_xh']['valuestack']);
\r
549 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
\r
551 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;
\r
555 $GLOBALS['_xh']['value'] = $temp;
\r
560 /// @todo this needs to treat correctly php-serialized objects,
\r
561 /// since std deserializing is done by php_xmlrpc_decode,
\r
562 /// which we will not be calling...
\r
563 if (isset($GLOBALS['_xh']['php_class']))
\r
567 // check if we are inside an array or struct:
\r
568 // if value just built is inside an array, let's move it into array on the stack
\r
569 $vscount = count($GLOBALS['_xh']['valuestack']);
\r
570 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
\r
572 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];
\r
581 case 'DATETIME.ISO8601':
\r
583 $GLOBALS['_xh']['vt']=strtolower($name);
\r
584 /// @todo: optimization creep - remove the if/elseif cycle below
\r
585 /// since the case() in which we are already did that
\r
586 if ($name=='STRING')
\r
588 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
\r
590 elseif ($name=='DATETIME.ISO8601')
\r
592 if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))
\r
594 error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);
\r
596 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];
\r
597 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
\r
599 elseif ($name=='BASE64')
\r
601 /// @todo check for failure of base64 decoding / catch warnings
\r
602 $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);
\r
604 elseif ($name=='BOOLEAN')
\r
606 // special case here: we translate boolean 1 or 0 into PHP
\r
607 // constants true or false.
\r
608 // Strings 'true' and 'false' are accepted, even though the
\r
609 // spec never mentions them (see eg. Blogger api docs)
\r
610 // NB: this simple checks helps a lot sanitizing input, ie no
\r
611 // security problems around here
\r
612 if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)
\r
614 $GLOBALS['_xh']['value']=true;
\r
618 // log if receiveing something strange, even though we set the value to false anyway
\r
619 if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($GLOBALS['_xh']['ac'], 'false') != 0)
\r
620 error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);
\r
621 $GLOBALS['_xh']['value']=false;
\r
624 elseif ($name=='DOUBLE')
\r
626 // we have a DOUBLE
\r
627 // we must check that only 0123456789-.<space> are characters here
\r
628 // NOTE: regexp could be much stricter than this...
\r
629 if (!preg_match('/^[+-eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))
\r
631 /// @todo: find a better way of throwing an error than this!
\r
632 error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);
\r
633 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
\r
637 // it's ok, add it on
\r
638 $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];
\r
643 // we have an I4/INT
\r
644 // we must check that only 0123456789-<space> are characters here
\r
645 if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))
\r
647 /// @todo find a better way of throwing an error than this!
\r
648 error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);
\r
649 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
\r
653 // it's ok, add it on
\r
654 $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];
\r
657 //$GLOBALS['_xh']['ac']=''; // is this necessary?
\r
658 $GLOBALS['_xh']['lv']=3; // indicate we've found a value
\r
661 $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];
\r
664 //$GLOBALS['_xh']['ac']=''; // is this necessary?
\r
665 // add to array in the stack the last element built,
\r
666 // unless no VALUE was found
\r
667 if ($GLOBALS['_xh']['vt'])
\r
669 $vscount = count($GLOBALS['_xh']['valuestack']);
\r
670 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];
\r
672 error_log('XML-RPC: missing VALUE inside STRUCT in received xml');
\r
675 //$GLOBALS['_xh']['ac']=''; // is this necessary?
\r
676 $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty
\r
680 // fetch out of stack array of values, and promote it to current value
\r
681 $curr_val = array_pop($GLOBALS['_xh']['valuestack']);
\r
682 $GLOBALS['_xh']['value'] = $curr_val['values'];
\r
683 $GLOBALS['_xh']['vt']=strtolower($name);
\r
684 if (isset($curr_val['php_class']))
\r
686 $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];
\r
690 // add to array of params the current value,
\r
691 // unless no VALUE was found
\r
692 if ($GLOBALS['_xh']['vt'])
\r
694 $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];
\r
695 $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];
\r
698 error_log('XML-RPC: missing VALUE inside PARAM in received xml');
\r
701 $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);
\r
705 if ($GLOBALS['xmlrpc_null_extension'])
\r
707 $GLOBALS['_xh']['vt']='null';
\r
708 $GLOBALS['_xh']['value']=null;
\r
709 $GLOBALS['_xh']['lv']=3;
\r
712 // drop through intentionally if nil extension not enabled
\r
716 case 'METHORESPONSE':
\r
719 // End of INVALID ELEMENT!
\r
720 // shall we add an assert here for unreachable code???
\r
726 /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values
\r
727 function xmlrpc_ee_fast($parser, $name)
\r
729 xmlrpc_ee($parser, $name, false);
\r
732 /// xml parser handler function for character data
\r
733 function xmlrpc_cd($parser, $data)
\r
735 // skip processing if xml fault already detected
\r
736 if ($GLOBALS['_xh']['isf'] < 2)
\r
738 // "lookforvalue==3" means that we've found an entire value
\r
739 // and should discard any further character data
\r
740 if($GLOBALS['_xh']['lv']!=3)
\r
742 // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2
\r
743 //if($GLOBALS['_xh']['lv']==1)
\r
745 // if we've found text and we're just in a <value> then
\r
746 // say we've found a value
\r
747 //$GLOBALS['_xh']['lv']=2;
\r
749 // we always initialize the accumulator before starting parsing, anyway...
\r
750 //if(!@isset($GLOBALS['_xh']['ac']))
\r
752 // $GLOBALS['_xh']['ac'] = '';
\r
754 $GLOBALS['_xh']['ac'].=$data;
\r
759 /// xml parser handler function for 'other stuff', ie. not char data or
\r
760 /// element start/end tag. In fact it only gets called on unknown entities...
\r
761 function xmlrpc_dh($parser, $data)
\r
763 // skip processing if xml fault already detected
\r
764 if ($GLOBALS['_xh']['isf'] < 2)
\r
766 if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')
\r
768 // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2
\r
769 //if($GLOBALS['_xh']['lv']==1)
\r
771 // $GLOBALS['_xh']['lv']=2;
\r
773 $GLOBALS['_xh']['ac'].=$data;
\r
779 class xmlrpc_client
\r
784 var $method='http';
\r
797 var $verifypeer=true;
\r
799 var $no_multicall=false;
\r
802 var $proxy_user='';
\r
803 var $proxy_pass='';
\r
804 var $proxy_authtype=1;
\r
805 var $cookies=array();
\r
806 var $extracurlopts=array();
\r
809 * List of http compression methods accepted by the client for responses.
\r
810 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
\r
812 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
\r
813 * in those cases it will be up to CURL to decide the compression methods
\r
814 * it supports. You might check for the presence of 'zlib' in the output of
\r
815 * curl_version() to determine wheter compression is supported or not
\r
817 var $accepted_compression = array();
\r
819 * Name of compression scheme to be used for sending requests.
\r
820 * Either null, gzip or deflate
\r
822 var $request_compression = '';
\r
824 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
\r
825 * http://curl.haxx.se/docs/faq.html#7.3)
\r
827 var $xmlrpc_curl_handle = null;
\r
828 /// Whether to use persistent connections for http 1.1 and https
\r
829 var $keepalive = false;
\r
830 /// Charset encodings that can be decoded without problems by the client
\r
831 var $accepted_charset_encodings = array();
\r
832 /// Charset encoding to be used in serializing request. NULL = use ASCII
\r
833 var $request_charset_encoding = '';
\r
835 * Decides the content of xmlrpcresp objects returned by calls to send()
\r
836 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
\r
838 var $return_type = 'xmlrpcvals';
\r
840 * Sent to servers in http headers
\r
845 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
\r
846 * @param string $server the server name / ip address
\r
847 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
\r
848 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
\r
850 function xmlrpc_client($path, $server='', $port='', $method='')
\r
852 // allow user to specify all params in $path
\r
853 if($server == '' and $port == '' and $method == '')
\r
855 $parts = parse_url($path);
\r
856 $server = $parts['host'];
\r
857 $path = isset($parts['path']) ? $parts['path'] : '';
\r
858 if(isset($parts['query']))
\r
860 $path .= '?'.$parts['query'];
\r
862 if(isset($parts['fragment']))
\r
864 $path .= '#'.$parts['fragment'];
\r
866 if(isset($parts['port']))
\r
868 $port = $parts['port'];
\r
870 if(isset($parts['scheme']))
\r
872 $method = $parts['scheme'];
\r
874 if(isset($parts['user']))
\r
876 $this->username = $parts['user'];
\r
878 if(isset($parts['pass']))
\r
880 $this->password = $parts['pass'];
\r
883 if($path == '' || $path[0] != '/')
\r
885 $this->path='/'.$path;
\r
891 $this->server=$server;
\r
898 $this->method=$method;
\r
901 // if ZLIB is enabled, let the client by default accept compressed responses
\r
902 if(function_exists('gzinflate') || (
\r
903 function_exists('curl_init') && (($info = curl_version()) &&
\r
904 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
\r
907 $this->accepted_compression = array('gzip', 'deflate');
\r
910 // keepalives: enabled by default
\r
911 $this->keepalive = true;
\r
913 // by default the xml parser can support these 3 charset encodings
\r
914 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
\r
916 // initialize user_agent string
\r
917 $this->user_agent = $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'];
\r
921 * Enables/disables the echoing to screen of the xmlrpc responses received
\r
922 * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
\r
925 function setDebug($in)
\r
931 * Add some http BASIC AUTH credentials, used by the client to authenticate
\r
932 * @param string $u username
\r
933 * @param string $p password
\r
934 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
\r
937 function setCredentials($u, $p, $t=1)
\r
939 $this->username=$u;
\r
940 $this->password=$p;
\r
941 $this->authtype=$t;
\r
945 * Add a client-side https certificate
\r
946 * @param string $cert
\r
947 * @param string $certpass
\r
950 function setCertificate($cert, $certpass)
\r
952 $this->cert = $cert;
\r
953 $this->certpass = $certpass;
\r
957 * Add a CA certificate to verify server with (see man page about
\r
958 * CURLOPT_CAINFO for more details)
\r
959 * @param string $cacert certificate file name (or dir holding certificates)
\r
960 * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false
\r
963 function setCaCertificate($cacert, $is_dir=false)
\r
967 $this->cacertdir = $cacert;
\r
971 $this->cacert = $cacert;
\r
976 * Set attributes for SSL communication: private SSL key
\r
977 * NB: does not work in older php/curl installs
\r
978 * Thanks to Daniel Convissor
\r
979 * @param string $key The name of a file containing a private SSL key
\r
980 * @param string $keypass The secret password needed to use the private SSL key
\r
983 function setKey($key, $keypass)
\r
986 $this->keypass = $keypass;
\r
990 * Set attributes for SSL communication: verify server certificate
\r
991 * @param bool $i enable/disable verification of peer certificate
\r
994 function setSSLVerifyPeer($i)
\r
996 $this->verifypeer = $i;
\r
1000 * Set attributes for SSL communication: verify match of server cert w. hostname
\r
1004 function setSSLVerifyHost($i)
\r
1006 $this->verifyhost = $i;
\r
1011 * @param string $proxyhost
\r
1012 * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS
\r
1013 * @param string $proxyusername Leave blank if proxy has public access
\r
1014 * @param string $proxypassword Leave blank if proxy has public access
\r
1015 * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy
\r
1018 function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)
\r
1020 $this->proxy = $proxyhost;
\r
1021 $this->proxyport = $proxyport;
\r
1022 $this->proxy_user = $proxyusername;
\r
1023 $this->proxy_pass = $proxypassword;
\r
1024 $this->proxy_authtype = $proxyauthtype;
\r
1028 * Enables/disables reception of compressed xmlrpc responses.
\r
1029 * Note that enabling reception of compressed responses merely adds some standard
\r
1030 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
\r
1031 * compressed responses when receiving such requests.
\r
1032 * @param string $compmethod either 'gzip', 'deflate', 'any' or ''
\r
1035 function setAcceptedCompression($compmethod)
\r
1037 if ($compmethod == 'any')
\r
1038 $this->accepted_compression = array('gzip', 'deflate');
\r
1040 if ($compmethod == false )
\r
1041 $this->accepted_compression = array();
\r
1043 $this->accepted_compression = array($compmethod);
\r
1047 * Enables/disables http compression of xmlrpc request.
\r
1048 * Take care when sending compressed requests: servers might not support them
\r
1049 * (and automatic fallback to uncompressed requests is not yet implemented)
\r
1050 * @param string $compmethod either 'gzip', 'deflate' or ''
\r
1053 function setRequestCompression($compmethod)
\r
1055 $this->request_compression = $compmethod;
\r
1059 * Adds a cookie to list of cookies that will be sent to server.
\r
1060 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
\r
1061 * do not do it unless you know what you are doing
\r
1062 * @param string $name
\r
1063 * @param string $value
\r
1064 * @param string $path
\r
1065 * @param string $domain
\r
1066 * @param int $port
\r
1069 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
\r
1071 function setCookie($name, $value='', $path='', $domain='', $port=null)
\r
1073 $this->cookies[$name]['value'] = urlencode($value);
\r
1074 if ($path || $domain || $port)
\r
1076 $this->cookies[$name]['path'] = $path;
\r
1077 $this->cookies[$name]['domain'] = $domain;
\r
1078 $this->cookies[$name]['port'] = $port;
\r
1079 $this->cookies[$name]['version'] = 1;
\r
1083 $this->cookies[$name]['version'] = 0;
\r
1088 * Directly set cURL options, for extra flexibility
\r
1089 * It allows eg. to bind client to a specific IP interface / address
\r
1090 * @param array $options
\r
1092 function SetCurlOptions( $options )
\r
1094 $this->extracurlopts = $options;
\r
1098 * Set user-agent string that will be used by this client instance
\r
1099 * in http headers sent to the server
\r
1101 function SetUserAgent( $agentstring )
\r
1103 $this->user_agent = $agentstring;
\r
1107 * Send an xmlrpc request
\r
1108 * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request
\r
1109 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
\r
1110 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
\r
1111 * @return xmlrpcresp
\r
1114 function& send($msg, $timeout=0, $method='')
\r
1116 // if user deos not specify http protocol, use native method of this client
\r
1117 // (i.e. method set during call to constructor)
\r
1120 $method = $this->method;
\r
1123 if(is_array($msg))
\r
1125 // $msg is an array of xmlrpcmsg's
\r
1126 $r = $this->multicall($msg, $timeout, $method);
\r
1129 elseif(is_string($msg))
\r
1131 $n = new xmlrpcmsg('');
\r
1132 $n->payload = $msg;
\r
1136 // where msg is an xmlrpcmsg
\r
1137 $msg->debug=$this->debug;
\r
1139 if($method == 'https')
\r
1141 $r =& $this->sendPayloadHTTPS(
\r
1155 $this->proxy_user,
\r
1156 $this->proxy_pass,
\r
1157 $this->proxy_authtype,
\r
1163 elseif($method == 'http11')
\r
1165 $r =& $this->sendPayloadCURL(
\r
1179 $this->proxy_user,
\r
1180 $this->proxy_pass,
\r
1181 $this->proxy_authtype,
\r
1188 $r =& $this->sendPayloadHTTP10(
\r
1198 $this->proxy_user,
\r
1199 $this->proxy_pass,
\r
1200 $this->proxy_authtype
\r
1210 function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,
\r
1211 $username='', $password='', $authtype=1, $proxyhost='',
\r
1212 $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)
\r
1219 // Only create the payload if it was not created previously
\r
1220 if(empty($msg->payload))
\r
1222 $msg->createPayload($this->request_charset_encoding);
\r
1225 $payload = $msg->payload;
\r
1226 // Deflate request body and set appropriate request headers
\r
1227 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
\r
1229 if($this->request_compression == 'gzip')
\r
1231 $a = @gzencode($payload);
\r
1235 $encoding_hdr = "Content-Encoding: gzip\r\n";
\r
1240 $a = @gzcompress($payload);
\r
1244 $encoding_hdr = "Content-Encoding: deflate\r\n";
\r
1250 $encoding_hdr = '';
\r
1253 // thanks to Grant Rauscher <grant7@firstworld.net> for this
\r
1257 $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
\r
1258 if ($authtype != 1)
\r
1260 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0');
\r
1264 $accepted_encoding = '';
\r
1265 if(is_array($this->accepted_compression) && count($this->accepted_compression))
\r
1267 $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
\r
1270 $proxy_credentials = '';
\r
1273 if($proxyport == 0)
\r
1275 $proxyport = 8080;
\r
1277 $connectserver = $proxyhost;
\r
1278 $connectport = $proxyport;
\r
1279 $uri = 'http://'.$server.':'.$port.$this->path;
\r
1280 if($proxyusername != '')
\r
1282 if ($proxyauthtype != 1)
\r
1284 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0');
\r
1286 $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";
\r
1291 $connectserver = $server;
\r
1292 $connectport = $port;
\r
1293 $uri = $this->path;
\r
1296 // Cookie generation, as per rfc2965 (version 1 cookies) or
\r
1297 // netscape's rules (version 0 cookies)
\r
1299 if (count($this->cookies))
\r
1302 foreach ($this->cookies as $name => $cookie)
\r
1304 if ($cookie['version'])
\r
1306 $version = ' $Version="' . $cookie['version'] . '";';
\r
1307 $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";';
\r
1308 if ($cookie['path'])
\r
1309 $cookieheader .= ' $Path="' . $cookie['path'] . '";';
\r
1310 if ($cookie['domain'])
\r
1311 $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';
\r
1312 if ($cookie['port'])
\r
1313 $cookieheader .= ' $Port="' . $cookie['port'] . '";';
\r
1317 $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";";
\r
1320 $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";
\r
1323 // omit port if 80
\r
1324 $port = ($port == 80) ? '' : (':' . $port);
\r
1326 $op= 'POST ' . $uri. " HTTP/1.0\r\n" .
\r
1327 'User-Agent: ' . $this->user_agent . "\r\n" .
\r
1328 'Host: '. $server . $port . "\r\n" .
\r
1330 $proxy_credentials .
\r
1331 $accepted_encoding .
\r
1333 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
\r
1335 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .
\r
1336 strlen($payload) . "\r\n\r\n" .
\r
1339 if($this->debug > 1)
\r
1341 print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";
\r
1342 // let the client see this now in case http times out...
\r
1348 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);
\r
1352 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);
\r
1356 if($timeout>0 && function_exists('stream_set_timeout'))
\r
1358 stream_set_timeout($fp, $timeout);
\r
1363 $this->errstr='Connect error: '.$this->errstr;
\r
1364 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');
\r
1368 if(!fputs($fp, $op, strlen($op)))
\r
1371 $this->errstr='Write error';
\r
1372 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);
\r
1377 // reset errno and errstr on successful socket connection
\r
1378 $this->errstr = '';
\r
1380 // G. Giunta 2005/10/24: close socket before parsing.
\r
1381 // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
\r
1385 // shall we check for $data === FALSE?
\r
1386 // as per the manual, it signals an error
\r
1387 $ipd.=fread($fp, 32768);
\r
1388 } while(!feof($fp));
\r
1390 $r =& $msg->parseResponse($ipd, false, $this->return_type);
\r
1398 function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
\r
1399 $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
\r
1400 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
\r
1401 $keepalive=false, $key='', $keypass='')
\r
1403 $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
\r
1404 $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
\r
1405 $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
\r
1410 * Contributed by Justin Miller <justin@voxel.net>
\r
1411 * Requires curl to be built into PHP
\r
1412 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
\r
1415 function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
\r
1416 $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
\r
1417 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
\r
1418 $keepalive=false, $key='', $keypass='')
\r
1420 if(!function_exists('curl_init'))
\r
1422 $this->errstr='CURL unavailable on this install';
\r
1423 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);
\r
1426 if($method == 'https')
\r
1428 if(($info = curl_version()) &&
\r
1429 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
\r
1431 $this->errstr='SSL unavailable on this install';
\r
1432 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);
\r
1439 if($method == 'http')
\r
1449 // Only create the payload if it was not created previously
\r
1450 if(empty($msg->payload))
\r
1452 $msg->createPayload($this->request_charset_encoding);
\r
1455 // Deflate request body and set appropriate request headers
\r
1456 $payload = $msg->payload;
\r
1457 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
\r
1459 if($this->request_compression == 'gzip')
\r
1461 $a = @gzencode($payload);
\r
1465 $encoding_hdr = 'Content-Encoding: gzip';
\r
1470 $a = @gzcompress($payload);
\r
1474 $encoding_hdr = 'Content-Encoding: deflate';
\r
1480 $encoding_hdr = '';
\r
1483 if($this->debug > 1)
\r
1485 print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
\r
1486 // let the client see this now in case http times out...
\r
1490 if(!$keepalive || !$this->xmlrpc_curl_handle)
\r
1492 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
\r
1495 $this->xmlrpc_curl_handle = $curl;
\r
1500 $curl = $this->xmlrpc_curl_handle;
\r
1503 // results into variable
\r
1504 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
\r
1508 curl_setopt($curl, CURLOPT_VERBOSE, 1);
\r
1510 curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
\r
1511 // required for XMLRPC: post the data
\r
1512 curl_setopt($curl, CURLOPT_POST, 1);
\r
1514 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
\r
1516 // return the header too
\r
1517 curl_setopt($curl, CURLOPT_HEADER, 1);
\r
1519 // NB: if we set an empty string, CURL will add http header indicating
\r
1520 // ALL methods it is supporting. This is possibly a better option than
\r
1521 // letting the user tell what curl can / cannot do...
\r
1522 if(is_array($this->accepted_compression) && count($this->accepted_compression))
\r
1524 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
\r
1525 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
\r
1526 if (count($this->accepted_compression) == 1)
\r
1528 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
\r
1531 curl_setopt($curl, CURLOPT_ENCODING, '');
\r
1534 $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
\r
1535 // if no keepalive is wanted, let the server know it in advance
\r
1538 $headers[] = 'Connection: close';
\r
1540 // request compression header
\r
1543 $headers[] = $encoding_hdr;
\r
1546 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
\r
1547 // timeout is borked
\r
1550 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
\r
1553 if($username && $password)
\r
1555 curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
\r
1556 if (defined('CURLOPT_HTTPAUTH'))
\r
1558 curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
\r
1560 else if ($authtype != 1)
\r
1562 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install');
\r
1566 if($method == 'https')
\r
1571 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
\r
1573 // set cert password
\r
1576 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
\r
1578 // whether to verify remote host's cert
\r
1579 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
\r
1580 // set ca certificates file/dir
\r
1583 curl_setopt($curl, CURLOPT_CAINFO, $cacert);
\r
1587 curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
\r
1589 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
\r
1592 curl_setopt($curl, CURLOPT_SSLKEY, $key);
\r
1594 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
\r
1597 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
\r
1599 // 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
\r
1600 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
\r
1606 if($proxyport == 0)
\r
1608 $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
\r
1610 curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);
\r
1611 //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
\r
1612 if($proxyusername)
\r
1614 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
\r
1615 if (defined('CURLOPT_PROXYAUTH'))
\r
1617 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
\r
1619 else if ($proxyauthtype != 1)
\r
1621 error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install');
\r
1626 // NB: should we build cookie http headers by hand rather than let CURL do it?
\r
1627 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
\r
1628 // set to client obj the the user...
\r
1629 if (count($this->cookies))
\r
1631 $cookieheader = '';
\r
1632 foreach ($this->cookies as $name => $cookie)
\r
1634 $cookieheader .= $name . '=' . $cookie['value'] . '; ';
\r
1636 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
\r
1639 foreach ($this->extracurlopts as $opt => $val)
\r
1641 curl_setopt($curl, $opt, $val);
\r
1644 $result = curl_exec($curl);
\r
1646 if ($this->debug > 1)
\r
1648 print "<PRE>\n---CURL INFO---\n";
\r
1649 foreach(curl_getinfo($curl) as $name => $val)
\r
1651 if (is_array($val))
\r
1653 $val = implode("\n", $val);
\r
1655 print $name . ': ' . htmlentities($val) . "\n";
\r
1658 print "---END---\n</PRE>";
\r
1661 if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?
\r
1663 $this->errstr='no response';
\r
1664 $resp=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));
\r
1665 curl_close($curl);
\r
1668 $this->xmlrpc_curl_handle = null;
\r
1675 curl_close($curl);
\r
1677 $resp =& $msg->parseResponse($result, true, $this->return_type);
\r
1678 // if we got back a 302, we can not reuse the curl handle for later calls
\r
1679 if($resp->faultCode() == $GLOBALS['xmlrpcerr']['http_error'] && $keepalive)
\r
1681 curl_close($curl);
\r
1682 $this->xmlrpc_curl_handle = null;
\r
1689 * Send an array of request messages and return an array of responses.
\r
1690 * Unless $this->no_multicall has been set to true, it will try first
\r
1691 * to use one single xmlrpc call to server method system.multicall, and
\r
1692 * revert to sending many successive calls in case of failure.
\r
1693 * This failure is also stored in $this->no_multicall for subsequent calls.
\r
1694 * Unfortunately, there is no server error code universally used to denote
\r
1695 * the fact that multicall is unsupported, so there is no way to reliably
\r
1696 * distinguish between that and a temporary failure.
\r
1697 * If you are sure that server supports multicall and do not want to
\r
1698 * fallback to using many single calls, set the fourth parameter to FALSE.
\r
1700 * NB: trying to shoehorn extra functionality into existing syntax has resulted
\r
1701 * in pretty much convoluted code...
\r
1703 * @param array $msgs an array of xmlrpcmsg objects
\r
1704 * @param integer $timeout connection timeout (in seconds)
\r
1705 * @param string $method the http protocol variant to be used
\r
1706 * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted
\r
1710 function multicall($msgs, $timeout=0, $method='', $fallback=true)
\r
1712 if ($method == '')
\r
1714 $method = $this->method;
\r
1716 if(!$this->no_multicall)
\r
1718 $results = $this->_try_multicall($msgs, $timeout, $method);
\r
1719 if(is_array($results))
\r
1721 // System.multicall succeeded
\r
1726 // either system.multicall is unsupported by server,
\r
1727 // or call failed for some other reason.
\r
1730 // Don't try it next time...
\r
1731 $this->no_multicall = true;
\r
1735 if (is_a($results, 'xmlrpcresp'))
\r
1737 $result = $results;
\r
1741 $result = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);
\r
1748 // override fallback, in case careless user tries to do two
\r
1749 // opposite things at the same time
\r
1753 $results = array();
\r
1756 // system.multicall is (probably) unsupported by server:
\r
1757 // emulate multicall via multiple requests
\r
1758 foreach($msgs as $msg)
\r
1760 $results[] =& $this->send($msg, $timeout, $method);
\r
1765 // user does NOT want to fallback on many single calls:
\r
1766 // since we should always return an array of responses,
\r
1767 // return an array with the same error repeated n times
\r
1768 foreach($msgs as $msg)
\r
1770 $results[] = $result;
\r
1777 * Attempt to boxcar $msgs via system.multicall.
\r
1778 * Returns either an array of xmlrpcreponses, an xmlrpc error response
\r
1779 * or false (when received response does not respect valid multicall syntax)
\r
1782 function _try_multicall($msgs, $timeout, $method)
\r
1784 // Construct multicall message
\r
1786 foreach($msgs as $msg)
\r
1788 $call['methodName'] = new xmlrpcval($msg->method(),'string');
\r
1789 $numParams = $msg->getNumParams();
\r
1790 $params = array();
\r
1791 for($i = 0; $i < $numParams; $i++)
\r
1793 $params[$i] = $msg->getParam($i);
\r
1795 $call['params'] = new xmlrpcval($params, 'array');
\r
1796 $calls[] = new xmlrpcval($call, 'struct');
\r
1798 $multicall = new xmlrpcmsg('system.multicall');
\r
1799 $multicall->addParam(new xmlrpcval($calls, 'array'));
\r
1801 // Attempt RPC call
\r
1802 $result =& $this->send($multicall, $timeout, $method);
\r
1804 if($result->faultCode() != 0)
\r
1806 // call to system.multicall failed
\r
1810 // Unpack responses.
\r
1811 $rets = $result->value();
\r
1813 if ($this->return_type == 'xml')
\r
1817 else if ($this->return_type == 'phpvals')
\r
1819 ///@todo test this code branch...
\r
1820 $rets = $result->value();
\r
1821 if(!is_array($rets))
\r
1823 return false; // bad return type from system.multicall
\r
1825 $numRets = count($rets);
\r
1826 if($numRets != count($msgs))
\r
1828 return false; // wrong number of return values.
\r
1831 $response = array();
\r
1832 for($i = 0; $i < $numRets; $i++)
\r
1835 if (!is_array($val)) {
\r
1838 switch(count($val))
\r
1841 if(!isset($val[0]))
\r
1843 return false; // Bad value
\r
1845 // Normal return value
\r
1846 $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');
\r
1849 /// @todo remove usage of @: it is apparently quite slow
\r
1850 $code = @$val['faultCode'];
\r
1851 if(!is_int($code))
\r
1855 $str = @$val['faultString'];
\r
1856 if(!is_string($str))
\r
1860 $response[$i] = new xmlrpcresp(0, $code, $str);
\r
1868 else // return type == 'xmlrpcvals'
\r
1870 $rets = $result->value();
\r
1871 if($rets->kindOf() != 'array')
\r
1873 return false; // bad return type from system.multicall
\r
1875 $numRets = $rets->arraysize();
\r
1876 if($numRets != count($msgs))
\r
1878 return false; // wrong number of return values.
\r
1881 $response = array();
\r
1882 for($i = 0; $i < $numRets; $i++)
\r
1884 $val = $rets->arraymem($i);
\r
1885 switch($val->kindOf())
\r
1888 if($val->arraysize() != 1)
\r
1890 return false; // Bad value
\r
1892 // Normal return value
\r
1893 $response[$i] = new xmlrpcresp($val->arraymem(0));
\r
1896 $code = $val->structmem('faultCode');
\r
1897 if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
\r
1901 $str = $val->structmem('faultString');
\r
1902 if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
\r
1906 $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
\r
1915 } // end class xmlrpc_client
\r
1924 var $hdrs = array();
\r
1925 var $_cookies = array();
\r
1926 var $content_type = 'text/xml';
\r
1927 var $raw_data = '';
\r
1930 * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
\r
1931 * @param integer $fcode set it to anything but 0 to create an error response
\r
1932 * @param string $fstr the error string, in case of an error response
\r
1933 * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
\r
1935 * @todo add check that $val / $fcode / $fstr is of correct type???
\r
1936 * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
\r
1937 * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
\r
1939 function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')
\r
1944 $this->errno = $fcode;
\r
1945 $this->errstr = $fstr;
\r
1946 //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
\r
1950 // successful response
\r
1951 $this->val = $val;
\r
1952 if ($valtyp == '')
\r
1954 // user did not declare type of response value: try to guess it
\r
1955 if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))
\r
1957 $this->valtyp = 'xmlrpcvals';
\r
1959 else if (is_string($this->val))
\r
1961 $this->valtyp = 'xml';
\r
1966 $this->valtyp = 'phpvals';
\r
1971 // user declares type of resp value: believe him
\r
1972 $this->valtyp = $valtyp;
\r
1978 * Returns the error code of the response.
\r
1979 * @return integer the error code of this response (0 for not-error responses)
\r
1982 function faultCode()
\r
1984 return $this->errno;
\r
1988 * Returns the error code of the response.
\r
1989 * @return string the error string of this response ('' for not-error responses)
\r
1992 function faultString()
\r
1994 return $this->errstr;
\r
1998 * Returns the value received by the server.
\r
1999 * @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
\r
2004 return $this->val;
\r
2008 * Returns an array with the cookies received from the server.
\r
2009 * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
\r
2010 * with attributes being e.g. 'expires', 'path', domain'.
\r
2011 * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
\r
2012 * are still present in the array. It is up to the user-defined code to decide
\r
2013 * how to use the received cookies, and whether they have to be sent back with the next
\r
2014 * request to the server (using xmlrpc_client::setCookie) or not
\r
2015 * @return array array of cookies received from the server
\r
2018 function cookies()
\r
2020 return $this->_cookies;
\r
2024 * Returns xml representation of the response. XML prologue not included
\r
2025 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
\r
2026 * @return string the xml representation of the response
\r
2029 function serialize($charset_encoding='')
\r
2031 if ($charset_encoding != '')
\r
2032 $this->content_type = 'text/xml; charset=' . $charset_encoding;
\r
2034 $this->content_type = 'text/xml';
\r
2035 if ($GLOBALS['xmlrpc_null_apache_encoding'])
\r
2037 $result = "<methodResponse xmlns:ex=\"".$GLOBALS['xmlrpc_null_apache_encoding_ns']."\">\n";
\r
2041 $result = "<methodResponse>\n";
\r
2045 // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
\r
2046 // by xml-encoding non ascii chars
\r
2047 $result .= "<fault>\n" .
\r
2048 "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
\r
2049 "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
\r
2050 xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
\r
2051 "</struct>\n</value>\n</fault>";
\r
2055 if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
\r
2057 if (is_string($this->val) && $this->valtyp == 'xml')
\r
2059 $result .= "<params>\n<param>\n" .
\r
2061 "</param>\n</params>";
\r
2065 /// @todo try to build something serializable?
\r
2066 die('cannot serialize xmlrpcresp objects whose content is native php values');
\r
2071 $result .= "<params>\n<param>\n" .
\r
2072 $this->val->serialize($charset_encoding) .
\r
2073 "</param>\n</params>";
\r
2076 $result .= "\n</methodResponse>";
\r
2077 $this->payload = $result;
\r
2086 var $params=array();
\r
2088 var $content_type = 'text/xml';
\r
2091 * @param string $meth the name of the method to invoke
\r
2092 * @param array $pars array of parameters to be passed to the method (xmlrpcval objects)
\r
2094 function xmlrpcmsg($meth, $pars=0)
\r
2096 $this->methodname=$meth;
\r
2097 if(is_array($pars) && count($pars)>0)
\r
2099 for($i=0; $i<count($pars); $i++)
\r
2101 $this->addParam($pars[$i]);
\r
2109 function xml_header($charset_encoding='')
\r
2111 if ($charset_encoding != '')
\r
2113 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
\r
2117 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
\r
2124 function xml_footer()
\r
2126 return '</methodCall>';
\r
2140 function createPayload($charset_encoding='')
\r
2142 if ($charset_encoding != '')
\r
2143 $this->content_type = 'text/xml; charset=' . $charset_encoding;
\r
2145 $this->content_type = 'text/xml';
\r
2146 $this->payload=$this->xml_header($charset_encoding);
\r
2147 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
\r
2148 $this->payload.="<params>\n";
\r
2149 for($i=0; $i<count($this->params); $i++)
\r
2151 $p=$this->params[$i];
\r
2152 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
\r
2155 $this->payload.="</params>\n";
\r
2156 $this->payload.=$this->xml_footer();
\r
2160 * Gets/sets the xmlrpc method to be invoked
\r
2161 * @param string $meth the method to be set (leave empty not to set it)
\r
2162 * @return string the method that will be invoked
\r
2165 function method($meth='')
\r
2169 $this->methodname=$meth;
\r
2171 return $this->methodname;
\r
2175 * Returns xml representation of the message. XML prologue included
\r
2176 * @param string $charset_encoding
\r
2177 * @return string the xml representation of the message, xml prologue included
\r
2180 function serialize($charset_encoding='')
\r
2182 $this->createPayload($charset_encoding);
\r
2183 return $this->payload;
\r
2187 * Add a parameter to the list of parameters to be used upon method invocation
\r
2188 * @param xmlrpcval $par
\r
2189 * @return boolean false on failure
\r
2192 function addParam($par)
\r
2194 // add check: do not add to self params which are not xmlrpcvals
\r
2195 if(is_object($par) && is_a($par, 'xmlrpcval'))
\r
2197 $this->params[]=$par;
\r
2207 * Returns the nth parameter in the message. The index zero-based.
\r
2208 * @param integer $i the index of the parameter to fetch (zero based)
\r
2209 * @return xmlrpcval the i-th parameter
\r
2212 function getParam($i) { return $this->params[$i]; }
\r
2215 * Returns the number of parameters in the messge.
\r
2216 * @return integer the number of parameters currently set
\r
2219 function getNumParams() { return count($this->params); }
\r
2222 * Given an open file handle, read all data available and parse it as axmlrpc response.
\r
2223 * NB: the file handle is not closed by this function.
\r
2224 * NNB: might have trouble in rare cases to work on network streams, as we
\r
2225 * check for a read of 0 bytes instead of feof($fp).
\r
2226 * But since checking for feof(null) returns false, we would risk an
\r
2227 * infinite loop in that case, because we cannot trust the caller
\r
2228 * to give us a valid pointer to an open file...
\r
2230 * @param resource $fp stream pointer
\r
2231 * @return xmlrpcresp
\r
2232 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
\r
2234 function &parseResponseFile($fp)
\r
2237 while($data=fread($fp, 32768))
\r
2242 $r =& $this->parseResponse($ipd);
\r
2247 * Parses HTTP headers and separates them from data.
\r
2250 function &parseResponseHeaders(&$data, $headers_processed=false)
\r
2252 // Support "web-proxy-tunelling" connections for https through proxies
\r
2253 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
\r
2255 // Look for CR/LF or simple LF as line separator,
\r
2256 // (even though it is not valid http)
\r
2257 $pos = strpos($data,"\r\n\r\n");
\r
2258 if($pos || is_int($pos))
\r
2264 $pos = strpos($data,"\n\n");
\r
2265 if($pos || is_int($pos))
\r
2271 // No separation between response headers and body: fault?
\r
2277 // this filters out all http headers from proxy.
\r
2278 // maybe we could take them into account, too?
\r
2279 $data = substr($data, $bd);
\r
2283 error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
\r
2284 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
\r
2289 // Strip HTTP 1.1 100 Continue header if present
\r
2290 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
\r
2292 $pos = strpos($data, 'HTTP', 12);
\r
2293 // server sent a Continue header without any (valid) content following...
\r
2294 // give the client a chance to know it
\r
2295 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
\r
2299 $data = substr($data, $pos);
\r
2301 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
\r
2303 $errstr= substr($data, 0, strpos($data, "\n")-1);
\r
2304 error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
\r
2305 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
\r
2309 $GLOBALS['_xh']['headers'] = array();
\r
2310 $GLOBALS['_xh']['cookies'] = array();
\r
2312 // be tolerant to usage of \n instead of \r\n to separate headers and data
\r
2313 // (even though it is not valid http)
\r
2314 $pos = strpos($data,"\r\n\r\n");
\r
2315 if($pos || is_int($pos))
\r
2321 $pos = strpos($data,"\n\n");
\r
2322 if($pos || is_int($pos))
\r
2328 // No separation between response headers and body: fault?
\r
2329 // we could take some action here instead of going on...
\r
2333 // be tolerant to line endings, and extra empty lines
\r
2334 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
\r
2335 while(list(,$line) = @each($ar))
\r
2337 // take care of multi-line headers and cookies
\r
2338 $arr = explode(':',$line,2);
\r
2339 if(count($arr) > 1)
\r
2341 $header_name = strtolower(trim($arr[0]));
\r
2342 /// @todo some other headers (the ones that allow a CSV list of values)
\r
2343 /// do allow many values to be passed using multiple header lines.
\r
2344 /// We should add content to $GLOBALS['_xh']['headers'][$header_name]
\r
2345 /// instead of replacing it for those...
\r
2346 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
\r
2348 if ($header_name == 'set-cookie2')
\r
2350 // version 2 cookies:
\r
2351 // there could be many cookies on one line, comma separated
\r
2352 $cookies = explode(',', $arr[1]);
\r
2356 $cookies = array($arr[1]);
\r
2358 foreach ($cookies as $cookie)
\r
2360 // glue together all received cookies, using a comma to separate them
\r
2361 // (same as php does with getallheaders())
\r
2362 if (isset($GLOBALS['_xh']['headers'][$header_name]))
\r
2363 $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
\r
2365 $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
\r
2366 // parse cookie attributes, in case user wants to correctly honour them
\r
2367 // feature creep: only allow rfc-compliant cookie attributes?
\r
2368 // @todo support for server sending multiple time cookie with same name, but using different PATHs
\r
2369 $cookie = explode(';', $cookie);
\r
2370 foreach ($cookie as $pos => $val)
\r
2372 $val = explode('=', $val, 2);
\r
2373 $tag = trim($val[0]);
\r
2374 $val = trim(@$val[1]);
\r
2375 /// @todo with version 1 cookies, we should strip leading and trailing " chars
\r
2378 $cookiename = $tag;
\r
2379 $GLOBALS['_xh']['cookies'][$tag] = array();
\r
2380 $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
\r
2384 if ($tag != 'value')
\r
2386 $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
\r
2394 $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
\r
2397 elseif(isset($header_name))
\r
2399 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
\r
2400 $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
\r
2404 $data = substr($data, $bd);
\r
2406 if($this->debug && count($GLOBALS['_xh']['headers']))
\r
2409 foreach($GLOBALS['_xh']['headers'] as $header => $value)
\r
2411 print htmlentities("HEADER: $header: $value\n");
\r
2413 foreach($GLOBALS['_xh']['cookies'] as $header => $value)
\r
2415 print htmlentities("COOKIE: $header={$value['value']}\n");
\r
2420 // if CURL was used for the call, http headers have been processed,
\r
2421 // and dechunking + reinflating have been carried out
\r
2422 if(!$headers_processed)
\r
2424 // Decode chunked encoding sent by http 1.1 servers
\r
2425 if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
\r
2427 if(!$data = decode_chunked($data))
\r
2429 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
\r
2430 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
\r
2435 // Decode gzip-compressed stuff
\r
2436 // code shamelessly inspired from nusoap library by Dietrich Ayala
\r
2437 if(isset($GLOBALS['_xh']['headers']['content-encoding']))
\r
2439 $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
\r
2440 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
\r
2442 // if decoding works, use it. else assume data wasn't gzencoded
\r
2443 if(function_exists('gzinflate'))
\r
2445 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
\r
2447 $data = $degzdata;
\r
2449 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
\r
2451 elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
\r
2453 $data = $degzdata;
\r
2455 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
\r
2459 error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
\r
2460 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
\r
2466 error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
\r
2467 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
\r
2472 } // end of 'if needed, de-chunk, re-inflate response'
\r
2474 // real stupid hack to avoid PHP complaining about returning NULL by ref
\r
2481 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
\r
2482 * @param string $data the xmlrpc response, eventually including http headers
\r
2483 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
\r
2484 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
\r
2485 * @return xmlrpcresp
\r
2488 function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
\r
2492 //by maHo, replaced htmlspecialchars with htmlentities
\r
2493 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
\r
2498 error_log('XML-RPC: '.__METHOD__.': no response received from server.');
\r
2499 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);
\r
2503 $GLOBALS['_xh']=array();
\r
2505 $raw_data = $data;
\r
2506 // parse the HTTP headers of the response, if present, and separate them from data
\r
2507 if(substr($data, 0, 4) == 'HTTP')
\r
2509 $r =& $this->parseResponseHeaders($data, $headers_processed);
\r
2512 // failed processing of HTTP response headers
\r
2513 // save into response obj the full payload received, for debugging
\r
2514 $r->raw_data = $data;
\r
2520 $GLOBALS['_xh']['headers'] = array();
\r
2521 $GLOBALS['_xh']['cookies'] = array();
\r
2526 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
\r
2529 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
\r
2530 $end = strpos($data, '-->', $start);
\r
2531 $comments = substr($data, $start, $end-$start);
\r
2532 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
\r
2536 // be tolerant of extra whitespace in response body
\r
2537 $data = trim($data);
\r
2539 /// @todo return an error msg if $data=='' ?
\r
2541 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
\r
2542 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
\r
2543 $pos = strrpos($data, '</methodResponse>');
\r
2544 if($pos !== false)
\r
2546 $data = substr($data, 0, $pos+17);
\r
2549 // if user wants back raw xml, give it to him
\r
2550 if ($return_type == 'xml')
\r
2552 $r = new xmlrpcresp($data, 0, '', 'xml');
\r
2553 $r->hdrs = $GLOBALS['_xh']['headers'];
\r
2554 $r->_cookies = $GLOBALS['_xh']['cookies'];
\r
2555 $r->raw_data = $raw_data;
\r
2559 // try to 'guestimate' the character encoding of the received response
\r
2560 $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);
\r
2562 $GLOBALS['_xh']['ac']='';
\r
2563 //$GLOBALS['_xh']['qt']=''; //unused...
\r
2564 $GLOBALS['_xh']['stack'] = array();
\r
2565 $GLOBALS['_xh']['valuestack'] = array();
\r
2566 $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
\r
2567 $GLOBALS['_xh']['isf_reason']='';
\r
2568 $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'
\r
2570 // if response charset encoding is not known / supported, try to use
\r
2571 // the default encoding and parse the xml anyway, but log a warning...
\r
2572 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
\r
2573 // the following code might be better for mb_string enabled installs, but
\r
2574 // makes the lib about 200% slower...
\r
2575 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
\r
2577 error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);
\r
2578 $resp_encoding = $GLOBALS['xmlrpc_defencoding'];
\r
2580 $parser = xml_parser_create($resp_encoding);
\r
2581 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
\r
2582 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
\r
2583 // the xml parser to give us back data in the expected charset.
\r
2584 // What if internal encoding is not in one of the 3 allowed?
\r
2585 // we use the broadest one, ie. utf8
\r
2586 // This allows to send data which is native in various charset,
\r
2587 // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
\r
2588 if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
\r
2590 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
\r
2594 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
\r
2597 if ($return_type == 'phpvals')
\r
2599 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
\r
2603 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
\r
2606 xml_set_character_data_handler($parser, 'xmlrpc_cd');
\r
2607 xml_set_default_handler($parser, 'xmlrpc_dh');
\r
2609 // first error check: xml not well formed
\r
2610 if(!xml_parse($parser, $data, count($data)))
\r
2612 // thanks to Peter Kocks <peter.kocks@baygate.com>
\r
2613 if((xml_get_current_line_number($parser)) == 1)
\r
2615 $errstr = 'XML error at line 1, check URL';
\r
2619 $errstr = sprintf('XML error: %s at line %d, column %d',
\r
2620 xml_error_string(xml_get_error_code($parser)),
\r
2621 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
\r
2623 error_log($errstr);
\r
2624 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');
\r
2625 xml_parser_free($parser);
\r
2630 $r->hdrs = $GLOBALS['_xh']['headers'];
\r
2631 $r->_cookies = $GLOBALS['_xh']['cookies'];
\r
2632 $r->raw_data = $raw_data;
\r
2635 xml_parser_free($parser);
\r
2636 // second error check: xml well formed but not xml-rpc compliant
\r
2637 if ($GLOBALS['_xh']['isf'] > 1)
\r
2641 /// @todo echo something for user?
\r
2644 $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
\r
2645 $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);
\r
2647 // third error check: parsing of the response has somehow gone boink.
\r
2648 // NB: shall we omit this check, since we trust the parsing code?
\r
2649 elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))
\r
2651 // something odd has happened
\r
2652 // and it's time to generate a client side error
\r
2653 // indicating something odd went on
\r
2654 $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
\r
2655 $GLOBALS['xmlrpcstr']['invalid_return']);
\r
2661 print "<PRE>---PARSED---\n";
\r
2662 // somehow htmlentities chokes on var_export, and some full html string...
\r
2663 //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
\r
2664 print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));
\r
2665 print "\n---END---</PRE>";
\r
2668 // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.
\r
2669 $v =& $GLOBALS['_xh']['value'];
\r
2671 if($GLOBALS['_xh']['isf'])
\r
2673 /// @todo we should test here if server sent an int and a string,
\r
2674 /// and/or coerce them into such...
\r
2675 if ($return_type == 'xmlrpcvals')
\r
2677 $errno_v = $v->structmem('faultCode');
\r
2678 $errstr_v = $v->structmem('faultString');
\r
2679 $errno = $errno_v->scalarval();
\r
2680 $errstr = $errstr_v->scalarval();
\r
2684 $errno = $v['faultCode'];
\r
2685 $errstr = $v['faultString'];
\r
2690 // FAULT returned, errno needs to reflect that
\r
2694 $r = new xmlrpcresp(0, $errno, $errstr);
\r
2698 $r=new xmlrpcresp($v, 0, '', $return_type);
\r
2702 $r->hdrs = $GLOBALS['_xh']['headers'];
\r
2703 $r->_cookies = $GLOBALS['_xh']['cookies'];
\r
2704 $r->raw_data = $raw_data;
\r
2713 var $_php_class=null;
\r
2716 * @param mixed $val
\r
2717 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
\r
2719 function xmlrpcval($val=-1, $type='')
\r
2721 /// @todo: optimization creep - do not call addXX, do it all inline.
\r
2722 /// downside: booleans will not be coerced anymore
\r
2723 if($val!==-1 || $type!='')
\r
2725 // optimization creep: inlined all work done by constructor
\r
2730 $this->me['string']=$val;
\r
2737 case 'dateTime.iso8601':
\r
2741 $this->me[$type]=$val;
\r
2745 $this->me['array']=$val;
\r
2749 $this->me['struct']=$val;
\r
2752 error_log("XML-RPC: ".__METHOD__.": not a known type ($type)");
\r
2758 if($GLOBALS['xmlrpcTypes'][$type]==1)
\r
2760 $this->addScalar($val,$type);
\r
2762 elseif($GLOBALS['xmlrpcTypes'][$type]==2)
\r
2764 $this->addArray($val);
\r
2766 elseif($GLOBALS['xmlrpcTypes'][$type]==3)
\r
2768 $this->addStruct($val);
\r
2774 * Add a single php value to an (unitialized) xmlrpcval
\r
2775 * @param mixed $val
\r
2776 * @param string $type
\r
2777 * @return int 1 or 0 on failure
\r
2779 function addScalar($val, $type='string')
\r
2781 $typeof=@$GLOBALS['xmlrpcTypes'][$type];
\r
2784 error_log("XML-RPC: ".__METHOD__.": not a scalar type ($type)");
\r
2788 // coerce booleans into correct values
\r
2789 // NB: we should either do it for datetimes, integers and doubles, too,
\r
2790 // or just plain remove this check, implemented on booleans only...
\r
2791 if($type==$GLOBALS['xmlrpcBoolean'])
\r
2793 if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))
\r
2803 switch($this->mytype)
\r
2806 error_log('XML-RPC: '.__METHOD__.': scalar xmlrpcval can have only one value');
\r
2809 error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval');
\r
2812 // we're adding a scalar value to an array here
\r
2813 //$ar=$this->me['array'];
\r
2814 //$ar[]=new xmlrpcval($val, $type);
\r
2815 //$this->me['array']=$ar;
\r
2816 // Faster (?) avoid all the costly array-copy-by-val done here...
\r
2817 $this->me['array'][]=new xmlrpcval($val, $type);
\r
2820 // a scalar, so set the value and remember we're scalar
\r
2821 $this->me[$type]=$val;
\r
2822 $this->mytype=$typeof;
\r
2828 * Add an array of xmlrpcval objects to an xmlrpcval
\r
2829 * @param array $vals
\r
2830 * @return int 1 or 0 on failure
\r
2833 * @todo add some checking for $vals to be an array of xmlrpcvals?
\r
2835 function addArray($vals)
\r
2837 if($this->mytype==0)
\r
2839 $this->mytype=$GLOBALS['xmlrpcTypes']['array'];
\r
2840 $this->me['array']=$vals;
\r
2843 elseif($this->mytype==2)
\r
2845 // we're adding to an array here
\r
2846 $this->me['array'] = array_merge($this->me['array'], $vals);
\r
2851 error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');
\r
2857 * Add an array of named xmlrpcval objects to an xmlrpcval
\r
2858 * @param array $vals
\r
2859 * @return int 1 or 0 on failure
\r
2862 * @todo add some checking for $vals to be an array?
\r
2864 function addStruct($vals)
\r
2866 if($this->mytype==0)
\r
2868 $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];
\r
2869 $this->me['struct']=$vals;
\r
2872 elseif($this->mytype==3)
\r
2874 // we're adding to a struct here
\r
2875 $this->me['struct'] = array_merge($this->me['struct'], $vals);
\r
2880 error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');
\r
2885 // poor man's version of print_r ???
\r
2887 function dump($ar)
\r
2889 foreach($ar as $key => $val)
\r
2891 echo "$key => $val<br />";
\r
2892 if($key == 'array')
\r
2894 while(list($key2, $val2) = each($val))
\r
2896 echo "-- $key2 => $val2<br />";
\r
2903 * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
\r
2909 switch($this->mytype)
\r
2928 function serializedata($typ, $val, $charset_encoding='')
\r
2931 switch(@$GLOBALS['xmlrpcTypes'][$typ])
\r
2936 case $GLOBALS['xmlrpcBase64']:
\r
2937 $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";
\r
2939 case $GLOBALS['xmlrpcBoolean']:
\r
2940 $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
\r
2942 case $GLOBALS['xmlrpcString']:
\r
2943 // G. Giunta 2005/2/13: do NOT use htmlentities, since
\r
2944 // it will produce named html entities, which are invalid xml
\r
2945 $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";
\r
2947 case $GLOBALS['xmlrpcInt']:
\r
2948 case $GLOBALS['xmlrpcI4']:
\r
2949 $rs.="<${typ}>".(int)$val."</${typ}>";
\r
2951 case $GLOBALS['xmlrpcDouble']:
\r
2952 // avoid using standard conversion of float to string because it is locale-dependent,
\r
2953 // and also because the xmlrpc spec forbids exponential notation.
\r
2954 // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
\r
2955 // The code below tries its best at keeping max precision while avoiding exp notation,
\r
2956 // but there is of course no limit in the number of decimal places to be used...
\r
2957 $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";
\r
2959 case $GLOBALS['xmlrpcDateTime']:
\r
2960 if (is_string($val))
\r
2962 $rs.="<${typ}>${val}</${typ}>";
\r
2964 else if(is_a($val, 'DateTime'))
\r
2966 $rs.="<${typ}>".$val->format('Ymd\TH:i:s')."</${typ}>";
\r
2968 else if(is_int($val))
\r
2970 $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val)."</${typ}>";
\r
2974 // not really a good idea here: but what shall we output anyway? left for backward compat...
\r
2975 $rs.="<${typ}>${val}</${typ}>";
\r
2978 case $GLOBALS['xmlrpcNull']:
\r
2979 if ($GLOBALS['xmlrpc_null_apache_encoding'])
\r
2989 // no standard type value should arrive here, but provide a possibility
\r
2990 // for xmlrpcvals of unknown type...
\r
2991 $rs.="<${typ}>${val}</${typ}>";
\r
2996 if ($this->_php_class)
\r
2998 $rs.='<struct php_class="' . $this->_php_class . "\">\n";
\r
3002 $rs.="<struct>\n";
\r
3004 foreach($val as $key2 => $val2)
\r
3006 $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";
\r
3007 //$rs.=$this->serializeval($val2);
\r
3008 $rs.=$val2->serialize($charset_encoding);
\r
3009 $rs.="</member>\n";
\r
3015 $rs.="<array>\n<data>\n";
\r
3016 for($i=0; $i<count($val); $i++)
\r
3018 //$rs.=$this->serializeval($val[$i]);
\r
3019 $rs.=$val[$i]->serialize($charset_encoding);
\r
3021 $rs.="</data>\n</array>";
\r
3030 * Returns xml representation of the value. XML prologue not included
\r
3031 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
\r
3035 function serialize($charset_encoding='')
\r
3037 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
\r
3038 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
\r
3041 list($typ, $val) = each($this->me);
\r
3042 return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";
\r
3047 function serializeval($o)
\r
3049 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
\r
3050 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
\r
3054 list($typ, $val) = each($ar);
\r
3055 return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
\r
3060 * Checks whether a struct member with a given name is present.
\r
3061 * Works only on xmlrpcvals of type struct.
\r
3062 * @param string $m the name of the struct member to be looked up
\r
3066 function structmemexists($m)
\r
3068 return array_key_exists($m, $this->me['struct']);
\r
3072 * Returns the value of a given struct member (an xmlrpcval object in itself).
\r
3073 * Will raise a php warning if struct member of given name does not exist
\r
3074 * @param string $m the name of the struct member to be looked up
\r
3075 * @return xmlrpcval
\r
3078 function structmem($m)
\r
3080 return $this->me['struct'][$m];
\r
3084 * Reset internal pointer for xmlrpcvals of type struct.
\r
3087 function structreset()
\r
3089 reset($this->me['struct']);
\r
3093 * Return next member element for xmlrpcvals of type struct.
\r
3094 * @return xmlrpcval
\r
3097 function structeach()
\r
3099 return each($this->me['struct']);
\r
3102 // DEPRECATED! this code looks like it is very fragile and has not been fixed
\r
3103 // for a long long time. Shall we remove it for 2.0?
\r
3108 list($a,$b)=each($this->me);
\r
3109 // contributed by I Sofer, 2001-03-24
\r
3110 // add support for nested arrays to scalarval
\r
3111 // i've created a new method here, so as to
\r
3112 // preserve back compatibility
\r
3117 while(list($id,$cont) = @each($b))
\r
3119 $b[$id] = $cont->scalarval();
\r
3123 // add support for structures directly encoding php objects
\r
3126 $t = get_object_vars($b);
\r
3128 while(list($id,$cont) = @each($t))
\r
3130 $t[$id] = $cont->scalarval();
\r
3133 while(list($id,$cont) = @each($t))
\r
3143 * Returns the value of a scalar xmlrpcval
\r
3147 function scalarval()
\r
3150 list(,$b)=each($this->me);
\r
3155 * Returns the type of the xmlrpcval.
\r
3156 * For integers, 'int' is always returned in place of 'i4'
\r
3160 function scalartyp()
\r
3163 list($a,)=each($this->me);
\r
3164 if($a==$GLOBALS['xmlrpcI4'])
\r
3166 $a=$GLOBALS['xmlrpcInt'];
\r
3172 * Returns the m-th member of an xmlrpcval of struct type
\r
3173 * @param integer $m the index of the value to be retrieved (zero based)
\r
3174 * @return xmlrpcval
\r
3177 function arraymem($m)
\r
3179 return $this->me['array'][$m];
\r
3183 * Returns the number of members in an xmlrpcval of array type
\r
3187 function arraysize()
\r
3189 return count($this->me['array']);
\r
3193 * Returns the number of members in an xmlrpcval of struct type
\r
3197 function structsize()
\r
3199 return count($this->me['struct']);
\r
3207 * Given a timestamp, return the corresponding ISO8601 encoded string.
\r
3209 * Really, timezones ought to be supported
\r
3210 * but the XML-RPC spec says:
\r
3212 * "Don't assume a timezone. It should be specified by the server in its
\r
3213 * documentation what assumptions it makes about timezones."
\r
3215 * These routines always assume localtime unless
\r
3216 * $utc is set to 1, in which case UTC is assumed
\r
3217 * and an adjustment for locale is made when encoding
\r
3219 * @param int $timet (timestamp)
\r
3220 * @param int $utc (0 or 1)
\r
3223 function iso8601_encode($timet, $utc=0)
\r
3227 $t=strftime("%Y%m%dT%H:%M:%S", $timet);
\r
3231 if(function_exists('gmstrftime'))
\r
3233 // gmstrftime doesn't exist in some versions
\r
3235 $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);
\r
3239 $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));
\r
3246 * Given an ISO8601 date string, return a timet in the localtime, or UTC
\r
3247 * @param string $idate
\r
3248 * @param int $utc either 0 or 1
\r
3249 * @return int (datetime)
\r
3251 function iso8601_decode($idate, $utc=0)
\r
3254 if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))
\r
3258 $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
\r
3262 $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
\r
3269 * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.
\r
3271 * Works with xmlrpc message objects as input, too.
\r
3273 * Given proper options parameter, can rebuild generic php object instances
\r
3274 * (provided those have been encoded to xmlrpc format using a corresponding
\r
3275 * option in php_xmlrpc_encode())
\r
3276 * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
\r
3277 * This means that the remote communication end can decide which php code will
\r
3278 * get executed on your server, leaving the door possibly open to 'php-injection'
\r
3279 * style of attacks (provided you have some classes defined on your server that
\r
3280 * might wreak havoc if instances are built outside an appropriate context).
\r
3281 * Make sure you trust the remote server/client before eanbling this!
\r
3283 * @author Dan Libby (dan@libby.com)
\r
3285 * @param xmlrpcval $xmlrpc_val
\r
3286 * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
\r
3289 function php_xmlrpc_decode($xmlrpc_val, $options=array())
\r
3291 switch($xmlrpc_val->kindOf())
\r
3294 if (in_array('extension_api', $options))
\r
3296 reset($xmlrpc_val->me);
\r
3297 list($typ,$val) = each($xmlrpc_val->me);
\r
3300 case 'dateTime.iso8601':
\r
3301 $xmlrpc_val->scalar = $val;
\r
3302 $xmlrpc_val->xmlrpc_type = 'datetime';
\r
3303 $xmlrpc_val->timestamp = iso8601_decode($val);
\r
3304 return $xmlrpc_val;
\r
3306 $xmlrpc_val->scalar = $val;
\r
3307 $xmlrpc_val->type = $typ;
\r
3308 return $xmlrpc_val;
\r
3310 return $xmlrpc_val->scalarval();
\r
3313 if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601')
\r
3315 // we return a Datetime object instead of a string
\r
3316 // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes,
\r
3317 // we cater to all 3 cases here
\r
3318 $out = $xmlrpc_val->scalarval();
\r
3319 if (is_string($out))
\r
3321 $out = strtotime($out);
\r
3325 $result = new Datetime();
\r
3326 $result->setTimestamp($out);
\r
3329 elseif (is_a($out, 'Datetime'))
\r
3334 return $xmlrpc_val->scalarval();
\r
3336 $size = $xmlrpc_val->arraysize();
\r
3338 for($i = 0; $i < $size; $i++)
\r
3340 $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);
\r
3344 $xmlrpc_val->structreset();
\r
3345 // If user said so, try to rebuild php objects for specific struct vals.
\r
3346 /// @todo should we raise a warning for class not found?
\r
3347 // shall we check for proper subclass of xmlrpcval instead of
\r
3348 // presence of _php_class to detect what we can do?
\r
3349 if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''
\r
3350 && class_exists($xmlrpc_val->_php_class))
\r
3352 $obj = @new $xmlrpc_val->_php_class;
\r
3353 while(list($key,$value)=$xmlrpc_val->structeach())
\r
3355 $obj->$key = php_xmlrpc_decode($value, $options);
\r
3362 while(list($key,$value)=$xmlrpc_val->structeach())
\r
3364 $arr[$key] = php_xmlrpc_decode($value, $options);
\r
3369 $paramcount = $xmlrpc_val->getNumParams();
\r
3371 for($i = 0; $i < $paramcount; $i++)
\r
3373 $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));
\r
3379 // This constant left here only for historical reasons...
\r
3380 // it was used to decide if we have to define xmlrpc_encode on our own, but
\r
3381 // we do not do it anymore
\r
3382 if(function_exists('xmlrpc_decode'))
\r
3384 define('XMLRPC_EPI_ENABLED','1');
\r
3388 define('XMLRPC_EPI_ENABLED','0');
\r
3392 * Takes native php types and encodes them into xmlrpc PHP object format.
\r
3393 * It will not re-encode xmlrpcval objects.
\r
3395 * Feature creep -- could support more types via optional type argument
\r
3396 * (string => datetime support has been added, ??? => base64 not yet)
\r
3398 * If given a proper options parameter, php object instances will be encoded
\r
3399 * into 'special' xmlrpc values, that can later be decoded into php objects
\r
3400 * by calling php_xmlrpc_decode() with a corresponding option
\r
3402 * @author Dan Libby (dan@libby.com)
\r
3404 * @param mixed $php_val the value to be converted into an xmlrpcval object
\r
3405 * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
\r
3406 * @return xmlrpcval
\r
3408 function php_xmlrpc_encode($php_val, $options=array())
\r
3410 $type = gettype($php_val);
\r
3414 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))
\r
3415 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);
\r
3417 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);
\r
3420 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);
\r
3423 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);
\r
3425 // <G_Giunta_2001-02-29>
\r
3426 // Add support for encoding/decoding of booleans, since they are supported in PHP
\r
3428 $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);
\r
3430 // </G_Giunta_2001-02-29>
\r
3432 // PHP arrays can be encoded to either xmlrpc structs or arrays,
\r
3433 // depending on wheter they are hashes or plain 0..n integer indexed
\r
3434 // A shorter one-liner would be
\r
3435 // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
\r
3436 // but execution time skyrockets!
\r
3440 foreach($php_val as $key => $val)
\r
3442 $arr[$key] = php_xmlrpc_encode($val, $options);
\r
3443 if(!$ko && $key !== $j)
\r
3451 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
\r
3455 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);
\r
3459 if(is_a($php_val, 'xmlrpcval'))
\r
3461 $xmlrpc_val = $php_val;
\r
3463 else if(is_a($php_val, 'DateTime'))
\r
3465 $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $GLOBALS['xmlrpcStruct']);
\r
3471 while(list($k,$v) = each($php_val))
\r
3473 $arr[$k] = php_xmlrpc_encode($v, $options);
\r
3475 $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
\r
3476 if (in_array('encode_php_objs', $options))
\r
3478 // let's save original class name into xmlrpcval:
\r
3479 // might be useful later on...
\r
3480 $xmlrpc_val->_php_class = get_class($php_val);
\r
3485 if (in_array('extension_api', $options))
\r
3487 $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcString']);
\r
3489 else if (in_array('null_extension', $options))
\r
3491 $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcNull']);
\r
3495 $xmlrpc_val = new xmlrpcval();
\r
3499 if (in_array('extension_api', $options))
\r
3501 $xmlrpc_val = new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);
\r
3505 $xmlrpc_val = new xmlrpcval();
\r
3507 // catch "user function", "unknown type"
\r
3509 // giancarlo pinerolo <ping@alt.it>
\r
3510 // it has to return
\r
3511 // an empty object in case, not a boolean.
\r
3512 $xmlrpc_val = new xmlrpcval();
\r
3515 return $xmlrpc_val;
\r
3519 * Convert the xml representation of a method response, method request or single
\r
3520 * xmlrpc value into the appropriate object (a.k.a. deserialize)
\r
3521 * @param string $xml_val
\r
3522 * @param array $options
\r
3523 * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp
\r
3525 function php_xmlrpc_decode_xml($xml_val, $options=array())
\r
3527 $GLOBALS['_xh'] = array();
\r
3528 $GLOBALS['_xh']['ac'] = '';
\r
3529 $GLOBALS['_xh']['stack'] = array();
\r
3530 $GLOBALS['_xh']['valuestack'] = array();
\r
3531 $GLOBALS['_xh']['params'] = array();
\r
3532 $GLOBALS['_xh']['pt'] = array();
\r
3533 $GLOBALS['_xh']['isf'] = 0;
\r
3534 $GLOBALS['_xh']['isf_reason'] = '';
\r
3535 $GLOBALS['_xh']['method'] = false;
\r
3536 $GLOBALS['_xh']['rt'] = '';
\r
3537 /// @todo 'guestimate' encoding
\r
3538 $parser = xml_parser_create();
\r
3539 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
\r
3540 // What if internal encoding is not in one of the 3 allowed?
\r
3541 // we use the broadest one, ie. utf8!
\r
3542 if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
\r
3544 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
\r
3548 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
\r
3550 xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
\r
3551 xml_set_character_data_handler($parser, 'xmlrpc_cd');
\r
3552 xml_set_default_handler($parser, 'xmlrpc_dh');
\r
3553 if(!xml_parse($parser, $xml_val, 1))
\r
3555 $errstr = sprintf('XML error: %s at line %d, column %d',
\r
3556 xml_error_string(xml_get_error_code($parser)),
\r
3557 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
\r
3558 error_log($errstr);
\r
3559 xml_parser_free($parser);
\r
3562 xml_parser_free($parser);
\r
3563 if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???
\r
3565 error_log($GLOBALS['_xh']['isf_reason']);
\r
3568 switch ($GLOBALS['_xh']['rt'])
\r
3570 case 'methodresponse':
\r
3571 $v =& $GLOBALS['_xh']['value'];
\r
3572 if ($GLOBALS['_xh']['isf'] == 1)
\r
3574 $vc = $v->structmem('faultCode');
\r
3575 $vs = $v->structmem('faultString');
\r
3576 $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());
\r
3580 $r = new xmlrpcresp($v);
\r
3583 case 'methodcall':
\r
3584 $m = new xmlrpcmsg($GLOBALS['_xh']['method']);
\r
3585 for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)
\r
3587 $m->addParam($GLOBALS['_xh']['params'][$i]);
\r
3591 return $GLOBALS['_xh']['value'];
\r
3598 * decode a string that is encoded w/ "chunked" transfer encoding
\r
3599 * as defined in rfc2068 par. 19.4.6
\r
3600 * code shamelessly stolen from nusoap library by Dietrich Ayala
\r
3602 * @param string $buffer the string to be decoded
\r
3605 function decode_chunked($buffer)
\r
3611 // read chunk-size, chunk-extension (if any) and crlf
\r
3612 // get the position of the linebreak
\r
3613 $chunkend = strpos($buffer,"\r\n") + 2;
\r
3614 $temp = substr($buffer,0,$chunkend);
\r
3615 $chunk_size = hexdec( trim($temp) );
\r
3616 $chunkstart = $chunkend;
\r
3617 while($chunk_size > 0)
\r
3619 $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);
\r
3621 // just in case we got a broken connection
\r
3622 if($chunkend == false)
\r
3624 $chunk = substr($buffer,$chunkstart);
\r
3625 // append chunk-data to entity-body
\r
3627 $length += strlen($chunk);
\r
3631 // read chunk-data and crlf
\r
3632 $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
\r
3633 // append chunk-data to entity-body
\r
3635 // length := length + chunk-size
\r
3636 $length += strlen($chunk);
\r
3637 // read chunk-size and crlf
\r
3638 $chunkstart = $chunkend + 2;
\r
3640 $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;
\r
3641 if($chunkend == false)
\r
3643 break; //just in case we got a broken connection
\r
3645 $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
\r
3646 $chunk_size = hexdec( trim($temp) );
\r
3647 $chunkstart = $chunkend;
\r
3653 * xml charset encoding guessing helper function.
\r
3654 * Tries to determine the charset encoding of an XML chunk received over HTTP.
\r
3655 * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
\r
3656 * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
\r
3657 * which will be most probably using UTF-8 anyway...
\r
3659 * @param string $httpheader the http Content-type header
\r
3660 * @param string $xmlchunk xml content buffer
\r
3661 * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)
\r
3664 * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
\r
3666 function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)
\r
3668 // discussion: see http://www.yale.edu/pclt/encoding/
\r
3669 // 1 - test if encoding is specified in HTTP HEADERS
\r
3672 // LWS: (\13\10)?( |\t)+
\r
3673 // token: (any char but excluded stuff)+
\r
3674 // quoted string: " (any char but double quotes and cointrol chars)* "
\r
3675 // header: Content-type = ...; charset=value(; ...)*
\r
3676 // where value is of type token, no LWS allowed between 'charset' and value
\r
3677 // Note: we do not check for invalid chars in VALUE:
\r
3678 // this had better be done using pure ereg as below
\r
3679 // Note 2: we might be removing whitespace/tabs that ought to be left in if
\r
3680 // the received charset is a quoted string. But nobody uses such charset names...
\r
3682 /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
\r
3683 $matches = array();
\r
3684 if(preg_match('/;\s*charset\s*=([^;]+)/i', $httpheader, $matches))
\r
3686 return strtoupper(trim($matches[1], " \t\""));
\r
3689 // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
\r
3690 // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
\r
3691 // NOTE: actually, according to the spec, even if we find the BOM and determine
\r
3692 // an encoding, we should check if there is an encoding specified
\r
3693 // in the xml declaration, and verify if they match.
\r
3694 /// @todo implement check as described above?
\r
3695 /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
\r
3696 if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))
\r
3700 elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))
\r
3704 elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))
\r
3709 // 3 - test if encoding is specified in the xml declaration
\r
3711 // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
\r
3712 // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
\r
3713 if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".
\r
3714 '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
\r
3715 $xmlchunk, $matches))
\r
3717 return strtoupper(substr($matches[2], 1, -1));
\r
3720 // 4 - if mbstring is available, let it do the guesswork
\r
3721 // NB: we favour finding an encoding that is compatible with what we can process
\r
3722 if(extension_loaded('mbstring'))
\r
3724 if($encoding_prefs)
\r
3726 $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);
\r
3730 $enc = mb_detect_encoding($xmlchunk);
\r
3732 // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
\r
3733 // IANA also likes better US-ASCII, so go with it
\r
3734 if($enc == 'ASCII')
\r
3736 $enc = 'US-'.$enc;
\r
3742 // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
\r
3743 // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
\r
3744 // this should be the standard. And we should be getting text/xml as request and response.
\r
3745 // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
\r
3746 return $GLOBALS['xmlrpc_defencoding'];
\r
3751 * Checks if a given charset encoding is present in a list of encodings or
\r
3752 * if it is a valid subset of any encoding in the list
\r
3753 * @param string $encoding charset to be tested
\r
3754 * @param mixed $validlist comma separated list of valid charsets (or array of charsets)
\r
3757 function is_valid_charset($encoding, $validlist)
\r
3759 $charset_supersets = array(
\r
3760 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
\r
3761 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
\r
3762 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
\r
3763 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
\r
3764 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')
\r
3766 if (is_string($validlist))
\r
3767 $validlist = explode(',', $validlist);
\r
3768 if (@in_array(strtoupper($encoding), $validlist))
\r
3772 if (array_key_exists($encoding, $charset_supersets))
\r
3773 foreach ($validlist as $allowed)
\r
3774 if (in_array($allowed, $charset_supersets[$encoding]))
\r