PageRenderTime 75ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/library/xmlrpc/xmlrpc/lib/xmlrpc.inc

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