PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/phpxmlrpc/xmlrpc.php

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