3 * @author Gaetano Giunta
4 * @copyright (C) 2006-2015 G. Giunta
5 * @license code licensed under the BSD License: see file license.txt
11 * PHP-XMLRPC "wrapper" class - generate stubs to transparently access xmlrpc methods as php functions and vice-versa.
12 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
14 * @todo use some better templating system for code generation?
15 * @todo implement method wrapping with preservation of php objs in calls
16 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
20 /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
21 public static $objHolder = array();
24 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
25 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
27 * - for php 'resource' types returns empty string, since resources cannot be serialized;
28 * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
29 * - for php arrays always return array, even though arrays sometimes serialize as json structs
30 * - for 'void' and 'null' returns 'undefined'
32 * @param string $phpType
36 public function php2XmlrpcType($phpType)
38 switch (strtolower($phpType)) {
40 return Value::$xmlrpcString;
42 case Value::$xmlrpcInt: // 'int'
43 case Value::$xmlrpcI4:
44 case Value::$xmlrpcI8:
45 return Value::$xmlrpcInt;
46 case Value::$xmlrpcDouble: // 'double'
47 return Value::$xmlrpcDouble;
49 case Value::$xmlrpcBoolean: // 'boolean'
52 return Value::$xmlrpcBoolean;
53 case Value::$xmlrpcArray: // 'array':
54 return Value::$xmlrpcArray;
56 case Value::$xmlrpcStruct: // 'struct'
57 return Value::$xmlrpcStruct;
58 case Value::$xmlrpcBase64:
59 return Value::$xmlrpcBase64;
63 if (class_exists($phpType)) {
64 return Value::$xmlrpcStruct;
66 // unknown: might be any 'extended' xmlrpc type
67 return Value::$xmlrpcValue;
73 * Given a string defining a phpxmlrpc type return the corresponding php type.
75 * @param string $xmlrpcType
79 public function xmlrpc2PhpType($xmlrpcType)
81 switch (strtolower($xmlrpcType)) {
83 case 'datetime.iso8601':
85 return Value::$xmlrpcString;
100 // unknown: might be any xmlrpc type
101 return strtolower($xmlrpcType);
106 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
107 * be exposed as xmlrpc method from an xmlrpc server object and called from remote
108 * clients (as well as its corresponding signature info).
110 * Since php is a typeless language, to infer types of input and output parameters,
111 * it relies on parsing the javadoc-style comment block associated with the given
112 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
113 * in the @param tag is also allowed, if you need the php function to receive/send
114 * data in that particular format (note that base64 encoding/decoding is transparently
115 * carried out by the lib, while datetime vals are passed around as strings)
118 * - only works for user-defined functions, not for PHP internal functions
119 * (reflection does not support retrieving number/type of params for those)
120 * - functions returning php objects will generate special structs in xmlrpc responses:
121 * when the xmlrpc decoding of those responses is carried out by this same lib, using
122 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
123 * In short: php objects can be serialized, too (except for their resource members),
124 * using this function.
125 * Other libs might choke on the very same xml that will be generated in this case
126 * (i.e. it has a nonstandard attribute on struct element tags)
128 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
129 * php functions (ie. functions not expecting a single Request obj as parameter)
130 * is by making use of the functions_parameters_type class member.
132 * @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
133 * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
134 * @param array $extraOptions (optional) array of options for conversion. valid values include:
135 * - bool return_source when true, php code w. function definition will be returned, instead of a closure
136 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
137 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
138 * - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
140 * @return array|false false on error, or an array containing the name of the new php function,
141 * its signature and docs, to be used in the server dispatch map
143 * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
144 * @todo finish using phpdoc info to build method sig if all params are named but out of order
145 * @todo add a check for params of 'resource' type
146 * @todo add some trigger_errors / error_log when returning false?
147 * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
148 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
149 * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
150 * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
152 public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
154 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
156 if (is_string($callable) && strpos($callable, '::') !== false) {
157 $callable = explode('::', $callable);
159 if (is_array($callable)) {
160 if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
161 error_log('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
164 if (is_string($callable[0])) {
165 $plainFuncName = implode('::', $callable);
166 } elseif (is_object($callable[0])) {
167 $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
169 $exists = method_exists($callable[0], $callable[1]);
170 } else if ($callable instanceof \Closure) {
171 // we do not support creating code which wraps closures, as php does not allow to serialize them
173 error_log('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
177 $plainFuncName = 'Closure';
180 $plainFuncName = $callable;
181 $exists = function_exists($callable);
185 error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName);
189 $funcDesc = $this->introspectFunction($callable, $plainFuncName);
194 $funcSigs = $this->buildMethodSignatures($funcDesc);
197 $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
199 $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
200 $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
204 'function' => $callable,
205 'signature' => $funcSigs['sigs'],
206 'docstring' => $funcDesc['desc'],
207 'signature_docs' => $funcSigs['sigsDocs'],
210 $ret['function'] = $newFuncName;
211 $ret['source'] = $code;
217 * Introspect a php callable and its phpdoc block and extract information about its signature
219 * @param callable $callable
220 * @param string $plainFuncName
221 * @return array|false
223 protected function introspectFunction($callable, $plainFuncName)
225 // start to introspect PHP code
226 if (is_array($callable)) {
227 $func = new \ReflectionMethod($callable[0], $callable[1]);
228 if ($func->isPrivate()) {
229 error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
232 if ($func->isProtected()) {
233 error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
236 if ($func->isConstructor()) {
237 error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
240 if ($func->isDestructor()) {
241 error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
244 if ($func->isAbstract()) {
245 error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
248 /// @todo add more checks for static vs. nonstatic?
250 $func = new \ReflectionFunction($callable);
252 if ($func->isInternal()) {
253 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
254 // instead of getparameters to fully reflect internal php functions ?
255 error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
259 // retrieve parameter names, types and description from javadoc comments
261 // function description
263 // type of return val: by default 'any'
264 $returns = Value::$xmlrpcValue;
265 // desc of return val
267 // type + name of function parameters
268 $paramDocs = array();
270 $docs = $func->getDocComment();
272 $docs = explode("\n", $docs);
274 foreach ($docs as $doc) {
275 $doc = trim($doc, " \r\t/*");
276 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
281 } elseif (strpos($doc, '@param') === 0) {
282 // syntax: @param type $name [desc]
283 if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
284 $name = strtolower(trim($matches[2]));
285 //$paramDocs[$name]['name'] = trim($matches[2]);
286 $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
287 $paramDocs[$name]['type'] = $matches[1];
290 } elseif (strpos($doc, '@return') === 0) {
291 // syntax: @return type [desc]
292 if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
293 $returns = $matches[1];
294 if (isset($matches[2])) {
295 $returnsDocs = trim($matches[2]);
302 // execute introspection of actual function prototype
305 foreach ($func->getParameters() as $paramObj) {
306 $params[$i] = array();
307 $params[$i]['name'] = '$' . $paramObj->getName();
308 $params[$i]['isoptional'] = $paramObj->isOptional();
315 'params' => $params, // array, positionally indexed
316 'paramDocs' => $paramDocs, // array, indexed by name
317 'returns' => $returns,
318 'returnsDocs' =>$returnsDocs,
323 * Given the method description given by introspection, create method signature data
325 * @todo support better docs with multiple types separated by pipes by creating multiple signatures
326 * (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
328 * @param array $funcDesc as generated by self::introspectFunction()
332 protected function buildMethodSignatures($funcDesc)
335 $parsVariations = array();
337 $pNum = count($funcDesc['params']);
338 foreach ($funcDesc['params'] as $param) {
339 /* // match by name real param and documented params
340 $name = strtolower($param['name']);
341 if (!isset($funcDesc['paramDocs'][$name])) {
342 $funcDesc['paramDocs'][$name] = array();
344 if (!isset($funcDesc['paramDocs'][$name]['type'])) {
345 $funcDesc['paramDocs'][$name]['type'] = 'mixed';
348 if ($param['isoptional']) {
349 // this particular parameter is optional. save as valid previous list of parameters
350 $parsVariations[] = $pars;
356 // last allowed parameters combination
357 $parsVariations[] = $pars;
361 if (count($parsVariations) == 0) {
362 // only known good synopsis = no parameters
363 $parsVariations[] = array();
368 foreach ($parsVariations as $pars) {
370 $sig = array($this->php2XmlrpcType($funcDesc['returns']));
371 $pSig = array($funcDesc['returnsDocs']);
372 for ($i = 0; $i < count($pars); $i++) {
373 $name = strtolower($funcDesc['params'][$i]['name']);
374 if (isset($funcDesc['paramDocs'][$name]['type'])) {
375 $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
377 $sig[] = Value::$xmlrpcValue;
379 $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
387 'sigsDocs' => $sigsDocs
392 * Creates a closure that will execute $callable
393 * @todo validate params? In theory all validation is left to the dispatch map...
394 * @todo add support for $catchWarnings
397 * @param array $extraOptions
398 * @param string $plainFuncName
399 * @param string $funcDesc
402 protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
404 $function = function($req) use($callable, $extraOptions, $funcDesc)
406 $nameSpace = '\\PhpXmlRpc\\';
407 $encoderClass = $nameSpace.'Encoder';
408 $responseClass = $nameSpace.'Response';
409 $valueClass = $nameSpace.'Value';
411 // validate number of parameters received
412 // this should be optional really, as we assume the server does the validation
413 $minPars = count($funcDesc['params']);
415 foreach ($funcDesc['params'] as $i => $param) {
416 if ($param['isoptional']) {
417 // this particular parameter is optional. We assume later ones are as well
422 $numPars = $req->getNumParams();
423 if ($numPars < $minPars || $numPars > $maxPars) {
424 return new $responseClass(0, 3, 'Incorrect parameters passed to method');
427 $encoder = new $encoderClass();
429 if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
430 $options[] = 'decode_php_objs';
432 $params = $encoder->decode($req, $options);
434 $result = call_user_func_array($callable, $params);
436 if (! is_a($result, $responseClass)) {
437 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
438 $result = new $valueClass($result, $funcDesc['returns']);
441 if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
442 $options[] = 'encode_php_objs';
445 $result = $encoder->encode($result, $options);
447 $result = new $responseClass($result);
457 * Return a name for a new function, based on $callable, insuring its uniqueness
458 * @param mixed $callable a php callable, or the name of an xmlrpc method
459 * @param string $newFuncName when not empty, it is used instead of the calculated version
462 protected function newFunctionName($callable, $newFuncName, $extraOptions)
464 // determine name of new php function
466 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
468 if ($newFuncName == '') {
469 if (is_array($callable)) {
470 if (is_string($callable[0])) {
471 $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
473 $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
476 if ($callable instanceof \Closure) {
477 $xmlrpcFuncName = "{$prefix}_closure";
479 $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
480 array('_', ''), $callable);
481 $xmlrpcFuncName = "{$prefix}_$callable";
485 $xmlrpcFuncName = $newFuncName;
488 while (function_exists($xmlrpcFuncName)) {
489 $xmlrpcFuncName .= 'x';
492 return $xmlrpcFuncName;
497 * @param string $newFuncName
498 * @param array $extraOptions
499 * @param string $plainFuncName
500 * @param array $funcDesc
503 * @todo add a nice phpdoc block in the generated source
505 protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
507 $namespace = '\\PhpXmlRpc\\';
509 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
510 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
511 $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
514 $parsVariations = array();
516 $pNum = count($funcDesc['params']);
517 foreach ($funcDesc['params'] as $param) {
519 if ($param['isoptional']) {
520 // this particular parameter is optional. save as valid previous list of parameters
521 $parsVariations[] = $pars;
527 // last allowed parameters combination
528 $parsVariations[] = $pars;
532 if (count($parsVariations) == 0) {
533 // only known good synopsis = no parameters
534 $parsVariations[] = array();
538 $minPars = count($parsVariations[0]);
539 $maxPars = count($parsVariations[count($parsVariations)-1]);
542 // build body of new function
544 $innerCode = "\$paramCount = \$req->getNumParams();\n";
545 $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
547 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
548 if ($decodePhpObjects) {
549 $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
551 $innerCode .= "\$p = \$encoder->decode(\$req);\n";
554 // since we are building source code for later use, if we are given an object instance,
555 // we go out of our way and store a pointer to it in a static class var var...
556 if (is_array($callable) && is_object($callable[0])) {
557 self::$objHolder[$newFuncName] = $callable[0];
558 $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
559 $realFuncName = '$obj->' . $callable[1];
561 $realFuncName = $plainFuncName;
563 foreach ($parsVariations as $i => $pars) {
564 $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
565 if ($i < (count($parsVariations) - 1))
566 $innerCode .= "else\n";
568 $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
569 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
570 $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
572 if ($encodePhpObjects) {
573 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
575 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
578 // shall we exclude functions returning by ref?
579 // if($func->returnsReference())
582 $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
588 * Given a user-defined PHP class or php object, map its methods onto a list of
589 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
590 * object and called from remote clients (as well as their corresponding signature info).
592 * @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
593 * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
594 * - 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
595 * - string method_filter a regexp used to filter methods to wrap based on their names
596 * - string prefix used for the names of the xmlrpc methods created
598 * @return array|false false on failure
600 public function wrapPhpClass($className, $extraOptions = array())
602 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
603 $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
604 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
607 $mList = get_class_methods($className);
608 foreach ($mList as $mName) {
609 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
610 $func = new \ReflectionMethod($className, $mName);
611 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
612 if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
613 (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
615 $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
617 if (is_object($className)) {
618 $realClassName = get_class($className);
620 $realClassName = $className;
622 $results[$prefix."$realClassName.$mName"] = $methodWrap;
633 * Given an xmlrpc client and a method name, register a php wrapper function
634 * that will call it and return results using native php types for both
635 * params and results. The generated php function will return a Response
636 * object for failed xmlrpc calls.
639 * - server must support system.methodsignature for the wanted xmlrpc method
640 * - for methods that expose many signatures, only one can be picked (we
641 * could in principle check if signatures differ only by number of params
642 * and not by type, but it would be more complication than we can spare time)
643 * - nested xmlrpc params: the caller of the generated php function has to
644 * encode on its own the params passed to the php function if these are structs
645 * or arrays whose (sub)members include values of type datetime or base64
647 * Notes: the connection properties of the given client will be copied
648 * and reused for the connection used during the call to the generated
650 * Calling the generated php function 'might' be slow: a new xmlrpc client
651 * is created on every invocation and an xmlrpc-connection opened+closed.
652 * An extra 'debug' param is appended to param list of xmlrpc method, useful
653 * for debugging purposes.
655 * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
656 * @todo if we can not retrieve method signature, create a php function with varargs
657 * @todo allow the created function to throw exceptions on method calls failures
658 * @todo if caller did not specify a specific sig, shall we support all of them?
659 * It might be hard (hence slow) to match based on type and number of arguments...
661 * @param Client $client an xmlrpc client set up correctly to communicate with target server
662 * @param string $methodName the xmlrpc method to be mapped to a php function
663 * @param array $extraOptions array of options that specify conversion details. Valid options include
664 * - integer signum the index of the method signature to use in mapping (if method exposes many sigs)
665 * - integer timeout timeout (in secs) to be used when executing function/calling remote method
666 * - string protocol 'http' (default), 'http11' or 'https'
667 * - string new_function_name the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
668 * - string return_source if true return php code w. function definition instead of function itself (closure)
669 * - bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
670 * - bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
671 * - 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
672 * - bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
673 * - 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)
675 * @return \closure|array|false false on failure, closure by default and array for return_source = true
677 public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
679 $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
681 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
683 $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
689 return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
691 // if in 'offline' mode, retrieve method description too.
692 // in online mode, favour speed of operation
693 $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
695 $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
697 $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
698 /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
699 $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
700 $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
701 $faultResponse, $namespace);*/
703 $results['function'] = $newFuncName;
711 * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
712 * @param Client $client
713 * @param string $methodName
714 * @param array $extraOptions
715 * @return false|array
717 protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
719 $namespace = '\\PhpXmlRpc\\';
720 $reqClass = $namespace . 'Request';
721 $valClass = $namespace . 'Value';
722 $decoderClass = $namespace . 'Encoder';
724 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
725 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
726 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
727 $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
729 $req = new $reqClass('system.methodSignature');
730 $req->addparam(new $valClass($methodName));
731 $client->setDebug($debug);
732 $response = $client->send($req, $timeout, $protocol);
733 if ($response->faultCode()) {
734 error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
738 $mSig = $response->value();
739 if ($client->return_type != 'phpvals') {
740 $decoder = new $decoderClass();
741 $mSig = $decoder->decode($mSig);
744 if (!is_array($mSig) || count($mSig) <= $sigNum) {
745 error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
749 return $mSig[$sigNum];
753 * @param Client $client
754 * @param string $methodName
755 * @param array $extraOptions
756 * @return string in case of any error, an empty string is returned, no warnings generated
758 protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
760 $namespace = '\\PhpXmlRpc\\';
761 $reqClass = $namespace . 'Request';
762 $valClass = $namespace . 'Value';
764 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
765 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
766 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
770 $req = new $reqClass('system.methodHelp');
771 $req->addparam(new $valClass($methodName));
772 $client->setDebug($debug);
773 $response = $client->send($req, $timeout, $protocol);
774 if (!$response->faultCode()) {
775 $mDesc = $response->value();
776 if ($client->return_type != 'phpvals') {
777 $mDesc = $mDesc->scalarval();
785 * @param Client $client
786 * @param string $methodName
787 * @param array $extraOptions
788 * @param string $mSig
791 * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
793 protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
795 // we clone the client, so that we can modify it a bit independently of the original
796 $clientClone = clone $client;
797 $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
799 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
800 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
801 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
802 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
803 if (isset($extraOptions['return_on_fault'])) {
805 $faultResponse = $extraOptions['return_on_fault'];
807 $decodeFault = false;
810 $namespace = '\\PhpXmlRpc\\';
811 $reqClass = $namespace . 'Request';
812 $encoderClass = $namespace . 'Encoder';
813 $valueClass = $namespace . 'Value';
815 $encoder = new $encoderClass();
816 $encodeOptions = array();
817 if ($encodePhpObjects) {
818 $encodeOptions[] = 'encode_php_objs';
820 $decodeOptions = array();
821 if ($decodePhpObjects) {
822 $decodeOptions[] = 'decode_php_objs';
825 /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
827 // support one extra parameter: debug
828 $maxArgs = count($mSig)-1; // 1st element is the return type
829 $currentArgs = func_get_args();
830 if (func_num_args() == ($maxArgs+1)) {
831 $debug = array_pop($currentArgs);
832 $clientClone->setDebug($debug);
835 $xmlrpcArgs = array();
836 foreach($currentArgs as $i => $arg) {
837 if ($i == $maxArgs) {
840 $pType = $mSig[$i+1];
841 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
842 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
844 // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
845 // we make sure to honour the xmlrpc signature
846 $xmlrpcArgs[] = new $valueClass($arg, $pType);
848 $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
852 $req = new $reqClass($methodName, $xmlrpcArgs);
853 // use this to get the maximum decoding flexibility
854 $clientClone->return_type = 'xmlrpcvals';
855 $resp = $clientClone->send($req, $timeout, $protocol);
856 if ($resp->faultcode()) {
858 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
859 (strpos($faultResponse, '%faultString%') !== false))) {
860 $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
861 array($resp->faultCode(), $resp->faultString()), $faultResponse);
863 return $faultResponse;
868 return $encoder->decode($resp->value(), $decodeOptions);
876 * @param Client $client
877 * @param string $methodName
878 * @param array $extraOptions
879 * @param string $newFuncName
881 * @param string $mDesc
884 public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
886 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
887 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
888 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
889 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
890 $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
891 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
892 if (isset($extraOptions['return_on_fault'])) {
894 $faultResponse = $extraOptions['return_on_fault'];
896 $decodeFault = false;
900 $namespace = '\\PhpXmlRpc\\';
902 $code = "function $newFuncName (";
903 if ($clientCopyMode < 2) {
904 // client copy mode 0 or 1 == full / partial client copy in emitted code
905 $verbatimClientCopy = !$clientCopyMode;
906 $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
907 $innerCode .= "\$client->setDebug(\$debug);\n";
910 // client copy mode 2 == no client copy in emitted code
914 $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
917 // take care that PHP comment is not terminated unwillingly by method description
918 $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
920 $mDesc = "/**\nFunction $newFuncName\n";
924 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
926 $pCount = count($mSig);
927 for ($i = 1; $i < $pCount; $i++) {
930 if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
931 $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
933 // only build directly xmlrpc values when type is known and scalar
934 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
936 if ($encodePhpObjects) {
937 $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
939 $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
942 $innerCode .= "\$req->addparam(\$p$i);\n";
943 $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
945 if ($clientCopyMode < 2) {
946 $plist[] = '$debug=0';
947 $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
949 $plist = implode(', ', $plist);
950 $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
952 $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
954 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
955 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
957 $respCode = var_export($faultResponse, true);
962 if ($decodePhpObjects) {
963 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
965 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
968 $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
970 return array('source' => $code, 'docstring' => $mDesc);
974 * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
975 * all xmlrpc methods exposed by the remote server as own methods.
976 * For more details see wrapXmlrpcMethod.
978 * For a slimmer alternative, see the code in demo/client/proxy.php
980 * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
982 * @param Client $client the client obj all set to query the desired server
983 * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
984 * - string method_filter regular expression
985 * - string new_class_name
987 * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
989 * @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)
991 public function wrapXmlrpcServer($client, $extraOptions = array())
993 $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
994 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
995 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
996 $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
997 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
998 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
999 $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1000 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1001 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1002 $namespace = '\\PhpXmlRpc\\';
1004 $reqClass = $namespace . 'Request';
1005 $decoderClass = $namespace . 'Encoder';
1007 $req = new $reqClass('system.listMethods');
1008 $response = $client->send($req, $timeout, $protocol);
1009 if ($response->faultCode()) {
1010 error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1014 $mList = $response->value();
1015 if ($client->return_type != 'phpvals') {
1016 $decoder = new $decoderClass();
1017 $mList = $decoder->decode($mList);
1019 if (!is_array($mList) || !count($mList)) {
1020 error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1024 // pick a suitable name for the new function, avoiding collisions
1025 if ($newClassName != '') {
1026 $xmlrpcClassName = $newClassName;
1028 $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1029 array('_', ''), $client->server) . '_client';
1031 while ($buildIt && class_exists($xmlrpcClassName)) {
1032 $xmlrpcClassName .= 'x';
1035 /// @todo add function setdebug() to new class, to enable/disable debugging
1036 $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1037 $source .= "function __construct()\n{\n";
1038 $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1039 $source .= "\$this->client = \$client;\n}\n\n";
1041 'return_source' => true,
1042 'simple_client_copy' => 2, // do not produce code to copy the client object
1043 'timeout' => $timeout,
1044 'protocol' => $protocol,
1045 'encode_php_objs' => $encodePhpObjects,
1046 'decode_php_objs' => $decodePhpObjects,
1047 'prefix' => $prefix,
1049 /// @todo build phpdoc for class definition, too
1050 foreach ($mList as $mName) {
1051 if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1052 // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1053 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1054 array('_', ''), $mName);
1055 $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1058 $source .= $methodWrap['docstring'];
1060 $source .= $methodWrap['source'] . "\n";
1062 error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1069 eval($source . '$allOK=1;');
1071 return $xmlrpcClassName;
1073 error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1077 return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1084 * Given necessary info, generate php code that will build a client object just like the given one.
1085 * Take care that no full checking of input parameters is done to ensure that
1086 * valid php code is emitted.
1087 * @param Client $client
1088 * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1089 * @param string $prefix used for the return_type of the created client
1090 * @param string $namespace
1094 protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
1096 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1097 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1099 // copy all client fields to the client that will be generated runtime
1100 // (this provides for future expansion or subclassing of client obj)
1101 if ($verbatimClientCopy) {
1102 foreach ($client as $fld => $val) {
1103 if ($fld != 'debug' && $fld != 'return_type') {
1104 $val = var_export($val, true);
1105 $code .= "\$client->$fld = $val;\n";
1109 // only make sure that client always returns the correct data type
1110 $code .= "\$client->return_type = '{$prefix}vals';\n";
1111 //$code .= "\$client->setDebug(\$debug);\n";