3 * @author Gaetano Giunta
4 * @copyright (C) 2006-2015 G. Giunta
5 * @license code licensed under the BSD License: see file license.txt
11 * PHP-XMLRPC "wrapper" class.
12 * Generate stubs to transparently access xmlrpc methods as php functions and viceversa.
13 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
15 * @todo separate introspection from code generation for func-2-method wrapping
16 * @todo use some better templating system for code generation?
17 * @todo implement method wrapping with preservation of php objs in calls
18 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
23 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
24 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
25 * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
26 * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
27 * for php arrays always return array, even though arrays sometimes serialize as json structs.
29 * @param string $phptype
33 public function php_2_xmlrpc_type($phptype)
35 switch (strtolower($phptype)) {
37 return Value::$xmlrpcString;
39 case Value::$xmlrpcInt: // 'int'
40 case Value::$xmlrpcI4:
41 return Value::$xmlrpcInt;
43 return Value::$xmlrpcDouble;
45 return Value::$xmlrpcBoolean;
47 return Value::$xmlrpcArray;
49 return Value::$xmlrpcStruct;
50 case Value::$xmlrpcBase64:
51 case Value::$xmlrpcStruct:
52 return strtolower($phptype);
56 if (class_exists($phptype)) {
57 return Value::$xmlrpcStruct;
59 // unknown: might be any 'extended' xmlrpc type
60 return Value::$xmlrpcValue;
66 * Given a string defining a phpxmlrpc type return corresponding php type.
68 * @param string $xmlrpctype
72 public function xmlrpc_2_php_type($xmlrpctype)
74 switch (strtolower($xmlrpctype)) {
76 case 'datetime.iso8601':
78 return Value::$xmlrpcString;
92 // unknown: might be any xmlrpc type
93 return strtolower($xmlrpctype);
98 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
99 * be exposed as xmlrpc method from an xmlrpc_server object and called from remote
100 * clients (as well as its corresponding signature info).
102 * Since php is a typeless language, to infer types of input and output parameters,
103 * it relies on parsing the javadoc-style comment block associated with the given
104 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
105 * in the @param tag is also allowed, if you need the php function to receive/send
106 * data in that particular format (note that base64 encoding/decoding is transparently
107 * carried out by the lib, while datetime vals are passed around as strings)
110 * - only works for user-defined functions, not for PHP internal functions
111 * (reflection does not support retrieving number/type of params for those)
112 * - functions returning php objects will generate special xmlrpc responses:
113 * when the xmlrpc decoding of those responses is carried out by this same lib, using
114 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
115 * In short: php objects can be serialized, too (except for their resource members),
116 * using this function.
117 * Other libs might choke on the very same xml that will be generated in this case
118 * (i.e. it has a nonstandard attribute on struct element tags)
119 * - usage of javadoc @param tags using param names in a different order from the
120 * function prototype is not considered valid (to be fixed?)
122 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
123 * php functions (ie. functions not expecting a single Request obj as parameter)
124 * is by making use of the functions_parameters_type class member.
126 * @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
127 * @param string $newfuncname (optional) name for function to be created
128 * @param array $extra_options (optional) array of options for conversion. valid values include:
129 * bool return_source when true, php code w. function definition will be returned, not evaluated
130 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
131 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
132 * bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
134 * @return false on error, or an array containing the name of the new php function,
135 * its signature and docs, to be used in the server dispatch map
137 * @todo decide how to deal with params passed by ref: bomb out or allow?
138 * @todo finish using javadoc info to build method sig if all params are named but out of order
139 * @todo add a check for params of 'resource' type
140 * @todo add some trigger_errors / error_log when returning false?
141 * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
142 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
143 * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
144 * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
146 public function wrap_php_function($funcname, $newfuncname = '', $extra_options = array())
148 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
149 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
150 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
151 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
152 $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
155 if (is_string($funcname) && strpos($funcname, '::') !== false) {
156 $funcname = explode('::', $funcname);
158 if (is_array($funcname)) {
159 if (count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) {
160 error_log('XML-RPC: syntax for function to be wrapped is wrong');
164 if (is_string($funcname[0])) {
165 $plainfuncname = implode('::', $funcname);
166 } elseif (is_object($funcname[0])) {
167 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
169 $exists = method_exists($funcname[0], $funcname[1]);
171 $plainfuncname = $funcname;
172 $exists = function_exists($funcname);
176 error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname);
180 // determine name of new php function
181 if ($newfuncname == '') {
182 if (is_array($funcname)) {
183 if (is_string($funcname[0])) {
184 $xmlrpcfuncname = "{$prefix}_" . implode('_', $funcname);
186 $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1];
189 $xmlrpcfuncname = "{$prefix}_$funcname";
192 $xmlrpcfuncname = $newfuncname;
194 while ($buildit && function_exists($xmlrpcfuncname)) {
195 $xmlrpcfuncname .= 'x';
198 // start to introspect PHP code
199 if (is_array($funcname)) {
200 $func = new \ReflectionMethod($funcname[0], $funcname[1]);
201 if ($func->isPrivate()) {
202 error_log('XML-RPC: method to be wrapped is private: ' . $plainfuncname);
206 if ($func->isProtected()) {
207 error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname);
211 if ($func->isConstructor()) {
212 error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname);
216 if ($func->isDestructor()) {
217 error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname);
221 if ($func->isAbstract()) {
222 error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname);
226 /// @todo add more checks for static vs. nonstatic?
228 $func = new \ReflectionFunction($funcname);
230 if ($func->isInternal()) {
231 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
232 // instead of getparameters to fully reflect internal php functions ?
233 error_log('XML-RPC: function to be wrapped is internal: ' . $plainfuncname);
238 // retrieve parameter names, types and description from javadoc comments
240 // function description
242 // type of return val: by default 'any'
243 $returns = Value::$xmlrpcValue;
244 // desc of return val
246 // type + name of function parameters
247 $paramDocs = array();
249 $docs = $func->getDocComment();
251 $docs = explode("\n", $docs);
253 foreach ($docs as $doc) {
254 $doc = trim($doc, " \r\t/*");
255 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
260 } elseif (strpos($doc, '@param') === 0) {
261 // syntax: @param type [$name] desc
262 if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
263 if (strpos($matches[1], '|')) {
264 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
265 $paramDocs[$i]['type'] = 'mixed';
267 $paramDocs[$i]['type'] = $matches[1];
269 $paramDocs[$i]['name'] = trim($matches[2]);
270 $paramDocs[$i]['doc'] = $matches[3];
273 } elseif (strpos($doc, '@return') === 0) {
274 // syntax: @return type desc
275 //$returns = preg_split('/\s+/', $doc);
276 if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
277 $returns = php_2_xmlrpc_type($matches[1]);
278 if (isset($matches[2])) {
279 $returnsDocs = $matches[2];
286 // execute introspection of actual function prototype
289 foreach ($func->getParameters() as $paramobj) {
290 $params[$i] = array();
291 $params[$i]['name'] = '$' . $paramobj->getName();
292 $params[$i]['isoptional'] = $paramobj->isOptional();
296 // start building of PHP code to be eval'd
299 $parsvariations = array();
301 $pnum = count($params);
302 foreach ($params as $param) {
303 if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name'])) {
304 // param name from phpdoc info does not match param definition!
305 $paramDocs[$i]['type'] = 'mixed';
308 if ($param['isoptional']) {
309 // this particular parameter is optional. save as valid previous list of parameters
310 $innercode .= "if (\$paramcount > $i) {\n";
311 $parsvariations[] = $pars;
313 $innercode .= "\$p$i = \$msg->getParam($i);\n";
314 if ($decode_php_objects) {
315 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
317 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
322 if ($param['isoptional']) {
326 // last allowed parameters combination
327 $parsvariations[] = $pars;
333 if (count($parsvariations) == 0) {
334 // only known good synopsis = no parameters
335 $parsvariations[] = array();
338 $minpars = count($parsvariations[0]);
342 // add to code the check for min params number
343 // NB: this check needs to be done BEFORE decoding param values
344 $innercode = "\$paramcount = \$msg->getNumParams();\n" .
345 "if (\$paramcount < $minpars) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode;
347 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
350 $innercode .= "\$np = false;\n";
351 // since there are no closures in php, if we are given an object instance,
352 // we store a pointer to it in a global var...
353 if (is_array($funcname) && is_object($funcname[0])) {
354 $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] = &$funcname[0];
355 $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
356 $realfuncname = '$obj->' . $funcname[1];
358 $realfuncname = $plainfuncname;
360 foreach ($parsvariations as $pars) {
361 $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
362 // build a 'generic' signature (only use an appropriate return type)
363 $sig = array($returns);
364 $psig = array($returnsDocs);
365 for ($i = 0; $i < count($pars); $i++) {
366 if (isset($paramDocs[$i]['type'])) {
367 $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
369 $sig[] = Value::$xmlrpcValue;
371 $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
376 $innercode .= "\$np = true;\n";
377 $innercode .= "if (\$np) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n";
378 //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
379 $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
380 if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) {
381 $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
383 if ($encode_php_objects) {
384 $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
386 $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
389 // shall we exclude functions returning by ref?
390 // if($func->returnsReference())
392 $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
396 eval($code . '$allOK=1;');
398 //$xmlrpcfuncname = create_function('$m', $innercode);
401 error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname);
407 /// @todo examine if $paramDocs matches $parsvariations and build array for
408 /// usage as method signature, plus put together a nice string for docs
410 $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
417 * Given a user-defined PHP class or php object, map its methods onto a list of
418 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
419 * object and called from remote clients (as well as their corresponding signature info).
421 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
422 * @param array $extra_options see the docs for wrap_php_method for more options
423 * 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
425 * @return array or false on failure
427 * @todo get_class_methods will return both static and non-static methods.
428 * we have to differentiate the action, depending on wheter we recived a class name or object
430 public function wrap_php_class($classname, $extra_options = array())
432 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
433 $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
436 $mlist = get_class_methods($classname);
437 foreach ($mlist as $mname) {
438 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
440 $func = new \ReflectionMethod($classname, $mname);
441 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
442 if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
443 (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
445 $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
447 $result[$methodwrap['function']] = $methodwrap['function'];
458 * Given an xmlrpc client and a method name, register a php wrapper function
459 * that will call it and return results using native php types for both
460 * params and results. The generated php function will return a Response
461 * object for failed xmlrpc calls.
464 * - server must support system.methodsignature for the wanted xmlrpc method
465 * - for methods that expose many signatures, only one can be picked (we
466 * could in principle check if signatures differ only by number of params
467 * and not by type, but it would be more complication than we can spare time)
468 * - nested xmlrpc params: the caller of the generated php function has to
469 * encode on its own the params passed to the php function if these are structs
470 * or arrays whose (sub)members include values of type datetime or base64
472 * Notes: the connection properties of the given client will be copied
473 * and reused for the connection used during the call to the generated
475 * Calling the generated php function 'might' be slow: a new xmlrpc client
476 * is created on every invocation and an xmlrpc-connection opened+closed.
477 * An extra 'debug' param is appended to param list of xmlrpc method, useful
478 * for debugging purposes.
480 * @param Client $client an xmlrpc client set up correctly to communicate with target server
481 * @param string $methodname the xmlrpc method to be mapped to a php function
482 * @param array $extra_options array of options that specify conversion details. valid options include
483 * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
484 * integer timeout timeout (in secs) to be used when executing function/calling remote method
485 * string protocol 'http' (default), 'http11' or 'https'
486 * string new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
487 * string return_source if true return php code w. function definition instead fo function name
488 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
489 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
490 * mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the Response object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
491 * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
493 * @return string the name of the generated php function (or false) - OR AN ARRAY...
495 public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $timeout = 0, $protocol = '', $newfuncname = '')
497 // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
498 // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
499 if (!is_array($extra_options)) {
500 $signum = $extra_options;
501 $extra_options = array();
503 $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
504 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
505 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
506 $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
508 //$encode_php_objects = in_array('encode_php_objects', $extra_options);
509 //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
510 // in_array('build_class_code', $extra_options) ? 2 : 0;
512 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
513 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
514 // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
515 $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
516 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
517 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
518 if (isset($extra_options['return_on_fault'])) {
519 $decode_fault = true;
520 $fault_response = $extra_options['return_on_fault'];
522 $decode_fault = false;
523 $fault_response = '';
525 $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
527 $msgclass = $prefix . 'msg';
528 $valclass = $prefix . 'val';
529 $decodefunc = 'php_' . $prefix . '_decode';
531 $msg = new $msgclass('system.methodSignature');
532 $msg->addparam(new $valclass($methodname));
533 $client->setDebug($debug);
534 $response = $client->send($msg, $timeout, $protocol);
535 if ($response->faultCode()) {
536 error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodname);
540 $msig = $response->value();
541 if ($client->return_type != 'phpvals') {
542 $msig = $decodefunc($msig);
544 if (!is_array($msig) || count($msig) <= $signum) {
545 error_log('XML-RPC: could not retrieve method signature nr.' . $signum . ' from remote server for method ' . $methodname);
549 // pick a suitable name for the new function, avoiding collisions
550 if ($newfuncname != '') {
551 $xmlrpcfuncname = $newfuncname;
553 // take care to insure that methodname is translated to valid
555 $xmlrpcfuncname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
556 array('_', ''), $methodname);
558 while ($buildit && function_exists($xmlrpcfuncname)) {
559 $xmlrpcfuncname .= 'x';
562 $msig = $msig[$signum];
564 // if in 'offline' mode, get method description too.
565 // in online mode, favour speed of operation
567 $msg = new $msgclass('system.methodHelp');
568 $msg->addparam(new $valclass($methodname));
569 $response = $client->send($msg, $timeout, $protocol);
570 if (!$response->faultCode()) {
571 $mdesc = $response->value();
572 if ($client->return_type != 'phpvals') {
573 $mdesc = $mdesc->scalarval();
578 $results = $this->build_remote_method_wrapper_code($client, $methodname,
579 $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
580 $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
586 eval($results['source'] . '$allOK=1;');
588 //$xmlrpcfuncname = create_function('$m', $innercode);
590 return $xmlrpcfuncname;
592 error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname);
597 $results['function'] = $xmlrpcfuncname;
606 * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
607 * all xmlrpc methods exposed by the remote server as own methods.
608 * For more details see wrap_xmlrpc_method.
610 * @param Client $client the client obj all set to query the desired server
611 * @param array $extra_options list of options for wrapped code
613 * @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)
615 public function wrap_xmlrpc_server($client, $extra_options = array())
617 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
618 //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
619 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
620 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
621 $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
622 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
623 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
624 $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
625 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
626 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
628 $msgclass = $prefix . 'msg';
629 //$valclass = $prefix.'val';
630 $decodefunc = 'php_' . $prefix . '_decode';
632 $msg = new $msgclass('system.listMethods');
633 $response = $client->send($msg, $timeout, $protocol);
634 if ($response->faultCode()) {
635 error_log('XML-RPC: could not retrieve method list from remote server');
639 $mlist = $response->value();
640 if ($client->return_type != 'phpvals') {
641 $mlist = $decodefunc($mlist);
643 if (!is_array($mlist) || !count($mlist)) {
644 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
648 // pick a suitable name for the new function, avoiding collisions
649 if ($newclassname != '') {
650 $xmlrpcclassname = $newclassname;
652 $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
653 array('_', ''), $client->server) . '_client';
655 while ($buildit && class_exists($xmlrpcclassname)) {
656 $xmlrpcclassname .= 'x';
659 /// @todo add function setdebug() to new class, to enable/disable debugging
660 $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
661 $source .= "function $xmlrpcclassname()\n{\n";
662 $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
663 $source .= "\$this->client =& \$client;\n}\n\n";
664 $opts = array('simple_client_copy' => 2, 'return_source' => true,
665 'timeout' => $timeout, 'protocol' => $protocol,
666 'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
667 'decode_php_objs' => $decode_php_objects,
669 /// @todo build javadoc for class definition, too
670 foreach ($mlist as $mname) {
671 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
672 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
673 array('_', ''), $mname);
674 $methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
677 $source .= $methodwrap['docstring'];
679 $source .= $methodwrap['source'] . "\n";
681 error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
688 eval($source . '$allOK=1;');
690 //$xmlrpcfuncname = create_function('$m', $innercode);
692 return $xmlrpcclassname;
694 error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server);
699 return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
706 * Given the necessary info, build php code that creates a new function to
707 * invoke a remote xmlrpc method.
708 * Take care that no full checking of input parameters is done to ensure that
709 * valid php code is emitted.
710 * Note: real spaghetti code follows...
712 protected function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
713 $msig, $mdesc = '', $timeout = 0, $protocol = '', $client_copy_mode = 0, $prefix = 'xmlrpc',
714 $decode_php_objects = false, $encode_php_objects = false, $decode_fault = false,
715 $fault_response = '')
717 $code = "function $xmlrpcfuncname (";
718 if ($client_copy_mode < 2) {
719 // client copy mode 0 or 1 == partial / full client copy in emitted code
720 $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix);
721 $innercode .= "\$client->setDebug(\$debug);\n";
724 // client copy mode 2 == no client copy in emitted code
728 $innercode .= "\$msg = new {$prefix}msg('$methodname');\n";
731 // take care that PHP comment is not terminated unwillingly by method description
732 $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
734 $mdesc = "/**\nFunction $xmlrpcfuncname\n";
739 $pcount = count($msig);
740 for ($i = 1; $i < $pcount; $i++) {
743 if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
744 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
746 // only build directly xmlrpcvals when type is known and scalar
747 $innercode .= "\$p$i = new {$prefix}val(\$p$i, '$ptype');\n";
749 if ($encode_php_objects) {
750 $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
752 $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i);\n";
755 $innercode .= "\$msg->addparam(\$p$i);\n";
756 $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
758 if ($client_copy_mode < 2) {
759 $plist[] = '$debug=0';
760 $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
762 $plist = implode(', ', $plist);
763 $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$prefix}resp obj instance if call fails)\n*/\n";
765 $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
767 if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false))) {
768 $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $fault_response) . "')";
770 $respcode = var_export($fault_response, true);
775 if ($decode_php_objects) {
776 $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
778 $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
781 $code = $code . $plist . ") {\n" . $innercode . "\n}\n";
783 return array('source' => $code, 'docstring' => $mdesc);
787 * Given necessary info, generate php code that will rebuild a client object
788 * Take care that no full checking of input parameters is done to ensure that
789 * valid php code is emitted.
791 protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc')
793 $code = "\$client = new {$prefix}_client('" . str_replace("'", "\'", $client->path) .
794 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
796 // copy all client fields to the client that will be generated runtime
797 // (this provides for future expansion or subclassing of client obj)
798 if ($verbatim_client_copy) {
799 foreach ($client as $fld => $val) {
800 if ($fld != 'debug' && $fld != 'return_type') {
801 $val = var_export($val, true);
802 $code .= "\$client->$fld = $val;\n";
806 // only make sure that client always returns the correct data type
807 $code .= "\$client->return_type = '{$prefix}vals';\n";
808 //$code .= "\$client->setDebug(\$debug);\n";