3 * @author Gaetano Giunta
4 * @copyright (C) 2006-2021 G. Giunta
5 * @license code licensed under the BSD License: see file license.txt
10 use PhpXmlRpc\Helper\Logger;
13 * PHP-XMLRPC "wrapper" class - generate stubs to transparently access xmlrpc methods as php functions and vice-versa.
14 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
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)
19 * @todo add support for 'epivals' mode
20 * @todo allow setting custom namespace for generated wrapping code
24 /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
25 public static $objHolder = array();
27 protected static $logger;
29 public function getLogger()
31 if (self::$logger === null) {
32 self::$logger = Logger::instance();
37 public static function setLogger($logger)
39 self::$logger = $logger;
43 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
44 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
46 * - for php 'resource' types returns empty string, since resources cannot be serialized;
47 * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
48 * - for php arrays always return array, even though arrays sometimes serialize as structs...
49 * - for 'void' and 'null' returns 'undefined'
51 * @param string $phpType
55 * @todo support notation `something[]` as 'array'
57 public function php2XmlrpcType($phpType)
59 switch (strtolower($phpType)) {
61 return Value::$xmlrpcString;
63 case Value::$xmlrpcInt: // 'int'
64 case Value::$xmlrpcI4:
65 case Value::$xmlrpcI8:
66 return Value::$xmlrpcInt;
67 case Value::$xmlrpcDouble: // 'double'
68 return Value::$xmlrpcDouble;
70 case Value::$xmlrpcBoolean: // 'boolean'
73 return Value::$xmlrpcBoolean;
74 case Value::$xmlrpcArray: // 'array':
76 return Value::$xmlrpcArray;
78 case Value::$xmlrpcStruct: // 'struct'
79 return Value::$xmlrpcStruct;
80 case Value::$xmlrpcBase64:
81 return Value::$xmlrpcBase64;
85 if (class_exists($phpType)) {
86 if (is_a($phpType, 'DateTimeInterface')) {
87 return Value::$xmlrpcDateTime;
89 return Value::$xmlrpcStruct;
91 // unknown: might be any 'extended' xmlrpc type
92 return Value::$xmlrpcValue;
98 * Given a string defining a phpxmlrpc type return the corresponding php type.
100 * @param string $xmlrpcType
104 public function xmlrpc2PhpType($xmlrpcType)
106 switch (strtolower($xmlrpcType)) {
108 case 'datetime.iso8601':
110 return Value::$xmlrpcString;
125 // unknown: might be any xmlrpc type
126 return strtolower($xmlrpcType);
131 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
132 * be exposed as xmlrpc method from an xmlrpc server object and called from remote
133 * clients (as well as its corresponding signature info).
135 * Since php is a typeless language, to infer types of input and output parameters,
136 * it relies on parsing the javadoc-style comment block associated with the given
137 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
138 * in the '@param' tag is also allowed, if you need the php function to receive/send
139 * data in that particular format (note that base64 encoding/decoding is transparently
140 * carried out by the lib, while datetime vals are passed around as strings)
143 * - only works for user-defined functions, not for PHP internal functions
144 * (reflection does not support retrieving number/type of params for those)
145 * - functions returning php objects will generate special structs in xmlrpc responses:
146 * when the xmlrpc decoding of those responses is carried out by this same lib, using
147 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
148 * In short: php objects can be serialized, too (except for their resource members),
149 * using this function.
150 * Other libs might choke on the very same xml that will be generated in this case
151 * (i.e. it has a nonstandard attribute on struct element tags)
153 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
154 * php functions (ie. functions not expecting a single Request obj as parameter)
155 * is by making use of the functions_parameters_type class member.
157 * @param callable $callable the PHP user function to be exposed as xmlrpc method/ a closure, function name, array($obj, 'methodname') or array('class', 'methodname') are ok
158 * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
159 * @param array $extraOptions (optional) array of options for conversion. valid values include:
160 * - bool return_source when true, php code w. function definition will be returned, instead of a closure
161 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
162 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
163 * - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
165 * @return array|false false on error, or an array containing the name of the new php function,
166 * its signature and docs, to be used in the server dispatch map
168 * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
169 * @todo finish using phpdoc info to build method sig if all params are named but out of order
170 * @todo add a check for params of 'resource' type
171 * @todo add some trigger_errors / error_log when returning false?
172 * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
173 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
174 * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
175 * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
177 public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
179 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
181 if (is_string($callable) && strpos($callable, '::') !== false) {
182 $callable = explode('::', $callable);
184 if (is_array($callable)) {
185 if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
186 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
189 if (is_string($callable[0])) {
190 $plainFuncName = implode('::', $callable);
191 } elseif (is_object($callable[0])) {
192 $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
194 $exists = method_exists($callable[0], $callable[1]);
195 } else if ($callable instanceof \Closure) {
196 // we do not support creating code which wraps closures, as php does not allow to serialize them
198 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
202 $plainFuncName = 'Closure';
205 $plainFuncName = $callable;
206 $exists = function_exists($callable);
210 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName);
214 $funcDesc = $this->introspectFunction($callable, $plainFuncName);
219 $funcSigs = $this->buildMethodSignatures($funcDesc);
222 $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
224 $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
225 $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
229 'function' => $callable,
230 'signature' => $funcSigs['sigs'],
231 'docstring' => $funcDesc['desc'],
232 'signature_docs' => $funcSigs['sigsDocs'],
235 $ret['function'] = $newFuncName;
236 $ret['source'] = $code;
242 * Introspect a php callable and its phpdoc block and extract information about its signature
244 * @param callable $callable
245 * @param string $plainFuncName
246 * @return array|false
248 protected function introspectFunction($callable, $plainFuncName)
250 // start to introspect PHP code
251 if (is_array($callable)) {
252 $func = new \ReflectionMethod($callable[0], $callable[1]);
253 if ($func->isPrivate()) {
254 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
257 if ($func->isProtected()) {
258 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
261 if ($func->isConstructor()) {
262 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
265 if ($func->isDestructor()) {
266 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
269 if ($func->isAbstract()) {
270 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
273 /// @todo add more checks for static vs. nonstatic?
275 $func = new \ReflectionFunction($callable);
277 if ($func->isInternal()) {
278 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
279 // instead of getparameters to fully reflect internal php functions ?
280 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
284 // retrieve parameter names, types and description from javadoc comments
286 // function description
288 // type of return val: by default 'any'
289 $returns = Value::$xmlrpcValue;
290 // desc of return val
292 // type + name of function parameters
293 $paramDocs = array();
295 $docs = $func->getDocComment();
297 $docs = explode("\n", $docs);
299 foreach ($docs as $doc) {
300 $doc = trim($doc, " \r\t/*");
301 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
306 } elseif (strpos($doc, '@param') === 0) {
307 // syntax: @param type $name [desc]
308 if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
309 $name = strtolower(trim($matches[2]));
310 //$paramDocs[$name]['name'] = trim($matches[2]);
311 $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
312 $paramDocs[$name]['type'] = $matches[1];
315 } elseif (strpos($doc, '@return') === 0) {
316 // syntax: @return type [desc]
317 if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
318 $returns = $matches[1];
319 if (isset($matches[2])) {
320 $returnsDocs = trim($matches[2]);
327 // execute introspection of actual function prototype
330 foreach ($func->getParameters() as $paramObj) {
331 $params[$i] = array();
332 $params[$i]['name'] = '$' . $paramObj->getName();
333 $params[$i]['isoptional'] = $paramObj->isOptional();
340 'params' => $params, // array, positionally indexed
341 'paramDocs' => $paramDocs, // array, indexed by name
342 'returns' => $returns,
343 'returnsDocs' =>$returnsDocs,
348 * Given the method description given by introspection, create method signature data
350 * @todo support better docs with multiple types separated by pipes by creating multiple signatures
351 * (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
353 * @param array $funcDesc as generated by self::introspectFunction()
357 protected function buildMethodSignatures($funcDesc)
360 $parsVariations = array();
362 $pNum = count($funcDesc['params']);
363 foreach ($funcDesc['params'] as $param) {
364 /* // match by name real param and documented params
365 $name = strtolower($param['name']);
366 if (!isset($funcDesc['paramDocs'][$name])) {
367 $funcDesc['paramDocs'][$name] = array();
369 if (!isset($funcDesc['paramDocs'][$name]['type'])) {
370 $funcDesc['paramDocs'][$name]['type'] = 'mixed';
373 if ($param['isoptional']) {
374 // this particular parameter is optional. save as valid previous list of parameters
375 $parsVariations[] = $pars;
381 // last allowed parameters combination
382 $parsVariations[] = $pars;
386 if (count($parsVariations) == 0) {
387 // only known good synopsis = no parameters
388 $parsVariations[] = array();
393 foreach ($parsVariations as $pars) {
395 $sig = array($this->php2XmlrpcType($funcDesc['returns']));
396 $pSig = array($funcDesc['returnsDocs']);
397 for ($i = 0; $i < count($pars); $i++) {
398 $name = strtolower($funcDesc['params'][$i]['name']);
399 if (isset($funcDesc['paramDocs'][$name]['type'])) {
400 $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
402 $sig[] = Value::$xmlrpcValue;
404 $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
412 'sigsDocs' => $sigsDocs
417 * Creates a closure that will execute $callable
418 * @todo validate params? In theory all validation is left to the dispatch map...
419 * @todo add support for $catchWarnings
422 * @param array $extraOptions
423 * @param string $plainFuncName
424 * @param array $funcDesc
427 protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
430 * @param Request $req
433 $function = function($req) use($callable, $extraOptions, $funcDesc)
435 $nameSpace = '\\PhpXmlRpc\\';
436 $encoderClass = $nameSpace.'Encoder';
437 $responseClass = $nameSpace.'Response';
438 $valueClass = $nameSpace.'Value';
440 // validate number of parameters received
441 // this should be optional really, as we assume the server does the validation
442 $minPars = count($funcDesc['params']);
444 foreach ($funcDesc['params'] as $i => $param) {
445 if ($param['isoptional']) {
446 // this particular parameter is optional. We assume later ones are as well
451 $numPars = $req->getNumParams();
452 if ($numPars < $minPars || $numPars > $maxPars) {
453 return new $responseClass(0, 3, 'Incorrect parameters passed to method');
456 $encoder = new $encoderClass();
458 if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
459 $options[] = 'decode_php_objs';
461 $params = $encoder->decode($req, $options);
463 $result = call_user_func_array($callable, $params);
465 if (! is_a($result, $responseClass)) {
466 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
467 $result = new $valueClass($result, $funcDesc['returns']);
470 if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
471 $options[] = 'encode_php_objs';
474 $result = $encoder->encode($result, $options);
476 $result = new $responseClass($result);
486 * Return a name for a new function, based on $callable, insuring its uniqueness
487 * @param mixed $callable a php callable, or the name of an xmlrpc method
488 * @param string $newFuncName when not empty, it is used instead of the calculated version
491 protected function newFunctionName($callable, $newFuncName, $extraOptions)
493 // determine name of new php function
495 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
497 if ($newFuncName == '') {
498 if (is_array($callable)) {
499 if (is_string($callable[0])) {
500 $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
502 $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
505 if ($callable instanceof \Closure) {
506 $xmlrpcFuncName = "{$prefix}_closure";
508 $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
509 array('_', ''), $callable);
510 $xmlrpcFuncName = "{$prefix}_$callable";
514 $xmlrpcFuncName = $newFuncName;
517 while (function_exists($xmlrpcFuncName)) {
518 $xmlrpcFuncName .= 'x';
521 return $xmlrpcFuncName;
526 * @param string $newFuncName
527 * @param array $extraOptions
528 * @param string $plainFuncName
529 * @param array $funcDesc
532 * @todo add a nice phpdoc block in the generated source
534 protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
536 $namespace = '\\PhpXmlRpc\\';
538 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
539 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
540 $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
543 $parsVariations = array();
545 $pNum = count($funcDesc['params']);
546 foreach ($funcDesc['params'] as $param) {
548 if ($param['isoptional']) {
549 // this particular parameter is optional. save as valid previous list of parameters
550 $parsVariations[] = $pars;
556 // last allowed parameters combination
557 $parsVariations[] = $pars;
561 if (count($parsVariations) == 0) {
562 // only known good synopsis = no parameters
563 $parsVariations[] = array();
567 $minPars = count($parsVariations[0]);
568 $maxPars = count($parsVariations[count($parsVariations)-1]);
571 // build body of new function
573 $innerCode = "\$paramCount = \$req->getNumParams();\n";
574 $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
576 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
577 if ($decodePhpObjects) {
578 $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
580 $innerCode .= "\$p = \$encoder->decode(\$req);\n";
583 // since we are building source code for later use, if we are given an object instance,
584 // we go out of our way and store a pointer to it in a static class var var...
585 if (is_array($callable) && is_object($callable[0])) {
586 self::$objHolder[$newFuncName] = $callable[0];
587 $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
588 $realFuncName = '$obj->' . $callable[1];
590 $realFuncName = $plainFuncName;
592 foreach ($parsVariations as $i => $pars) {
593 $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
594 if ($i < (count($parsVariations) - 1))
595 $innerCode .= "else\n";
597 $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
598 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
599 $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
601 if ($encodePhpObjects) {
602 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
604 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
607 // shall we exclude functions returning by ref?
608 // if($func->returnsReference())
611 $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
617 * Given a user-defined PHP class or php object, map its methods onto a list of
618 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
619 * object and called from remote clients (as well as their corresponding signature info).
621 * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
622 * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
623 * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance
624 * - string method_filter a regexp used to filter methods to wrap based on their names
625 * - string prefix used for the names of the xmlrpc methods created
627 * @return array|false false on failure
629 public function wrapPhpClass($className, $extraOptions = array())
631 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
632 $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
633 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
636 $mList = get_class_methods($className);
637 foreach ($mList as $mName) {
638 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
639 $func = new \ReflectionMethod($className, $mName);
640 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
641 if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
642 (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
644 $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
646 if (is_object($className)) {
647 $realClassName = get_class($className);
649 $realClassName = $className;
651 $results[$prefix."$realClassName.$mName"] = $methodWrap;
662 * Given an xmlrpc client and a method name, register a php wrapper function
663 * that will call it and return results using native php types for both
664 * params and results. The generated php function will return a Response
665 * object for failed xmlrpc calls.
668 * - server must support system.methodsignature for the wanted xmlrpc method
669 * - for methods that expose many signatures, only one can be picked (we
670 * could in principle check if signatures differ only by number of params
671 * and not by type, but it would be more complication than we can spare time)
672 * - nested xmlrpc params: the caller of the generated php function has to
673 * encode on its own the params passed to the php function if these are structs
674 * or arrays whose (sub)members include values of type datetime or base64
676 * Notes: the connection properties of the given client will be copied
677 * and reused for the connection used during the call to the generated
679 * Calling the generated php function 'might' be slow: a new xmlrpc client
680 * is created on every invocation and an xmlrpc-connection opened+closed.
681 * An extra 'debug' param is appended to param list of xmlrpc method, useful
682 * for debugging purposes.
684 * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
685 * @todo if we can not retrieve method signature, create a php function with varargs
686 * @todo allow the created function to throw exceptions on method calls failures
687 * @todo if caller did not specify a specific sig, shall we support all of them?
688 * It might be hard (hence slow) to match based on type and number of arguments...
690 * @param Client $client an xmlrpc client set up correctly to communicate with target server
691 * @param string $methodName the xmlrpc method to be mapped to a php function
692 * @param array $extraOptions array of options that specify conversion details. Valid options include
693 * - integer signum the index of the method signature to use in mapping (if method exposes many sigs)
694 * - integer timeout timeout (in secs) to be used when executing function/calling remote method
695 * - string protocol 'http' (default), 'http11' or 'https'
696 * - string new_function_name the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
697 * - string return_source if true return php code w. function definition instead of function itself (closure)
698 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
699 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
700 * - 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
701 * - bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
702 * - int simple_client_copy set it to 1 to have a lightweight copy of the $client object made in the generated code (only used when return_source = true)
704 * @return \closure|string[]|false false on failure, closure by default and array for return_source = true
706 public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
708 $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
710 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
712 $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
718 return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
720 // if in 'offline' mode, retrieve method description too.
721 // in online mode, favour speed of operation
722 $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
724 $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
726 $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
727 /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
728 $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
729 $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
730 $faultResponse, $namespace);*/
732 $results['function'] = $newFuncName;
740 * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
741 * @param Client $client
742 * @param string $methodName
743 * @param array $extraOptions
744 * @return false|array
746 protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
748 $namespace = '\\PhpXmlRpc\\';
749 $reqClass = $namespace . 'Request';
750 $valClass = $namespace . 'Value';
751 $decoderClass = $namespace . 'Encoder';
753 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
754 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
755 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
756 $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
758 $req = new $reqClass('system.methodSignature');
759 $req->addparam(new $valClass($methodName));
760 $client->setDebug($debug);
761 $response = $client->send($req, $timeout, $protocol);
762 if ($response->faultCode()) {
763 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
767 $mSig = $response->value();
768 if ($client->return_type != 'phpvals') {
769 $decoder = new $decoderClass();
770 $mSig = $decoder->decode($mSig);
773 if (!is_array($mSig) || count($mSig) <= $sigNum) {
774 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
778 return $mSig[$sigNum];
782 * @param Client $client
783 * @param string $methodName
784 * @param array $extraOptions
785 * @return string in case of any error, an empty string is returned, no warnings generated
787 protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
789 $namespace = '\\PhpXmlRpc\\';
790 $reqClass = $namespace . 'Request';
791 $valClass = $namespace . 'Value';
793 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
794 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
795 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
799 $req = new $reqClass('system.methodHelp');
800 $req->addparam(new $valClass($methodName));
801 $client->setDebug($debug);
802 $response = $client->send($req, $timeout, $protocol);
803 if (!$response->faultCode()) {
804 $mDesc = $response->value();
805 if ($client->return_type != 'phpvals') {
806 $mDesc = $mDesc->scalarval();
814 * @param Client $client
815 * @param string $methodName
816 * @param array $extraOptions
820 * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
822 protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
824 // we clone the client, so that we can modify it a bit independently of the original
825 $clientClone = clone $client;
826 $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
828 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
829 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
830 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
831 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
832 if (isset($extraOptions['return_on_fault'])) {
834 $faultResponse = $extraOptions['return_on_fault'];
836 $decodeFault = false;
839 $namespace = '\\PhpXmlRpc\\';
840 $reqClass = $namespace . 'Request';
841 $encoderClass = $namespace . 'Encoder';
842 $valueClass = $namespace . 'Value';
844 $encoder = new $encoderClass();
845 $encodeOptions = array();
846 if ($encodePhpObjects) {
847 $encodeOptions[] = 'encode_php_objs';
849 $decodeOptions = array();
850 if ($decodePhpObjects) {
851 $decodeOptions[] = 'decode_php_objs';
854 /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
856 // support one extra parameter: debug
857 $maxArgs = count($mSig)-1; // 1st element is the return type
858 $currentArgs = func_get_args();
859 if (func_num_args() == ($maxArgs+1)) {
860 $debug = array_pop($currentArgs);
861 $clientClone->setDebug($debug);
864 $xmlrpcArgs = array();
865 foreach($currentArgs as $i => $arg) {
866 if ($i == $maxArgs) {
869 $pType = $mSig[$i+1];
870 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
871 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
873 // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
874 // we make sure to honour the xmlrpc signature
875 $xmlrpcArgs[] = new $valueClass($arg, $pType);
877 $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
881 $req = new $reqClass($methodName, $xmlrpcArgs);
882 // use this to get the maximum decoding flexibility
883 $clientClone->return_type = 'xmlrpcvals';
884 $resp = $clientClone->send($req, $timeout, $protocol);
885 if ($resp->faultcode()) {
887 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
888 (strpos($faultResponse, '%faultString%') !== false))) {
889 $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
890 array($resp->faultCode(), $resp->faultString()), $faultResponse);
892 return $faultResponse;
897 return $encoder->decode($resp->value(), $decodeOptions);
905 * @param Client $client
906 * @param string $methodName
907 * @param array $extraOptions
908 * @param string $newFuncName
910 * @param string $mDesc
911 * @return string[] keys: source, docstring
913 public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
915 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
916 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
917 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
918 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
919 $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
920 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
921 if (isset($extraOptions['return_on_fault'])) {
923 $faultResponse = $extraOptions['return_on_fault'];
925 $decodeFault = false;
929 $namespace = '\\PhpXmlRpc\\';
931 $code = "function $newFuncName (";
932 if ($clientCopyMode < 2) {
933 // client copy mode 0 or 1 == full / partial client copy in emitted code
934 $verbatimClientCopy = !$clientCopyMode;
935 $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
936 $innerCode .= "\$client->setDebug(\$debug);\n";
939 // client copy mode 2 == no client copy in emitted code
943 $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
946 // take care that PHP comment is not terminated unwillingly by method description
947 $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
949 $mDesc = "/**\nFunction $newFuncName\n";
953 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
955 $pCount = count($mSig);
956 for ($i = 1; $i < $pCount; $i++) {
959 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
960 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
962 // only build directly xmlrpc values when type is known and scalar
963 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
965 if ($encodePhpObjects) {
966 $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
968 $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
971 $innerCode .= "\$req->addparam(\$p$i);\n";
972 $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
974 if ($clientCopyMode < 2) {
975 $plist[] = '$debug=0';
976 $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
978 $plist = implode(', ', $plist);
979 $mDesc .= '* @return {$namespace}Response|' . $this->xmlrpc2PhpType($mSig[0]) . " (an {$namespace}Response obj instance if call fails)\n*/\n";
981 $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
983 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
984 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
986 $respCode = var_export($faultResponse, true);
991 if ($decodePhpObjects) {
992 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
994 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
997 $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
999 return array('source' => $code, 'docstring' => $mDesc);
1003 * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
1004 * all xmlrpc methods exposed by the remote server as own methods.
1005 * For more details see wrapXmlrpcMethod.
1007 * For a slimmer alternative, see the code in demo/client/proxy.php
1009 * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
1011 * @param Client $client the client obj all set to query the desired server
1012 * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
1013 * - string method_filter regular expression
1014 * - string new_class_name
1016 * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
1018 * @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 appropriate option is set in extra_options)
1020 public function wrapXmlrpcServer($client, $extraOptions = array())
1022 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
1023 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
1024 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
1025 $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
1026 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
1027 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
1028 $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1029 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1030 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1031 $namespace = '\\PhpXmlRpc\\';
1033 $reqClass = $namespace . 'Request';
1034 $decoderClass = $namespace . 'Encoder';
1036 $req = new $reqClass('system.listMethods');
1037 $response = $client->send($req, $timeout, $protocol);
1038 if ($response->faultCode()) {
1039 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1043 $mList = $response->value();
1044 if ($client->return_type != 'phpvals') {
1045 $decoder = new $decoderClass();
1046 $mList = $decoder->decode($mList);
1048 if (!is_array($mList) || !count($mList)) {
1049 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1053 // pick a suitable name for the new function, avoiding collisions
1054 if ($newClassName != '') {
1055 $xmlrpcClassName = $newClassName;
1057 $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1058 array('_', ''), $client->server) . '_client';
1060 while ($buildIt && class_exists($xmlrpcClassName)) {
1061 $xmlrpcClassName .= 'x';
1064 /// @todo add function setdebug() to new class, to enable/disable debugging
1065 $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1066 $source .= "function __construct()\n{\n";
1067 $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1068 $source .= "\$this->client = \$client;\n}\n\n";
1070 'return_source' => true,
1071 'simple_client_copy' => 2, // do not produce code to copy the client object
1072 'timeout' => $timeout,
1073 'protocol' => $protocol,
1074 'encode_php_objs' => $encodePhpObjects,
1075 'decode_php_objs' => $decodePhpObjects,
1076 'prefix' => $prefix,
1078 /// @todo build phpdoc for class definition, too
1079 foreach ($mList as $mName) {
1080 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1081 // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1082 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1083 array('_', ''), $mName);
1084 $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1087 $source .= $methodWrap['docstring'];
1089 $source .= $methodWrap['source'] . "\n";
1091 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1098 eval($source . '$allOK=1;');
1100 return $xmlrpcClassName;
1102 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1106 return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1113 * Given necessary info, generate php code that will build a client object just like the given one.
1114 * Take care that no full checking of input parameters is done to ensure that
1115 * valid php code is emitted.
1116 * @param Client $client
1117 * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1118 * @param string $prefix used for the return_type of the created client
1119 * @param string $namespace
1123 protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
1125 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1126 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1128 // copy all client fields to the client that will be generated runtime
1129 // (this provides for future expansion or subclassing of client obj)
1130 if ($verbatimClientCopy) {
1131 foreach ($client as $fld => $val) {
1132 /// @todo in php 8.0, curl handles became objects, but they have no __set_state, thus var_export will
1133 /// fail for xmlrpc_curl_handle. So we disabled copying it.
1134 /// We should examine in depth if this change can have side effects - at first sight if the
1135 /// client's curl handle is not set, all curl options are (re)set on each http call, so there
1136 /// should be no loss of state...
1137 if ($fld != 'debug' && $fld != 'return_type' && $fld != 'xmlrpc_curl_handle') {
1138 $val = var_export($val, true);
1139 $code .= "\$client->$fld = $val;\n";
1143 // only make sure that client always returns the correct data type
1144 $code .= "\$client->return_type = '{$prefix}vals';\n";
1145 //$code .= "\$client->setDebug(\$debug);\n";