PageRenderTime 33ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/lib/xmlrpc/xmlrpc.inc

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