PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/php_xmlrpc/xmlrpc.inc

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
PHP | 2143 lines | 1520 code | 109 blank | 514 comment | 262 complexity | 621dba3017b7a068d0755e2bf315e0df MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, GPL-3.0, GPL-2.0, AGPL-3.0, JSON, BSD-3-Clause
  1. <?php
  2. // by Edd Dumbill (C) 1999-2002
  3. // <edd@usefulinc.com>
  4. // $Id: xmlrpc.inc,v 1.174 2009/03/16 19:36:38 ggiunta Exp $
  5. // Copyright (c) 1999,2000,2002 Edd Dumbill.
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // * Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // * Neither the name of the "XML-RPC for PHP" nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  33. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  34. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  35. // OF THE POSSIBILITY OF SUCH DAMAGE.
  36. if(!function_exists('xml_parser_create'))
  37. {
  38. // For PHP 4 onward, XML functionality is always compiled-in on windows:
  39. // no more need to dl-open it. It might have been compiled out on *nix...
  40. if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
  41. {
  42. dl('xml.so');
  43. }
  44. }
  45. // Try to be backward compat with php < 4.2 (are we not being nice ?)
  46. $phpversion = phpversion();
  47. if($phpversion[0] == '4' && $phpversion[2] < 2)
  48. {
  49. // give an opportunity to user to specify where to include other files from
  50. if(!defined('PHP_XMLRPC_COMPAT_DIR'))
  51. {
  52. define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
  53. }
  54. if($phpversion[2] == '0')
  55. {
  56. if($phpversion[4] < 6)
  57. {
  58. include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
  59. }
  60. include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
  61. include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
  62. include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
  63. }
  64. include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
  65. include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
  66. }
  67. // G. Giunta 2005/01/29: declare global these variables,
  68. // so that xmlrpc.inc will work even if included from within a function
  69. // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
  70. $GLOBALS['xmlrpcI4']='i4';
  71. $GLOBALS['xmlrpcInt']='int';
  72. $GLOBALS['xmlrpcBoolean']='boolean';
  73. $GLOBALS['xmlrpcDouble']='double';
  74. $GLOBALS['xmlrpcString']='string';
  75. $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
  76. $GLOBALS['xmlrpcBase64']='base64';
  77. $GLOBALS['xmlrpcArray']='array';
  78. $GLOBALS['xmlrpcStruct']='struct';
  79. $GLOBALS['xmlrpcValue']='undefined';
  80. $GLOBALS['xmlrpcTypes']=array(
  81. $GLOBALS['xmlrpcI4'] => 1,
  82. $GLOBALS['xmlrpcInt'] => 1,
  83. $GLOBALS['xmlrpcBoolean'] => 1,
  84. $GLOBALS['xmlrpcString'] => 1,
  85. $GLOBALS['xmlrpcDouble'] => 1,
  86. $GLOBALS['xmlrpcDateTime'] => 1,
  87. $GLOBALS['xmlrpcBase64'] => 1,
  88. $GLOBALS['xmlrpcArray'] => 2,
  89. $GLOBALS['xmlrpcStruct'] => 3
  90. );
  91. $GLOBALS['xmlrpc_valid_parents'] = array(
  92. 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
  93. 'BOOLEAN' => array('VALUE'),
  94. 'I4' => array('VALUE'),
  95. 'INT' => array('VALUE'),
  96. 'STRING' => array('VALUE'),
  97. 'DOUBLE' => array('VALUE'),
  98. 'DATETIME.ISO8601' => array('VALUE'),
  99. 'BASE64' => array('VALUE'),
  100. 'MEMBER' => array('STRUCT'),
  101. 'NAME' => array('MEMBER'),
  102. 'DATA' => array('ARRAY'),
  103. 'ARRAY' => array('VALUE'),
  104. 'STRUCT' => array('VALUE'),
  105. 'PARAM' => array('PARAMS'),
  106. 'METHODNAME' => array('METHODCALL'),
  107. 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
  108. 'FAULT' => array('METHODRESPONSE'),
  109. 'NIL' => array('VALUE') // only used when extension activated
  110. );
  111. // define extra types for supporting NULL (useful for json or <NIL/>)
  112. $GLOBALS['xmlrpcNull']='null';
  113. $GLOBALS['xmlrpcTypes']['null']=1;
  114. // Not in use anymore since 2.0. Shall we remove it?
  115. /// @deprecated
  116. $GLOBALS['xmlEntities']=array(
  117. 'amp' => '&',
  118. 'quot' => '"',
  119. 'lt' => '<',
  120. 'gt' => '>',
  121. 'apos' => "'"
  122. );
  123. // tables used for transcoding different charsets into us-ascii xml
  124. $GLOBALS['xml_iso88591_Entities']=array();
  125. $GLOBALS['xml_iso88591_Entities']['in'] = array();
  126. $GLOBALS['xml_iso88591_Entities']['out'] = array();
  127. for ($i = 0; $i < 32; $i++)
  128. {
  129. $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
  130. $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
  131. }
  132. for ($i = 160; $i < 256; $i++)
  133. {
  134. $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
  135. $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
  136. }
  137. /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
  138. /// These will NOT be present in true ISO-8859-1, but will save the unwary
  139. /// windows user from sending junk (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.2';
  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 & 15);
  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 & 7);
  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($GLOBALS['_xh']['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. fclose($fp);
  1314. $this->errstr='Write error';
  1315. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);
  1316. return $r;
  1317. }
  1318. else
  1319. {
  1320. // reset errno and errstr on succesful socket connection
  1321. $this->errstr = '';
  1322. }
  1323. // G. Giunta 2005/10/24: close socket before parsing.
  1324. // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
  1325. $ipd='';
  1326. do
  1327. {
  1328. // shall we check for $data === FALSE?
  1329. // as per the manual, it signals an error
  1330. $ipd.=fread($fp, 32768);
  1331. } while(!feof($fp));
  1332. fclose($fp);
  1333. $r =& $msg->parseResponse($ipd, false, $this->return_type);
  1334. return $r;
  1335. }
  1336. /**
  1337. * @access private
  1338. */
  1339. function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
  1340. $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
  1341. $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
  1342. $keepalive=false, $key='', $keypass='')
  1343. {
  1344. $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
  1345. $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
  1346. $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
  1347. return $r;
  1348. }
  1349. /**
  1350. * Contributed by Justin Miller <justin@voxel.net>
  1351. * Requires curl to be built into PHP
  1352. * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
  1353. * @access private
  1354. */
  1355. function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
  1356. $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
  1357. $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
  1358. $keepalive=false, $key='', $keypass='')
  1359. {
  1360. if(!function_exists('curl_init'))
  1361. {
  1362. $this->errstr='CURL unavailable on this install';
  1363. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);
  1364. return $r;
  1365. }
  1366. if($method == 'https')
  1367. {
  1368. if(($info = curl_version()) &&
  1369. ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
  1370. {
  1371. $this->errstr='SSL unavailable on this install';
  1372. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);
  1373. return $r;
  1374. }
  1375. }
  1376. if($port == 0)
  1377. {
  1378. if($method == 'http')
  1379. {
  1380. $port = 80;
  1381. }
  1382. else
  1383. {
  1384. $port = 443;
  1385. }
  1386. }
  1387. // Only create the payload if it was not created previously
  1388. if(empty($msg->payload))
  1389. {
  1390. $msg->createPayload($this->request_charset_encoding);
  1391. }
  1392. // Deflate request body and set appropriate request headers
  1393. $payload = $msg->payload;
  1394. if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
  1395. {
  1396. if($this->request_compression == 'gzip')
  1397. {
  1398. $a = @gzencode($payload);
  1399. if($a)
  1400. {
  1401. $payload = $a;
  1402. $encoding_hdr = 'Content-Encoding: gzip';
  1403. }
  1404. }
  1405. else
  1406. {
  1407. $a = @gzcompress($payload);
  1408. if($a)
  1409. {
  1410. $payload = $a;
  1411. $encoding_hdr = 'Content-Encoding: deflate';
  1412. }
  1413. }
  1414. }
  1415. else
  1416. {
  1417. $encoding_hdr = '';
  1418. }
  1419. if($this->debug > 1)
  1420. {
  1421. print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
  1422. // let the client see this now in case http times out...
  1423. flush();
  1424. }
  1425. if(!$keepalive || !$this->xmlrpc_curl_handle)
  1426. {
  1427. $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
  1428. if($keepalive)
  1429. {
  1430. $this->xmlrpc_curl_handle = $curl;
  1431. }
  1432. }
  1433. else
  1434. {
  1435. $curl = $this->xmlrpc_curl_handle;
  1436. }
  1437. // results into variable
  1438. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1439. if($this->debug)
  1440. {
  1441. curl_setopt($curl, CURLOPT_VERBOSE, 1);
  1442. }
  1443. curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);
  1444. // required for XMLRPC: post the data
  1445. curl_setopt($curl, CURLOPT_POST, 1);
  1446. // the data
  1447. curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
  1448. // return the header too
  1449. curl_setopt($curl, CURLOPT_HEADER, 1);
  1450. // will only work with PHP >= 5.0
  1451. // NB: if we set an empty string, CURL will add http header indicating
  1452. // ALL methods it is supporting. This is possibly a better option than
  1453. // letting the user tell what curl can / cannot do...
  1454. if(is_array($this->accepted_compression) && count($this->accepted_compression))
  1455. {
  1456. //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
  1457. // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1458. if (count($this->accepted_compression) == 1)
  1459. {
  1460. curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
  1461. }
  1462. else
  1463. curl_setopt($curl, CURLOPT_ENCODING, '');
  1464. }
  1465. // extra headers
  1466. $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
  1467. // if no keepalive is wanted, let the server know it in advance
  1468. if(!$keepalive)
  1469. {
  1470. $headers[] = 'Connection: close';
  1471. }
  1472. // request compression header
  1473. if($encoding_hdr)
  1474. {
  1475. $headers[] = $encoding_hdr;
  1476. }
  1477. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  1478. // timeout is borked
  1479. if($timeout)
  1480. {
  1481. curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
  1482. }
  1483. if($username && $password)
  1484. {
  1485. curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
  1486. if (defined('CURLOPT_HTTPAUTH'))
  1487. {
  1488. curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
  1489. }
  1490. else if ($authtype != 1)
  1491. {
  1492. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');
  1493. }
  1494. }
  1495. if($method == 'https')
  1496. {
  1497. // set cert file
  1498. if($cert)
  1499. {
  1500. curl_setopt($curl, CURLOPT_SSLCERT, $cert);
  1501. }
  1502. // set cert password
  1503. if($certpass)
  1504. {
  1505. curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
  1506. }
  1507. // whether to verify remote host's cert
  1508. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
  1509. // set ca certificates file/dir
  1510. if($cacert)
  1511. {
  1512. curl_setopt($curl, CURLOPT_CAINFO, $cacert);
  1513. }
  1514. if($cacertdir)
  1515. {
  1516. curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
  1517. }
  1518. // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1519. if($key)
  1520. {
  1521. curl_setopt($curl, CURLOPT_SSLKEY, $key);
  1522. }
  1523. // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1524. if($keypass)
  1525. {
  1526. curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
  1527. }
  1528. // 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
  1529. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
  1530. }
  1531. // proxy info
  1532. if($proxyhost)
  1533. {
  1534. if($proxyport == 0)
  1535. {
  1536. $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
  1537. }
  1538. curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);
  1539. //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
  1540. if($proxyusername)
  1541. {
  1542. curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
  1543. if (defined('CURLOPT_PROXYAUTH'))
  1544. {
  1545. curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
  1546. }
  1547. else if ($proxyauthtype != 1)
  1548. {
  1549. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');
  1550. }
  1551. }
  1552. }
  1553. // NB: should we build cookie http headers by hand rather than let CURL do it?
  1554. // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
  1555. // set to client obj the the user...
  1556. if (count($this->cookies))
  1557. {
  1558. $cookieheader = '';
  1559. foreach ($this->cookies as $name => $cookie)
  1560. {
  1561. $cookieheader .= $name . '=' . $cookie['value'] . '; ';
  1562. }
  1563. curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
  1564. }
  1565. $result = curl_exec($curl);
  1566. if ($this->debug > 1)
  1567. {
  1568. print "<PRE>\n---CURL INFO---\n";
  1569. foreach(curl_getinfo($curl) as $name => $val)
  1570. print $name . ': ' . htmlentities($val). "\n";
  1571. print "---END---\n</PRE>";
  1572. }
  1573. if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?
  1574. {
  1575. $this->errstr='no response';
  1576. $resp=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));
  1577. curl_close($curl);
  1578. if($keepalive)
  1579. {
  1580. $this->xmlrpc_curl_handle = null;
  1581. }
  1582. }
  1583. else
  1584. {
  1585. if(!$keepalive)
  1586. {
  1587. curl_close($curl);
  1588. }
  1589. $resp =& $msg->parseResponse($result, true, $this->return_type);
  1590. }
  1591. return $resp;
  1592. }
  1593. /**
  1594. * Send an array of request messages and return an array of responses.
  1595. * Unless $this->no_multicall has been set to true, it will try first
  1596. * to use one single xmlrpc call to server method system.multicall, and
  1597. * revert to sending many successive calls in case of failure.
  1598. * This failure is also stored in $this->no_multicall for subsequent calls.
  1599. * Unfortunately, there is no server error code universally used to denote
  1600. * the fact that multicall is unsupported, so there is no way to reliably
  1601. * distinguish between that and a temporary failure.
  1602. * If you are sure that server supports multicall and do not want to
  1603. * fallback to using many single calls, set the fourth parameter to FALSE.
  1604. *
  1605. * NB: trying to shoehorn extra functionality into existing syntax has resulted
  1606. * in pretty much convoluted code...
  1607. *
  1608. * @param array $msgs an array of xmlrpcmsg objects
  1609. * @param integer $timeout connection timeout (in seconds)
  1610. * @param string $method the http protocol variant to be used
  1611. * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted
  1612. * @return array
  1613. * @access public
  1614. */
  1615. function multicall($msgs, $timeout=0, $method='', $fallback=true)
  1616. {
  1617. if ($method == '')
  1618. {
  1619. $method = $this->method;
  1620. }
  1621. if(!$this->no_multicall)
  1622. {
  1623. $results = $this->_try_multicall($msgs, $timeout, $method);
  1624. if(is_array($results))
  1625. {
  1626. // System.multicall succeeded
  1627. return $results;
  1628. }
  1629. else
  1630. {
  1631. // either system.multicall is unsupported by server,
  1632. // or call failed for some other reason.
  1633. if ($fallback)
  1634. {
  1635. // Don't try it next time...
  1636. $this->no_multicall = true;
  1637. }
  1638. else
  1639. {
  1640. if (is_a($results, 'xmlrpcresp'))
  1641. {
  1642. $result = $results;
  1643. }
  1644. else
  1645. {
  1646. $result =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. else
  1652. {
  1653. // override fallback, in case careless user tries to do two
  1654. // opposite things at the same time
  1655. $fallback = true;
  1656. }
  1657. $results = array();
  1658. if ($fallback)
  1659. {
  1660. // system.multicall is (probably) unsupported by server:
  1661. // emulate multicall via multiple requests
  1662. foreach($msgs as $msg)
  1663. {
  1664. $results[] =& $this->send($msg, $timeout, $method);
  1665. }
  1666. }
  1667. else
  1668. {
  1669. // user does NOT want to fallback on many single calls:
  1670. // since we should always return an array of responses,
  1671. // return an array with the same error repeated n times
  1672. foreach($msgs as $msg)
  1673. {
  1674. $results[] = $result;
  1675. }
  1676. }
  1677. return $results;
  1678. }
  1679. /**
  1680. * Attempt to boxcar $msgs via system.multicall.
  1681. * Returns either an array of xmlrpcreponses, an xmlrpc error response
  1682. * or false (when received response does not respect valid multicall syntax)
  1683. * @access private
  1684. */
  1685. function _try_multicall($msgs, $timeout, $method)
  1686. {
  1687. // Construct multicall message
  1688. $calls = array();
  1689. foreach($msgs as $msg)
  1690. {
  1691. $call['methodName'] =& new xmlrpcval($msg->method(),'string');
  1692. $numParams = $msg->getNumParams();
  1693. $params = array();
  1694. for($i = 0; $i < $numParams; $i++)
  1695. {
  1696. $params[$i] = $msg->getParam($i);
  1697. }
  1698. $call['params'] =& new xmlrpcval($params, 'array');
  1699. $calls[] =& new xmlrpcval($call, 'struct');
  1700. }
  1701. $multicall =& new xmlrpcmsg('system.multicall');
  1702. $multicall->addParam(new xmlrpcval($calls, 'array'));
  1703. // Attempt RPC call
  1704. $result =& $this->send($multicall, $timeout, $method);
  1705. if($result->faultCode() != 0)
  1706. {
  1707. // call to system.multicall failed
  1708. return $result;
  1709. }
  1710. // Unpack responses.
  1711. $rets = $result->value();
  1712. if ($this->return_type == 'xml')
  1713. {
  1714. return $rets;
  1715. }
  1716. else if ($this->return_type == 'phpvals')
  1717. {
  1718. ///@todo test this code branch...
  1719. $rets = $result->value();
  1720. if(!is_array($rets))
  1721. {
  1722. return false; // bad return type from system.multicall
  1723. }
  1724. $numRets = count($rets);
  1725. if($numRets != count($msgs))
  1726. {
  1727. return false; // wrong number of return values.
  1728. }
  1729. $response = array();
  1730. for($i = 0; $i < $numRets; $i++)
  1731. {
  1732. $val = $rets[$i];
  1733. if (!is_array($val)) {
  1734. return false;
  1735. }
  1736. switch(count($val))
  1737. {
  1738. case 1:
  1739. if(!isset($val[0]))
  1740. {
  1741. return false; // Bad value
  1742. }
  1743. // Normal return value
  1744. $response[$i] =& new xmlrpcresp($val[0], 0, '', 'phpvals');
  1745. break;
  1746. case 2:
  1747. /// @todo remove usage of @: it is apparently quite slow
  1748. $code = @$val['faultCode'];
  1749. if(!is_int($code))
  1750. {
  1751. return false;
  1752. }
  1753. $str = @$val['faultString'];
  1754. if(!is_string($str))
  1755. {
  1756. return false;
  1757. }
  1758. $response[$i] =& new xmlrpcresp(0, $code, $str);
  1759. break;
  1760. default:
  1761. return false;
  1762. }
  1763. }
  1764. return $response;
  1765. }
  1766. else // return type == 'xmlrpcvals'
  1767. {
  1768. $rets = $result->value();
  1769. if($rets->kindOf() != 'array')
  1770. {
  1771. return false; // bad return type from system.multicall
  1772. }
  1773. $numRets = $rets->arraysize();
  1774. if($numRets != count($msgs))
  1775. {
  1776. return false; // wrong number of return values.
  1777. }
  1778. $response = array();
  1779. for($i = 0; $i < $numRets; $i++)
  1780. {
  1781. $val = $rets->arraymem($i);
  1782. switch($val->kindOf())
  1783. {
  1784. case 'array':
  1785. if($val->arraysize() != 1)
  1786. {
  1787. return false; // Bad value
  1788. }
  1789. // Normal return value
  1790. $response[$i] =& new xmlrpcresp($val->arraymem(0));
  1791. break;
  1792. case 'struct':
  1793. $code = $val->structmem('faultCode');
  1794. if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
  1795. {
  1796. return false;
  1797. }
  1798. $str = $val->structmem('faultString');
  1799. if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
  1800. {
  1801. return false;
  1802. }
  1803. $response[$i] =& new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
  1804. break;
  1805. default:
  1806. return false;
  1807. }
  1808. }
  1809. return $response;
  1810. }
  1811. }
  1812. } // end class xmlrpc_client
  1813. class xmlrpcresp
  1814. {
  1815. var $val = 0;
  1816. var $valtyp;
  1817. var $errno = 0;
  1818. var $errstr = '';
  1819. var $payload;
  1820. var $hdrs = array();
  1821. var $_cookies = array();
  1822. var $content_type = 'text/xml';
  1823. var $raw_data = '';
  1824. /**
  1825. * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
  1826. * @param integer $fcode set it to anything but 0 to create an error response
  1827. * @param string $fstr the error string, in case of an error response
  1828. * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
  1829. *
  1830. * @todo add check that $val / $fcode / $fstr is of correct type???
  1831. * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
  1832. * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
  1833. */
  1834. function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')
  1835. {
  1836. if($fcode != 0)
  1837. {
  1838. // error response
  1839. $this->errno = $fcode;
  1840. $this->errstr = $fstr;
  1841. //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
  1842. }
  1843. else
  1844. {
  1845. // successful response
  1846. $this->val = $val;
  1847. if ($valtyp == '')
  1848. {
  1849. // user did not declare type of response value: try to guess it
  1850. if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))
  1851. {
  1852. $this->valtyp = 'xmlrpcvals';
  1853. }
  1854. else if (is_string($this->val))
  1855. {
  1856. $this->valtyp = 'xml';
  1857. }
  1858. else
  1859. {
  1860. $this->valtyp = 'phpvals';
  1861. }
  1862. }
  1863. else
  1864. {
  1865. // user declares type of resp value: believe him
  1866. $this->valtyp = $valtyp;
  1867. }
  1868. }
  1869. }
  1870. /**
  1871. * Returns the error code of the response.
  1872. * @return integer the error code of this response (0 for not-error responses)
  1873. * @access public
  1874. */
  1875. function faultCode()
  1876. {
  1877. return $this->errno;
  1878. }
  1879. /**
  1880. * Returns the error code of the response.
  1881. * @return string the error string of this response ('' for not-error responses)
  1882. * @access public
  1883. */
  1884. function faultString()
  1885. {
  1886. return $this->errstr;
  1887. }
  1888. /**
  1889. * Returns the value received by the server.
  1890. * @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
  1891. * @access public
  1892. */
  1893. function value()
  1894. {
  1895. return $this->val;
  1896. }
  1897. /**
  1898. * Returns an array with the cookies received from the server.
  1899. * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
  1900. * with attributes being e.g. 'expires', 'path', domain'.
  1901. * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
  1902. * are still present in the array. It is up to the user-defined code to decide
  1903. * how to use the received cookies, and wheter they have to be sent back with the next
  1904. * request to the server (using xmlrpc_client::setCookie) or not
  1905. * @return array array of cookies received from the server
  1906. * @access public
  1907. */
  1908. function cookies()
  1909. {
  1910. return $this->_cookies;
  1911. }
  1912. /**
  1913. * Returns xml representation of the response. XML prologue not included
  1914. * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
  1915. * @return string the xml representation of the response
  1916. * @access public
  1917. */
  1918. function serialize($charset_encoding='')
  1919. {
  1920. if ($charset_encoding != '')
  1921. $this->content_type = 'text/xml; charset=' . $charset_encoding;
  1922. else
  1923. $this->content_type = 'text/xml';
  1924. $result = "<methodResponse>\n";
  1925. if($this->errno)
  1926. {
  1927. // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
  1928. // by xml-encoding non ascii chars
  1929. $result .= "<fault>\n" .
  1930. "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
  1931. "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
  1932. xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
  1933. "</struct>\n</value>\n</fault>";
  1934. }
  1935. else
  1936. {
  1937. if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
  1938. {
  1939. if (is_string($this->val) && $this->valtyp == 'xml')
  1940. {
  1941. $result .= "<params>\n<param>\n" .
  1942. $this->val .
  1943. "</param>\n</params>";
  1944. }
  1945. else
  1946. {
  1947. /// @todo try to build something serializable?
  1948. die('cannot serialize xmlrpcresp objects whose content is native php values');
  1949. }
  1950. }
  1951. else
  1952. {
  1953. $result .= "<params>\n<param>\n" .
  1954. $this->val->serialize($charset_encoding) .
  1955. "</param>\n</params>";
  1956. }
  1957. }
  1958. $result .= "\n</methodResponse>";
  1959. $this->payload = $result;
  1960. return $result;
  1961. }
  1962. }
  1963. class xmlrpcmsg
  1964. {
  1965. var $payload;
  1966. var $methodname;
  1967. var $params=array();
  1968. var $debug=0;
  1969. var $content_type = 'text/xml';
  1970. /**
  1971. * @param string $meth the name of the method to invoke
  1972. * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)
  1973. */
  1974. function xmlrpcmsg($meth, $pars=0)
  1975. {
  1976. $this->methodname=$meth;
  1977. if(is_array($pars) && count($pars)>0)
  1978. {
  1979. for($i=0; $i<count($pars); $i++)
  1980. {
  1981. $this->addParam($pars[$i]);
  1982. }
  1983. }
  1984. }
  1985. /**
  1986. * @access private
  1987. */
  1988. function xml_header($charset_encoding='')
  1989. {
  1990. if ($charset_encoding != '')
  1991. {
  1992. return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
  1993. }
  1994. else
  1995. {
  1996. return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
  1997. }
  1998. }
  1999. /**
  2000. * @access private
  2001. */
  2002. function xml_footer()
  2003. {
  2004. return '</methodCall>';
  2005. }
  2006. /**
  2007. * @access private
  2008. */
  2009. function kindOf()
  2010. {
  2011. return 'msg';
  2012. }
  2013. /**
  2014. * @access private
  2015. */
  2016. function createPayload($charset_encoding='')
  2017. {
  2018. if ($charset_encoding != '')
  2019. $this->content_type = 'text/xml; charset=' . $charset_encoding;
  2020. else
  2021. $this->content_type = 'text/xml';
  2022. $this->payload=$this->xml_header($charset_encoding);
  2023. $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
  2024. $this->payload.="<params>\n";
  2025. for($i=0; $i<count($this->params); $i++)
  2026. {
  2027. $p=$this->params[$i];
  2028. $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
  2029. "</param>\n";
  2030. }
  2031. $this->payload.="</params>\n";
  2032. $this->payload.=