3 * @author Gaetano Giunta
4 * @copyright (C) 2006-2014 G. Giunta
5 * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/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)
24 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
25 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
26 * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
27 * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
28 * for php arrays always return array, even though arrays sometimes serialize as json structs
29 * @param string $phptype
32 public function php_2_xmlrpc_type($phptype)
34 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))
58 return Value::$xmlrpcStruct;
62 // unknown: might be any 'extended' xmlrpc type
63 return Value::$xmlrpcValue;
69 * Given a string defining a phpxmlrpc type return corresponding php type.
70 * @param string $xmlrpctype
73 public function xmlrpc_2_php_type($xmlrpctype)
75 switch(strtolower($xmlrpctype))
78 case 'datetime.iso8601':
80 return Value::$xmlrpcString;
94 // unknown: might be any xmlrpc type
95 return strtolower($xmlrpctype);
100 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
101 * be exposed as xmlrpc method from an xmlrpc_server object and called from remote
102 * clients (as well as its corresponding signature info).
104 * Since php is a typeless language, to infer types of input and output parameters,
105 * it relies on parsing the javadoc-style comment block associated with the given
106 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
107 * in the @param tag is also allowed, if you need the php function to receive/send
108 * data in that particular format (note that base64 encoding/decoding is transparently
109 * carried out by the lib, while datetime vals are passed around as strings)
112 * - only works for user-defined functions, not for PHP internal functions
113 * (reflection does not support retrieving number/type of params for those)
114 * - functions returning php objects will generate special xmlrpc responses:
115 * when the xmlrpc decoding of those responses is carried out by this same lib, using
116 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
117 * In short: php objects can be serialized, too (except for their resource members),
118 * using this function.
119 * Other libs might choke on the very same xml that will be generated in this case
120 * (i.e. it has a nonstandard attribute on struct element tags)
121 * - usage of javadoc @param tags using param names in a different order from the
122 * function prototype is not considered valid (to be fixed?)
124 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
125 * php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)
126 * is by making use of the functions_parameters_type class member.
128 * @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
129 * @param string $newfuncname (optional) name for function to be created
130 * @param array $extra_options (optional) array of options for conversion. valid values include:
131 * bool return_source when true, php code w. function definition will be returned, not evaluated
132 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
133 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
134 * bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
135 * @return false on error, or an array containing the name of the new php function,
136 * its signature and docs, to be used in the server dispatch map
138 * @todo decide how to deal with params passed by ref: bomb out or allow?
139 * @todo finish using javadoc info to build method sig if all params are named but out of order
140 * @todo add a check for params of 'resource' type
141 * @todo add some trigger_errors / error_log when returning false?
142 * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
143 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
144 * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
145 * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
147 public function wrap_php_function($funcname, $newfuncname='', $extra_options=array())
149 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
150 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
151 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
152 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
153 $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
156 if (is_string($funcname) && strpos($funcname, '::') !== false)
158 $funcname = explode('::', $funcname);
160 if(is_array($funcname))
162 if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0])))
164 error_log('XML-RPC: syntax for function to be wrapped is wrong');
167 if(is_string($funcname[0]))
169 $plainfuncname = implode('::', $funcname);
171 elseif(is_object($funcname[0]))
173 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
175 $exists = method_exists($funcname[0], $funcname[1]);
179 $plainfuncname = $funcname;
180 $exists = function_exists($funcname);
185 error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname);
190 // determine name of new php function
191 if($newfuncname == '')
193 if(is_array($funcname))
195 if(is_string($funcname[0]))
196 $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);
198 $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1];
202 $xmlrpcfuncname = "{$prefix}_$funcname";
207 $xmlrpcfuncname = $newfuncname;
209 while($buildit && function_exists($xmlrpcfuncname))
211 $xmlrpcfuncname .= 'x';
214 // start to introspect PHP code
215 if(is_array($funcname))
217 $func = new \ReflectionMethod($funcname[0], $funcname[1]);
218 if($func->isPrivate())
220 error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname);
223 if($func->isProtected())
225 error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname);
228 if($func->isConstructor())
230 error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname);
233 if($func->isDestructor())
235 error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname);
238 if($func->isAbstract())
240 error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname);
243 /// @todo add more checks for static vs. nonstatic?
247 $func = new \ReflectionFunction($funcname);
249 if($func->isInternal())
251 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
252 // instead of getparameters to fully reflect internal php functions ?
253 error_log('XML-RPC: function to be wrapped is internal: '.$plainfuncname);
257 // retrieve parameter names, types and description from javadoc comments
259 // function description
261 // type of return val: by default 'any'
262 $returns = Value::$xmlrpcValue;
263 // desc of return val
265 // type + name of function parameters
266 $paramDocs = array();
268 $docs = $func->getDocComment();
271 $docs = explode("\n", $docs);
273 foreach($docs as $doc)
275 $doc = trim($doc, " \r\t/*");
276 if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)
284 elseif(strpos($doc, '@param') === 0)
286 // syntax: @param type [$name] desc
287 if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches))
289 if(strpos($matches[1], '|'))
291 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
292 $paramDocs[$i]['type'] = 'mixed';
296 $paramDocs[$i]['type'] = $matches[1];
298 $paramDocs[$i]['name'] = trim($matches[2]);
299 $paramDocs[$i]['doc'] = $matches[3];
303 elseif(strpos($doc, '@return') === 0)
305 // syntax: @return type desc
306 //$returns = preg_split('/\s+/', $doc);
307 if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))
309 $returns = php_2_xmlrpc_type($matches[1]);
310 if(isset($matches[2]))
312 $returnsDocs = $matches[2];
319 // execute introspection of actual function prototype
322 foreach($func->getParameters() as $paramobj)
324 $params[$i] = array();
325 $params[$i]['name'] = '$'.$paramobj->getName();
326 $params[$i]['isoptional'] = $paramobj->isOptional();
331 // start building of PHP code to be eval'd
334 $parsvariations = array();
336 $pnum = count($params);
337 foreach($params as $param)
339 if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name']))
341 // param name from phpdoc info does not match param definition!
342 $paramDocs[$i]['type'] = 'mixed';
345 if($param['isoptional'])
347 // this particular parameter is optional. save as valid previous list of parameters
348 $innercode .= "if (\$paramcount > $i) {\n";
349 $parsvariations[] = $pars;
351 $innercode .= "\$p$i = \$msg->getParam($i);\n";
352 if ($decode_php_objects)
354 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
358 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
363 if($param['isoptional'])
369 // last allowed parameters combination
370 $parsvariations[] = $pars;
376 if(count($parsvariations) == 0)
378 // only known good synopsis = no parameters
379 $parsvariations[] = array();
384 $minpars = count($parsvariations[0]);
389 // add to code the check for min params number
390 // NB: this check needs to be done BEFORE decoding param values
391 $innercode = "\$paramcount = \$msg->getNumParams();\n" .
392 "if (\$paramcount < $minpars) return new {$prefix}resp(0, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."');\n" . $innercode;
396 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
399 $innercode .= "\$np = false;\n";
400 // since there are no closures in php, if we are given an object instance,
401 // we store a pointer to it in a global var...
402 if ( is_array($funcname) && is_object($funcname[0]) )
404 $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0];
405 $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
406 $realfuncname = '$obj->'.$funcname[1];
410 $realfuncname = $plainfuncname;
412 foreach($parsvariations as $pars)
414 $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
415 // build a 'generic' signature (only use an appropriate return type)
416 $sig = array($returns);
417 $psig = array($returnsDocs);
418 for($i=0; $i < count($pars); $i++)
420 if (isset($paramDocs[$i]['type']))
422 $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
426 $sig[] = Value::$xmlrpcValue;
428 $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
433 $innercode .= "\$np = true;\n";
434 $innercode .= "if (\$np) return new {$prefix}resp(0, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."'); else {\n";
435 //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
436 $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
437 if($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64)
439 $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
443 if ($encode_php_objects)
444 $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
446 $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
448 // shall we exclude functions returning by ref?
449 // if($func->returnsReference())
451 $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
456 eval($code.'$allOK=1;');
458 //$xmlrpcfuncname = create_function('$m', $innercode);
462 error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$plainfuncname);
467 /// @todo examine if $paramDocs matches $parsvariations and build array for
468 /// usage as method signature, plus put together a nice string for docs
470 $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
476 * Given a user-defined PHP class or php object, map its methods onto a list of
477 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
478 * object and called from remote clients (as well as their corresponding signature info).
480 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
481 * @param array $extra_options see the docs for wrap_php_method for more options
482 * 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
483 * @return array or false on failure
485 * @todo get_class_methods will return both static and non-static methods.
486 * we have to differentiate the action, depending on wheter we recived a class name or object
488 public function wrap_php_class($classname, $extra_options=array())
490 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
491 $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
494 $mlist = get_class_methods($classname);
495 foreach($mlist as $mname)
497 if ($methodfilter == '' || preg_match($methodfilter, $mname))
500 $func = new ReflectionMethod($classname, $mname);
501 if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract())
503 if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
504 (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))))
506 $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
509 $result[$methodwrap['function']] = $methodwrap['function'];
519 * Given an xmlrpc client and a method name, register a php wrapper function
520 * that will call it and return results using native php types for both
521 * params and results. The generated php function will return an xmlrpcresp
522 * object for failed xmlrpc calls
525 * - server must support system.methodsignature for the wanted xmlrpc method
526 * - for methods that expose many signatures, only one can be picked (we
527 * could in principle check if signatures differ only by number of params
528 * and not by type, but it would be more complication than we can spare time)
529 * - nested xmlrpc params: the caller of the generated php function has to
530 * encode on its own the params passed to the php function if these are structs
531 * or arrays whose (sub)members include values of type datetime or base64
533 * Notes: the connection properties of the given client will be copied
534 * and reused for the connection used during the call to the generated
536 * Calling the generated php function 'might' be slow: a new xmlrpc client
537 * is created on every invocation and an xmlrpc-connection opened+closed.
538 * An extra 'debug' param is appended to param list of xmlrpc method, useful
539 * for debugging purposes.
541 * @param xmlrpc_client $client an xmlrpc client set up correctly to communicate with target server
542 * @param string $methodname the xmlrpc method to be mapped to a php function
543 * @param array $extra_options array of options that specify conversion details. valid options include
544 * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
545 * integer timeout timeout (in secs) to be used when executing function/calling remote method
546 * string protocol 'http' (default), 'http11' or 'https'
547 * string new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
548 * string return_source if true return php code w. function definition instead fo function name
549 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
550 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
551 * 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
552 * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
553 * @return string the name of the generated php function (or false) - OR AN ARRAY...
555 public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')
557 // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
558 // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
559 if (!is_array($extra_options))
561 $signum = $extra_options;
562 $extra_options = array();
566 $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
567 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
568 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
569 $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
571 //$encode_php_objects = in_array('encode_php_objects', $extra_options);
572 //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
573 // in_array('build_class_code', $extra_options) ? 2 : 0;
575 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
576 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
577 // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
578 $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
579 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
580 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
581 if (isset($extra_options['return_on_fault']))
583 $decode_fault = true;
584 $fault_response = $extra_options['return_on_fault'];
588 $decode_fault = false;
589 $fault_response = '';
591 $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
593 $msgclass = $prefix.'msg';
594 $valclass = $prefix.'val';
595 $decodefunc = 'php_'.$prefix.'_decode';
597 $msg = new $msgclass('system.methodSignature');
598 $msg->addparam(new $valclass($methodname));
599 $client->setDebug($debug);
600 $response = $client->send($msg, $timeout, $protocol);
601 if($response->faultCode())
603 error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);
608 $msig = $response->value();
609 if ($client->return_type != 'phpvals')
611 $msig = $decodefunc($msig);
613 if(!is_array($msig) || count($msig) <= $signum)
615 error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);
620 // pick a suitable name for the new function, avoiding collisions
621 if($newfuncname != '')
623 $xmlrpcfuncname = $newfuncname;
627 // take care to insure that methodname is translated to valid
629 $xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
630 array('_', ''), $methodname);
632 while($buildit && function_exists($xmlrpcfuncname))
634 $xmlrpcfuncname .= 'x';
637 $msig = $msig[$signum];
639 // if in 'offline' mode, get method description too.
640 // in online mode, favour speed of operation
643 $msg = new $msgclass('system.methodHelp');
644 $msg->addparam(new $valclass($methodname));
645 $response = $client->send($msg, $timeout, $protocol);
646 if (!$response->faultCode())
648 $mdesc = $response->value();
649 if ($client->return_type != 'phpvals')
651 $mdesc = $mdesc->scalarval();
656 $results = $this->build_remote_method_wrapper_code($client, $methodname,
657 $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
658 $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
665 eval($results['source'].'$allOK=1;');
667 //$xmlrpcfuncname = create_function('$m', $innercode);
670 return $xmlrpcfuncname;
674 error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
680 $results['function'] = $xmlrpcfuncname;
688 * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
689 * all xmlrpc methods exposed by the remote server as own methods.
690 * For more details see wrap_xmlrpc_method.
691 * @param xmlrpc_client $client the client obj all set to query the desired server
692 * @param array $extra_options list of options for wrapped code
693 * @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)
695 public function wrap_xmlrpc_server($client, $extra_options=array())
697 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
698 //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
699 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
700 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
701 $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
702 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
703 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
704 $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
705 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
706 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
708 $msgclass = $prefix.'msg';
709 //$valclass = $prefix.'val';
710 $decodefunc = 'php_'.$prefix.'_decode';
712 $msg = new $msgclass('system.listMethods');
713 $response = $client->send($msg, $timeout, $protocol);
714 if($response->faultCode())
716 error_log('XML-RPC: could not retrieve method list from remote server');
721 $mlist = $response->value();
722 if ($client->return_type != 'phpvals')
724 $mlist = $decodefunc($mlist);
726 if(!is_array($mlist) || !count($mlist))
728 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
733 // pick a suitable name for the new function, avoiding collisions
734 if($newclassname != '')
736 $xmlrpcclassname = $newclassname;
740 $xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
741 array('_', ''), $client->server).'_client';
743 while($buildit && class_exists($xmlrpcclassname))
745 $xmlrpcclassname .= 'x';
748 /// @todo add function setdebug() to new class, to enable/disable debugging
749 $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
750 $source .= "function $xmlrpcclassname()\n{\n";
751 $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
752 $source .= "\$this->client =& \$client;\n}\n\n";
753 $opts = array('simple_client_copy' => 2, 'return_source' => true,
754 'timeout' => $timeout, 'protocol' => $protocol,
755 'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
756 'decode_php_objs' => $decode_php_objects
758 /// @todo build javadoc for class definition, too
759 foreach($mlist as $mname)
761 if ($methodfilter == '' || preg_match($methodfilter, $mname))
763 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
764 array('_', ''), $mname);
765 $methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
770 $source .= $methodwrap['docstring'];
772 $source .= $methodwrap['source']."\n";
776 error_log('XML-RPC: will not create class method to wrap remote method '.$mname);
784 eval($source.'$allOK=1;');
786 //$xmlrpcfuncname = create_function('$m', $innercode);
789 return $xmlrpcclassname;
793 error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
799 return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
806 * Given the necessary info, build php code that creates a new function to
807 * invoke a remote xmlrpc method.
808 * Take care that no full checking of input parameters is done to ensure that
809 * valid php code is emitted.
810 * Note: real spaghetti code follows...
812 protected function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
813 $msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',
814 $decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,
817 $code = "function $xmlrpcfuncname (";
818 if ($client_copy_mode < 2)
820 // client copy mode 0 or 1 == partial / full client copy in emitted code
821 $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix);
822 $innercode .= "\$client->setDebug(\$debug);\n";
827 // client copy mode 2 == no client copy in emitted code
831 $innercode .= "\$msg = new {$prefix}msg('$methodname');\n";
835 // take care that PHP comment is not terminated unwillingly by method description
836 $mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
840 $mdesc = "/**\nFunction $xmlrpcfuncname\n";
845 $pcount = count($msig);
846 for($i = 1; $i < $pcount; $i++)
850 if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
851 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')
853 // only build directly xmlrpcvals when type is known and scalar
854 $innercode .= "\$p$i = new {$prefix}val(\$p$i, '$ptype');\n";
858 if ($encode_php_objects)
860 $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
864 $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i);\n";
867 $innercode .= "\$msg->addparam(\$p$i);\n";
868 $mdesc .= '* @param '.$this->xmlrpc_2_php_type($ptype)." \$p$i\n";
870 if ($client_copy_mode < 2)
872 $plist[] = '$debug=0';
873 $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
875 $plist = implode(', ', $plist);
876 $mdesc .= '* @return '.$this->xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";
878 $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
881 if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))
883 $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";
887 $respcode = var_export($fault_response, true);
894 if ($decode_php_objects)
896 $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
900 $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
903 $code = $code . $plist. ") {\n" . $innercode . "\n}\n";
905 return array('source' => $code, 'docstring' => $mdesc);
909 * Given necessary info, generate php code that will rebuild a client object
910 * Take care that no full checking of input parameters is done to ensure that
911 * valid php code is emitted.
913 protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
915 $code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).
916 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
918 // copy all client fields to the client that will be generated runtime
919 // (this provides for future expansion or subclassing of client obj)
920 if ($verbatim_client_copy)
922 foreach($client as $fld => $val)
924 if($fld != 'debug' && $fld != 'return_type')
926 $val = var_export($val, true);
927 $code .= "\$client->$fld = $val;\n";
931 // only make sure that client always returns the correct data type
932 $code .= "\$client->return_type = '{$prefix}vals';\n";
933 //$code .= "\$client->setDebug(\$debug);\n";