xmlrpcs.inc 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. <?php
  2. // by Edd Dumbill (C) 1999-2002
  3. // <edd@usefulinc.com>
  4. // $Id: xmlrpcs.inc,v 1.71 2008/10/29 23:41:28 ggiunta Exp $
  5. // Copyright (c) 1999,2000,2002 Edd Dumbill.
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // * Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // * Neither the name of the "XML-RPC for PHP" nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  33. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  34. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  35. // OF THE POSSIBILITY OF SUCH DAMAGE.
  36. // XML RPC Server class
  37. // requires: xmlrpc.inc
  38. $GLOBALS['xmlrpcs_capabilities'] = array(
  39. // xmlrpc spec: always supported
  40. 'xmlrpc' => new xmlrpcval(array(
  41. 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'),
  42. 'specVersion' => new xmlrpcval(1, 'int')
  43. ), 'struct'),
  44. // if we support system.xxx functions, we always support multicall, too...
  45. // Note that, as of 2006/09/17, the following URL does not respond anymore
  46. 'system.multicall' => new xmlrpcval(array(
  47. 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
  48. 'specVersion' => new xmlrpcval(1, 'int')
  49. ), 'struct'),
  50. // introspection: version 2! we support 'mixed', too
  51. 'introspection' => new xmlrpcval(array(
  52. 'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
  53. 'specVersion' => new xmlrpcval(2, 'int')
  54. ), 'struct')
  55. );
  56. /* Functions that implement system.XXX methods of xmlrpc servers */
  57. $_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct']));
  58. $_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to';
  59. $_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec'));
  60. function _xmlrpcs_getCapabilities($server, $m=null)
  61. {
  62. $outAr = $GLOBALS['xmlrpcs_capabilities'];
  63. // NIL extension
  64. if ($GLOBALS['xmlrpc_null_extension']) {
  65. $outAr['nil'] = new xmlrpcval(array(
  66. 'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
  67. 'specVersion' => new xmlrpcval(1, 'int')
  68. ), 'struct');
  69. }
  70. return new xmlrpcresp(new xmlrpcval($outAr, 'struct'));
  71. }
  72. // listMethods: signature was either a string, or nothing.
  73. // The useless string variant has been removed
  74. $_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray']));
  75. $_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch';
  76. $_xmlrpcs_listMethods_sdoc=array(array('list of method names'));
  77. function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
  78. {
  79. $outAr=array();
  80. foreach($server->dmap as $key => $val)
  81. {
  82. $outAr[]=new xmlrpcval($key, 'string');
  83. }
  84. if($server->allow_system_funcs)
  85. {
  86. foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val)
  87. {
  88. $outAr[]=new xmlrpcval($key, 'string');
  89. }
  90. }
  91. return new xmlrpcresp(new xmlrpcval($outAr, 'array'));
  92. }
  93. $_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString']));
  94. $_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)';
  95. $_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described'));
  96. function _xmlrpcs_methodSignature($server, $m)
  97. {
  98. // let accept as parameter both an xmlrpcval or string
  99. if (is_object($m))
  100. {
  101. $methName=$m->getParam(0);
  102. $methName=$methName->scalarval();
  103. }
  104. else
  105. {
  106. $methName=$m;
  107. }
  108. if(strpos($methName, "system.") === 0)
  109. {
  110. $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;
  111. }
  112. else
  113. {
  114. $dmap=$server->dmap; $sysCall=0;
  115. }
  116. if(isset($dmap[$methName]))
  117. {
  118. if(isset($dmap[$methName]['signature']))
  119. {
  120. $sigs=array();
  121. foreach($dmap[$methName]['signature'] as $inSig)
  122. {
  123. $cursig=array();
  124. foreach($inSig as $sig)
  125. {
  126. $cursig[]=new xmlrpcval($sig, 'string');
  127. }
  128. $sigs[]=new xmlrpcval($cursig, 'array');
  129. }
  130. $r=new xmlrpcresp(new xmlrpcval($sigs, 'array'));
  131. }
  132. else
  133. {
  134. // NB: according to the official docs, we should be returning a
  135. // "none-array" here, which means not-an-array
  136. $r=new xmlrpcresp(new xmlrpcval('undef', 'string'));
  137. }
  138. }
  139. else
  140. {
  141. $r=new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);
  142. }
  143. return $r;
  144. }
  145. $_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString']));
  146. $_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string';
  147. $_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described'));
  148. function _xmlrpcs_methodHelp($server, $m)
  149. {
  150. // let accept as parameter both an xmlrpcval or string
  151. if (is_object($m))
  152. {
  153. $methName=$m->getParam(0);
  154. $methName=$methName->scalarval();
  155. }
  156. else
  157. {
  158. $methName=$m;
  159. }
  160. if(strpos($methName, "system.") === 0)
  161. {
  162. $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;
  163. }
  164. else
  165. {
  166. $dmap=$server->dmap; $sysCall=0;
  167. }
  168. if(isset($dmap[$methName]))
  169. {
  170. if(isset($dmap[$methName]['docstring']))
  171. {
  172. $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string');
  173. }
  174. else
  175. {
  176. $r=new xmlrpcresp(new xmlrpcval('', 'string'));
  177. }
  178. }
  179. else
  180. {
  181. $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);
  182. }
  183. return $r;
  184. }
  185. $_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray']));
  186. $_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';
  187. $_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"'));
  188. function _xmlrpcs_multicall_error($err)
  189. {
  190. if(is_string($err))
  191. {
  192. $str = $GLOBALS['xmlrpcstr']["multicall_${err}"];
  193. $code = $GLOBALS['xmlrpcerr']["multicall_${err}"];
  194. }
  195. else
  196. {
  197. $code = $err->faultCode();
  198. $str = $err->faultString();
  199. }
  200. $struct = array();
  201. $struct['faultCode'] = new xmlrpcval($code, 'int');
  202. $struct['faultString'] = new xmlrpcval($str, 'string');
  203. return new xmlrpcval($struct, 'struct');
  204. }
  205. function _xmlrpcs_multicall_do_call($server, $call)
  206. {
  207. if($call->kindOf() != 'struct')
  208. {
  209. return _xmlrpcs_multicall_error('notstruct');
  210. }
  211. $methName = @$call->structmem('methodName');
  212. if(!$methName)
  213. {
  214. return _xmlrpcs_multicall_error('nomethod');
  215. }
  216. if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string')
  217. {
  218. return _xmlrpcs_multicall_error('notstring');
  219. }
  220. if($methName->scalarval() == 'system.multicall')
  221. {
  222. return _xmlrpcs_multicall_error('recursion');
  223. }
  224. $params = @$call->structmem('params');
  225. if(!$params)
  226. {
  227. return _xmlrpcs_multicall_error('noparams');
  228. }
  229. if($params->kindOf() != 'array')
  230. {
  231. return _xmlrpcs_multicall_error('notarray');
  232. }
  233. $numParams = $params->arraysize();
  234. $msg = new xmlrpcmsg($methName->scalarval());
  235. for($i = 0; $i < $numParams; $i++)
  236. {
  237. if(!$msg->addParam($params->arraymem($i)))
  238. {
  239. $i++;
  240. return _xmlrpcs_multicall_error(new xmlrpcresp(0,
  241. $GLOBALS['xmlrpcerr']['incorrect_params'],
  242. $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i));
  243. }
  244. }
  245. $result = $server->execute($msg);
  246. if($result->faultCode() != 0)
  247. {
  248. return _xmlrpcs_multicall_error($result); // Method returned fault.
  249. }
  250. return new xmlrpcval(array($result->value()), 'array');
  251. }
  252. function _xmlrpcs_multicall_do_call_phpvals($server, $call)
  253. {
  254. if(!is_array($call))
  255. {
  256. return _xmlrpcs_multicall_error('notstruct');
  257. }
  258. if(!array_key_exists('methodName', $call))
  259. {
  260. return _xmlrpcs_multicall_error('nomethod');
  261. }
  262. if (!is_string($call['methodName']))
  263. {
  264. return _xmlrpcs_multicall_error('notstring');
  265. }
  266. if($call['methodName'] == 'system.multicall')
  267. {
  268. return _xmlrpcs_multicall_error('recursion');
  269. }
  270. if(!array_key_exists('params', $call))
  271. {
  272. return _xmlrpcs_multicall_error('noparams');
  273. }
  274. if(!is_array($call['params']))
  275. {
  276. return _xmlrpcs_multicall_error('notarray');
  277. }
  278. // this is a real dirty and simplistic hack, since we might have received a
  279. // base64 or datetime values, but they will be listed as strings here...
  280. $numParams = count($call['params']);
  281. $pt = array();
  282. foreach($call['params'] as $val)
  283. $pt[] = php_2_xmlrpc_type(gettype($val));
  284. $result = $server->execute($call['methodName'], $call['params'], $pt);
  285. if($result->faultCode() != 0)
  286. {
  287. return _xmlrpcs_multicall_error($result); // Method returned fault.
  288. }
  289. return new xmlrpcval(array($result->value()), 'array');
  290. }
  291. function _xmlrpcs_multicall($server, $m)
  292. {
  293. $result = array();
  294. // let accept a plain list of php parameters, beside a single xmlrpc msg object
  295. if (is_object($m))
  296. {
  297. $calls = $m->getParam(0);
  298. $numCalls = $calls->arraysize();
  299. for($i = 0; $i < $numCalls; $i++)
  300. {
  301. $call = $calls->arraymem($i);
  302. $result[$i] = _xmlrpcs_multicall_do_call($server, $call);
  303. }
  304. }
  305. else
  306. {
  307. $numCalls=count($m);
  308. for($i = 0; $i < $numCalls; $i++)
  309. {
  310. $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);
  311. }
  312. }
  313. return new xmlrpcresp(new xmlrpcval($result, 'array'));
  314. }
  315. $GLOBALS['_xmlrpcs_dmap']=array(
  316. 'system.listMethods' => array(
  317. 'function' => '_xmlrpcs_listMethods',
  318. 'signature' => $_xmlrpcs_listMethods_sig,
  319. 'docstring' => $_xmlrpcs_listMethods_doc,
  320. 'signature_docs' => $_xmlrpcs_listMethods_sdoc),
  321. 'system.methodHelp' => array(
  322. 'function' => '_xmlrpcs_methodHelp',
  323. 'signature' => $_xmlrpcs_methodHelp_sig,
  324. 'docstring' => $_xmlrpcs_methodHelp_doc,
  325. 'signature_docs' => $_xmlrpcs_methodHelp_sdoc),
  326. 'system.methodSignature' => array(
  327. 'function' => '_xmlrpcs_methodSignature',
  328. 'signature' => $_xmlrpcs_methodSignature_sig,
  329. 'docstring' => $_xmlrpcs_methodSignature_doc,
  330. 'signature_docs' => $_xmlrpcs_methodSignature_sdoc),
  331. 'system.multicall' => array(
  332. 'function' => '_xmlrpcs_multicall',
  333. 'signature' => $_xmlrpcs_multicall_sig,
  334. 'docstring' => $_xmlrpcs_multicall_doc,
  335. 'signature_docs' => $_xmlrpcs_multicall_sdoc),
  336. 'system.getCapabilities' => array(
  337. 'function' => '_xmlrpcs_getCapabilities',
  338. 'signature' => $_xmlrpcs_getCapabilities_sig,
  339. 'docstring' => $_xmlrpcs_getCapabilities_doc,
  340. 'signature_docs' => $_xmlrpcs_getCapabilities_sdoc)
  341. );
  342. $GLOBALS['_xmlrpcs_occurred_errors'] = '';
  343. $GLOBALS['_xmlrpcs_prev_ehandler'] = '';
  344. /**
  345. * Error handler used to track errors that occur during server-side execution of PHP code.
  346. * This allows to report back to the client whether an internal error has occurred or not
  347. * using an xmlrpc response object, instead of letting the client deal with the html junk
  348. * that a PHP execution error on the server generally entails.
  349. *
  350. * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
  351. *
  352. */
  353. function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)
  354. {
  355. // obey the @ protocol
  356. if (error_reporting() == 0)
  357. return;
  358. //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)
  359. if($errcode != E_STRICT)
  360. {
  361. $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n";
  362. }
  363. // Try to avoid as much as possible disruption to the previous error handling
  364. // mechanism in place
  365. if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')
  366. {
  367. // The previous error handler was the default: all we should do is log error
  368. // to the default error log (if level high enough)
  369. if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))
  370. {
  371. error_log($errstring);
  372. }
  373. }
  374. else
  375. {
  376. // Pass control on to previous error handler, trying to avoid loops...
  377. if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler')
  378. {
  379. // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers
  380. if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))
  381. {
  382. // the following works both with static class methods and plain object methods as error handler
  383. call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context));
  384. }
  385. else
  386. {
  387. $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);
  388. }
  389. }
  390. }
  391. }
  392. $GLOBALS['_xmlrpc_debuginfo']='';
  393. /**
  394. * Add a string to the debug info that can be later seralized by the server
  395. * as part of the response message.
  396. * Note that for best compatbility, the debug string should be encoded using
  397. * the $GLOBALS['xmlrpc_internalencoding'] character set.
  398. * @param string $m
  399. * @access public
  400. */
  401. function xmlrpc_debugmsg($m)
  402. {
  403. $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n";
  404. }
  405. class xmlrpc_server
  406. {
  407. /**
  408. * Array defining php functions exposed as xmlrpc methods by this server
  409. * @access private
  410. */
  411. var $dmap=array();
  412. /**
  413. * Defines how functions in dmap will be invoked: either using an xmlrpc msg object
  414. * or plain php values.
  415. * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
  416. */
  417. var $functions_parameters_type='xmlrpcvals';
  418. /**
  419. * Option used for fine-tuning the encoding the php values returned from
  420. * functions registered in the dispatch map when the functions_parameters_types
  421. * member is set to 'phpvals'
  422. * @see php_xmlrpc_encode for a list of values
  423. */
  424. var $phpvals_encoding_options = array( 'auto_dates' );
  425. /// controls wether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3
  426. var $debug = 1;
  427. /**
  428. * Controls behaviour of server when invoked user function throws an exception:
  429. * 0 = catch it and return an 'internal error' xmlrpc response (default)
  430. * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
  431. * 2 = allow the exception to float to the upper layers
  432. */
  433. var $exception_handling = 0;
  434. /**
  435. * When set to true, it will enable HTTP compression of the response, in case
  436. * the client has declared its support for compression in the request.
  437. */
  438. var $compress_response = false;
  439. /**
  440. * List of http compression methods accepted by the server for requests.
  441. * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
  442. */
  443. var $accepted_compression = array();
  444. /// shall we serve calls to system.* methods?
  445. var $allow_system_funcs = true;
  446. /// list of charset encodings natively accepted for requests
  447. var $accepted_charset_encodings = array();
  448. /**
  449. * charset encoding to be used for response.
  450. * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
  451. * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
  452. * null (leave unspecified in response, convert output stream to US_ASCII),
  453. * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
  454. * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway).
  455. * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
  456. */
  457. var $response_charset_encoding = '';
  458. /**
  459. * Storage for internal debug info
  460. * @access private
  461. */
  462. var $debug_info = '';
  463. /**
  464. * Extra data passed at runtime to method handling functions. Used only by EPI layer
  465. */
  466. var $user_data = null;
  467. /**
  468. * @param array $dispmap the dispatch map withd efinition of exposed services
  469. * @param boolean $servicenow set to false to prevent the server from runnung upon construction
  470. */
  471. function xmlrpc_server($dispMap=null, $serviceNow=true)
  472. {
  473. // if ZLIB is enabled, let the server by default accept compressed requests,
  474. // and compress responses sent to clients that support them
  475. if(function_exists('gzinflate'))
  476. {
  477. $this->accepted_compression = array('gzip', 'deflate');
  478. $this->compress_response = true;
  479. }
  480. // by default the xml parser can support these 3 charset encodings
  481. $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
  482. // dispMap is a dispatch array of methods
  483. // mapped to function names and signatures
  484. // if a method
  485. // doesn't appear in the map then an unknown
  486. // method error is generated
  487. /* milosch - changed to make passing dispMap optional.
  488. * instead, you can use the class add_to_map() function
  489. * to add functions manually (borrowed from SOAPX4)
  490. */
  491. if($dispMap)
  492. {
  493. $this->dmap = $dispMap;
  494. if($serviceNow)
  495. {
  496. $this->service();
  497. }
  498. }
  499. }
  500. /**
  501. * Set debug level of server.
  502. * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
  503. * 0 = no debug info,
  504. * 1 = msgs set from user with debugmsg(),
  505. * 2 = add complete xmlrpc request (headers and body),
  506. * 3 = add also all processing warnings happened during method processing
  507. * (NB: this involves setting a custom error handler, and might interfere
  508. * with the standard processing of the php function exposed as method. In
  509. * particular, triggering an USER_ERROR level error will not halt script
  510. * execution anymore, but just end up logged in the xmlrpc response)
  511. * Note that info added at elevel 2 and 3 will be base64 encoded
  512. * @access public
  513. */
  514. function setDebug($in)
  515. {
  516. $this->debug=$in;
  517. }
  518. /**
  519. * Return a string with the serialized representation of all debug info
  520. * @param string $charset_encoding the target charset encoding for the serialization
  521. * @return string an XML comment (or two)
  522. */
  523. function serializeDebug($charset_encoding='')
  524. {
  525. // Tough encoding problem: which internal charset should we assume for debug info?
  526. // It might contain a copy of raw data received from client, ie with unknown encoding,
  527. // intermixed with php generated data and user generated data...
  528. // so we split it: system debug is base 64 encoded,
  529. // user debug info should be encoded by the end user using the INTERNAL_ENCODING
  530. $out = '';
  531. if ($this->debug_info != '')
  532. {
  533. $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n".base64_encode($this->debug_info)."\n-->\n";
  534. }
  535. if($GLOBALS['_xmlrpc_debuginfo']!='')
  536. {
  537. $out .= "<!-- DEBUG INFO:\n" . xmlrpc_encode_entitites(str_replace('--', '_-', $GLOBALS['_xmlrpc_debuginfo']), $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n-->\n";
  538. // NB: a better solution MIGHT be to use CDATA, but we need to insert it
  539. // into return payload AFTER the beginning tag
  540. //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n";
  541. }
  542. return $out;
  543. }
  544. /**
  545. * Execute the xmlrpc request, printing the response
  546. * @param string $data the request body. If null, the http POST request will be examined
  547. * @return xmlrpcresp the response object (usually not used by caller...)
  548. * @access public
  549. */
  550. function service($data=null, $return_payload=false)
  551. {
  552. if ($data === null)
  553. {
  554. // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA
  555. $ver = phpversion();
  556. if ($ver[0] >= 5)
  557. {
  558. $data = file_get_contents('php://input');
  559. }
  560. else
  561. {
  562. $data = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
  563. }
  564. }
  565. $raw_data = $data;
  566. // reset internal debug info
  567. $this->debug_info = '';
  568. // Echo back what we received, before parsing it
  569. if($this->debug > 1)
  570. {
  571. $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
  572. }
  573. $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);
  574. if (!$r)
  575. {
  576. $r=$this->parseRequest($data, $req_charset);
  577. }
  578. // save full body of request into response, for more debugging usages
  579. $r->raw_data = $raw_data;
  580. if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors'])
  581. {
  582. $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
  583. $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++");
  584. }
  585. $payload=$this->xml_header($resp_charset);
  586. if($this->debug > 0)
  587. {
  588. $payload = $payload . $this->serializeDebug($resp_charset);
  589. }
  590. // G. Giunta 2006-01-27: do not create response serialization if it has
  591. // already happened. Helps building json magic
  592. if (empty($r->payload))
  593. {
  594. $r->serialize($resp_charset);
  595. }
  596. $payload = $payload . $r->payload;
  597. if ($return_payload)
  598. {
  599. return $payload;
  600. }
  601. // if we get a warning/error that has output some text before here, then we cannot
  602. // add a new header. We cannot say we are sending xml, either...
  603. if(!headers_sent())
  604. {
  605. header('Content-Type: '.$r->content_type);
  606. // we do not know if client actually told us an accepted charset, but if he did
  607. // we have to tell him what we did
  608. header("Vary: Accept-Charset");
  609. // http compression of output: only
  610. // if we can do it, and we want to do it, and client asked us to,
  611. // and php ini settings do not force it already
  612. $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
  613. if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
  614. && $php_no_self_compress)
  615. {
  616. if(strpos($resp_encoding, 'gzip') !== false)
  617. {
  618. $payload = gzencode($payload);
  619. header("Content-Encoding: gzip");
  620. header("Vary: Accept-Encoding");
  621. }
  622. elseif (strpos($resp_encoding, 'deflate') !== false)
  623. {
  624. $payload = gzcompress($payload);
  625. header("Content-Encoding: deflate");
  626. header("Vary: Accept-Encoding");
  627. }
  628. }
  629. // do not ouput content-length header if php is compressing output for us:
  630. // it will mess up measurements
  631. if($php_no_self_compress)
  632. {
  633. header('Content-Length: ' . (int)strlen($payload));
  634. }
  635. }
  636. else
  637. {
  638. error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages');
  639. }
  640. print $payload;
  641. // return request, in case subclasses want it
  642. return $r;
  643. }
  644. /**
  645. * Add a method to the dispatch map
  646. * @param string $methodname the name with which the method will be made available
  647. * @param string $function the php function that will get invoked
  648. * @param array $sig the array of valid method signatures
  649. * @param string $doc method documentation
  650. * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)
  651. * @access public
  652. */
  653. function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false)
  654. {
  655. $this->dmap[$methodname] = array(
  656. 'function' => $function,
  657. 'docstring' => $doc
  658. );
  659. if ($sig)
  660. {
  661. $this->dmap[$methodname]['signature'] = $sig;
  662. }
  663. if ($sigdoc)
  664. {
  665. $this->dmap[$methodname]['signature_docs'] = $sigdoc;
  666. }
  667. }
  668. /**
  669. * Verify type and number of parameters received against a list of known signatures
  670. * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
  671. * @param array $sig array of known signatures to match against
  672. * @access private
  673. */
  674. function verifySignature($in, $sig)
  675. {
  676. // check each possible signature in turn
  677. if (is_object($in))
  678. {
  679. $numParams = $in->getNumParams();
  680. }
  681. else
  682. {
  683. $numParams = count($in);
  684. }
  685. foreach($sig as $cursig)
  686. {
  687. if(count($cursig)==$numParams+1)
  688. {
  689. $itsOK=1;
  690. for($n=0; $n<$numParams; $n++)
  691. {
  692. if (is_object($in))
  693. {
  694. $p=$in->getParam($n);
  695. if($p->kindOf() == 'scalar')
  696. {
  697. $pt=$p->scalartyp();
  698. }
  699. else
  700. {
  701. $pt=$p->kindOf();
  702. }
  703. }
  704. else
  705. {
  706. $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
  707. }
  708. // param index is $n+1, as first member of sig is return type
  709. if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue'])
  710. {
  711. $itsOK=0;
  712. $pno=$n+1;
  713. $wanted=$cursig[$n+1];
  714. $got=$pt;
  715. break;
  716. }
  717. }
  718. if($itsOK)
  719. {
  720. return array(1,'');
  721. }
  722. }
  723. }
  724. if(isset($wanted))
  725. {
  726. return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
  727. }
  728. else
  729. {
  730. return array(0, "No method signature matches number of parameters");
  731. }
  732. }
  733. /**
  734. * Parse http headers received along with xmlrpc request. If needed, inflate request
  735. * @return null on success or an xmlrpcresp
  736. * @access private
  737. */
  738. function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
  739. {
  740. // check if $_SERVER is populated: it might have been disabled via ini file
  741. // (this is true even when in CLI mode)
  742. if (count($_SERVER) == 0)
  743. {
  744. error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');
  745. }
  746. if($this->debug > 1)
  747. {
  748. if(function_exists('getallheaders'))
  749. {
  750. $this->debugmsg(''); // empty line
  751. foreach(getallheaders() as $name => $val)
  752. {
  753. $this->debugmsg("HEADER: $name: $val");
  754. }
  755. }
  756. }
  757. if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
  758. {
  759. $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
  760. }
  761. else
  762. {
  763. $content_encoding = '';
  764. }
  765. // check if request body has been compressed and decompress it
  766. if($content_encoding != '' && strlen($data))
  767. {
  768. if($content_encoding == 'deflate' || $content_encoding == 'gzip')
  769. {
  770. // if decoding works, use it. else assume data wasn't gzencoded
  771. if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
  772. {
  773. if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
  774. {
  775. $data = $degzdata;
  776. if($this->debug > 1)
  777. {
  778. $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
  779. }
  780. }
  781. elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
  782. {
  783. $data = $degzdata;
  784. if($this->debug > 1)
  785. $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
  786. }
  787. else
  788. {
  789. $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']);
  790. return $r;
  791. }
  792. }
  793. else
  794. {
  795. //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
  796. $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']);
  797. return $r;
  798. }
  799. }
  800. }
  801. // check if client specified accepted charsets, and if we know how to fulfill
  802. // the request
  803. if ($this->response_charset_encoding == 'auto')
  804. {
  805. $resp_encoding = '';
  806. if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
  807. {
  808. // here we should check if we can match the client-requested encoding
  809. // with the encodings we know we can generate.
  810. /// @todo we should parse q=0.x preferences instead of getting first charset specified...
  811. $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
  812. // Give preference to internal encoding
  813. $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII');
  814. foreach ($known_charsets as $charset)
  815. {
  816. foreach ($client_accepted_charsets as $accepted)
  817. if (strpos($accepted, $charset) === 0)
  818. {
  819. $resp_encoding = $charset;
  820. break;
  821. }
  822. if ($resp_encoding)
  823. break;
  824. }
  825. }
  826. }
  827. else
  828. {
  829. $resp_encoding = $this->response_charset_encoding;
  830. }
  831. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
  832. {
  833. $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
  834. }
  835. else
  836. {
  837. $resp_compression = '';
  838. }
  839. // 'guestimate' request encoding
  840. /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
  841. $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
  842. $data);
  843. return null;
  844. }
  845. /**
  846. * Parse an xml chunk containing an xmlrpc request and execute the corresponding
  847. * php function registered with the server
  848. * @param string $data the xml request
  849. * @param string $req_encoding (optional) the charset encoding of the xml request
  850. * @return xmlrpcresp
  851. * @access private
  852. */
  853. function parseRequest($data, $req_encoding='')
  854. {
  855. // 2005/05/07 commented and moved into caller function code
  856. //if($data=='')
  857. //{
  858. // $data=$GLOBALS['HTTP_RAW_POST_DATA'];
  859. //}
  860. // G. Giunta 2005/02/13: we do NOT expect to receive html entities
  861. // so we do not try to convert them into xml character entities
  862. //$data = xmlrpc_html_entity_xlate($data);
  863. $GLOBALS['_xh']=array();
  864. $GLOBALS['_xh']['ac']='';
  865. $GLOBALS['_xh']['stack']=array();
  866. $GLOBALS['_xh']['valuestack'] = array();
  867. $GLOBALS['_xh']['params']=array();
  868. $GLOBALS['_xh']['pt']=array();
  869. $GLOBALS['_xh']['isf']=0;
  870. $GLOBALS['_xh']['isf_reason']='';
  871. $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not
  872. $GLOBALS['_xh']['rt']='';
  873. // decompose incoming XML into request structure
  874. if ($req_encoding != '')
  875. {
  876. if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  877. // the following code might be better for mb_string enabled installs, but
  878. // makes the lib about 200% slower...
  879. //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  880. {
  881. error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding);
  882. $req_encoding = $GLOBALS['xmlrpc_defencoding'];
  883. }
  884. /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
  885. // the encoding is not UTF8 and there are non-ascii chars in the text...
  886. /// @todo use an ampty string for php 5 ???
  887. $parser = xml_parser_create($req_encoding);
  888. }
  889. else
  890. {
  891. $parser = xml_parser_create();
  892. }
  893. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
  894. // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
  895. // the xml parser to give us back data in the expected charset
  896. // What if internal encoding is not in one of the 3 allowed?
  897. // we use the broadest one, ie. utf8
  898. // This allows to send data which is native in various charset,
  899. // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
  900. if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  901. {
  902. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
  903. }
  904. else
  905. {
  906. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
  907. }
  908. if ($this->functions_parameters_type != 'xmlrpcvals')
  909. xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
  910. else
  911. xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
  912. xml_set_character_data_handler($parser, 'xmlrpc_cd');
  913. xml_set_default_handler($parser, 'xmlrpc_dh');
  914. if(!xml_parse($parser, $data, 1))
  915. {
  916. // return XML error as a faultCode
  917. $r=new xmlrpcresp(0,
  918. $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser),
  919. sprintf('XML error: %s at line %d, column %d',
  920. xml_error_string(xml_get_error_code($parser)),
  921. xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
  922. xml_parser_free($parser);
  923. }
  924. elseif ($GLOBALS['_xh']['isf'])
  925. {
  926. xml_parser_free($parser);
  927. $r=new xmlrpcresp(0,
  928. $GLOBALS['xmlrpcerr']['invalid_request'],
  929. $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']);
  930. }
  931. else
  932. {
  933. xml_parser_free($parser);
  934. // small layering violation in favor of speed and memory usage:
  935. // we should allow the 'execute' method handle this, but in the
  936. // most common scenario (xmlrpcvals type server with some methods
  937. // registered as phpvals) that would mean a useless encode+decode pass
  938. if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals')))
  939. {
  940. if($this->debug > 1)
  941. {
  942. $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++");
  943. }
  944. $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']);
  945. }
  946. else
  947. {
  948. // build an xmlrpcmsg object with data parsed from xml
  949. $m=new xmlrpcmsg($GLOBALS['_xh']['method']);
  950. // now add parameters in
  951. for($i=0; $i<count($GLOBALS['_xh']['params']); $i++)
  952. {
  953. $m->addParam($GLOBALS['_xh']['params'][$i]);
  954. }
  955. if($this->debug > 1)
  956. {
  957. $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");
  958. }
  959. $r = $this->execute($m);
  960. }
  961. }
  962. return $r;
  963. }
  964. /**
  965. * Execute a method invoked by the client, checking parameters used
  966. * @param mixed $m either an xmlrpcmsg obj or a method name
  967. * @param array $params array with method parameters as php types (if m is method name only)
  968. * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
  969. * @return xmlrpcresp
  970. * @access private
  971. */
  972. function execute($m, $params=null, $paramtypes=null)
  973. {
  974. if (is_object($m))
  975. {
  976. $methName = $m->method();
  977. }
  978. else
  979. {
  980. $methName = $m;
  981. }
  982. $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
  983. $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap;
  984. if(!isset($dmap[$methName]['function']))
  985. {
  986. // No such method
  987. return new xmlrpcresp(0,
  988. $GLOBALS['xmlrpcerr']['unknown_method'],
  989. $GLOBALS['xmlrpcstr']['unknown_method']);
  990. }
  991. // Check signature
  992. if(isset($dmap[$methName]['signature']))
  993. {
  994. $sig = $dmap[$methName]['signature'];
  995. if (is_object($m))
  996. {
  997. list($ok, $errstr) = $this->verifySignature($m, $sig);
  998. }
  999. else
  1000. {
  1001. list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
  1002. }
  1003. if(!$ok)
  1004. {
  1005. // Didn't match.
  1006. return new xmlrpcresp(
  1007. 0,
  1008. $GLOBALS['xmlrpcerr']['incorrect_params'],
  1009. $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}"
  1010. );
  1011. }
  1012. }
  1013. $func = $dmap[$methName]['function'];
  1014. // let the 'class::function' syntax be accepted in dispatch maps
  1015. if(is_string($func) && strpos($func, '::'))
  1016. {
  1017. $func = explode('::', $func);
  1018. }
  1019. // verify that function to be invoked is in fact callable
  1020. if(!is_callable($func))
  1021. {
  1022. error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");
  1023. return new xmlrpcresp(
  1024. 0,
  1025. $GLOBALS['xmlrpcerr']['server_error'],
  1026. $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"
  1027. );
  1028. }
  1029. // If debug level is 3, we should catch all errors generated during
  1030. // processing of user function, and log them as part of response
  1031. if($this->debug > 2)
  1032. {
  1033. $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');
  1034. }
  1035. try
  1036. {
  1037. // Allow mixed-convention servers
  1038. if (is_object($m))
  1039. {
  1040. if($sysCall)
  1041. {
  1042. $r = call_user_func($func, $this, $m);
  1043. }
  1044. else
  1045. {
  1046. $r = call_user_func($func, $m);
  1047. }
  1048. if (!is_a($r, 'xmlrpcresp'))
  1049. {
  1050. error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object");
  1051. if (is_a($r, 'xmlrpcval'))
  1052. {
  1053. $r = new xmlrpcresp($r);
  1054. }
  1055. else
  1056. {
  1057. $r = new xmlrpcresp(
  1058. 0,
  1059. $GLOBALS['xmlrpcerr']['server_error'],
  1060. $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object"
  1061. );
  1062. }
  1063. }
  1064. }
  1065. else
  1066. {
  1067. // call a 'plain php' function
  1068. if($sysCall)
  1069. {
  1070. array_unshift($params, $this);
  1071. $r = call_user_func_array($func, $params);
  1072. }
  1073. else
  1074. {
  1075. // 3rd API convention for method-handling functions: EPI-style
  1076. if ($this->functions_parameters_type == 'epivals')
  1077. {
  1078. $r = call_user_func_array($func, array($methName, $params, $this->user_data));
  1079. // mimic EPI behaviour: if we get an array that looks like an error, make it
  1080. // an eror response
  1081. if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
  1082. {
  1083. $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']);
  1084. }
  1085. else
  1086. {
  1087. // functions using EPI api should NOT return resp objects,
  1088. // so make sure we encode the return type correctly
  1089. $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api')));
  1090. }
  1091. }
  1092. else
  1093. {
  1094. $r = call_user_func_array($func, $params);
  1095. }
  1096. }
  1097. // the return type can be either an xmlrpcresp object or a plain php value...
  1098. if (!is_a($r, 'xmlrpcresp'))
  1099. {
  1100. // what should we assume here about automatic encoding of datetimes
  1101. // and php classes instances???
  1102. $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
  1103. }
  1104. }
  1105. }
  1106. catch(Exception $e)
  1107. {
  1108. // (barring errors in the lib) an uncatched exception happened
  1109. // in the called function, we wrap it in a proper error-response
  1110. switch($this->exception_handling)
  1111. {
  1112. case 2:
  1113. throw $e;
  1114. break;
  1115. case 1:
  1116. $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage());
  1117. break;
  1118. default:
  1119. $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']);
  1120. }
  1121. }
  1122. if($this->debug > 2)
  1123. {
  1124. // note: restore the error handler we found before calling the
  1125. // user func, even if it has been changed inside the func itself
  1126. if($GLOBALS['_xmlrpcs_prev_ehandler'])
  1127. {
  1128. set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
  1129. }
  1130. else
  1131. {
  1132. restore_error_handler();
  1133. }
  1134. }
  1135. return $r;
  1136. }
  1137. /**
  1138. * add a string to the 'internal debug message' (separate from 'user debug message')
  1139. * @param string $strings
  1140. * @access private
  1141. */
  1142. function debugmsg($string)
  1143. {
  1144. $this->debug_info .= $string."\n";
  1145. }
  1146. /**
  1147. * @access private
  1148. */
  1149. function xml_header($charset_encoding='')
  1150. {
  1151. if ($charset_encoding != '')
  1152. {
  1153. return "<?xml version=\"1.0\" encoding=\"$charset_encoding\"?" . ">\n";
  1154. }
  1155. else
  1156. {
  1157. return "<?xml version=\"1.0\"?" . ">\n";
  1158. }
  1159. }
  1160. /**
  1161. * A debugging routine: just echoes back the input packet as a string value
  1162. * DEPRECATED!
  1163. */
  1164. function echoInput()
  1165. {
  1166. $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
  1167. print $r->serialize();
  1168. }
  1169. }
  1170. ?>