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
23 /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
24 public static $objHolder = array();
27 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
28 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
30 * - for php 'resource' types returns empty string, since resources cannot be serialized;
31 * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
32 * - for php arrays always return array, even though arrays sometimes serialize as structs...
33 * - for 'void' and 'null' returns 'undefined'
35 * @param string $phpType
39 * @todo support notation `something[]` as 'array'
41 public function php2XmlrpcType($phpType)
43 switch (strtolower($phpType)) {
45 return Value::$xmlrpcString;
47 case Value::$xmlrpcInt: // 'int'
48 case Value::$xmlrpcI4:
49 case Value::$xmlrpcI8:
50 return Value::$xmlrpcInt;
51 case Value::$xmlrpcDouble: // 'double'
52 return Value::$xmlrpcDouble;
54 case Value::$xmlrpcBoolean: // 'boolean'
57 return Value::$xmlrpcBoolean;
58 case Value::$xmlrpcArray: // 'array':
60 return Value::$xmlrpcArray;
62 case Value::$xmlrpcStruct: // 'struct'
63 return Value::$xmlrpcStruct;
64 case Value::$xmlrpcBase64:
65 return Value::$xmlrpcBase64;
69 if (class_exists($phpType)) {
70 if (is_a($phpType, 'DateTimeInterface')) {
71 return Value::$xmlrpcDateTime;
73 return Value::$xmlrpcStruct;
75 // unknown: might be any 'extended' xmlrpc type
76 return Value::$xmlrpcValue;
82 * Given a string defining a phpxmlrpc type return the corresponding php type.
84 * @param string $xmlrpcType
88 public function xmlrpc2PhpType($xmlrpcType)
90 switch (strtolower($xmlrpcType)) {
92 case 'datetime.iso8601':
94 return Value::$xmlrpcString;
109 // unknown: might be any xmlrpc type
110 return strtolower($xmlrpcType);
115 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
116 * be exposed as xmlrpc method from an xmlrpc server object and called from remote
117 * clients (as well as its corresponding signature info).
119 * Since php is a typeless language, to infer types of input and output parameters,
120 * it relies on parsing the javadoc-style comment block associated with the given
121 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
122 * in the '@param' tag is also allowed, if you need the php function to receive/send
123 * data in that particular format (note that base64 encoding/decoding is transparently
124 * carried out by the lib, while datetime vals are passed around as strings)
127 * - only works for user-defined functions, not for PHP internal functions
128 * (reflection does not support retrieving number/type of params for those)
129 * - functions returning php objects will generate special structs in xmlrpc responses:
130 * when the xmlrpc decoding of those responses is carried out by this same lib, using
131 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
132 * In short: php objects can be serialized, too (except for their resource members),
133 * using this function.
134 * Other libs might choke on the very same xml that will be generated in this case
135 * (i.e. it has a nonstandard attribute on struct element tags)
137 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
138 * php functions (ie. functions not expecting a single Request obj as parameter)
139 * is by making use of the functions_parameters_type class member.
141 * @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
142 * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
143 * @param array $extraOptions (optional) array of options for conversion. valid values include:
144 * - bool return_source when true, php code w. function definition will be returned, instead of a closure
145 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
146 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
147 * - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
149 * @return array|false false on error, or an array containing the name of the new php function,
150 * its signature and docs, to be used in the server dispatch map
152 * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
153 * @todo finish using phpdoc info to build method sig if all params are named but out of order
154 * @todo add a check for params of 'resource' type
155 * @todo add some trigger_errors / error_log when returning false?
156 * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
157 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
158 * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
159 * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
161 public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
163 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
165 if (is_string($callable) && strpos($callable, '::') !== false) {
166 $callable = explode('::', $callable);
168 if (is_array($callable)) {
169 if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
170 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
173 if (is_string($callable[0])) {
174 $plainFuncName = implode('::', $callable);
175 } elseif (is_object($callable[0])) {
176 $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
178 $exists = method_exists($callable[0], $callable[1]);
179 } else if ($callable instanceof \Closure) {
180 // we do not support creating code which wraps closures, as php does not allow to serialize them
182 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
186 $plainFuncName = 'Closure';
189 $plainFuncName = $callable;
190 $exists = function_exists($callable);
194 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName);
198 $funcDesc = $this->introspectFunction($callable, $plainFuncName);
203 $funcSigs = $this->buildMethodSignatures($funcDesc);
206 $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
208 $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
209 $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
213 'function' => $callable,
214 'signature' => $funcSigs['sigs'],
215 'docstring' => $funcDesc['desc'],
216 'signature_docs' => $funcSigs['sigsDocs'],
219 $ret['function'] = $newFuncName;
220 $ret['source'] = $code;
226 * Introspect a php callable and its phpdoc block and extract information about its signature
228 * @param callable $callable
229 * @param string $plainFuncName
230 * @return array|false
232 protected function introspectFunction($callable, $plainFuncName)
234 // start to introspect PHP code
235 if (is_array($callable)) {
236 $func = new \ReflectionMethod($callable[0], $callable[1]);
237 if ($func->isPrivate()) {
238 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
241 if ($func->isProtected()) {
242 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
245 if ($func->isConstructor()) {
246 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
249 if ($func->isDestructor()) {
250 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
253 if ($func->isAbstract()) {
254 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
257 /// @todo add more checks for static vs. nonstatic?
259 $func = new \ReflectionFunction($callable);
261 if ($func->isInternal()) {
262 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
263 // instead of getparameters to fully reflect internal php functions ?
264 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
268 // retrieve parameter names, types and description from javadoc comments
270 // function description
272 // type of return val: by default 'any'
273 $returns = Value::$xmlrpcValue;
274 // desc of return val
276 // type + name of function parameters
277 $paramDocs = array();
279 $docs = $func->getDocComment();
281 $docs = explode("\n", $docs);
283 foreach ($docs as $doc) {
284 $doc = trim($doc, " \r\t/*");
285 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
290 } elseif (strpos($doc, '@param') === 0) {
291 // syntax: @param type $name [desc]
292 if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
293 $name = strtolower(trim($matches[2]));
294 //$paramDocs[$name]['name'] = trim($matches[2]);
295 $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
296 $paramDocs[$name]['type'] = $matches[1];
299 } elseif (strpos($doc, '@return') === 0) {
300 // syntax: @return type [desc]
301 if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
302 $returns = $matches[1];
303 if (isset($matches[2])) {
304 $returnsDocs = trim($matches[2]);
311 // execute introspection of actual function prototype
314 foreach ($func->getParameters() as $paramObj) {
315 $params[$i] = array();
316 $params[$i]['name'] = '$' . $paramObj->getName();
317 $params[$i]['isoptional'] = $paramObj->isOptional();
324 'params' => $params, // array, positionally indexed
325 'paramDocs' => $paramDocs, // array, indexed by name
326 'returns' => $returns,
327 'returnsDocs' =>$returnsDocs,
332 * Given the method description given by introspection, create method signature data
334 * @todo support better docs with multiple types separated by pipes by creating multiple signatures
335 * (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
337 * @param array $funcDesc as generated by self::introspectFunction()
341 protected function buildMethodSignatures($funcDesc)
344 $parsVariations = array();
346 $pNum = count($funcDesc['params']);
347 foreach ($funcDesc['params'] as $param) {
348 /* // match by name real param and documented params
349 $name = strtolower($param['name']);
350 if (!isset($funcDesc['paramDocs'][$name])) {
351 $funcDesc['paramDocs'][$name] = array();
353 if (!isset($funcDesc['paramDocs'][$name]['type'])) {
354 $funcDesc['paramDocs'][$name]['type'] = 'mixed';
357 if ($param['isoptional']) {
358 // this particular parameter is optional. save as valid previous list of parameters
359 $parsVariations[] = $pars;
365 // last allowed parameters combination
366 $parsVariations[] = $pars;
370 if (count($parsVariations) == 0) {
371 // only known good synopsis = no parameters
372 $parsVariations[] = array();
377 foreach ($parsVariations as $pars) {
379 $sig = array($this->php2XmlrpcType($funcDesc['returns']));
380 $pSig = array($funcDesc['returnsDocs']);
381 for ($i = 0; $i < count($pars); $i++) {
382 $name = strtolower($funcDesc['params'][$i]['name']);
383 if (isset($funcDesc['paramDocs'][$name]['type'])) {
384 $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
386 $sig[] = Value::$xmlrpcValue;
388 $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
396 'sigsDocs' => $sigsDocs
401 * Creates a closure that will execute $callable
402 * @todo validate params? In theory all validation is left to the dispatch map...
403 * @todo add support for $catchWarnings
406 * @param array $extraOptions
407 * @param string $plainFuncName
408 * @param array $funcDesc
411 protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
414 * @param Request $req
417 $function = function($req) use($callable, $extraOptions, $funcDesc)
419 $nameSpace = '\\PhpXmlRpc\\';
420 $encoderClass = $nameSpace.'Encoder';
421 $responseClass = $nameSpace.'Response';
422 $valueClass = $nameSpace.'Value';
424 // validate number of parameters received
425 // this should be optional really, as we assume the server does the validation
426 $minPars = count($funcDesc['params']);
428 foreach ($funcDesc['params'] as $i => $param) {
429 if ($param['isoptional']) {
430 // this particular parameter is optional. We assume later ones are as well
435 $numPars = $req->getNumParams();
436 if ($numPars < $minPars || $numPars > $maxPars) {
437 return new $responseClass(0, 3, 'Incorrect parameters passed to method');
440 $encoder = new $encoderClass();
442 if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
443 $options[] = 'decode_php_objs';
445 $params = $encoder->decode($req, $options);
447 $result = call_user_func_array($callable, $params);
449 if (! is_a($result, $responseClass)) {
450 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
451 $result = new $valueClass($result, $funcDesc['returns']);
454 if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
455 $options[] = 'encode_php_objs';
458 $result = $encoder->encode($result, $options);
460 $result = new $responseClass($result);
470 * Return a name for a new function, based on $callable, insuring its uniqueness
471 * @param mixed $callable a php callable, or the name of an xmlrpc method
472 * @param string $newFuncName when not empty, it is used instead of the calculated version
475 protected function newFunctionName($callable, $newFuncName, $extraOptions)
477 // determine name of new php function
479 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
481 if ($newFuncName == '') {
482 if (is_array($callable)) {
483 if (is_string($callable[0])) {
484 $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
486 $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
489 if ($callable instanceof \Closure) {
490 $xmlrpcFuncName = "{$prefix}_closure";
492 $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
493 array('_', ''), $callable);
494 $xmlrpcFuncName = "{$prefix}_$callable";
498 $xmlrpcFuncName = $newFuncName;
501 while (function_exists($xmlrpcFuncName)) {
502 $xmlrpcFuncName .= 'x';
505 return $xmlrpcFuncName;
510 * @param string $newFuncName
511 * @param array $extraOptions
512 * @param string $plainFuncName
513 * @param array $funcDesc
516 * @todo add a nice phpdoc block in the generated source
518 protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
520 $namespace = '\\PhpXmlRpc\\';
522 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
523 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
524 $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
527 $parsVariations = array();
529 $pNum = count($funcDesc['params']);
530 foreach ($funcDesc['params'] as $param) {
532 if ($param['isoptional']) {
533 // this particular parameter is optional. save as valid previous list of parameters
534 $parsVariations[] = $pars;
540 // last allowed parameters combination
541 $parsVariations[] = $pars;
545 if (count($parsVariations) == 0) {
546 // only known good synopsis = no parameters
547 $parsVariations[] = array();
551 $minPars = count($parsVariations[0]);
552 $maxPars = count($parsVariations[count($parsVariations)-1]);
555 // build body of new function
557 $innerCode = "\$paramCount = \$req->getNumParams();\n";
558 $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
560 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
561 if ($decodePhpObjects) {
562 $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
564 $innerCode .= "\$p = \$encoder->decode(\$req);\n";
567 // since we are building source code for later use, if we are given an object instance,
568 // we go out of our way and store a pointer to it in a static class var var...
569 if (is_array($callable) && is_object($callable[0])) {
570 self::$objHolder[$newFuncName] = $callable[0];
571 $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
572 $realFuncName = '$obj->' . $callable[1];
574 $realFuncName = $plainFuncName;
576 foreach ($parsVariations as $i => $pars) {
577 $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
578 if ($i < (count($parsVariations) - 1))
579 $innerCode .= "else\n";
581 $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
582 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
583 $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
585 if ($encodePhpObjects) {
586 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
588 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
591 // shall we exclude functions returning by ref?
592 // if($func->returnsReference())
595 $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
601 * Given a user-defined PHP class or php object, map its methods onto a list of
602 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
603 * object and called from remote clients (as well as their corresponding signature info).
605 * @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
606 * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
607 * - 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
608 * - string method_filter a regexp used to filter methods to wrap based on their names
609 * - string prefix used for the names of the xmlrpc methods created
611 * @return array|false false on failure
613 public function wrapPhpClass($className, $extraOptions = array())
615 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
616 $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
617 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
620 $mList = get_class_methods($className);
621 foreach ($mList as $mName) {
622 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
623 $func = new \ReflectionMethod($className, $mName);
624 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
625 if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
626 (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
628 $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
630 if (is_object($className)) {
631 $realClassName = get_class($className);
633 $realClassName = $className;
635 $results[$prefix."$realClassName.$mName"] = $methodWrap;
646 * Given an xmlrpc client and a method name, register a php wrapper function
647 * that will call it and return results using native php types for both
648 * params and results. The generated php function will return a Response
649 * object for failed xmlrpc calls.
652 * - server must support system.methodsignature for the wanted xmlrpc method
653 * - for methods that expose many signatures, only one can be picked (we
654 * could in principle check if signatures differ only by number of params
655 * and not by type, but it would be more complication than we can spare time)
656 * - nested xmlrpc params: the caller of the generated php function has to
657 * encode on its own the params passed to the php function if these are structs
658 * or arrays whose (sub)members include values of type datetime or base64
660 * Notes: the connection properties of the given client will be copied
661 * and reused for the connection used during the call to the generated
663 * Calling the generated php function 'might' be slow: a new xmlrpc client
664 * is created on every invocation and an xmlrpc-connection opened+closed.
665 * An extra 'debug' param is appended to param list of xmlrpc method, useful
666 * for debugging purposes.
668 * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
669 * @todo if we can not retrieve method signature, create a php function with varargs
670 * @todo allow the created function to throw exceptions on method calls failures
671 * @todo if caller did not specify a specific sig, shall we support all of them?
672 * It might be hard (hence slow) to match based on type and number of arguments...
674 * @param Client $client an xmlrpc client set up correctly to communicate with target server
675 * @param string $methodName the xmlrpc method to be mapped to a php function
676 * @param array $extraOptions array of options that specify conversion details. Valid options include
677 * - integer signum the index of the method signature to use in mapping (if method exposes many sigs)
678 * - integer timeout timeout (in secs) to be used when executing function/calling remote method
679 * - string protocol 'http' (default), 'http11' or 'https'
680 * - string new_function_name the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
681 * - string return_source if true return php code w. function definition instead of function itself (closure)
682 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
683 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
684 * - 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
685 * - bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
686 * - 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)
688 * @return \closure|string[]|false false on failure, closure by default and array for return_source = true
690 public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
692 $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
694 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
696 $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
702 return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
704 // if in 'offline' mode, retrieve method description too.
705 // in online mode, favour speed of operation
706 $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
708 $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
710 $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
711 /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
712 $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
713 $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
714 $faultResponse, $namespace);*/
716 $results['function'] = $newFuncName;
724 * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
725 * @param Client $client
726 * @param string $methodName
727 * @param array $extraOptions
728 * @return false|array
730 protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
732 $namespace = '\\PhpXmlRpc\\';
733 $reqClass = $namespace . 'Request';
734 $valClass = $namespace . 'Value';
735 $decoderClass = $namespace . 'Encoder';
737 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
738 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
739 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
740 $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
742 $req = new $reqClass('system.methodSignature');
743 $req->addparam(new $valClass($methodName));
744 $client->setDebug($debug);
745 $response = $client->send($req, $timeout, $protocol);
746 if ($response->faultCode()) {
747 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
751 $mSig = $response->value();
752 if ($client->return_type != 'phpvals') {
753 $decoder = new $decoderClass();
754 $mSig = $decoder->decode($mSig);
757 if (!is_array($mSig) || count($mSig) <= $sigNum) {
758 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
762 return $mSig[$sigNum];
766 * @param Client $client
767 * @param string $methodName
768 * @param array $extraOptions
769 * @return string in case of any error, an empty string is returned, no warnings generated
771 protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
773 $namespace = '\\PhpXmlRpc\\';
774 $reqClass = $namespace . 'Request';
775 $valClass = $namespace . 'Value';
777 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
778 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
779 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
783 $req = new $reqClass('system.methodHelp');
784 $req->addparam(new $valClass($methodName));
785 $client->setDebug($debug);
786 $response = $client->send($req, $timeout, $protocol);
787 if (!$response->faultCode()) {
788 $mDesc = $response->value();
789 if ($client->return_type != 'phpvals') {
790 $mDesc = $mDesc->scalarval();
798 * @param Client $client
799 * @param string $methodName
800 * @param array $extraOptions
804 * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
806 protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
808 // we clone the client, so that we can modify it a bit independently of the original
809 $clientClone = clone $client;
810 $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
812 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
813 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
814 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
815 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
816 if (isset($extraOptions['return_on_fault'])) {
818 $faultResponse = $extraOptions['return_on_fault'];
820 $decodeFault = false;
823 $namespace = '\\PhpXmlRpc\\';
824 $reqClass = $namespace . 'Request';
825 $encoderClass = $namespace . 'Encoder';
826 $valueClass = $namespace . 'Value';
828 $encoder = new $encoderClass();
829 $encodeOptions = array();
830 if ($encodePhpObjects) {
831 $encodeOptions[] = 'encode_php_objs';
833 $decodeOptions = array();
834 if ($decodePhpObjects) {
835 $decodeOptions[] = 'decode_php_objs';
838 /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
840 // support one extra parameter: debug
841 $maxArgs = count($mSig)-1; // 1st element is the return type
842 $currentArgs = func_get_args();
843 if (func_num_args() == ($maxArgs+1)) {
844 $debug = array_pop($currentArgs);
845 $clientClone->setDebug($debug);
848 $xmlrpcArgs = array();
849 foreach($currentArgs as $i => $arg) {
850 if ($i == $maxArgs) {
853 $pType = $mSig[$i+1];
854 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
855 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
857 // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
858 // we make sure to honour the xmlrpc signature
859 $xmlrpcArgs[] = new $valueClass($arg, $pType);
861 $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
865 $req = new $reqClass($methodName, $xmlrpcArgs);
866 // use this to get the maximum decoding flexibility
867 $clientClone->return_type = 'xmlrpcvals';
868 $resp = $clientClone->send($req, $timeout, $protocol);
869 if ($resp->faultcode()) {
871 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
872 (strpos($faultResponse, '%faultString%') !== false))) {
873 $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
874 array($resp->faultCode(), $resp->faultString()), $faultResponse);
876 return $faultResponse;
881 return $encoder->decode($resp->value(), $decodeOptions);
889 * @param Client $client
890 * @param string $methodName
891 * @param array $extraOptions
892 * @param string $newFuncName
894 * @param string $mDesc
895 * @return string[] keys: source, docstring
897 public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
899 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
900 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
901 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
902 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
903 $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
904 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
905 if (isset($extraOptions['return_on_fault'])) {
907 $faultResponse = $extraOptions['return_on_fault'];
909 $decodeFault = false;
913 $namespace = '\\PhpXmlRpc\\';
915 $code = "function $newFuncName (";
916 if ($clientCopyMode < 2) {
917 // client copy mode 0 or 1 == full / partial client copy in emitted code
918 $verbatimClientCopy = !$clientCopyMode;
919 $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
920 $innerCode .= "\$client->setDebug(\$debug);\n";
923 // client copy mode 2 == no client copy in emitted code
927 $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
930 // take care that PHP comment is not terminated unwillingly by method description
931 $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
933 $mDesc = "/**\nFunction $newFuncName\n";
937 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
939 $pCount = count($mSig);
940 for ($i = 1; $i < $pCount; $i++) {
943 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
944 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
946 // only build directly xmlrpc values when type is known and scalar
947 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
949 if ($encodePhpObjects) {
950 $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
952 $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
955 $innerCode .= "\$req->addparam(\$p$i);\n";
956 $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
958 if ($clientCopyMode < 2) {
959 $plist[] = '$debug=0';
960 $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
962 $plist = implode(', ', $plist);
963 $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
965 $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
967 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
968 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
970 $respCode = var_export($faultResponse, true);
975 if ($decodePhpObjects) {
976 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
978 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
981 $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
983 return array('source' => $code, 'docstring' => $mDesc);
987 * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
988 * all xmlrpc methods exposed by the remote server as own methods.
989 * For more details see wrapXmlrpcMethod.
991 * For a slimmer alternative, see the code in demo/client/proxy.php
993 * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
995 * @param Client $client the client obj all set to query the desired server
996 * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
997 * - string method_filter regular expression
998 * - string new_class_name
1000 * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
1002 * @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)
1004 public function wrapXmlrpcServer($client, $extraOptions = array())
1006 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
1007 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
1008 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
1009 $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
1010 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
1011 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
1012 $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1013 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1014 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1015 $namespace = '\\PhpXmlRpc\\';
1017 $reqClass = $namespace . 'Request';
1018 $decoderClass = $namespace . 'Encoder';
1020 $req = new $reqClass('system.listMethods');
1021 $response = $client->send($req, $timeout, $protocol);
1022 if ($response->faultCode()) {
1023 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1027 $mList = $response->value();
1028 if ($client->return_type != 'phpvals') {
1029 $decoder = new $decoderClass();
1030 $mList = $decoder->decode($mList);
1032 if (!is_array($mList) || !count($mList)) {
1033 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1037 // pick a suitable name for the new function, avoiding collisions
1038 if ($newClassName != '') {
1039 $xmlrpcClassName = $newClassName;
1041 $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1042 array('_', ''), $client->server) . '_client';
1044 while ($buildIt && class_exists($xmlrpcClassName)) {
1045 $xmlrpcClassName .= 'x';
1048 /// @todo add function setdebug() to new class, to enable/disable debugging
1049 $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1050 $source .= "function __construct()\n{\n";
1051 $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1052 $source .= "\$this->client = \$client;\n}\n\n";
1054 'return_source' => true,
1055 'simple_client_copy' => 2, // do not produce code to copy the client object
1056 'timeout' => $timeout,
1057 'protocol' => $protocol,
1058 'encode_php_objs' => $encodePhpObjects,
1059 'decode_php_objs' => $decodePhpObjects,
1060 'prefix' => $prefix,
1062 /// @todo build phpdoc for class definition, too
1063 foreach ($mList as $mName) {
1064 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1065 // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1066 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1067 array('_', ''), $mName);
1068 $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1071 $source .= $methodWrap['docstring'];
1073 $source .= $methodWrap['source'] . "\n";
1075 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1082 eval($source . '$allOK=1;');
1084 return $xmlrpcClassName;
1086 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1090 return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1097 * Given necessary info, generate php code that will build a client object just like the given one.
1098 * Take care that no full checking of input parameters is done to ensure that
1099 * valid php code is emitted.
1100 * @param Client $client
1101 * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1102 * @param string $prefix used for the return_type of the created client
1103 * @param string $namespace
1107 protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
1109 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1110 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1112 // copy all client fields to the client that will be generated runtime
1113 // (this provides for future expansion or subclassing of client obj)
1114 if ($verbatimClientCopy) {
1115 foreach ($client as $fld => $val) {
1116 /// @todo in php 8.0, curl handles became objects, but they have no __set_state, thus var_export will
1117 /// fail for xmlrpc_curl_handle. So we disabled copying it.
1118 /// We should examine in depth if this change can have side effects - at first sight if the
1119 /// client's curl handle is not set, all curl options are (re)set on each http call, so there
1120 /// should be no loss of state...
1121 if ($fld != 'debug' && $fld != 'return_type' && $fld != 'xmlrpc_curl_handle') {
1122 $val = var_export($val, true);
1123 $code .= "\$client->$fld = $val;\n";
1127 // only make sure that client always returns the correct data type
1128 $code .= "\$client->return_type = '{$prefix}vals';\n";
1129 //$code .= "\$client->setDebug(\$debug);\n";