clockwerk-www – Blame information for rev 5

Subversion Repositories:
Rev:
Rev Author Line No. Line
5 vero 1 <?php
2 // by Edd Dumbill (C) 1999-2002
3 // <edd@usefulinc.com>
4 // $Id: xmlrpc.inc,v 1.174 2009/03/16 19:36:38 ggiunta Exp $
5  
6 // Copyright (c) 1999,2000,2002 Edd Dumbill.
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 // * Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
15 //
16 // * Redistributions in binary form must reproduce the above
17 // copyright notice, this list of conditions and the following
18 // disclaimer in the documentation and/or other materials provided
19 // with the distribution.
20 //
21 // * Neither the name of the "XML-RPC for PHP" nor the names of its
22 // contributors may be used to endorse or promote products derived
23 // from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
36 // OF THE POSSIBILITY OF SUCH DAMAGE.
37  
38 if(!function_exists('xml_parser_create'))
39 {
40 // For PHP 4 onward, XML functionality is always compiled-in on windows:
41 // no more need to dl-open it. It might have been compiled out on *nix...
42 if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
43 {
44 dl('xml.so');
45 }
46 }
47  
48 // Try to be backward compat with php < 4.2 (are we not being nice ?)
49 $phpversion = phpversion();
50 if($phpversion[0] == '4' && $phpversion[2] < 2)
51 {
52 // give an opportunity to user to specify where to include other files from
53 if(!defined('PHP_XMLRPC_COMPAT_DIR'))
54 {
55 define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
56 }
57 if($phpversion[2] == '0')
58 {
59 if($phpversion[4] < 6)
60 {
61 include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
62 }
63 include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
64 include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
65 include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
66 }
67 include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
68 include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
69 }
70  
71 // G. Giunta 2005/01/29: declare global these variables,
72 // so that xmlrpc.inc will work even if included from within a function
73 // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
74 $GLOBALS['xmlrpcI4']='i4';
75 $GLOBALS['xmlrpcInt']='int';
76 $GLOBALS['xmlrpcBoolean']='boolean';
77 $GLOBALS['xmlrpcDouble']='double';
78 $GLOBALS['xmlrpcString']='string';
79 $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
80 $GLOBALS['xmlrpcBase64']='base64';
81 $GLOBALS['xmlrpcArray']='array';
82 $GLOBALS['xmlrpcStruct']='struct';
83 $GLOBALS['xmlrpcValue']='undefined';
84  
85 $GLOBALS['xmlrpcTypes']=array(
86 $GLOBALS['xmlrpcI4'] => 1,
87 $GLOBALS['xmlrpcInt'] => 1,
88 $GLOBALS['xmlrpcBoolean'] => 1,
89 $GLOBALS['xmlrpcString'] => 1,
90 $GLOBALS['xmlrpcDouble'] => 1,
91 $GLOBALS['xmlrpcDateTime'] => 1,
92 $GLOBALS['xmlrpcBase64'] => 1,
93 $GLOBALS['xmlrpcArray'] => 2,
94 $GLOBALS['xmlrpcStruct'] => 3
95 );
96  
97 $GLOBALS['xmlrpc_valid_parents'] = array(
98 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
99 'BOOLEAN' => array('VALUE'),
100 'I4' => array('VALUE'),
101 'INT' => array('VALUE'),
102 'STRING' => array('VALUE'),
103 'DOUBLE' => array('VALUE'),
104 'DATETIME.ISO8601' => array('VALUE'),
105 'BASE64' => array('VALUE'),
106 'MEMBER' => array('STRUCT'),
107 'NAME' => array('MEMBER'),
108 'DATA' => array('ARRAY'),
109 'ARRAY' => array('VALUE'),
110 'STRUCT' => array('VALUE'),
111 'PARAM' => array('PARAMS'),
112 'METHODNAME' => array('METHODCALL'),
113 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
114 'FAULT' => array('METHODRESPONSE'),
115 'NIL' => array('VALUE') // only used when extension activated
116 );
117  
118 // define extra types for supporting NULL (useful for json or <NIL/>)
119 $GLOBALS['xmlrpcNull']='null';
120 $GLOBALS['xmlrpcTypes']['null']=1;
121  
122 // Not in use anymore since 2.0. Shall we remove it?
123 /// @deprecated
124 $GLOBALS['xmlEntities']=array(
125 'amp' => '&',
126 'quot' => '"',
127 'lt' => '<',
128 'gt' => '>',
129 'apos' => "'"
130 );
131  
132 // tables used for transcoding different charsets into us-ascii xml
133  
134 $GLOBALS['xml_iso88591_Entities']=array();
135 $GLOBALS['xml_iso88591_Entities']['in'] = array();
136 $GLOBALS['xml_iso88591_Entities']['out'] = array();
137 for ($i = 0; $i < 32; $i++)
138 {
139 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
140 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
141 }
142 for ($i = 160; $i < 256; $i++)
143 {
144 $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
145 $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
146 }
147  
148 /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
149 /// These will NOT be present in true ISO-8859-1, but will save the unwary
150 /// windows user from sending junk (though no luck when reciving them...)
151 /*
152 $GLOBALS['xml_cp1252_Entities']=array();
153 for ($i = 128; $i < 160; $i++)
154 {
155 $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i);
156 }
157 $GLOBALS['xml_cp1252_Entities']['out'] = array(
158 '&#x20AC;', '?', '&#x201A;', '&#x0192;',
159 '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
160 '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
161 '&#x0152;', '?', '&#x017D;', '?',
162 '?', '&#x2018;', '&#x2019;', '&#x201C;',
163 '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
164 '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
165 '&#x0153;', '?', '&#x017E;', '&#x0178;'
166 );
167 */
168  
169 $GLOBALS['xmlrpcerr'] = array(
170 'unknown_method'=>1,
171 'invalid_return'=>2,
172 'incorrect_params'=>3,
173 'introspect_unknown'=>4,
174 'http_error'=>5,
175 'no_data'=>6,
176 'no_ssl'=>7,
177 'curl_fail'=>8,
178 'invalid_request'=>15,
179 'no_curl'=>16,
180 'server_error'=>17,
181 'multicall_error'=>18,
182 'multicall_notstruct'=>9,
183 'multicall_nomethod'=>10,
184 'multicall_notstring'=>11,
185 'multicall_recursion'=>12,
186 'multicall_noparams'=>13,
187 'multicall_notarray'=>14,
188  
189 'cannot_decompress'=>103,
190 'decompress_fail'=>104,
191 'dechunk_fail'=>105,
192 'server_cannot_decompress'=>106,
193 'server_decompress_fail'=>107
194 );
195  
196 $GLOBALS['xmlrpcstr'] = array(
197 'unknown_method'=>'Unknown method',
198 'invalid_return'=>'Invalid return payload: enable debugging to examine incoming payload',
199 'incorrect_params'=>'Incorrect parameters passed to method',
200 'introspect_unknown'=>"Can't introspect: method unknown",
201 'http_error'=>"Didn't receive 200 OK from remote server.",
202 'no_data'=>'No data received from server.',
203 'no_ssl'=>'No SSL support compiled in.',
204 'curl_fail'=>'CURL error',
205 'invalid_request'=>'Invalid request payload',
206 'no_curl'=>'No CURL support compiled in.',
207 'server_error'=>'Internal server error',
208 'multicall_error'=>'Received from server invalid multicall response',
209 'multicall_notstruct'=>'system.multicall expected struct',
210 'multicall_nomethod'=>'missing methodName',
211 'multicall_notstring'=>'methodName is not a string',
212 'multicall_recursion'=>'recursive system.multicall forbidden',
213 'multicall_noparams'=>'missing params',
214 'multicall_notarray'=>'params is not an array',
215  
216 'cannot_decompress'=>'Received from server compressed HTTP and cannot decompress',
217 'decompress_fail'=>'Received from server invalid compressed HTTP',
218 'dechunk_fail'=>'Received from server invalid chunked HTTP',
219 'server_cannot_decompress'=>'Received from client compressed HTTP request and cannot decompress',
220 'server_decompress_fail'=>'Received from client invalid compressed HTTP request'
221 );
222  
223 // The charset encoding used by the server for received messages and
224 // by the client for received responses when received charset cannot be determined
225 // or is not supported
226 $GLOBALS['xmlrpc_defencoding']='UTF-8';
227  
228 // The encoding used internally by PHP.
229 // String values received as xml will be converted to this, and php strings will be converted to xml
230 // as if having been coded with this
231  
232 // by Fumi.Iseki for Japanese
233 //$GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
234 if ($GLOBALS['xmlrpc_internalencoding']=="") {
235 if (defined('_CHARSET')) {
236 $GLOBALS['xmlrpc_internalencoding']=_CHARSET;
237 }
238 else {
239 $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
240 }
241 }
242  
243 $GLOBALS['xmlrpcName']='XML-RPC for PHP';
244 $GLOBALS['xmlrpcVersion']='2.2.2';
245  
246 // let user errors start at 800
247 $GLOBALS['xmlrpcerruser']=800;
248 // let XML parse errors start at 100
249 $GLOBALS['xmlrpcerrxml']=100;
250  
251 // formulate backslashes for escaping regexp
252 // Not in use anymore since 2.0. Shall we remove it?
253 /// @deprecated
254 $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
255  
256 // set to TRUE to enable correct decoding of <NIL/> values
257 $GLOBALS['xmlrpc_null_extension']=false;
258  
259 // used to store state during parsing
260 // quick explanation of components:
261 // ac - used to accumulate values
262 // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
263 // isf_reason - used for storing xmlrpcresp fault string
264 // lv - used to indicate "looking for a value": implements
265 // the logic to allow values with no types to be strings
266 // params - used to store parameters in method calls
267 // method - used to store method name
268 // stack - array with genealogy of xml elements names:
269 // used to validate nesting of xmlrpc elements
270 $GLOBALS['_xh']=null;
271  
272 /**
273 * Convert a string to the correct XML representation in a target charset
274 * To help correct communication of non-ascii chars inside strings, regardless
275 * of the charset used when sending requests, parsing them, sending responses
276 * and parsing responses, an option is to convert all non-ascii chars present in the message
277 * into their equivalent 'charset entity'. Charset entities enumerated this way
278 * are independent of the charset encoding used to transmit them, and all XML
279 * parsers are bound to understand them.
280 * Note that in the std case we are not sending a charset encoding mime type
281 * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
282 *
283 * @todo do a bit of basic benchmarking (strtr vs. str_replace)
284 * @todo make usage of iconv() or recode_string() or mb_string() where available
285 */
286 function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
287 {
288 if ($src_encoding == '')
289 {
290 // lame, but we know no better...
291 $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
292 }
293  
294 switch(strtoupper($src_encoding.'_'.$dest_encoding))
295 {
296 case 'ISO-8859-1_':
297 case 'ISO-8859-1_US-ASCII':
298 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
299 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
300 break;
301 case 'ISO-8859-1_UTF-8':
302 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
303 $escaped_data = utf8_encode($escaped_data);
304 break;
305 case 'ISO-8859-1_ISO-8859-1':
306 case 'US-ASCII_US-ASCII':
307 case 'US-ASCII_UTF-8':
308 case 'US-ASCII_':
309 case 'US-ASCII_ISO-8859-1':
310 case 'UTF-8_UTF-8':
311 //case 'CP1252_CP1252':
312 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
313 break;
314 case 'UTF-8_':
315 case 'UTF-8_US-ASCII':
316 case 'UTF-8_ISO-8859-1':
317 // NB: this will choke on invalid UTF-8, going most likely beyond EOF
318 $escaped_data = '';
319 // be kind to users creating string xmlrpcvals out of different php types
320 $data = (string) $data;
321 $ns = strlen ($data);
322 for ($nn = 0; $nn < $ns; $nn++)
323 {
324 $ch = $data[$nn];
325 $ii = ord($ch);
326 //1 7 0bbbbbbb (127)
327 if ($ii < 128)
328 {
329 /// @todo shall we replace this with a (supposedly) faster str_replace?
330 switch($ii){
331 case 34:
332 $escaped_data .= '&quot;';
333 break;
334 case 38:
335 $escaped_data .= '&amp;';
336 break;
337 case 39:
338 $escaped_data .= '&apos;';
339 break;
340 case 60:
341 $escaped_data .= '&lt;';
342 break;
343 case 62:
344 $escaped_data .= '&gt;';
345 break;
346 default:
347 $escaped_data .= $ch;
348 } // switch
349 }
350 //2 11 110bbbbb 10bbbbbb (2047)
351 else if ($ii>>5 == 6)
352 {
353 $b1 = ($ii & 31);
354 $ii = ord($data[$nn+1]);
355 $b2 = ($ii & 63);
356 $ii = ($b1 * 64) + $b2;
357 $ent = sprintf ('&#%d;', $ii);
358 $escaped_data .= $ent;
359 $nn += 1;
360 }
361 //3 16 1110bbbb 10bbbbbb 10bbbbbb
362 else if ($ii>>4 == 14)
363 {
364 $b1 = ($ii & 15);
365 $ii = ord($data[$nn+1]);
366 $b2 = ($ii & 63);
367 $ii = ord($data[$nn+2]);
368 $b3 = ($ii & 63);
369 $ii = ((($b1 * 64) + $b2) * 64) + $b3;
370 $ent = sprintf ('&#%d;', $ii);
371 $escaped_data .= $ent;
372 $nn += 2;
373 }
374 //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
375 else if ($ii>>3 == 30)
376 {
377 $b1 = ($ii & 7);
378 $ii = ord($data[$nn+1]);
379 $b2 = ($ii & 63);
380 $ii = ord($data[$nn+2]);
381 $b3 = ($ii & 63);
382 $ii = ord($data[$nn+3]);
383 $b4 = ($ii & 63);
384 $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
385 $ent = sprintf ('&#%d;', $ii);
386 $escaped_data .= $ent;
387 $nn += 3;
388 }
389 }
390 break;
391 /*
392 case 'CP1252_':
393 case 'CP1252_US-ASCII':
394 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
395 $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
396 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
397 break;
398 case 'CP1252_UTF-8':
399 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
400 /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)
401 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
402 $escaped_data = utf8_encode($escaped_data);
403 break;
404 case 'CP1252_ISO-8859-1':
405 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
406 // 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...
407 $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);
408 break;
409 */
410 default:
411 $escaped_data = '';
412 error_log("Converting from $src_encoding to $dest_encoding: not supported...");
413 }
414 return $escaped_data;
415 }
416  
417 /// xml parser handler function for opening element tags
418 function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
419 {
420 // if invalid xmlrpc already detected, skip all processing
421 if ($GLOBALS['_xh']['isf'] < 2)
422 {
423 // check for correct element nesting
424 // top level element can only be of 2 types
425 /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
426 /// there is only a single top level element in xml anyway
427 if (count($GLOBALS['_xh']['stack']) == 0)
428 {
429 if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
430 $name != 'VALUE' && !$accept_single_vals))
431 {
432 $GLOBALS['_xh']['isf'] = 2;
433 $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
434 return;
435 }
436 else
437 {
438 $GLOBALS['_xh']['rt'] = strtolower($name);
439 }
440 }
441 else
442 {
443 // not top level element: see if parent is OK
444 $parent = end($GLOBALS['_xh']['stack']);
445 if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
446 {
447 $GLOBALS['_xh']['isf'] = 2;
448 $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
449 return;
450 }
451 }
452  
453 switch($name)
454 {
455 // optimize for speed switch cases: most common cases first
456 case 'VALUE':
457 /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
458 $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
459 $GLOBALS['_xh']['ac']='';
460 $GLOBALS['_xh']['lv']=1;
461 $GLOBALS['_xh']['php_class']=null;
462 break;
463 case 'I4':
464 case 'INT':
465 case 'STRING':
466 case 'BOOLEAN':
467 case 'DOUBLE':
468 case 'DATETIME.ISO8601':
469 case 'BASE64':
470 if ($GLOBALS['_xh']['vt']!='value')
471 {
472 //two data elements inside a value: an error occurred!
473 $GLOBALS['_xh']['isf'] = 2;
474 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
475 return;
476 }
477 $GLOBALS['_xh']['ac']=''; // reset the accumulator
478 break;
479 case 'STRUCT':
480 case 'ARRAY':
481 if ($GLOBALS['_xh']['vt']!='value')
482 {
483 //two data elements inside a value: an error occurred!
484 $GLOBALS['_xh']['isf'] = 2;
485 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
486 return;
487 }
488 // create an empty array to hold child values, and push it onto appropriate stack
489 $cur_val = array();
490 $cur_val['values'] = array();
491 $cur_val['type'] = $name;
492 // check for out-of-band information to rebuild php objs
493 // and in case it is found, save it
494 if (@isset($attrs['PHP_CLASS']))
495 {
496 $cur_val['php_class'] = $attrs['PHP_CLASS'];
497 }
498 $GLOBALS['_xh']['valuestack'][] = $cur_val;
499 $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
500 break;
501 case 'DATA':
502 if ($GLOBALS['_xh']['vt']!='data')
503 {
504 //two data elements inside a value: an error occurred!
505 $GLOBALS['_xh']['isf'] = 2;
506 $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
507 return;
508 }
509 case 'METHODCALL':
510 case 'METHODRESPONSE':
511 case 'PARAMS':
512 // valid elements that add little to processing
513 break;
514 case 'METHODNAME':
515 case 'NAME':
516 /// @todo we could check for 2 NAME elements inside a MEMBER element
517 $GLOBALS['_xh']['ac']='';
518 break;
519 case 'FAULT':
520 $GLOBALS['_xh']['isf']=1;
521 break;
522 case 'MEMBER':
523 $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
524 //$GLOBALS['_xh']['ac']='';
525 // Drop trough intentionally
526 case 'PARAM':
527 // clear value type, so we can check later if no value has been passed for this param/member
528 $GLOBALS['_xh']['vt']=null;
529 break;
530 case 'NIL':
531 if ($GLOBALS['xmlrpc_null_extension'])
532 {
533 if ($GLOBALS['_xh']['vt']!='value')
534 {
535 //two data elements inside a value: an error occurred!
536 $GLOBALS['_xh']['isf'] = 2;
537 $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
538 return;
539 }
540 $GLOBALS['_xh']['ac']=''; // reset the accumulator
541 break;
542 }
543 // we do not support the <NIL/> extension, so
544 // drop through intentionally
545 default:
546 /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
547 $GLOBALS['_xh']['isf'] = 2;
548 $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";
549 break;
550 }
551  
552 // Save current element name to stack, to validate nesting
553 $GLOBALS['_xh']['stack'][] = $name;
554  
555 /// @todo optimization creep: move this inside the big switch() above
556 if($name!='VALUE')
557 {
558 $GLOBALS['_xh']['lv']=0;
559 }
560 }
561 }
562  
563 /// Used in decoding xml chunks that might represent single xmlrpc values
564 function xmlrpc_se_any($parser, $name, $attrs)
565 {
566 xmlrpc_se($parser, $name, $attrs, true);
567 }
568  
569 /// xml parser handler function for close element tags
570 function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)
571 {
572 if ($GLOBALS['_xh']['isf'] < 2)
573 {
574 // push this element name from stack
575 // NB: if XML validates, correct opening/closing is guaranteed and
576 // we do not have to check for $name == $curr_elem.
577 // we also checked for proper nesting at start of elements...
578 $curr_elem = array_pop($GLOBALS['_xh']['stack']);
579  
580 switch($name)
581 {
582 case 'VALUE':
583 // This if() detects if no scalar was inside <VALUE></VALUE>
584 if ($GLOBALS['_xh']['vt']=='value')
585 {
586 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
587 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
588 }
589  
590 if ($rebuild_xmlrpcvals)
591 {
592 // build the xmlrpc val out of the data received, and substitute it
593 $temp =& new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);
594 // in case we got info about underlying php class, save it
595 // in the object we're rebuilding
596 if (isset($GLOBALS['_xh']['php_class']))
597 $temp->_php_class = $GLOBALS['_xh']['php_class'];
598 // check if we are inside an array or struct:
599 // if value just built is inside an array, let's move it into array on the stack
600 $vscount = count($GLOBALS['_xh']['valuestack']);
601 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
602 {
603 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;
604 }
605 else
606 {
607 $GLOBALS['_xh']['value'] = $temp;
608 }
609 }
610 else
611 {
612 /// @todo this needs to treat correctly php-serialized objects,
613 /// since std deserializing is done by php_xmlrpc_decode,
614 /// which we will not be calling...
615 if (isset($GLOBALS['_xh']['php_class']))
616 {
617 }
618  
619 // check if we are inside an array or struct:
620 // if value just built is inside an array, let's move it into array on the stack
621 $vscount = count($GLOBALS['_xh']['valuestack']);
622 if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
623 {
624 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];
625 }
626 }
627 break;
628 case 'BOOLEAN':
629 case 'I4':
630 case 'INT':
631 case 'STRING':
632 case 'DOUBLE':
633 case 'DATETIME.ISO8601':
634 case 'BASE64':
635 $GLOBALS['_xh']['vt']=strtolower($name);
636 /// @todo: optimization creep - remove the if/elseif cycle below
637 /// since the case() in which we are already did that
638 if ($name=='STRING')
639 {
640 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
641 }
642 elseif ($name=='DATETIME.ISO8601')
643 {
644 if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))
645 {
646 error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);
647 }
648 $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];
649 $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
650 }
651 elseif ($name=='BASE64')
652 {
653 /// @todo check for failure of base64 decoding / catch warnings
654 $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);
655 }
656 elseif ($name=='BOOLEAN')
657 {
658 // special case here: we translate boolean 1 or 0 into PHP
659 // constants true or false.
660 // Strings 'true' and 'false' are accepted, even though the
661 // spec never mentions them (see eg. Blogger api docs)
662 // NB: this simple checks helps a lot sanitizing input, ie no
663 // security problems around here
664 if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)
665 {
666 $GLOBALS['_xh']['value']=true;
667 }
668 else
669 {
670 // log if receiveing something strange, even though we set the value to false anyway
671 if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($GLOBALS['_xh']['ac'], 'false') != 0)
672 error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);
673 $GLOBALS['_xh']['value']=false;
674 }
675 }
676 elseif ($name=='DOUBLE')
677 {
678 // we have a DOUBLE
679 // we must check that only 0123456789-.<space> are characters here
680 // NOTE: regexp could be much stricter than this...
681 if (!preg_match('/^[+-eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))
682 {
683 /// @todo: find a better way of throwing an error than this!
684 error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);
685 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
686 }
687 else
688 {
689 // it's ok, add it on
690 $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];
691 }
692 }
693 else
694 {
695 // we have an I4/INT
696 // we must check that only 0123456789-<space> are characters here
697 if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))
698 {
699 /// @todo find a better way of throwing an error than this!
700 error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);
701 $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
702 }
703 else
704 {
705 // it's ok, add it on
706 $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];
707 }
708 }
709 //$GLOBALS['_xh']['ac']=''; // is this necessary?
710 $GLOBALS['_xh']['lv']=3; // indicate we've found a value
711 break;
712 case 'NAME':
713 $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];
714 break;
715 case 'MEMBER':
716 //$GLOBALS['_xh']['ac']=''; // is this necessary?
717 // add to array in the stack the last element built,
718 // unless no VALUE was found
719 if ($GLOBALS['_xh']['vt'])
720 {
721 $vscount = count($GLOBALS['_xh']['valuestack']);
722 $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];
723 } else
724 error_log('XML-RPC: missing VALUE inside STRUCT in received xml');
725 break;
726 case 'DATA':
727 //$GLOBALS['_xh']['ac']=''; // is this necessary?
728 $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty
729 break;
730 case 'STRUCT':
731 case 'ARRAY':
732 // fetch out of stack array of values, and promote it to current value
733 $curr_val = array_pop($GLOBALS['_xh']['valuestack']);
734 $GLOBALS['_xh']['value'] = $curr_val['values'];
735 $GLOBALS['_xh']['vt']=strtolower($name);
736 if (isset($curr_val['php_class']))
737 {
738 $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];
739 }
740 break;
741 case 'PARAM':
742 // add to array of params the current value,
743 // unless no VALUE was found
744 if ($GLOBALS['_xh']['vt'])
745 {
746 $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];
747 $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];
748 }
749 else
750 error_log('XML-RPC: missing VALUE inside PARAM in received xml');
751 break;
752 case 'METHODNAME':
753 $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);
754 break;
755 case 'NIL':
756 if ($GLOBALS['xmlrpc_null_extension'])
757 {
758 $GLOBALS['_xh']['vt']='null';
759 $GLOBALS['_xh']['value']=null;
760 $GLOBALS['_xh']['lv']=3;
761 break;
762 }
763 // drop through intentionally if nil extension not enabled
764 case 'PARAMS':
765 case 'FAULT':
766 case 'METHODCALL':
767 case 'METHORESPONSE':
768 break;
769 default:
770 // End of INVALID ELEMENT!
771 // shall we add an assert here for unreachable code???
772 break;
773 }
774 }
775 }
776  
777 /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values
778 function xmlrpc_ee_fast($parser, $name)
779 {
780 xmlrpc_ee($parser, $name, false);
781 }
782  
783 /// xml parser handler function for character data
784 function xmlrpc_cd($parser, $data)
785 {
786 // skip processing if xml fault already detected
787 if ($GLOBALS['_xh']['isf'] < 2)
788 {
789 // "lookforvalue==3" means that we've found an entire value
790 // and should discard any further character data
791 if($GLOBALS['_xh']['lv']!=3)
792 {
793 // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2
794 //if($GLOBALS['_xh']['lv']==1)
795 //{
796 // if we've found text and we're just in a <value> then
797 // say we've found a value
798 //$GLOBALS['_xh']['lv']=2;
799 //}
800 // we always initialize the accumulator before starting parsing, anyway...
801 //if(!@isset($GLOBALS['_xh']['ac']))
802 //{
803 // $GLOBALS['_xh']['ac'] = '';
804 //}
805 $GLOBALS['_xh']['ac'].=$data;
806 }
807 }
808 }
809  
810 /// xml parser handler function for 'other stuff', ie. not char data or
811 /// element start/end tag. In fact it only gets called on unknown entities...
812 function xmlrpc_dh($parser, $data)
813 {
814 // skip processing if xml fault already detected
815 if ($GLOBALS['_xh']['isf'] < 2)
816 {
817 if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')
818 {
819 // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2
820 //if($GLOBALS['_xh']['lv']==1)
821 //{
822 // $GLOBALS['_xh']['lv']=2;
823 //}
824 $GLOBALS['_xh']['ac'].=$data;
825 }
826 }
827 return true;
828 }
829  
830 class xmlrpc_client
831 {
832 var $path;
833 var $server;
834 var $port=0;
835 var $method='http';
836 var $errno;
837 var $errstr;
838 var $debug=0;
839 var $username='';
840 var $password='';
841 var $authtype=1;
842 var $cert='';
843 var $certpass='';
844 var $cacert='';
845 var $cacertdir='';
846 var $key='';
847 var $keypass='';
848 var $verifypeer=true;
849 var $verifyhost=1;
850 var $no_multicall=false;
851 var $proxy='';
852 var $proxyport=0;
853 var $proxy_user='';
854 var $proxy_pass='';
855 var $proxy_authtype=1;
856 var $cookies=array();
857 /**
858 * List of http compression methods accepted by the client for responses.
859 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
860 *
861 * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
862 * in those cases it will be up to CURL to decide the compression methods
863 * it supports. You might check for the presence of 'zlib' in the output of
864 * curl_version() to determine wheter compression is supported or not
865 */
866 var $accepted_compression = array();
867 /**
868 * Name of compression scheme to be used for sending requests.
869 * Either null, gzip or deflate
870 */
871 var $request_compression = '';
872 /**
873 * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
874 * http://curl.haxx.se/docs/faq.html#7.3)
875 */
876 var $xmlrpc_curl_handle = null;
877 /// Wheter to use persistent connections for http 1.1 and https
878 var $keepalive = false;
879 /// Charset encodings that can be decoded without problems by the client
880 var $accepted_charset_encodings = array();
881 /// Charset encoding to be used in serializing request. NULL = use ASCII
882 var $request_charset_encoding = '';
883 /**
884 * Decides the content of xmlrpcresp objects returned by calls to send()
885 * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
886 */
887 var $return_type = 'xmlrpcvals';
888  
889 /**
890 * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
891 * @param string $server the server name / ip address
892 * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
893 * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
894 */
895 function xmlrpc_client($path, $server='', $port='', $method='')
896 {
897 // allow user to specify all params in $path
898 if($server == '' and $port == '' and $method == '')
899 {
900 $parts = parse_url($path);
901 $server = $parts['host'];
902 $path = isset($parts['path']) ? $parts['path'] : '';
903 if(isset($parts['query']))
904 {
905 $path .= '?'.$parts['query'];
906 }
907 if(isset($parts['fragment']))
908 {
909 $path .= '#'.$parts['fragment'];
910 }
911 if(isset($parts['port']))
912 {
913 $port = $parts['port'];
914 }
915 if(isset($parts['scheme']))
916 {
917 $method = $parts['scheme'];
918 }
919 if(isset($parts['user']))
920 {
921 $this->username = $parts['user'];
922 }
923 if(isset($parts['pass']))
924 {
925 $this->password = $parts['pass'];
926 }
927 }
928 if($path == '' || $path[0] != '/')
929 {
930 $this->path='/'.$path;
931 }
932 else
933 {
934 $this->path=$path;
935 }
936 $this->server=$server;
937 if($port != '')
938 {
939 $this->port=$port;
940 }
941 if($method != '')
942 {
943 $this->method=$method;
944 }
945  
946 // if ZLIB is enabled, let the client by default accept compressed responses
947 if(function_exists('gzinflate') || (
948 function_exists('curl_init') && (($info = curl_version()) &&
949 ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
950 ))
951 {
952 $this->accepted_compression = array('gzip', 'deflate');
953 }
954  
955 // keepalives: enabled by default ONLY for PHP >= 4.3.8
956 // (see http://curl.haxx.se/docs/faq.html#7.3)
957 if(version_compare(phpversion(), '4.3.8') >= 0)
958 {
959 $this->keepalive = true;
960 }
961  
962 // by default the xml parser can support these 3 charset encodings
963 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
964 }
965  
966 /**
967 * Enables/disables the echoing to screen of the xmlrpc responses received
968 * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
969 * @access public
970 */
971 function setDebug($in)
972 {
973 $this->debug=$in;
974 }
975  
976 /**
977 * Add some http BASIC AUTH credentials, used by the client to authenticate
978 * @param string $u username
979 * @param string $p password
980 * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
981 * @access public
982 */
983 function setCredentials($u, $p, $t=1)
984 {
985 $this->username=$u;
986 $this->password=$p;
987 $this->authtype=$t;
988 }
989  
990 /**
991 * Add a client-side https certificate
992 * @param string $cert
993 * @param string $certpass
994 * @access public
995 */
996 function setCertificate($cert, $certpass)
997 {
998 $this->cert = $cert;
999 $this->certpass = $certpass;
1000 }
1001  
1002 /**
1003 * Add a CA certificate to verify server with (see man page about
1004 * CURLOPT_CAINFO for more details
1005 * @param string $cacert certificate file name (or dir holding certificates)
1006 * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false
1007 * @access public
1008 */
1009 function setCaCertificate($cacert, $is_dir=false)
1010 {
1011 if ($is_dir)
1012 {
1013 $this->cacertdir = $cacert;
1014 }
1015 else
1016 {
1017 $this->cacert = $cacert;
1018 }
1019 }
1020  
1021 /**
1022 * Set attributes for SSL communication: private SSL key
1023 * NB: does not work in older php/curl installs
1024 * Thanks to Daniel Convissor
1025 * @param string $key The name of a file containing a private SSL key
1026 * @param string $keypass The secret password needed to use the private SSL key
1027 * @access public
1028 */
1029 function setKey($key, $keypass)
1030 {
1031 $this->key = $key;
1032 $this->keypass = $keypass;
1033 }
1034  
1035 /**
1036 * Set attributes for SSL communication: verify server certificate
1037 * @param bool $i enable/disable verification of peer certificate
1038 * @access public
1039 */
1040 function setSSLVerifyPeer($i)
1041 {
1042 $this->verifypeer = $i;
1043 }
1044  
1045 /**
1046 * Set attributes for SSL communication: verify match of server cert w. hostname
1047 * @param int $i
1048 * @access public
1049 */
1050 function setSSLVerifyHost($i)
1051 {
1052 $this->verifyhost = $i;
1053 }
1054  
1055 /**
1056 * Set proxy info
1057 * @param string $proxyhost
1058 * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS
1059 * @param string $proxyusername Leave blank if proxy has public access
1060 * @param string $proxypassword Leave blank if proxy has public access
1061 * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy
1062 * @access public
1063 */
1064 function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)
1065 {
1066 $this->proxy = $proxyhost;
1067 $this->proxyport = $proxyport;
1068 $this->proxy_user = $proxyusername;
1069 $this->proxy_pass = $proxypassword;
1070 $this->proxy_authtype = $proxyauthtype;
1071 }
1072  
1073 /**
1074 * Enables/disables reception of compressed xmlrpc responses.
1075 * Note that enabling reception of compressed responses merely adds some standard
1076 * http headers to xmlrpc requests. It is up to the xmlrpc server to return
1077 * compressed responses when receiving such requests.
1078 * @param string $compmethod either 'gzip', 'deflate', 'any' or ''
1079 * @access public
1080 */
1081 function setAcceptedCompression($compmethod)
1082 {
1083 if ($compmethod == 'any')
1084 $this->accepted_compression = array('gzip', 'deflate');
1085 else
1086 $this->accepted_compression = array($compmethod);
1087 }
1088  
1089 /**
1090 * Enables/disables http compression of xmlrpc request.
1091 * Take care when sending compressed requests: servers might not support them
1092 * (and automatic fallback to uncompressed requests is not yet implemented)
1093 * @param string $compmethod either 'gzip', 'deflate' or ''
1094 * @access public
1095 */
1096 function setRequestCompression($compmethod)
1097 {
1098 $this->request_compression = $compmethod;
1099 }
1100  
1101 /**
1102 * Adds a cookie to list of cookies that will be sent to server.
1103 * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
1104 * do not do it unless you know what you are doing
1105 * @param string $name
1106 * @param string $value
1107 * @param string $path
1108 * @param string $domain
1109 * @param int $port
1110 * @access public
1111 *
1112 * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
1113 */
1114 function setCookie($name, $value='', $path='', $domain='', $port=null)
1115 {
1116 $this->cookies[$name]['value'] = urlencode($value);
1117 if ($path || $domain || $port)
1118 {
1119 $this->cookies[$name]['path'] = $path;
1120 $this->cookies[$name]['domain'] = $domain;
1121 $this->cookies[$name]['port'] = $port;
1122 $this->cookies[$name]['version'] = 1;
1123 }
1124 else
1125 {
1126 $this->cookies[$name]['version'] = 0;
1127 }
1128 }
1129  
1130 /**
1131 * Send an xmlrpc request
1132 * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request
1133 * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
1134 * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
1135 * @return xmlrpcresp
1136 * @access public
1137 */
1138 function& send($msg, $timeout=0, $method='')
1139 {
1140 // if user deos not specify http protocol, use native method of this client
1141 // (i.e. method set during call to constructor)
1142 if($method == '')
1143 {
1144 $method = $this->method;
1145 }
1146  
1147 if(is_array($msg))
1148 {
1149 // $msg is an array of xmlrpcmsg's
1150 $r = $this->multicall($msg, $timeout, $method);
1151 return $r;
1152 }
1153 elseif(is_string($msg))
1154 {
1155 $n =& new xmlrpcmsg('');
1156 $n->payload = $msg;
1157 $msg = $n;
1158 }
1159  
1160 // where msg is an xmlrpcmsg
1161 $msg->debug=$this->debug;
1162  
1163 if($method == 'https')
1164 {
1165 $r =& $this->sendPayloadHTTPS(
1166 $msg,
1167 $this->server,
1168 $this->port,
1169 $timeout,
1170 $this->username,
1171 $this->password,
1172 $this->authtype,
1173 $this->cert,
1174 $this->certpass,
1175 $this->cacert,
1176 $this->cacertdir,
1177 $this->proxy,
1178 $this->proxyport,
1179 $this->proxy_user,
1180 $this->proxy_pass,
1181 $this->proxy_authtype,
1182 $this->keepalive,
1183 $this->key,
1184 $this->keypass
1185 );
1186 }
1187 elseif($method == 'http11')
1188 {
1189 $r =& $this->sendPayloadCURL(
1190 $msg,
1191 $this->server,
1192 $this->port,
1193 $timeout,
1194 $this->username,
1195 $this->password,
1196 $this->authtype,
1197 null,
1198 null,
1199 null,
1200 null,
1201 $this->proxy,
1202 $this->proxyport,
1203 $this->proxy_user,
1204 $this->proxy_pass,
1205 $this->proxy_authtype,
1206 'http',
1207 $this->keepalive
1208 );
1209 }
1210 else
1211 {
1212 $r =& $this->sendPayloadHTTP10(
1213 $msg,
1214 $this->server,
1215 $this->port,
1216 $timeout,
1217 $this->username,
1218 $this->password,
1219 $this->authtype,
1220 $this->proxy,
1221 $this->proxyport,
1222 $this->proxy_user,
1223 $this->proxy_pass,
1224 $this->proxy_authtype
1225 );
1226 }
1227  
1228 return $r;
1229 }
1230  
1231 /**
1232 * @access private
1233 */
1234 function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,
1235 $username='', $password='', $authtype=1, $proxyhost='',
1236 $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)
1237 {
1238 if($port==0)
1239 {
1240 $port=80;
1241 }
1242  
1243 // Only create the payload if it was not created previously
1244 if(empty($msg->payload))
1245 {
1246 $msg->createPayload($this->request_charset_encoding);
1247 }
1248  
1249 $payload = $msg->payload;
1250 // Deflate request body and set appropriate request headers
1251 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
1252 {
1253 if($this->request_compression == 'gzip')
1254 {
1255 $a = @gzencode($payload);
1256 if($a)
1257 {
1258 $payload = $a;
1259 $encoding_hdr = "Content-Encoding: gzip\r\n";
1260 }
1261 }
1262 else
1263 {
1264 $a = @gzcompress($payload);
1265 if($a)
1266 {
1267 $payload = $a;
1268 $encoding_hdr = "Content-Encoding: deflate\r\n";
1269 }
1270 }
1271 }
1272 else
1273 {
1274 $encoding_hdr = '';
1275 }
1276  
1277 // thanks to Grant Rauscher <grant7@firstworld.net> for this
1278 $credentials='';
1279 if($username!='')
1280 {
1281 $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
1282 if ($authtype != 1)
1283 {
1284 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');
1285 }
1286 }
1287  
1288 $accepted_encoding = '';
1289 if(is_array($this->accepted_compression) && count($this->accepted_compression))
1290 {
1291 $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
1292 }
1293  
1294 $proxy_credentials = '';
1295 if($proxyhost)
1296 {
1297 if($proxyport == 0)
1298 {
1299 $proxyport = 8080;
1300 }
1301 $connectserver = $proxyhost;
1302 $connectport = $proxyport;
1303 $uri = 'http://'.$server.':'.$port.$this->path;
1304 if($proxyusername != '')
1305 {
1306 if ($proxyauthtype != 1)
1307 {
1308 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');
1309 }
1310 $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";
1311 }
1312 }
1313 else
1314 {
1315 $connectserver = $server;
1316 $connectport = $port;
1317 $uri = $this->path;
1318 }
1319  
1320 // Cookie generation, as per rfc2965 (version 1 cookies) or
1321 // netscape's rules (version 0 cookies)
1322 $cookieheader='';
1323 if (count($this->cookies))
1324 {
1325 $version = '';
1326 foreach ($this->cookies as $name => $cookie)
1327 {
1328 if ($cookie['version'])
1329 {
1330 $version = ' $Version="' . $cookie['version'] . '";';
1331 $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";';
1332 if ($cookie['path'])
1333 $cookieheader .= ' $Path="' . $cookie['path'] . '";';
1334 if ($cookie['domain'])
1335 $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';
1336 if ($cookie['port'])
1337 $cookieheader .= ' $Port="' . $cookie['port'] . '";';
1338 }
1339 else
1340 {
1341 $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";";
1342 }
1343 }
1344 $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";
1345 }
1346  
1347 $op= 'POST ' . $uri. " HTTP/1.0\r\n" .
1348 'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" .
1349 'Host: '. $server . ':' . $port . "\r\n" .
1350 $credentials .
1351 $proxy_credentials .
1352 $accepted_encoding .
1353 $encoding_hdr .
1354 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
1355 $cookieheader .
1356 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .
1357 strlen($payload) . "\r\n\r\n" .
1358 $payload;
1359  
1360 if($this->debug > 1)
1361 {
1362 print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";
1363 // let the client see this now in case http times out...
1364 flush();
1365 }
1366  
1367 if($timeout>0)
1368 {
1369 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);
1370 }
1371 else
1372 {
1373 $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);
1374 }
1375 if($fp)
1376 {
1377 if($timeout>0 && function_exists('stream_set_timeout'))
1378 {
1379 stream_set_timeout($fp, $timeout);
1380 }
1381 }
1382 else
1383 {
1384 $this->errstr='Connect error: '.$this->errstr;
1385 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');
1386 return $r;
1387 }
1388  
1389 if(!fputs($fp, $op, strlen($op)))
1390 {
1391 fclose($fp);
1392 $this->errstr='Write error';
1393 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);
1394 return $r;
1395 }
1396 else
1397 {
1398 // reset errno and errstr on succesful socket connection
1399 $this->errstr = '';
1400 }
1401 // G. Giunta 2005/10/24: close socket before parsing.
1402 // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
1403 $ipd='';
1404 do
1405 {
1406 // shall we check for $data === FALSE?
1407 // as per the manual, it signals an error
1408 $ipd.=fread($fp, 32768);
1409 } while(!feof($fp));
1410 fclose($fp);
1411 $r =& $msg->parseResponse($ipd, false, $this->return_type);
1412 return $r;
1413  
1414 }
1415  
1416 /**
1417 * @access private
1418 */
1419 function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
1420 $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
1421 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
1422 $keepalive=false, $key='', $keypass='')
1423 {
1424 $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
1425 $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
1426 $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
1427 return $r;
1428 }
1429  
1430 /**
1431 * Contributed by Justin Miller <justin@voxel.net>
1432 * Requires curl to be built into PHP
1433 * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
1434 * @access private
1435 */
1436 function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
1437 $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
1438 $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
1439 $keepalive=false, $key='', $keypass='')
1440 {
1441 if(!function_exists('curl_init'))
1442 {
1443 $this->errstr='CURL unavailable on this install';
1444 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);
1445 return $r;
1446 }
1447 if($method == 'https')
1448 {
1449 if(($info = curl_version()) &&
1450 ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
1451 {
1452 $this->errstr='SSL unavailable on this install';
1453 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);
1454 return $r;
1455 }
1456 }
1457  
1458 if($port == 0)
1459 {
1460 if($method == 'http')
1461 {
1462 $port = 80;
1463 }
1464 else
1465 {
1466 $port = 443;
1467 }
1468 }
1469  
1470 // Only create the payload if it was not created previously
1471 if(empty($msg->payload))
1472 {
1473 $msg->createPayload($this->request_charset_encoding);
1474 }
1475  
1476 // Deflate request body and set appropriate request headers
1477 $payload = $msg->payload;
1478 if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
1479 {
1480 if($this->request_compression == 'gzip')
1481 {
1482 $a = @gzencode($payload);
1483 if($a)
1484 {
1485 $payload = $a;
1486 $encoding_hdr = 'Content-Encoding: gzip';
1487 }
1488 }
1489 else
1490 {
1491 $a = @gzcompress($payload);
1492 if($a)
1493 {
1494 $payload = $a;
1495 $encoding_hdr = 'Content-Encoding: deflate';
1496 }
1497 }
1498 }
1499 else
1500 {
1501 $encoding_hdr = '';
1502 }
1503  
1504 if($this->debug > 1)
1505 {
1506 print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
1507 // let the client see this now in case http times out...
1508 flush();
1509 }
1510  
1511 if(!$keepalive || !$this->xmlrpc_curl_handle)
1512 {
1513 $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
1514 if($keepalive)
1515 {
1516 $this->xmlrpc_curl_handle = $curl;
1517 }
1518 }
1519 else
1520 {
1521 $curl = $this->xmlrpc_curl_handle;
1522 }
1523  
1524 // results into variable
1525 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
1526  
1527 if($this->debug)
1528 {
1529 curl_setopt($curl, CURLOPT_VERBOSE, 1);
1530 }
1531 curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);
1532 // required for XMLRPC: post the data
1533 curl_setopt($curl, CURLOPT_POST, 1);
1534 // the data
1535 curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
1536  
1537 // return the header too
1538 curl_setopt($curl, CURLOPT_HEADER, 1);
1539  
1540 // will only work with PHP >= 5.0
1541 // NB: if we set an empty string, CURL will add http header indicating
1542 // ALL methods it is supporting. This is possibly a better option than
1543 // letting the user tell what curl can / cannot do...
1544 if(is_array($this->accepted_compression) && count($this->accepted_compression))
1545 {
1546 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
1547 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1548 if (count($this->accepted_compression) == 1)
1549 {
1550 curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
1551 }
1552 else
1553 curl_setopt($curl, CURLOPT_ENCODING, '');
1554 }
1555 // extra headers
1556 $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
1557 // if no keepalive is wanted, let the server know it in advance
1558 if(!$keepalive)
1559 {
1560 $headers[] = 'Connection: close';
1561 }
1562 // request compression header
1563 if($encoding_hdr)
1564 {
1565 $headers[] = $encoding_hdr;
1566 }
1567  
1568 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
1569 // timeout is borked
1570 if($timeout)
1571 {
1572 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
1573 }
1574  
1575 if($username && $password)
1576 {
1577 curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
1578 if (defined('CURLOPT_HTTPAUTH'))
1579 {
1580 curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
1581 }
1582 else if ($authtype != 1)
1583 {
1584 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');
1585 }
1586 }
1587  
1588 if($method == 'https')
1589 {
1590 // set cert file
1591 if($cert)
1592 {
1593 curl_setopt($curl, CURLOPT_SSLCERT, $cert);
1594 }
1595 // set cert password
1596 if($certpass)
1597 {
1598 curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
1599 }
1600 // whether to verify remote host's cert
1601 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
1602 // set ca certificates file/dir
1603 if($cacert)
1604 {
1605 curl_setopt($curl, CURLOPT_CAINFO, $cacert);
1606 }
1607 if($cacertdir)
1608 {
1609 curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
1610 }
1611 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1612 if($key)
1613 {
1614 curl_setopt($curl, CURLOPT_SSLKEY, $key);
1615 }
1616 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
1617 if($keypass)
1618 {
1619 curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
1620 }
1621 // 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
1622 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
1623 }
1624  
1625 // proxy info
1626 if($proxyhost)
1627 {
1628 if($proxyport == 0)
1629 {
1630 $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
1631 }
1632 curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);
1633 //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
1634 if($proxyusername)
1635 {
1636 curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
1637 if (defined('CURLOPT_PROXYAUTH'))
1638 {
1639 curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
1640 }
1641 else if ($proxyauthtype != 1)
1642 {
1643 error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');
1644 }
1645 }
1646 }
1647  
1648 // NB: should we build cookie http headers by hand rather than let CURL do it?
1649 // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
1650 // set to client obj the the user...
1651 if (count($this->cookies))
1652 {
1653 $cookieheader = '';
1654 foreach ($this->cookies as $name => $cookie)
1655 {
1656 $cookieheader .= $name . '=' . $cookie['value'] . '; ';
1657 }
1658 curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
1659 }
1660  
1661 $result = curl_exec($curl);
1662  
1663 if ($this->debug > 1)
1664 {
1665 print "<PRE>\n---CURL INFO---\n";
1666 foreach(curl_getinfo($curl) as $name => $val)
1667 print $name . ': ' . htmlentities($val). "\n";
1668 print "---END---\n</PRE>";
1669 }
1670  
1671 if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?
1672 {
1673 $this->errstr='no response';
1674 $resp=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));
1675 curl_close($curl);
1676 if($keepalive)
1677 {
1678 $this->xmlrpc_curl_handle = null;
1679 }
1680 }
1681 else
1682 {
1683 if(!$keepalive)
1684 {
1685 curl_close($curl);
1686 }
1687 $resp =& $msg->parseResponse($result, true, $this->return_type);
1688 }
1689 return $resp;
1690 }
1691  
1692 /**
1693 * Send an array of request messages and return an array of responses.
1694 * Unless $this->no_multicall has been set to true, it will try first
1695 * to use one single xmlrpc call to server method system.multicall, and
1696 * revert to sending many successive calls in case of failure.
1697 * This failure is also stored in $this->no_multicall for subsequent calls.
1698 * Unfortunately, there is no server error code universally used to denote
1699 * the fact that multicall is unsupported, so there is no way to reliably
1700 * distinguish between that and a temporary failure.
1701 * If you are sure that server supports multicall and do not want to
1702 * fallback to using many single calls, set the fourth parameter to FALSE.
1703 *
1704 * NB: trying to shoehorn extra functionality into existing syntax has resulted
1705 * in pretty much convoluted code...
1706 *
1707 * @param array $msgs an array of xmlrpcmsg objects
1708 * @param integer $timeout connection timeout (in seconds)
1709 * @param string $method the http protocol variant to be used
1710 * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted
1711 * @return array
1712 * @access public
1713 */
1714 function multicall($msgs, $timeout=0, $method='', $fallback=true)
1715 {
1716 if ($method == '')
1717 {
1718 $method = $this->method;
1719 }
1720 if(!$this->no_multicall)
1721 {
1722 $results = $this->_try_multicall($msgs, $timeout, $method);
1723 if(is_array($results))
1724 {
1725 // System.multicall succeeded
1726 return $results;
1727 }
1728 else
1729 {
1730 // either system.multicall is unsupported by server,
1731 // or call failed for some other reason.
1732 if ($fallback)
1733 {
1734 // Don't try it next time...
1735 $this->no_multicall = true;
1736 }
1737 else
1738 {
1739 if (is_a($results, 'xmlrpcresp'))
1740 {
1741 $result = $results;
1742 }
1743 else
1744 {
1745 $result =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);
1746 }
1747 }
1748 }
1749 }
1750 else
1751 {
1752 // override fallback, in case careless user tries to do two
1753 // opposite things at the same time
1754 $fallback = true;
1755 }
1756  
1757 $results = array();
1758 if ($fallback)
1759 {
1760 // system.multicall is (probably) unsupported by server:
1761 // emulate multicall via multiple requests
1762 foreach($msgs as $msg)
1763 {
1764 $results[] =& $this->send($msg, $timeout, $method);
1765 }
1766 }
1767 else
1768 {
1769 // user does NOT want to fallback on many single calls:
1770 // since we should always return an array of responses,
1771 // return an array with the same error repeated n times
1772 foreach($msgs as $msg)
1773 {
1774 $results[] = $result;
1775 }
1776 }
1777 return $results;
1778 }
1779  
1780 /**
1781 * Attempt to boxcar $msgs via system.multicall.
1782 * Returns either an array of xmlrpcreponses, an xmlrpc error response
1783 * or false (when received response does not respect valid multicall syntax)
1784 * @access private
1785 */
1786 function _try_multicall($msgs, $timeout, $method)
1787 {
1788 // Construct multicall message
1789 $calls = array();
1790 foreach($msgs as $msg)
1791 {
1792 $call['methodName'] =& new xmlrpcval($msg->method(),'string');
1793 $numParams = $msg->getNumParams();
1794 $params = array();
1795 for($i = 0; $i < $numParams; $i++)
1796 {
1797 $params[$i] = $msg->getParam($i);
1798 }
1799 $call['params'] =& new xmlrpcval($params, 'array');
1800 $calls[] =& new xmlrpcval($call, 'struct');
1801 }
1802 $multicall =& new xmlrpcmsg('system.multicall');
1803 $multicall->addParam(new xmlrpcval($calls, 'array'));
1804  
1805 // Attempt RPC call
1806 $result =& $this->send($multicall, $timeout, $method);
1807  
1808 if($result->faultCode() != 0)
1809 {
1810 // call to system.multicall failed
1811 return $result;
1812 }
1813  
1814 // Unpack responses.
1815 $rets = $result->value();
1816  
1817 if ($this->return_type == 'xml')
1818 {
1819 return $rets;
1820 }
1821 else if ($this->return_type == 'phpvals')
1822 {
1823 ///@todo test this code branch...
1824 $rets = $result->value();
1825 if(!is_array($rets))
1826 {
1827 return false; // bad return type from system.multicall
1828 }
1829 $numRets = count($rets);
1830 if($numRets != count($msgs))
1831 {
1832 return false; // wrong number of return values.
1833 }
1834  
1835 $response = array();
1836 for($i = 0; $i < $numRets; $i++)
1837 {
1838 $val = $rets[$i];
1839 if (!is_array($val)) {
1840 return false;
1841 }
1842 switch(count($val))
1843 {
1844 case 1:
1845 if(!isset($val[0]))
1846 {
1847 return false; // Bad value
1848 }
1849 // Normal return value
1850 $response[$i] =& new xmlrpcresp($val[0], 0, '', 'phpvals');
1851 break;
1852 case 2:
1853 /// @todo remove usage of @: it is apparently quite slow
1854 $code = @$val['faultCode'];
1855 if(!is_int($code))
1856 {
1857 return false;
1858 }
1859 $str = @$val['faultString'];
1860 if(!is_string($str))
1861 {
1862 return false;
1863 }
1864 $response[$i] =& new xmlrpcresp(0, $code, $str);
1865 break;
1866 default:
1867 return false;
1868 }
1869 }
1870 return $response;
1871 }
1872 else // return type == 'xmlrpcvals'
1873 {
1874 $rets = $result->value();
1875 if($rets->kindOf() != 'array')
1876 {
1877 return false; // bad return type from system.multicall
1878 }
1879 $numRets = $rets->arraysize();
1880 if($numRets != count($msgs))
1881 {
1882 return false; // wrong number of return values.
1883 }
1884  
1885 $response = array();
1886 for($i = 0; $i < $numRets; $i++)
1887 {
1888 $val = $rets->arraymem($i);
1889 switch($val->kindOf())
1890 {
1891 case 'array':
1892 if($val->arraysize() != 1)
1893 {
1894 return false; // Bad value
1895 }
1896 // Normal return value
1897 $response[$i] =& new xmlrpcresp($val->arraymem(0));
1898 break;
1899 case 'struct':
1900 $code = $val->structmem('faultCode');
1901 if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
1902 {
1903 return false;
1904 }
1905 $str = $val->structmem('faultString');
1906 if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
1907 {
1908 return false;
1909 }
1910 $response[$i] =& new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
1911 break;
1912 default:
1913 return false;
1914 }
1915 }
1916 return $response;
1917 }
1918 }
1919 } // end class xmlrpc_client
1920  
1921 class xmlrpcresp
1922 {
1923 var $val = 0;
1924 var $valtyp;
1925 var $errno = 0;
1926 var $errstr = '';
1927 var $payload;
1928 var $hdrs = array();
1929 var $_cookies = array();
1930 var $content_type = 'text/xml';
1931 var $raw_data = '';
1932  
1933 /**
1934 * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
1935 * @param integer $fcode set it to anything but 0 to create an error response
1936 * @param string $fstr the error string, in case of an error response
1937 * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
1938 *
1939 * @todo add check that $val / $fcode / $fstr is of correct type???
1940 * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
1941 * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
1942 */
1943 function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')
1944 {
1945 if($fcode != 0)
1946 {
1947 // error response
1948 $this->errno = $fcode;
1949 $this->errstr = $fstr;
1950 //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
1951 }
1952 else
1953 {
1954 // successful response
1955 $this->val = $val;
1956 if ($valtyp == '')
1957 {
1958 // user did not declare type of response value: try to guess it
1959 if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))
1960 {
1961 $this->valtyp = 'xmlrpcvals';
1962 }
1963 else if (is_string($this->val))
1964 {
1965 $this->valtyp = 'xml';
1966  
1967 }
1968 else
1969 {
1970 $this->valtyp = 'phpvals';
1971 }
1972 }
1973 else
1974 {
1975 // user declares type of resp value: believe him
1976 $this->valtyp = $valtyp;
1977 }
1978 }
1979 }
1980  
1981 /**
1982 * Returns the error code of the response.
1983 * @return integer the error code of this response (0 for not-error responses)
1984 * @access public
1985 */
1986 function faultCode()
1987 {
1988 return $this->errno;
1989 }
1990  
1991 /**
1992 * Returns the error code of the response.
1993 * @return string the error string of this response ('' for not-error responses)
1994 * @access public
1995 */
1996 function faultString()
1997 {
1998 return $this->errstr;
1999 }
2000  
2001 /**
2002 * Returns the value received by the server.
2003 * @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
2004 * @access public
2005 */
2006 function value()
2007 {
2008 return $this->val;
2009 }
2010  
2011 /**
2012 * Returns an array with the cookies received from the server.
2013 * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
2014 * with attributes being e.g. 'expires', 'path', domain'.
2015 * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
2016 * are still present in the array. It is up to the user-defined code to decide
2017 * how to use the received cookies, and wheter they have to be sent back with the next
2018 * request to the server (using xmlrpc_client::setCookie) or not
2019 * @return array array of cookies received from the server
2020 * @access public
2021 */
2022 function cookies()
2023 {
2024 return $this->_cookies;
2025 }
2026  
2027 /**
2028 * Returns xml representation of the response. XML prologue not included
2029 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
2030 * @return string the xml representation of the response
2031 * @access public
2032 */
2033 function serialize($charset_encoding='')
2034 {
2035 if ($charset_encoding != '')
2036 $this->content_type = 'text/xml; charset=' . $charset_encoding;
2037 else
2038 $this->content_type = 'text/xml';
2039 $result = "<methodResponse>\n";
2040 if($this->errno)
2041 {
2042 // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
2043 // by xml-encoding non ascii chars
2044 $result .= "<fault>\n" .
2045 "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
2046 "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
2047 xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
2048 "</struct>\n</value>\n</fault>";
2049 }
2050 else
2051 {
2052 if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
2053 {
2054 if (is_string($this->val) && $this->valtyp == 'xml')
2055 {
2056 $result .= "<params>\n<param>\n" .
2057 $this->val .
2058 "</param>\n</params>";
2059 }
2060 else
2061 {
2062 /// @todo try to build something serializable?
2063 die('cannot serialize xmlrpcresp objects whose content is native php values');
2064 }
2065 }
2066 else
2067 {
2068 $result .= "<params>\n<param>\n" .
2069 $this->val->serialize($charset_encoding) .
2070 "</param>\n</params>";
2071 }
2072 }
2073 $result .= "\n</methodResponse>";
2074 $this->payload = $result;
2075 return $result;
2076 }
2077 }
2078  
2079 class xmlrpcmsg
2080 {
2081 var $payload;
2082 var $methodname;
2083 var $params=array();
2084 var $debug=0;
2085 var $content_type = 'text/xml';
2086  
2087 /**
2088 * @param string $meth the name of the method to invoke
2089 * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)
2090 */
2091 function xmlrpcmsg($meth, $pars=0)
2092 {
2093 $this->methodname=$meth;
2094 if(is_array($pars) && count($pars)>0)
2095 {
2096 for($i=0; $i<count($pars); $i++)
2097 {
2098 $this->addParam($pars[$i]);
2099 }
2100 }
2101 }
2102  
2103 /**
2104 * @access private
2105 */
2106 function xml_header($charset_encoding='')
2107 {
2108 if ($charset_encoding != '')
2109 {
2110 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
2111 }
2112 else
2113 {
2114 return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
2115 }
2116 }
2117  
2118 /**
2119 * @access private
2120 */
2121 function xml_footer()
2122 {
2123 return '</methodCall>';
2124 }
2125  
2126 /**
2127 * @access private
2128 */
2129 function kindOf()
2130 {
2131 return 'msg';
2132 }
2133  
2134 /**
2135 * @access private
2136 */
2137 function createPayload($charset_encoding='')
2138 {
2139 if ($charset_encoding != '')
2140 $this->content_type = 'text/xml; charset=' . $charset_encoding;
2141 else
2142 $this->content_type = 'text/xml';
2143 $this->payload=$this->xml_header($charset_encoding);
2144 $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
2145 $this->payload.="<params>\n";
2146 for($i=0; $i<count($this->params); $i++)
2147 {
2148 $p=$this->params[$i];
2149 $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
2150 "</param>\n";
2151 }
2152 $this->payload.="</params>\n";
2153 $this->payload.=$this->xml_footer();
2154 }
2155  
2156 /**
2157 * Gets/sets the xmlrpc method to be invoked
2158 * @param string $meth the method to be set (leave empty not to set it)
2159 * @return string the method that will be invoked
2160 * @access public
2161 */
2162 function method($meth='')
2163 {
2164 if($meth!='')
2165 {
2166 $this->methodname=$meth;
2167 }
2168 return $this->methodname;
2169 }
2170  
2171 /**
2172 * Returns xml representation of the message. XML prologue included
2173 * @return string the xml representation of the message, xml prologue included
2174 * @access public
2175 */
2176 function serialize($charset_encoding='')
2177 {
2178 $this->createPayload($charset_encoding);
2179 return $this->payload;
2180 }
2181  
2182 /**
2183 * Add a parameter to the list of parameters to be used upon method invocation
2184 * @param xmlrpcval $par
2185 * @return boolean false on failure
2186 * @access public
2187 */
2188 function addParam($par)
2189 {
2190 // add check: do not add to self params which are not xmlrpcvals
2191 if(is_object($par) && is_a($par, 'xmlrpcval'))
2192 {
2193 $this->params[]=$par;
2194 return true;
2195 }
2196 else
2197 {
2198 return false;
2199 }
2200 }
2201  
2202 /**
2203 * Returns the nth parameter in the message. The index zero-based.
2204 * @param integer $i the index of the parameter to fetch (zero based)
2205 * @return xmlrpcval the i-th parameter
2206 * @access public
2207 */
2208 function getParam($i) { return $this->params[$i]; }
2209  
2210 /**
2211 * Returns the number of parameters in the messge.
2212 * @return integer the number of parameters currently set
2213 * @access public
2214 */
2215 function getNumParams() { return count($this->params); }
2216  
2217 /**
2218 * Given an open file handle, read all data available and parse it as axmlrpc response.
2219 * NB: the file handle is not closed by this function.
2220 * NNB: might have trouble in rare cases to work on network streams, as we
2221 * check for a read of 0 bytes instead of feof($fp).
2222 * But since checking for feof(null) returns false, we would risk an
2223 * infinite loop in that case, because we cannot trust the caller
2224 * to give us a valid pointer to an open file...
2225 * @access public
2226 * @return xmlrpcresp
2227 * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
2228 */
2229 function &parseResponseFile($fp)
2230 {
2231 $ipd='';
2232 while($data=fread($fp, 32768))
2233 {
2234 $ipd.=$data;
2235 }
2236 //fclose($fp);
2237 $r =& $this->parseResponse($ipd);
2238 return $r;
2239 }
2240  
2241 /**
2242 * Parses HTTP headers and separates them from data.
2243 * @access private
2244 */
2245 function &parseResponseHeaders(&$data, $headers_processed=false)
2246 {
2247 // Support "web-proxy-tunelling" connections for https through proxies
2248 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
2249 {
2250 // Look for CR/LF or simple LF as line separator,
2251 // (even though it is not valid http)
2252 $pos = strpos($data,"\r\n\r\n");
2253 if($pos || is_int($pos))
2254 {
2255 $bd = $pos+4;
2256 }
2257 else
2258 {
2259 $pos = strpos($data,"\n\n");
2260 if($pos || is_int($pos))
2261 {
2262 $bd = $pos+2;
2263 }
2264 else
2265 {
2266 // No separation between response headers and body: fault?
2267 $bd = 0;
2268 }
2269 }
2270 if ($bd)
2271 {
2272 // this filters out all http headers from proxy.
2273 // maybe we could take them into account, too?
2274 $data = substr($data, $bd);
2275 }
2276 else
2277 {
2278 error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed');
2279 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
2280 return $r;
2281 }
2282 }
2283  
2284 // Strip HTTP 1.1 100 Continue header if present
2285 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
2286 {
2287 $pos = strpos($data, 'HTTP', 12);
2288 // server sent a Continue header without any (valid) content following...
2289 // give the client a chance to know it
2290 if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
2291 {
2292 break;
2293 }
2294 $data = substr($data, $pos);
2295 }
2296 if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
2297 {
2298 $errstr= substr($data, 0, strpos($data, "\n")-1);
2299 error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);
2300 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
2301 return $r;
2302 }
2303  
2304 $GLOBALS['_xh']['headers'] = array();
2305 $GLOBALS['_xh']['cookies'] = array();
2306  
2307 // be tolerant to usage of \n instead of \r\n to separate headers and data
2308 // (even though it is not valid http)
2309 $pos = strpos($data,"\r\n\r\n");
2310 if($pos || is_int($pos))
2311 {
2312 $bd = $pos+4;
2313 }
2314 else
2315 {
2316 $pos = strpos($data,"\n\n");
2317 if($pos || is_int($pos))
2318 {
2319 $bd = $pos+2;
2320 }
2321 else
2322 {
2323 // No separation between response headers and body: fault?
2324 // we could take some action here instead of going on...
2325 $bd = 0;
2326 }
2327 }
2328 // be tolerant to line endings, and extra empty lines
2329 $ar = split("\r?\n", trim(substr($data, 0, $pos)));
2330 while(list(,$line) = @each($ar))
2331 {
2332 // take care of multi-line headers and cookies
2333 $arr = explode(':',$line,2);
2334 if(count($arr) > 1)
2335 {
2336 $header_name = strtolower(trim($arr[0]));
2337 /// @todo some other headers (the ones that allow a CSV list of values)
2338 /// do allow many values to be passed using multiple header lines.
2339 /// We should add content to $GLOBALS['_xh']['headers'][$header_name]
2340 /// instead of replacing it for those...
2341 if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
2342 {
2343 if ($header_name == 'set-cookie2')
2344 {
2345 // version 2 cookies:
2346 // there could be many cookies on one line, comma separated
2347 $cookies = explode(',', $arr[1]);
2348 }
2349 else
2350 {
2351 $cookies = array($arr[1]);
2352 }
2353 foreach ($cookies as $cookie)
2354 {
2355 // glue together all received cookies, using a comma to separate them
2356 // (same as php does with getallheaders())
2357 if (isset($GLOBALS['_xh']['headers'][$header_name]))
2358 $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
2359 else
2360 $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
2361 // parse cookie attributes, in case user wants to correctly honour them
2362 // feature creep: only allow rfc-compliant cookie attributes?
2363 // @todo support for server sending multiple time cookie with same name, but using different PATHs
2364 $cookie = explode(';', $cookie);
2365 foreach ($cookie as $pos => $val)
2366 {
2367 $val = explode('=', $val, 2);
2368 $tag = trim($val[0]);
2369 $val = trim(@$val[1]);
2370 /// @todo with version 1 cookies, we should strip leading and trailing " chars
2371 if ($pos == 0)
2372 {
2373 $cookiename = $tag;
2374 $GLOBALS['_xh']['cookies'][$tag] = array();
2375 $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
2376 }
2377 else
2378 {
2379 if ($tag != 'value')
2380 {
2381 $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
2382 }
2383 }
2384 }
2385 }
2386 }
2387 else
2388 {
2389 $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
2390 }
2391 }
2392 elseif(isset($header_name))
2393 {
2394 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
2395 $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
2396 }
2397 }
2398  
2399 $data = substr($data, $bd);
2400  
2401 if($this->debug && count($GLOBALS['_xh']['headers']))
2402 {
2403 print '<PRE>';
2404 foreach($GLOBALS['_xh']['headers'] as $header => $value)
2405 {
2406 print htmlentities("HEADER: $header: $value\n");
2407 }
2408 foreach($GLOBALS['_xh']['cookies'] as $header => $value)
2409 {
2410 print htmlentities("COOKIE: $header={$value['value']}\n");
2411 }
2412 print "</PRE>\n";
2413 }
2414  
2415 // if CURL was used for the call, http headers have been processed,
2416 // and dechunking + reinflating have been carried out
2417 if(!$headers_processed)
2418 {
2419 // Decode chunked encoding sent by http 1.1 servers
2420 if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
2421 {
2422 if(!$data = decode_chunked($data))
2423 {
2424 error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');
2425 $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
2426 return $r;
2427 }
2428 }
2429  
2430 // Decode gzip-compressed stuff
2431 // code shamelessly inspired from nusoap library by Dietrich Ayala
2432 if(isset($GLOBALS['_xh']['headers']['content-encoding']))
2433 {
2434 $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
2435 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
2436 {
2437 // if decoding works, use it. else assume data wasn't gzencoded
2438 if(function_exists('gzinflate'))
2439 {
2440 if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
2441 {
2442 $data = $degzdata;
2443 if($this->debug)
2444 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
2445 }
2446 elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
2447 {
2448 $data = $degzdata;
2449 if($this->debug)
2450 print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
2451 }
2452 else
2453 {
2454 error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');
2455 $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
2456 return $r;
2457 }
2458 }
2459 else
2460 {
2461 error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
2462 $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
2463 return $r;
2464 }
2465 }
2466 }
2467 } // end of 'if needed, de-chunk, re-inflate response'
2468  
2469 // real stupid hack to avoid PHP 4 complaining about returning NULL by ref
2470 $r = null;
2471 $r =& $r;
2472 return $r;
2473 }
2474  
2475 /**
2476 * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
2477 * @param string $data the xmlrpc response, eventually including http headers
2478 * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
2479 * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
2480 * @return xmlrpcresp
2481 * @access public
2482 */
2483 function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
2484 {
2485 if($this->debug)
2486 {
2487 //by maHo, replaced htmlspecialchars with htmlentities
2488 print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
2489 }
2490  
2491 if($data == '')
2492 {
2493 error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');
2494 $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);
2495 return $r;
2496 }
2497  
2498 $GLOBALS['_xh']=array();
2499  
2500 $raw_data = $data;
2501 // parse the HTTP headers of the response, if present, and separate them from data
2502 if(substr($data, 0, 4) == 'HTTP')
2503 {
2504 $r =& $this->parseResponseHeaders($data, $headers_processed);
2505 if ($r)
2506 {
2507 // failed processing of HTTP response headers
2508 // save into response obj the full payload received, for debugging
2509 $r->raw_data = $data;
2510 return $r;
2511 }
2512 }
2513 else
2514 {
2515 $GLOBALS['_xh']['headers'] = array();
2516 $GLOBALS['_xh']['cookies'] = array();
2517 }
2518  
2519 if($this->debug)
2520 {
2521 $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
2522 if ($start)
2523 {
2524 $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
2525 $end = strpos($data, '-->', $start);
2526 $comments = substr($data, $start, $end-$start);
2527 print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
2528 }
2529 }
2530  
2531 // be tolerant of extra whitespace in response body
2532 $data = trim($data);
2533  
2534 /// @todo return an error msg if $data=='' ?
2535  
2536 // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
2537 // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
2538 $bd = false;
2539 // Poor man's version of strrpos for php 4...
2540 $pos = strpos($data, '</methodResponse>');
2541 while($pos || is_int($pos))
2542 {
2543 $bd = $pos+17;
2544 $pos = strpos($data, '</methodResponse>', $bd);
2545 }
2546 if($bd)
2547 {
2548 $data = substr($data, 0, $bd);
2549 }
2550  
2551 // if user wants back raw xml, give it to him
2552 if ($return_type == 'xml')
2553 {
2554 $r =& new xmlrpcresp($data, 0, '', 'xml');
2555 $r->hdrs = $GLOBALS['_xh']['headers'];
2556 $r->_cookies = $GLOBALS['_xh']['cookies'];
2557 $r->raw_data = $raw_data;
2558 return $r;
2559 }
2560  
2561 // try to 'guestimate' the character encoding of the received response
2562 $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);
2563  
2564 $GLOBALS['_xh']['ac']='';
2565 //$GLOBALS['_xh']['qt']=''; //unused...
2566 $GLOBALS['_xh']['stack'] = array();
2567 $GLOBALS['_xh']['valuestack'] = array();
2568 $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
2569 $GLOBALS['_xh']['isf_reason']='';
2570 $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'
2571  
2572 // if response charset encoding is not known / supported, try to use
2573 // the default encoding and parse the xml anyway, but log a warning...
2574 if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
2575 // the following code might be better for mb_string enabled installs, but
2576 // makes the lib about 200% slower...
2577 //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
2578 {
2579 error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);
2580 $resp_encoding = $GLOBALS['xmlrpc_defencoding'];
2581 }
2582 $parser = xml_parser_create($resp_encoding);
2583 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
2584 // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
2585 // the xml parser to give us back data in the expected charset.
2586 // What if internal encoding is not in one of the 3 allowed?
2587 // we use the broadest one, ie. utf8
2588 // This allows to send data which is native in various charset,
2589 // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
2590 if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
2591 {
2592 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
2593 }
2594 else
2595 {
2596 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
2597 }
2598  
2599 if ($return_type == 'phpvals')
2600 {
2601 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
2602 }
2603 else
2604 {
2605 xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
2606 }
2607  
2608 xml_set_character_data_handler($parser, 'xmlrpc_cd');
2609 xml_set_default_handler($parser, 'xmlrpc_dh');
2610  
2611 // first error check: xml not well formed
2612 if(!xml_parse($parser, $data, count($data)))
2613 {
2614 // thanks to Peter Kocks <peter.kocks@baygate.com>
2615 if((xml_get_current_line_number($parser)) == 1)
2616 {
2617 $errstr = 'XML error at line 1, check URL';
2618 }
2619 else
2620 {
2621 $errstr = sprintf('XML error: %s at line %d, column %d',
2622 xml_error_string(xml_get_error_code($parser)),
2623 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
2624 }
2625 error_log($errstr);
2626 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');
2627 xml_parser_free($parser);
2628 if($this->debug)
2629 {
2630 print $errstr;
2631 }
2632 $r->hdrs = $GLOBALS['_xh']['headers'];
2633 $r->_cookies = $GLOBALS['_xh']['cookies'];
2634 $r->raw_data = $raw_data;
2635 return $r;
2636 }
2637 xml_parser_free($parser);
2638 // second error check: xml well formed but not xml-rpc compliant
2639 if ($GLOBALS['_xh']['isf'] > 1)
2640 {
2641 if ($this->debug)
2642 {
2643 /// @todo echo something for user?
2644 }
2645  
2646 $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
2647 $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);
2648 }
2649 // third error check: parsing of the response has somehow gone boink.
2650 // NB: shall we omit this check, since we trust the parsing code?
2651 elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))
2652 {
2653 // something odd has happened
2654 // and it's time to generate a client side error
2655 // indicating something odd went on
2656 $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
2657 $GLOBALS['xmlrpcstr']['invalid_return']);
2658 }
2659 else
2660 {
2661 if ($this->debug)
2662 {
2663 print "<PRE>---PARSED---\n";
2664 // somehow htmlentities chokes on var_export, and some full html string...
2665 //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
2666 print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));
2667 print "\n---END---</PRE>";
2668 }
2669  
2670 // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.
2671 $v =& $GLOBALS['_xh']['value'];
2672  
2673 if($GLOBALS['_xh']['isf'])
2674 {
2675 /// @todo we should test here if server sent an int and a string,
2676 /// and/or coerce them into such...
2677 if ($return_type == 'xmlrpcvals')
2678 {
2679 $errno_v = $v->structmem('faultCode');
2680 $errstr_v = $v->structmem('faultString');
2681 $errno = $errno_v->scalarval();
2682 $errstr = $errstr_v->scalarval();
2683 }
2684 else
2685 {
2686 $errno = $v['faultCode'];
2687 $errstr = $v['faultString'];
2688 }
2689  
2690 if($errno == 0)
2691 {
2692 // FAULT returned, errno needs to reflect that
2693 $errno = -1;
2694 }
2695  
2696 $r =& new xmlrpcresp(0, $errno, $errstr);
2697 }
2698 else
2699 {
2700 $r=&new xmlrpcresp($v, 0, '', $return_type);
2701 }
2702 }
2703  
2704 $r->hdrs = $GLOBALS['_xh']['headers'];
2705 $r->_cookies = $GLOBALS['_xh']['cookies'];
2706 $r->raw_data = $raw_data;
2707 return $r;
2708 }
2709 }
2710  
2711 class xmlrpcval
2712 {
2713 var $me=array();
2714 var $mytype=0;
2715 var $_php_class=null;
2716  
2717 /**
2718 * @param mixed $val
2719 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
2720 */
2721 function xmlrpcval($val=-1, $type='')
2722 {
2723 /// @todo: optimization creep - do not call addXX, do it all inline.
2724 /// downside: booleans will not be coerced anymore
2725 if($val!==-1 || $type!='')
2726 {
2727 // optimization creep: inlined all work done by constructor
2728 switch($type)
2729 {
2730 case '':
2731 $this->mytype=1;
2732 $this->me['string']=$val;
2733 break;
2734 case 'i4':
2735 case 'int':
2736 case 'double':
2737 case 'string':
2738 case 'boolean':
2739 case 'dateTime.iso8601':
2740 case 'base64':
2741 case 'null':
2742 $this->mytype=1;
2743 $this->me[$type]=$val;
2744 break;
2745 case 'array':
2746 $this->mytype=2;
2747 $this->me['array']=$val;
2748 break;
2749 case 'struct':
2750 $this->mytype=3;
2751 $this->me['struct']=$val;
2752 break;
2753 default:
2754 error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");
2755 }
2756 /*if($type=='')
2757 {
2758 $type='string';
2759 }
2760 if($GLOBALS['xmlrpcTypes'][$type]==1)
2761 {
2762 $this->addScalar($val,$type);
2763 }
2764 elseif($GLOBALS['xmlrpcTypes'][$type]==2)
2765 {
2766 $this->addArray($val);
2767 }
2768 elseif($GLOBALS['xmlrpcTypes'][$type]==3)
2769 {
2770 $this->addStruct($val);
2771 }*/
2772 }
2773 }
2774  
2775 /**
2776 * Add a single php value to an (unitialized) xmlrpcval
2777 * @param mixed $val
2778 * @param string $type
2779 * @return int 1 or 0 on failure
2780 */
2781 function addScalar($val, $type='string')
2782 {
2783 $typeof=@$GLOBALS['xmlrpcTypes'][$type];
2784 if($typeof!=1)
2785 {
2786 error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");
2787 return 0;
2788 }
2789  
2790 // coerce booleans into correct values
2791 // NB: we should iether do it for datetimes, integers and doubles, too,
2792 // or just plain remove this check, implemnted on booleans only...
2793 if($type==$GLOBALS['xmlrpcBoolean'])
2794 {
2795 if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))
2796 {
2797 $val=true;
2798 }
2799 else
2800 {
2801 $val=false;
2802 }
2803 }
2804  
2805 switch($this->mytype)
2806 {
2807 case 1:
2808 error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');
2809 return 0;
2810 case 3:
2811 error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');
2812 return 0;
2813 case 2:
2814 // we're adding a scalar value to an array here
2815 //$ar=$this->me['array'];
2816 //$ar[]=&new xmlrpcval($val, $type);
2817 //$this->me['array']=$ar;
2818 // Faster (?) avoid all the costly array-copy-by-val done here...
2819 $this->me['array'][]=&new xmlrpcval($val, $type);
2820 return 1;
2821 default:
2822 // a scalar, so set the value and remember we're scalar
2823 $this->me[$type]=$val;
2824 $this->mytype=$typeof;
2825 return 1;
2826 }
2827 }
2828  
2829 /**
2830 * Add an array of xmlrpcval objects to an xmlrpcval
2831 * @param array $vals
2832 * @return int 1 or 0 on failure
2833 * @access public
2834 *
2835 * @todo add some checking for $vals to be an array of xmlrpcvals?
2836 */
2837 function addArray($vals)
2838 {
2839 if($this->mytype==0)
2840 {
2841 $this->mytype=$GLOBALS['xmlrpcTypes']['array'];
2842 $this->me['array']=$vals;
2843 return 1;
2844 }
2845 elseif($this->mytype==2)
2846 {
2847 // we're adding to an array here
2848 $this->me['array'] = array_merge($this->me['array'], $vals);
2849 return 1;
2850 }
2851 else
2852 {
2853 error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']');
2854 return 0;
2855 }
2856 }
2857  
2858 /**
2859 * Add an array of named xmlrpcval objects to an xmlrpcval
2860 * @param array $vals
2861 * @return int 1 or 0 on failure
2862 * @access public
2863 *
2864 * @todo add some checking for $vals to be an array?
2865 */
2866 function addStruct($vals)
2867 {
2868 if($this->mytype==0)
2869 {
2870 $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];
2871 $this->me['struct']=$vals;
2872 return 1;
2873 }
2874 elseif($this->mytype==3)
2875 {
2876 // we're adding to a struct here
2877 $this->me['struct'] = array_merge($this->me['struct'], $vals);
2878 return 1;
2879 }
2880 else
2881 {
2882 error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']');
2883 return 0;
2884 }
2885 }
2886  
2887 // poor man's version of print_r ???
2888 // DEPRECATED!
2889 function dump($ar)
2890 {
2891 foreach($ar as $key => $val)
2892 {
2893 echo "$key => $val<br />";
2894 if($key == 'array')
2895 {
2896 while(list($key2, $val2) = each($val))
2897 {
2898 echo "-- $key2 => $val2<br />";
2899 }
2900 }
2901 }
2902 }
2903  
2904 /**
2905 * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
2906 * @return string
2907 * @access public
2908 */
2909 function kindOf()
2910 {
2911 switch($this->mytype)
2912 {
2913 case 3:
2914 return 'struct';
2915 break;
2916 case 2:
2917 return 'array';
2918 break;
2919 case 1:
2920 return 'scalar';
2921 break;
2922 default:
2923 return 'undef';
2924 }
2925 }
2926  
2927 /**
2928 * @access private
2929 */
2930 function serializedata($typ, $val, $charset_encoding='')
2931 {
2932 $rs='';
2933 switch(@$GLOBALS['xmlrpcTypes'][$typ])
2934 {
2935 case 1:
2936 switch($typ)
2937 {
2938 case $GLOBALS['xmlrpcBase64']:
2939 $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";
2940 break;
2941 case $GLOBALS['xmlrpcBoolean']:
2942 $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
2943 break;
2944 case $GLOBALS['xmlrpcString']:
2945 // G. Giunta 2005/2/13: do NOT use htmlentities, since
2946 // it will produce named html entities, which are invalid xml
2947 $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";
2948 break;
2949 case $GLOBALS['xmlrpcInt']:
2950 case $GLOBALS['xmlrpcI4']:
2951 $rs.="<${typ}>".(int)$val."</${typ}>";
2952 break;
2953 case $GLOBALS['xmlrpcDouble']:
2954 // avoid using standard conversion of float to string because it is locale-dependent,
2955 // and also because the xmlrpc spec forbids exponential notation
2956 // sprintf('%F') would be most likely ok but it is only available since PHP 4.3.10 and PHP 5.0.3.
2957 // The code below tries its best at keeping max precision while avoiding exp notation,
2958 // but there is of course no limit in the number of decimal places to be used...
2959 $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";
2960 break;
2961 case $GLOBALS['xmlrpcNull']:
2962 $rs.="<nil/>";
2963 break;
2964 default:
2965 // no standard type value should arrive here, but provide a possibility
2966 // for xmlrpcvals of unknown type...
2967 $rs.="<${typ}>${val}</${typ}>";
2968 }
2969 break;
2970 case 3:
2971 // struct
2972 if ($this->_php_class)
2973 {
2974 $rs.='<struct php_class="' . $this->_php_class . "\">\n";
2975 }
2976 else
2977 {
2978 $rs.="<struct>\n";
2979 }
2980 foreach($val as $key2 => $val2)
2981 {
2982 $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";
2983 //$rs.=$this->serializeval($val2);
2984 $rs.=$val2->serialize($charset_encoding);
2985 $rs.="</member>\n";
2986 }
2987 $rs.='</struct>';
2988 break;
2989 case 2:
2990 // array
2991 $rs.="<array>\n<data>\n";
2992 for($i=0; $i<count($val); $i++)
2993 {
2994 //$rs.=$this->serializeval($val[$i]);
2995 $rs.=$val[$i]->serialize($charset_encoding);
2996 }
2997 $rs.="</data>\n</array>";
2998 break;
2999 default:
3000 break;
3001 }
3002 return $rs;
3003 }
3004  
3005 /**
3006 * Returns xml representation of the value. XML prologue not included
3007 * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
3008 * @return string
3009 * @access public
3010 */
3011 function serialize($charset_encoding='')
3012 {
3013 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
3014 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
3015 //{
3016 reset($this->me);
3017 list($typ, $val) = each($this->me);
3018 return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";
3019 //}
3020 }
3021  
3022 // DEPRECATED
3023 function serializeval($o)
3024 {
3025 // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
3026 //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
3027 //{
3028 $ar=$o->me;
3029 reset($ar);
3030 list($typ, $val) = each($ar);
3031 return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
3032 //}
3033 }
3034  
3035 /**
3036 * Checks wheter a struct member with a given name is present.
3037 * Works only on xmlrpcvals of type struct.
3038 * @param string $m the name of the struct member to be looked up
3039 * @return boolean
3040 * @access public
3041 */
3042 function structmemexists($m)
3043 {
3044 return array_key_exists($m, $this->me['struct']);
3045 }
3046  
3047 /**
3048 * Returns the value of a given struct member (an xmlrpcval object in itself).
3049 * Will raise a php warning if struct member of given name does not exist
3050 * @param string $m the name of the struct member to be looked up
3051 * @return xmlrpcval
3052 * @access public
3053 */
3054 function structmem($m)
3055 {
3056 return $this->me['struct'][$m];
3057 }
3058  
3059 /**
3060 * Reset internal pointer for xmlrpcvals of type struct.
3061 * @access public
3062 */
3063 function structreset()
3064 {
3065 reset($this->me['struct']);
3066 }
3067  
3068 /**
3069 * Return next member element for xmlrpcvals of type struct.
3070 * @return xmlrpcval
3071 * @access public
3072 */
3073 function structeach()
3074 {
3075 return each($this->me['struct']);
3076 }
3077  
3078 // DEPRECATED! this code looks like it is very fragile and has not been fixed
3079 // for a long long time. Shall we remove it for 2.0?
3080 function getval()
3081 {
3082 // UNSTABLE
3083 reset($this->me);
3084 list($a,$b)=each($this->me);
3085 // contributed by I Sofer, 2001-03-24
3086 // add support for nested arrays to scalarval
3087 // i've created a new method here, so as to
3088 // preserve back compatibility
3089  
3090 if(is_array($b))
3091 {
3092 @reset($b);
3093 while(list($id,$cont) = @each($b))
3094 {
3095 $b[$id] = $cont->scalarval();
3096 }
3097 }
3098  
3099 // add support for structures directly encoding php objects
3100 if(is_object($b))
3101 {
3102 $t = get_object_vars($b);
3103 @reset($t);
3104 while(list($id,$cont) = @each($t))
3105 {
3106 $t[$id] = $cont->scalarval();
3107 }
3108 @reset($t);
3109 while(list($id,$cont) = @each($t))
3110 {
3111 @$b->$id = $cont;
3112 }
3113 }
3114 // end contrib
3115 return $b;
3116 }
3117  
3118 /**
3119 * Returns the value of a scalar xmlrpcval
3120 * @return mixed
3121 * @access public
3122 */
3123 function scalarval()
3124 {
3125 reset($this->me);
3126 list(,$b)=each($this->me);
3127 return $b;
3128 }
3129  
3130 /**
3131 * Returns the type of the xmlrpcval.
3132 * For integers, 'int' is always returned in place of 'i4'
3133 * @return string
3134 * @access public
3135 */
3136 function scalartyp()
3137 {
3138 reset($this->me);
3139 list($a,)=each($this->me);
3140 if($a==$GLOBALS['xmlrpcI4'])
3141 {
3142 $a=$GLOBALS['xmlrpcInt'];
3143 }
3144 return $a;
3145 }
3146  
3147 /**
3148 * Returns the m-th member of an xmlrpcval of struct type
3149 * @param integer $m the index of the value to be retrieved (zero based)
3150 * @return xmlrpcval
3151 * @access public
3152 */
3153 function arraymem($m)
3154 {
3155 return $this->me['array'][$m];
3156 }
3157  
3158 /**
3159 * Returns the number of members in an xmlrpcval of array type
3160 * @return integer
3161 * @access public
3162 */
3163 function arraysize()
3164 {
3165 return count($this->me['array']);
3166 }
3167  
3168 /**
3169 * Returns the number of members in an xmlrpcval of struct type
3170 * @return integer
3171 * @access public
3172 */
3173 function structsize()
3174 {
3175 return count($this->me['struct']);
3176 }
3177 }
3178  
3179  
3180 // date helpers
3181  
3182 /**
3183 * Given a timestamp, return the corresponding ISO8601 encoded string.
3184 *
3185 * Really, timezones ought to be supported
3186 * but the XML-RPC spec says:
3187 *
3188 * "Don't assume a timezone. It should be specified by the server in its
3189 * documentation what assumptions it makes about timezones."
3190 *
3191 * These routines always assume localtime unless
3192 * $utc is set to 1, in which case UTC is assumed
3193 * and an adjustment for locale is made when encoding
3194 *
3195 * @param int $timet (timestamp)
3196 * @param int $utc (0 or 1)
3197 * @return string
3198 */
3199 function iso8601_encode($timet, $utc=0)
3200 {
3201 if(!$utc)
3202 {
3203 $t=strftime("%Y%m%dT%H:%M:%S", $timet);
3204 }
3205 else
3206 {
3207 if(function_exists('gmstrftime'))
3208 {
3209 // gmstrftime doesn't exist in some versions
3210 // of PHP
3211 $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);
3212 }
3213 else
3214 {
3215 $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));
3216 }
3217 }
3218 return $t;
3219 }
3220  
3221 /**
3222 * Given an ISO8601 date string, return a timet in the localtime, or UTC
3223 * @param string $idate
3224 * @param int $utc either 0 or 1
3225 * @return int (datetime)
3226 */
3227 function iso8601_decode($idate, $utc=0)
3228 {
3229 $t=0;
3230 if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))
3231 {
3232 if($utc)
3233 {
3234 $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
3235 }
3236 else
3237 {
3238 $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
3239 }
3240 }
3241 return $t;
3242 }
3243  
3244 /**
3245 * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.
3246 *
3247 * Works with xmlrpc message objects as input, too.
3248 *
3249 * Given proper options parameter, can rebuild generic php object instances
3250 * (provided those have been encoded to xmlrpc format using a corresponding
3251 * option in php_xmlrpc_encode())
3252 * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
3253 * This means that the remote communication end can decide which php code will
3254 * get executed on your server, leaving the door possibly open to 'php-injection'
3255 * style of attacks (provided you have some classes defined on your server that
3256 * might wreak havoc if instances are built outside an appropriate context).
3257 * Make sure you trust the remote server/client before eanbling this!
3258 *
3259 * @author Dan Libby (dan@libby.com)
3260 *
3261 * @param xmlrpcval $xmlrpc_val
3262 * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects
3263 * @return mixed
3264 */
3265 function php_xmlrpc_decode($xmlrpc_val, $options=array())
3266 {
3267 switch($xmlrpc_val->kindOf())
3268 {
3269 case 'scalar':
3270 if (in_array('extension_api', $options))
3271 {
3272 reset($xmlrpc_val->me);
3273 list($typ,$val) = each($xmlrpc_val->me);
3274 switch ($typ)
3275 {
3276 case 'dateTime.iso8601':
3277 $xmlrpc_val->scalar = $val;
3278 $xmlrpc_val->xmlrpc_type = 'datetime';
3279 $xmlrpc_val->timestamp = iso8601_decode($val);
3280 return $xmlrpc_val;
3281 case 'base64':
3282 $xmlrpc_val->scalar = $val;
3283 $xmlrpc_val->type = $typ;
3284 return $xmlrpc_val;
3285 default:
3286 return $xmlrpc_val->scalarval();
3287 }
3288 }
3289 return $xmlrpc_val->scalarval();
3290 case 'array':
3291 $size = $xmlrpc_val->arraysize();
3292 $arr = array();
3293 for($i = 0; $i < $size; $i++)
3294 {
3295 $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);
3296 }
3297 return $arr;
3298 case 'struct':
3299 $xmlrpc_val->structreset();
3300 // If user said so, try to rebuild php objects for specific struct vals.
3301 /// @todo should we raise a warning for class not found?
3302 // shall we check for proper subclass of xmlrpcval instead of
3303 // presence of _php_class to detect what we can do?
3304 if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''
3305 && class_exists($xmlrpc_val->_php_class))
3306 {
3307 $obj = @new $xmlrpc_val->_php_class;
3308 while(list($key,$value)=$xmlrpc_val->structeach())
3309 {
3310 $obj->$key = php_xmlrpc_decode($value, $options);
3311 }
3312 return $obj;
3313 }
3314 else
3315 {
3316 $arr = array();
3317 while(list($key,$value)=$xmlrpc_val->structeach())
3318 {
3319 $arr[$key] = php_xmlrpc_decode($value, $options);
3320 }
3321 return $arr;
3322 }
3323 case 'msg':
3324 $paramcount = $xmlrpc_val->getNumParams();
3325 $arr = array();
3326 for($i = 0; $i < $paramcount; $i++)
3327 {
3328 $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));
3329 }
3330 return $arr;
3331 }
3332 }
3333  
3334 // This constant left here only for historical reasons...
3335 // it was used to decide if we have to define xmlrpc_encode on our own, but
3336 // we do not do it anymore
3337 if(function_exists('xmlrpc_decode'))
3338 {
3339 define('XMLRPC_EPI_ENABLED','1');
3340 }
3341 else
3342 {
3343 define('XMLRPC_EPI_ENABLED','0');
3344 }
3345  
3346 /**
3347 * Takes native php types and encodes them into xmlrpc PHP object format.
3348 * It will not re-encode xmlrpcval objects.
3349 *
3350 * Feature creep -- could support more types via optional type argument
3351 * (string => datetime support has been added, ??? => base64 not yet)
3352 *
3353 * If given a proper options parameter, php object instances will be encoded
3354 * into 'special' xmlrpc values, that can later be decoded into php objects
3355 * by calling php_xmlrpc_decode() with a corresponding option
3356 *
3357 * @author Dan Libby (dan@libby.com)
3358 *
3359 * @param mixed $php_val the value to be converted into an xmlrpcval object
3360 * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
3361 * @return xmlrpcval
3362 */
3363 function &php_xmlrpc_encode($php_val, $options=array())
3364 {
3365 $type = gettype($php_val);
3366 switch($type)
3367 {
3368 case 'string':
3369 if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))
3370 $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);
3371 else
3372 $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);
3373 break;
3374 case 'integer':
3375 $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);
3376 break;
3377 case 'double':
3378 $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);
3379 break;
3380 // <G_Giunta_2001-02-29>
3381 // Add support for encoding/decoding of booleans, since they are supported in PHP
3382 case 'boolean':
3383 $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);
3384 break;
3385 // </G_Giunta_2001-02-29>
3386 case 'array':
3387 // PHP arrays can be encoded to either xmlrpc structs or arrays,
3388 // depending on wheter they are hashes or plain 0..n integer indexed
3389 // A shorter one-liner would be
3390 // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
3391 // but execution time skyrockets!
3392 $j = 0;
3393 $arr = array();
3394 $ko = false;
3395 foreach($php_val as $key => $val)
3396 {
3397 $arr[$key] =& php_xmlrpc_encode($val, $options);
3398 if(!$ko && $key !== $j)
3399 {
3400 $ko = true;
3401 }
3402 $j++;
3403 }
3404 if($ko)
3405 {
3406 $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
3407 }
3408 else
3409 {
3410 $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);
3411 }
3412 break;
3413 case 'object':
3414 if(is_a($php_val, 'xmlrpcval'))
3415 {
3416 $xmlrpc_val = $php_val;
3417 }
3418 else
3419 {
3420 $arr = array();
3421 while(list($k,$v) = each($php_val))
3422 {
3423 $arr[$k] = php_xmlrpc_encode($v, $options);
3424 }
3425 $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
3426 if (in_array('encode_php_objs', $options))
3427 {
3428 // let's save original class name into xmlrpcval:
3429 // might be useful later on...
3430 $xmlrpc_val->_php_class = get_class($php_val);
3431 }
3432 }
3433 break;
3434 case 'NULL':
3435 if (in_array('extension_api', $options))
3436 {
3437 $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcString']);
3438 }
3439 if (in_array('null_extension', $options))
3440 {
3441 $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcNull']);
3442 }
3443 else
3444 {
3445 $xmlrpc_val =& new xmlrpcval();
3446 }
3447 break;
3448 case 'resource':
3449 if (in_array('extension_api', $options))
3450 {
3451 $xmlrpc_val =& new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);
3452 }
3453 else
3454 {
3455 $xmlrpc_val =& new xmlrpcval();
3456 }
3457 // catch "user function", "unknown type"
3458 default:
3459 // giancarlo pinerolo <ping@alt.it>
3460 // it has to return
3461 // an empty object in case, not a boolean.
3462 $xmlrpc_val =& new xmlrpcval();
3463 break;
3464 }
3465 return $xmlrpc_val;
3466 }
3467  
3468 /**
3469 * Convert the xml representation of a method response, method request or single
3470 * xmlrpc value into the appropriate object (a.k.a. deserialize)
3471 * @param string $xml_val
3472 * @param array $options
3473 * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp
3474 */
3475 function php_xmlrpc_decode_xml($xml_val, $options=array())
3476 {
3477 $GLOBALS['_xh'] = array();
3478 $GLOBALS['_xh']['ac'] = '';
3479 $GLOBALS['_xh']['stack'] = array();
3480 $GLOBALS['_xh']['valuestack'] = array();
3481 $GLOBALS['_xh']['params'] = array();
3482 $GLOBALS['_xh']['pt'] = array();
3483 $GLOBALS['_xh']['isf'] = 0;
3484 $GLOBALS['_xh']['isf_reason'] = '';
3485 $GLOBALS['_xh']['method'] = false;
3486 $GLOBALS['_xh']['rt'] = '';
3487 /// @todo 'guestimate' encoding
3488 $parser = xml_parser_create();
3489 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
3490 // What if internal encoding is not in one of the 3 allowed?
3491 // we use the broadest one, ie. utf8!
3492 if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
3493 {
3494 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
3495 }
3496 else
3497 {
3498 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
3499 }
3500 xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
3501 xml_set_character_data_handler($parser, 'xmlrpc_cd');
3502 xml_set_default_handler($parser, 'xmlrpc_dh');
3503 if(!xml_parse($parser, $xml_val, 1))
3504 {
3505 $errstr = sprintf('XML error: %s at line %d, column %d',
3506 xml_error_string(xml_get_error_code($parser)),
3507 xml_get_current_line_number($parser), xml_get_current_column_number($parser));
3508 error_log($errstr);
3509 xml_parser_free($parser);
3510 return false;
3511 }
3512 xml_parser_free($parser);
3513 if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???
3514 {
3515 error_log($GLOBALS['_xh']['isf_reason']);
3516 return false;
3517 }
3518 switch ($GLOBALS['_xh']['rt'])
3519 {
3520 case 'methodresponse':
3521 $v =& $GLOBALS['_xh']['value'];
3522 if ($GLOBALS['_xh']['isf'] == 1)
3523 {
3524 $vc = $v->structmem('faultCode');
3525 $vs = $v->structmem('faultString');
3526 $r =& new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());
3527 }
3528 else
3529 {
3530 $r =& new xmlrpcresp($v);
3531 }
3532 return $r;
3533 case 'methodcall':
3534 $m =& new xmlrpcmsg($GLOBALS['_xh']['method']);
3535 for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)
3536 {
3537 $m->addParam($GLOBALS['_xh']['params'][$i]);
3538 }
3539 return $m;
3540 case 'value':
3541 return $GLOBALS['_xh']['value'];
3542 default:
3543 return false;
3544 }
3545 }
3546  
3547 /**
3548 * decode a string that is encoded w/ "chunked" transfer encoding
3549 * as defined in rfc2068 par. 19.4.6
3550 * code shamelessly stolen from nusoap library by Dietrich Ayala
3551 *
3552 * @param string $buffer the string to be decoded
3553 * @return string
3554 */
3555 function decode_chunked($buffer)
3556 {
3557 // length := 0
3558 $length = 0;
3559 $new = '';
3560  
3561 // read chunk-size, chunk-extension (if any) and crlf
3562 // get the position of the linebreak
3563 $chunkend = strpos($buffer,"\r\n") + 2;
3564 $temp = substr($buffer,0,$chunkend);
3565 $chunk_size = hexdec( trim($temp) );
3566 $chunkstart = $chunkend;
3567 while($chunk_size > 0)
3568 {
3569 $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);
3570  
3571 // just in case we got a broken connection
3572 if($chunkend == false)
3573 {
3574 $chunk = substr($buffer,$chunkstart);
3575 // append chunk-data to entity-body
3576 $new .= $chunk;
3577 $length += strlen($chunk);
3578 break;
3579 }
3580  
3581 // read chunk-data and crlf
3582 $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
3583 // append chunk-data to entity-body
3584 $new .= $chunk;
3585 // length := length + chunk-size
3586 $length += strlen($chunk);
3587 // read chunk-size and crlf
3588 $chunkstart = $chunkend + 2;
3589  
3590 $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;
3591 if($chunkend == false)
3592 {
3593 break; //just in case we got a broken connection
3594 }
3595 $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
3596 $chunk_size = hexdec( trim($temp) );
3597 $chunkstart = $chunkend;
3598 }
3599 return $new;
3600 }
3601  
3602 /**
3603 * xml charset encoding guessing helper function.
3604 * Tries to determine the charset encoding of an XML chunk received over HTTP.
3605 * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
3606 * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
3607 * which will be most probably using UTF-8 anyway...
3608 *
3609 * @param string $httpheaders the http Content-type header
3610 * @param string $xmlchunk xml content buffer
3611 * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)
3612 *
3613 * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
3614 */
3615 function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)
3616 {
3617 // discussion: see http://www.yale.edu/pclt/encoding/
3618 // 1 - test if encoding is specified in HTTP HEADERS
3619  
3620 //Details:
3621 // LWS: (\13\10)?( |\t)+
3622 // token: (any char but excluded stuff)+
3623 // quoted string: " (any char but double quotes and cointrol chars)* "
3624 // header: Content-type = ...; charset=value(; ...)*
3625 // where value is of type token, no LWS allowed between 'charset' and value
3626 // Note: we do not check for invalid chars in VALUE:
3627 // this had better be done using pure ereg as below
3628 // Note 2: we might be removing whitespace/tabs that ought to be left in if
3629 // the received charset is a quoted string. But nobody uses such charset names...
3630  
3631 /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
3632 $matches = array();
3633 if(preg_match('/;\s*charset\s*=([^;]+)/i', $httpheader, $matches))
3634 {
3635 return strtoupper(trim($matches[1], " \t\""));
3636 }
3637  
3638 // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
3639 // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
3640 // NOTE: actually, according to the spec, even if we find the BOM and determine
3641 // an encoding, we should check if there is an encoding specified
3642 // in the xml declaration, and verify if they match.
3643 /// @todo implement check as described above?
3644 /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
3645 if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))
3646 {
3647 return 'UCS-4';
3648 }
3649 elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))
3650 {
3651 return 'UTF-16';
3652 }
3653 elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))
3654 {
3655 return 'UTF-8';
3656 }
3657  
3658 // 3 - test if encoding is specified in the xml declaration
3659 // Details:
3660 // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
3661 // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
3662 if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".
3663 '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
3664 $xmlchunk, $matches))
3665 {
3666 return strtoupper(substr($matches[2], 1, -1));
3667 }
3668  
3669 // 4 - if mbstring is available, let it do the guesswork
3670 // NB: we favour finding an encoding that is compatible with what we can process
3671 if(extension_loaded('mbstring'))
3672 {
3673 if($encoding_prefs)
3674 {
3675 $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);
3676 }
3677 else
3678 {
3679 $enc = mb_detect_encoding($xmlchunk);
3680 }
3681 // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
3682 // IANA also likes better US-ASCII, so go with it
3683 if($enc == 'ASCII')
3684 {
3685 $enc = 'US-'.$enc;
3686 }
3687 return $enc;
3688 }
3689 else
3690 {
3691 // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
3692 // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
3693 // this should be the standard. And we should be getting text/xml as request and response.
3694 // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
3695 return $GLOBALS['xmlrpc_defencoding'];
3696 }
3697 }
3698  
3699 /**
3700 * Checks if a given charset encoding is present in a list of encodings or
3701 * if it is a valid subset of any encoding in the list
3702 * @param string $encoding charset to be tested
3703 * @param mixed $validlist comma separated list of valid charsets (or array of charsets)
3704 */
3705 function is_valid_charset($encoding, $validlist)
3706 {
3707 $charset_supersets = array(
3708 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
3709 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
3710 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
3711 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
3712 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')
3713 );
3714 if (is_string($validlist))
3715 $validlist = explode(',', $validlist);
3716 if (@in_array(strtoupper($encoding), $validlist))
3717 return true;
3718 else
3719 {
3720 if (array_key_exists($encoding, $charset_supersets))
3721 foreach ($validlist as $allowed)
3722 if (in_array($allowed, $charset_supersets[$encoding]))
3723 return true;
3724 return false;
3725 }
3726 }
3727  
3728 ?>