PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/lib/xmlrpc/xmlrpc_wrappers.inc

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