PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/libs/xmlrpc_wrappers.php

http://swan.googlecode.com/
PHP | 947 lines | 524 code | 32 blank | 391 comment | 92 complexity | 85aa7a476bf4de0f52d981cf03b5c1a4 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. defined('SW_') or die('Access Error');
  3. /**
  4. * PHP-XMLRPC "wrapper" functions
  5. * Generate stubs to transparently access xmlrpc methods as php functions and viceversa
  6. *
  7. * @version $Id: xmlrpc_wrappers.inc,v 1.13 2008/09/20 01:23:47 ggiunta Exp $
  8. * @author Gaetano Giunta
  9. * @copyright (C) 2006-2008 G. Giunta
  10. * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
  11. *
  12. * @todo separate introspection from code generation for func-2-method wrapping
  13. * @todo use some better templating system for code generation?
  14. * @todo implement method wrapping with preservation of php objs in calls
  15. * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
  16. * @todo implement self-parsing of php code for PHP <= 4
  17. */
  18. // requires: xmlrpc.inc
  19. /**
  20. * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
  21. * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
  22. * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
  23. * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
  24. * @param string $phptype
  25. * @return string
  26. */
  27. function php_2_xmlrpc_type($phptype)
  28. {
  29. switch(strtolower($phptype))
  30. {
  31. case 'string':
  32. return $GLOBALS['xmlrpcString'];
  33. case 'integer':
  34. case $GLOBALS['xmlrpcInt']: // 'int'
  35. case $GLOBALS['xmlrpcI4']:
  36. return $GLOBALS['xmlrpcInt'];
  37. case 'double':
  38. return $GLOBALS['xmlrpcDouble'];
  39. case 'boolean':
  40. return $GLOBALS['xmlrpcBoolean'];
  41. case 'array':
  42. return $GLOBALS['xmlrpcArray'];
  43. case 'object':
  44. return $GLOBALS['xmlrpcStruct'];
  45. case $GLOBALS['xmlrpcBase64']:
  46. case $GLOBALS['xmlrpcStruct']:
  47. return strtolower($phptype);
  48. case 'resource':
  49. return '';
  50. default:
  51. if(class_exists($phptype))
  52. {
  53. return $GLOBALS['xmlrpcStruct'];
  54. }
  55. else
  56. {
  57. // unknown: might be any 'extended' xmlrpc type
  58. return $GLOBALS['xmlrpcValue'];
  59. }
  60. }
  61. }
  62. /**
  63. * Given a string defining a phpxmlrpc type return corresponding php type.
  64. * @param string $xmlrpctype
  65. * @return string
  66. */
  67. function xmlrpc_2_php_type($xmlrpctype)
  68. {
  69. switch(strtolower($xmlrpctype))
  70. {
  71. case 'base64':
  72. case 'datetime.iso8601':
  73. case 'string':
  74. return $GLOBALS['xmlrpcString'];
  75. case 'int':
  76. case 'i4':
  77. return 'integer';
  78. case 'struct':
  79. case 'array':
  80. return 'array';
  81. case 'double':
  82. return 'float';
  83. case 'undefined':
  84. return 'mixed';
  85. case 'boolean':
  86. case 'null':
  87. default:
  88. // unknown: might be any xmlrpc type
  89. return strtolower($xmlrpctype);
  90. }
  91. }
  92. /**
  93. * Given a user-defined PHP function, create a PHP 'wrapper' function that can
  94. * be exposed as xmlrpc method from an xmlrpc_server object and called from remote
  95. * clients (as well as its corresponding signature info).
  96. *
  97. * Since php is a typeless language, to infer types of input and output parameters,
  98. * it relies on parsing the javadoc-style comment block associated with the given
  99. * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
  100. * in the @param tag is also allowed, if you need the php function to receive/send
  101. * data in that particular format (note that base64 encoding/decoding is transparently
  102. * carried out by the lib, while datetime vals are passed around as strings)
  103. *
  104. * Known limitations:
  105. * - requires PHP 5.0.3 +
  106. * - only works for user-defined functions, not for PHP internal functions
  107. * (reflection does not support retrieving number/type of params for those)
  108. * - functions returning php objects will generate special xmlrpc responses:
  109. * when the xmlrpc decoding of those responses is carried out by this same lib, using
  110. * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
  111. * In short: php objects can be serialized, too (except for their resource members),
  112. * using this function.
  113. * Other libs might choke on the very same xml that will be generated in this case
  114. * (i.e. it has a nonstandard attribute on struct element tags)
  115. * - usage of javadoc @param tags using param names in a different order from the
  116. * function prototype is not considered valid (to be fixed?)
  117. *
  118. * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
  119. * php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)
  120. * is by making use of the functions_parameters_type class member.
  121. *
  122. * @param string $funcname the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
  123. * @param string $newfuncname (optional) name for function to be created
  124. * @param array $extra_options (optional) array of options for conversion. valid values include:
  125. * bool return_source when true, php code w. function definition will be returned, not evaluated
  126. * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
  127. * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
  128. * bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
  129. * @return false on error, or an array containing the name of the new php function,
  130. * its signature and docs, to be used in the server dispatch map
  131. *
  132. * @todo decide how to deal with params passed by ref: bomb out or allow?
  133. * @todo finish using javadoc info to build method sig if all params are named but out of order
  134. * @todo add a check for params of 'resource' type
  135. * @todo add some trigger_errors / error_log when returning false?
  136. * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
  137. * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
  138. * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
  139. * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
  140. */
  141. function wrap_php_function($funcname, $newfuncname='', $extra_options=array())
  142. {
  143. $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
  144. $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
  145. $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
  146. $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
  147. $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
  148. if(version_compare(phpversion(), '5.0.3') == -1)
  149. {
  150. // up to php 5.0.3 some useful reflection methods were missing
  151. error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
  152. return false;
  153. }
  154. $exists = false;
  155. if(is_array($funcname))
  156. {
  157. if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0])))
  158. {
  159. error_log('XML-RPC: syntax for function to be wrapped is wrong');
  160. return false;
  161. }
  162. if(is_string($funcname[0]))
  163. {
  164. $plainfuncname = implode('::', $funcname);
  165. }
  166. elseif(is_object($funcname[0]))
  167. {
  168. $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
  169. }
  170. $exists = method_exists($funcname[0], $funcname[1]);
  171. }
  172. else
  173. {
  174. $plainfuncname = $funcname;
  175. $exists = function_exists($funcname);
  176. }
  177. if(!$exists)
  178. {
  179. error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname);
  180. return false;
  181. }
  182. else
  183. {
  184. // determine name of new php function
  185. if($newfuncname == '')
  186. {
  187. if(is_array($funcname))
  188. {
  189. if(is_string($funcname[0]))
  190. $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);
  191. else
  192. $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1];
  193. }
  194. else
  195. {
  196. $xmlrpcfuncname = "{$prefix}_$funcname";
  197. }
  198. }
  199. else
  200. {
  201. $xmlrpcfuncname = $newfuncname;
  202. }
  203. while($buildit && function_exists($xmlrpcfuncname))
  204. {
  205. $xmlrpcfuncname .= 'x';
  206. }
  207. // start to introspect PHP code
  208. if(is_array($funcname))
  209. {
  210. $func =& new ReflectionMethod($funcname[0], $funcname[1]);
  211. if($func->isPrivate())
  212. {
  213. error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname);
  214. return false;
  215. }
  216. if($func->isProtected())
  217. {
  218. error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname);
  219. return false;
  220. }
  221. if($func->isConstructor())
  222. {
  223. error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname);
  224. return false;
  225. }
  226. if($func->isDestructor())
  227. {
  228. error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname);
  229. return false;
  230. }
  231. if($func->isAbstract())
  232. {
  233. error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname);
  234. return false;
  235. }
  236. /// @todo add more checks for static vs. nonstatic?
  237. }
  238. else
  239. {
  240. $func =& new ReflectionFunction($funcname);
  241. }
  242. if($func->isInternal())
  243. {
  244. // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
  245. // instead of getparameters to fully reflect internal php functions ?
  246. error_log('XML-RPC: function to be wrapped is internal: '.$plainfuncname);
  247. return false;
  248. }
  249. // retrieve parameter names, types and description from javadoc comments
  250. // function description
  251. $desc = '';
  252. // type of return val: by default 'any'
  253. $returns = $GLOBALS['xmlrpcValue'];
  254. // desc of return val
  255. $returnsDocs = '';
  256. // type + name of function parameters
  257. $paramDocs = array();
  258. $docs = $func->getDocComment();
  259. if($docs != '')
  260. {
  261. $docs = explode("\n", $docs);
  262. $i = 0;
  263. foreach($docs as $doc)
  264. {
  265. $doc = trim($doc, " \r\t/*");
  266. if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)
  267. {
  268. if($desc)
  269. {
  270. $desc .= "\n";
  271. }
  272. $desc .= $doc;
  273. }
  274. elseif(strpos($doc, '@param') === 0)
  275. {
  276. // syntax: @param type [$name] desc
  277. if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches))
  278. {
  279. if(strpos($matches[1], '|'))
  280. {
  281. //$paramDocs[$i]['type'] = explode('|', $matches[1]);
  282. $paramDocs[$i]['type'] = 'mixed';
  283. }
  284. else
  285. {
  286. $paramDocs[$i]['type'] = $matches[1];
  287. }
  288. $paramDocs[$i]['name'] = trim($matches[2]);
  289. $paramDocs[$i]['doc'] = $matches[3];
  290. }
  291. $i++;
  292. }
  293. elseif(strpos($doc, '@return') === 0)
  294. {
  295. // syntax: @return type desc
  296. //$returns = preg_split('/\s+/', $doc);
  297. if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))
  298. {
  299. $returns = php_2_xmlrpc_type($matches[1]);
  300. if(isset($matches[2]))
  301. {
  302. $returnsDocs = $matches[2];
  303. }
  304. }
  305. }
  306. }
  307. }
  308. // execute introspection of actual function prototype
  309. $params = array();
  310. $i = 0;
  311. foreach($func->getParameters() as $paramobj)
  312. {
  313. $params[$i] = array();
  314. $params[$i]['name'] = '$'.$paramobj->getName();
  315. $params[$i]['isoptional'] = $paramobj->isOptional();
  316. $i++;
  317. }
  318. // start building of PHP code to be eval'd
  319. $innercode = '';
  320. $i = 0;
  321. $parsvariations = array();
  322. $pars = array();
  323. $pnum = count($params);
  324. foreach($params as $param)
  325. {
  326. if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name']))
  327. {
  328. // param name from phpdoc info does not match param definition!
  329. $paramDocs[$i]['type'] = 'mixed';
  330. }
  331. if($param['isoptional'])
  332. {
  333. // this particular parameter is optional. save as valid previous list of parameters
  334. $innercode .= "if (\$paramcount > $i) {\n";
  335. $parsvariations[] = $pars;
  336. }
  337. $innercode .= "\$p$i = \$msg->getParam($i);\n";
  338. if ($decode_php_objects)
  339. {
  340. $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
  341. }
  342. else
  343. {
  344. $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
  345. }
  346. $pars[] = "\$p$i";
  347. $i++;
  348. if($param['isoptional'])
  349. {
  350. $innercode .= "}\n";
  351. }
  352. if($i == $pnum)
  353. {
  354. // last allowed parameters combination
  355. $parsvariations[] = $pars;
  356. }
  357. }
  358. $sigs = array();
  359. $psigs = array();
  360. if(count($parsvariations) == 0)
  361. {
  362. // only known good synopsis = no parameters
  363. $parsvariations[] = array();
  364. $minpars = 0;
  365. }
  366. else
  367. {
  368. $minpars = count($parsvariations[0]);
  369. }
  370. if($minpars)
  371. {
  372. // add to code the check for min params number
  373. // NB: this check needs to be done BEFORE decoding param values
  374. $innercode = "\$paramcount = \$msg->getNumParams();\n" .
  375. "if (\$paramcount < $minpars) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . $innercode;
  376. }
  377. else
  378. {
  379. $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
  380. }
  381. $innercode .= "\$np = false;\n";
  382. // since there are no closures in php, if we are given an object instance,
  383. // we store a pointer to it in a global var...
  384. if ( is_array($funcname) && is_object($funcname[0]) )
  385. {
  386. $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0];
  387. $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
  388. $realfuncname = '$obj->'.$funcname[1];
  389. }
  390. else
  391. {
  392. $realfuncname = $plainfuncname;
  393. }
  394. foreach($parsvariations as $pars)
  395. {
  396. $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
  397. // build a 'generic' signature (only use an appropriate return type)
  398. $sig = array($returns);
  399. $psig = array($returnsDocs);
  400. for($i=0; $i < count($pars); $i++)
  401. {
  402. if (isset($paramDocs[$i]['type']))
  403. {
  404. $sig[] = php_2_xmlrpc_type($paramDocs[$i]['type']);
  405. }
  406. else
  407. {
  408. $sig[] = $GLOBALS['xmlrpcValue'];
  409. }
  410. $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
  411. }
  412. $sigs[] = $sig;
  413. $psigs[] = $psig;
  414. }
  415. $innercode .= "\$np = true;\n";
  416. $innercode .= "if (\$np) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n";
  417. //$innercode .= "if (\$_xmlrpcs_error_occurred) return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
  418. $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
  419. if($returns == $GLOBALS['xmlrpcDateTime'] || $returns == $GLOBALS['xmlrpcBase64'])
  420. {
  421. $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
  422. }
  423. else
  424. {
  425. if ($encode_php_objects)
  426. $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
  427. else
  428. $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
  429. }
  430. // shall we exclude functions returning by ref?
  431. // if($func->returnsReference())
  432. // return false;
  433. $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
  434. //print_r($code);
  435. if ($buildit)
  436. {
  437. $allOK = 0;
  438. eval($code.'$allOK=1;');
  439. // alternative
  440. //$xmlrpcfuncname = create_function('$m', $innercode);
  441. if(!$allOK)
  442. {
  443. error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$plainfuncname);
  444. return false;
  445. }
  446. }
  447. /// @todo examine if $paramDocs matches $parsvariations and build array for
  448. /// usage as method signature, plus put together a nice string for docs
  449. $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
  450. return $ret;
  451. }
  452. }
  453. /**
  454. * Given a user-defined PHP class or php object, map its methods onto a list of
  455. * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
  456. * object and called from remote clients (as well as their corresponding signature info).
  457. *
  458. * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
  459. * @param array $extra_options see the docs for wrap_php_method for more options
  460. * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
  461. * @return array or false on failure
  462. *
  463. * @todo get_class_methods will return both static and non-static methods.
  464. * we have to differentiate the action, depending on wheter we recived a class name or object
  465. */
  466. function wrap_php_class($classname, $extra_options=array())
  467. {
  468. $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
  469. $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
  470. if(version_compare(phpversion(), '5.0.3') == -1)
  471. {
  472. // up to php 5.0.3 some useful reflection methods were missing
  473. error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
  474. return false;
  475. }
  476. $result = array();
  477. $mlist = get_class_methods($classname);
  478. foreach($mlist as $mname)
  479. {
  480. if ($methodfilter == '' || preg_match($methodfilter, $mname))
  481. {
  482. // echo $mlist."\n";
  483. $func =& new ReflectionMethod($classname, $mname);
  484. if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract())
  485. {
  486. if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
  487. (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))))
  488. {
  489. $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
  490. if ( $methodwrap )
  491. {
  492. $result[$methodwrap['function']] = $methodwrap['function'];
  493. }
  494. }
  495. }
  496. }
  497. }
  498. return $result;
  499. }
  500. /**
  501. * Given an xmlrpc client and a method name, register a php wrapper function
  502. * that will call it and return results using native php types for both
  503. * params and results. The generated php function will return an xmlrpcresp
  504. * oject for failed xmlrpc calls
  505. *
  506. * Known limitations:
  507. * - server must support system.methodsignature for the wanted xmlrpc method
  508. * - for methods that expose many signatures, only one can be picked (we
  509. * could in priciple check if signatures differ only by number of params
  510. * and not by type, but it would be more complication than we can spare time)
  511. * - nested xmlrpc params: the caller of the generated php function has to
  512. * encode on its own the params passed to the php function if these are structs
  513. * or arrays whose (sub)members include values of type datetime or base64
  514. *
  515. * Notes: the connection properties of the given client will be copied
  516. * and reused for the connection used during the call to the generated
  517. * php function.
  518. * Calling the generated php function 'might' be slow: a new xmlrpc client
  519. * is created on every invocation and an xmlrpc-connection opened+closed.
  520. * An extra 'debug' param is appended to param list of xmlrpc method, useful
  521. * for debugging purposes.
  522. *
  523. * @param xmlrpc_client $client an xmlrpc client set up correctly to communicate with target server
  524. * @param string $methodname the xmlrpc method to be mapped to a php function
  525. * @param array $extra_options array of options that specify conversion details. valid ptions include
  526. * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
  527. * integer timeout timeout (in secs) to be used when executing function/calling remote method
  528. * string protocol 'http' (default), 'http11' or 'https'
  529. * string new_function_name the name of php function to create. If unsepcified, lib will pick an appropriate name
  530. * string return_source if true return php code w. function definition instead fo function name
  531. * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
  532. * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
  533. * mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the xmlrpcresp object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
  534. * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
  535. * @return string the name of the generated php function (or false) - OR AN ARRAY...
  536. */
  537. function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')
  538. {
  539. // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
  540. // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
  541. if (!is_array($extra_options))
  542. {
  543. $signum = $extra_options;
  544. $extra_options = array();
  545. }
  546. else
  547. {
  548. $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
  549. $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
  550. $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
  551. $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
  552. }
  553. //$encode_php_objects = in_array('encode_php_objects', $extra_options);
  554. //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
  555. // in_array('build_class_code', $extra_options) ? 2 : 0;
  556. $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
  557. $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
  558. $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
  559. $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
  560. $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
  561. if (isset($extra_options['return_on_fault']))
  562. {
  563. $decode_fault = true;
  564. $fault_response = $extra_options['return_on_fault'];
  565. }
  566. else
  567. {
  568. $decode_fault = false;
  569. $fault_response = '';
  570. }
  571. $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
  572. $msgclass = $prefix.'msg';
  573. $valclass = $prefix.'val';
  574. $decodefunc = 'php_'.$prefix.'_decode';
  575. $msg =& new $msgclass('system.methodSignature');
  576. $msg->addparam(new $valclass($methodname));
  577. $client->setDebug($debug);
  578. $response =& $client->send($msg, $timeout, $protocol);
  579. if($response->faultCode())
  580. {
  581. error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);
  582. return false;
  583. }
  584. else
  585. {
  586. $msig = $response->value();
  587. if ($client->return_type != 'phpvals')
  588. {
  589. $msig = $decodefunc($msig);
  590. }
  591. if(!is_array($msig) || count($msig) <= $signum)
  592. {
  593. error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);
  594. return false;
  595. }
  596. else
  597. {
  598. // pick a suitable name for the new function, avoiding collisions
  599. if($newfuncname != '')
  600. {
  601. $xmlrpcfuncname = $newfuncname;
  602. }
  603. else
  604. {
  605. // take care to insure that methodname is translated to valid
  606. // php function name
  607. $xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
  608. array('_', ''), $methodname);
  609. }
  610. while($buildit && function_exists($xmlrpcfuncname))
  611. {
  612. $xmlrpcfuncname .= 'x';
  613. }
  614. $msig = $msig[$signum];
  615. $mdesc = '';
  616. // if in 'offline' mode, get method description too.
  617. // in online mode, favour speed of operation
  618. if(!$buildit)
  619. {
  620. $msg =& new $msgclass('system.methodHelp');
  621. $msg->addparam(new $valclass($methodname));
  622. $response =& $client->send($msg, $timeout, $protocol);
  623. if (!$response->faultCode())
  624. {
  625. $mdesc = $response->value();
  626. if ($client->return_type != 'phpvals')
  627. {
  628. $mdesc = $mdesc->scalarval();
  629. }
  630. }
  631. }
  632. $results = build_remote_method_wrapper_code($client, $methodname,
  633. $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
  634. $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
  635. $fault_response);
  636. //print_r($code);
  637. if ($buildit)
  638. {
  639. $allOK = 0;
  640. eval($results['source'].'$allOK=1;');
  641. // alternative
  642. //$xmlrpcfuncname = create_function('$m', $innercode);
  643. if($allOK)
  644. {
  645. return $xmlrpcfuncname;
  646. }
  647. else
  648. {
  649. error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
  650. return false;
  651. }
  652. }
  653. else
  654. {
  655. $results['function'] = $xmlrpcfuncname;
  656. return $results;
  657. }
  658. }
  659. }
  660. }
  661. /**
  662. * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
  663. * all xmlrpc methods exposed by the remote server as own methods.
  664. * For more details see wrap_xmlrpc_method.
  665. * @param xmlrpc_client $client the client obj all set to query the desired server
  666. * @param array $extra_options list of options for wrapped code
  667. * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options)
  668. */
  669. function wrap_xmlrpc_server($client, $extra_options=array())
  670. {
  671. $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
  672. //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
  673. $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
  674. $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
  675. $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
  676. $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
  677. $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
  678. $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
  679. $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
  680. $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
  681. $msgclass = $prefix.'msg';
  682. //$valclass = $prefix.'val';
  683. $decodefunc = 'php_'.$prefix.'_decode';
  684. $msg =& new $msgclass('system.listMethods');
  685. $response =& $client->send($msg, $timeout, $protocol);
  686. if($response->faultCode())
  687. {
  688. error_log('XML-RPC: could not retrieve method list from remote server');
  689. return false;
  690. }
  691. else
  692. {
  693. $mlist = $response->value();
  694. if ($client->return_type != 'phpvals')
  695. {
  696. $mlist = $decodefunc($mlist);
  697. }
  698. if(!is_array($mlist) || !count($mlist))
  699. {
  700. error_log('XML-RPC: could not retrieve meaningful method list from remote server');
  701. return false;
  702. }
  703. else
  704. {
  705. // pick a suitable name for the new function, avoiding collisions
  706. if($newclassname != '')
  707. {
  708. $xmlrpcclassname = $newclassname;
  709. }
  710. else
  711. {
  712. $xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
  713. array('_', ''), $client->server).'_client';
  714. }
  715. while($buildit && class_exists($xmlrpcclassname))
  716. {
  717. $xmlrpcclassname .= 'x';
  718. }
  719. /// @todo add function setdebug() to new class, to enable/disable debugging
  720. $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
  721. $source .= "function $xmlrpcclassname()\n{\n";
  722. $source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
  723. $source .= "\$this->client =& \$client;\n}\n\n";
  724. $opts = array('simple_client_copy' => 2, 'return_source' => true,
  725. 'timeout' => $timeout, 'protocol' => $protocol,
  726. 'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
  727. 'decode_php_objs' => $decode_php_objects
  728. );
  729. /// @todo build javadoc for class definition, too
  730. foreach($mlist as $mname)
  731. {
  732. if ($methodfilter == '' || preg_match($methodfilter, $mname))
  733. {
  734. $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
  735. array('_', ''), $mname);
  736. $methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
  737. if ($methodwrap)
  738. {
  739. if (!$buildit)
  740. {
  741. $source .= $methodwrap['docstring'];
  742. }
  743. $source .= $methodwrap['source']."\n";
  744. }
  745. else
  746. {
  747. error_log('XML-RPC: will not create class method to wrap remote method '.$mname);
  748. }
  749. }
  750. }
  751. $source .= "}\n";
  752. if ($buildit)
  753. {
  754. $allOK = 0;
  755. eval($source.'$allOK=1;');
  756. // alternative
  757. //$xmlrpcfuncname = create_function('$m', $innercode);
  758. if($allOK)
  759. {
  760. return $xmlrpcclassname;
  761. }
  762. else
  763. {
  764. error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
  765. return false;
  766. }
  767. }
  768. else
  769. {
  770. return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
  771. }
  772. }
  773. }
  774. }
  775. /**
  776. * Given the necessary info, build php code that creates a new function to
  777. * invoke a remote xmlrpc method.
  778. * Take care that no full checking of input parameters is done to ensure that
  779. * valid php code is emitted.
  780. * Note: real spaghetti code follows...
  781. * @access private
  782. */
  783. function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
  784. $msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',
  785. $decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,
  786. $fault_response='')
  787. {
  788. $code = "function $xmlrpcfuncname (";
  789. if ($client_copy_mode < 2)
  790. {
  791. // client copy mode 0 or 1 == partial / full client copy in emitted code
  792. $innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix);
  793. $innercode .= "\$client->setDebug(\$debug);\n";
  794. $this_ = '';
  795. }
  796. else
  797. {
  798. // client copy mode 2 == no client copy in emitted code
  799. $innercode = '';
  800. $this_ = 'this->';
  801. }
  802. $innercode .= "\$msg =& new {$prefix}msg('$methodname');\n";
  803. if ($mdesc != '')
  804. {
  805. // take care that PHP comment is not terminated unwillingly by method description
  806. $mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
  807. }
  808. else
  809. {
  810. $mdesc = "/**\nFunction $xmlrpcfuncname\n";
  811. }
  812. // param parsing
  813. $plist = array();
  814. $pcount = count($msig);
  815. for($i = 1; $i < $pcount; $i++)
  816. {
  817. $plist[] = "\$p$i";
  818. $ptype = $msig[$i];
  819. if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
  820. $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')
  821. {
  822. // only build directly xmlrpcvals when type is known and scalar
  823. $innercode .= "\$p$i =& new {$prefix}val(\$p$i, '$ptype');\n";
  824. }
  825. else
  826. {
  827. if ($encode_php_objects)
  828. {
  829. $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
  830. }
  831. else
  832. {
  833. $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n";
  834. }
  835. }
  836. $innercode .= "\$msg->addparam(\$p$i);\n";
  837. $mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n";
  838. }
  839. if ($client_copy_mode < 2)
  840. {
  841. $plist[] = '$debug=0';
  842. $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
  843. }
  844. $plist = implode(', ', $plist);
  845. $mdesc .= '* @return '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";
  846. $innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
  847. if ($decode_fault)
  848. {
  849. if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))
  850. {
  851. $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";
  852. }
  853. else
  854. {
  855. $respcode = var_export($fault_response, true);
  856. }
  857. }
  858. else
  859. {
  860. $respcode = '$res';
  861. }
  862. if ($decode_php_objects)
  863. {
  864. $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
  865. }
  866. else
  867. {
  868. $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
  869. }
  870. $code = $code . $plist. ") {\n" . $innercode . "\n}\n";
  871. return array('source' => $code, 'docstring' => $mdesc);
  872. }
  873. /**
  874. * Given necessary info, generate php code that will rebuild a client object
  875. * Take care that no full checking of input parameters is done to ensure that
  876. * valid php code is emitted.
  877. * @access private
  878. */
  879. function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
  880. {
  881. $code = "\$client =& new {$prefix}_client('".str_replace("'", "\'", $client->path).
  882. "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
  883. // copy all client fields to the client that will be generated runtime
  884. // (this provides for future expansion or subclassing of client obj)
  885. if ($verbatim_client_copy)
  886. {
  887. foreach($client as $fld => $val)
  888. {
  889. if($fld != 'debug' && $fld != 'return_type')
  890. {
  891. $val = var_export($val, true);
  892. $code .= "\$client->$fld = $val;\n";
  893. }
  894. }
  895. }
  896. // only make sure that client always returns the correct data type
  897. $code .= "\$client->return_type = '{$prefix}vals';\n";
  898. //$code .= "\$client->setDebug(\$debug);\n";
  899. return $code;
  900. }
  901. ?>