PageRenderTime 62ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/wishlist-member/extlib/xmlrpc.php

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