3 * @author Gaetano Giunta
4 * @copyright (C) 2006-2015 G. Giunta
5 * @license code licensed under the BSD License: see file license.txt
11 * PHP-XMLRPC "wrapper" class.
12 * Generate stubs to transparently access xmlrpc methods as php functions and vice-versa.
13 * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
15 * @todo use some better templating system for code generation?
16 * @todo implement method wrapping with preservation of php objs in calls
17 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
22 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
23 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
24 * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
25 * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
26 * for php arrays always return array, even though arrays sometimes serialize as json structs.
28 * @param string $phpType
32 public function php_2_xmlrpc_type($phpType)
34 switch (strtolower($phpType)) {
36 return Value::$xmlrpcString;
38 case Value::$xmlrpcInt: // 'int'
39 case Value::$xmlrpcI4:
40 return Value::$xmlrpcInt;
42 return Value::$xmlrpcDouble;
44 return Value::$xmlrpcBoolean;
46 return Value::$xmlrpcArray;
48 return Value::$xmlrpcStruct;
49 case Value::$xmlrpcBase64:
50 case Value::$xmlrpcStruct:
51 return strtolower($phpType);
55 if (class_exists($phpType)) {
56 return Value::$xmlrpcStruct;
58 // unknown: might be any 'extended' xmlrpc type
59 return Value::$xmlrpcValue;
65 * Given a string defining a phpxmlrpc type return corresponding php type.
67 * @param string $xmlrpcType
71 public function xmlrpc_2_php_type($xmlrpcType)
73 switch (strtolower($xmlrpcType)) {
75 case 'datetime.iso8601':
77 return Value::$xmlrpcString;
91 // unknown: might be any xmlrpc type
92 return strtolower($xmlrpcType);
97 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
98 * be exposed as xmlrpc method from an xmlrpc server object and called from remote
99 * clients (as well as its corresponding signature info).
101 * Since php is a typeless language, to infer types of input and output parameters,
102 * it relies on parsing the javadoc-style comment block associated with the given
103 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
104 * in the @param tag is also allowed, if you need the php function to receive/send
105 * data in that particular format (note that base64 encoding/decoding is transparently
106 * carried out by the lib, while datetime vals are passed around as strings)
109 * - only works for user-defined functions, not for PHP internal functions
110 * (reflection does not support retrieving number/type of params for those)
111 * - functions returning php objects will generate special xmlrpc responses:
112 * when the xmlrpc decoding of those responses is carried out by this same lib, using
113 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
114 * In short: php objects can be serialized, too (except for their resource members),
115 * using this function.
116 * Other libs might choke on the very same xml that will be generated in this case
117 * (i.e. it has a nonstandard attribute on struct element tags)
118 * - usage of javadoc @param tags using param names in a different order from the
119 * function prototype is not considered valid (to be fixed?)
121 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
122 * php functions (ie. functions not expecting a single Request obj as parameter)
123 * is by making use of the functions_parameters_type class member.
125 * @param string|array $funcName the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
126 * @param string $newFuncName (optional) name for function to be created
127 * @param array $extraOptions (optional) array of options for conversion. valid values include:
128 * bool return_source when true, php code w. function definition will be returned, not evaluated
129 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
130 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
131 * bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
133 * @return array|false false on error, or an array containing the name of the new php function,
134 * its signature and docs, to be used in the server dispatch map
136 * @todo decide how to deal with params passed by ref: bomb out or allow?
137 * @todo finish using phpdoc info to build method sig if all params are named but out of order
138 * @todo add a check for params of 'resource' type
139 * @todo add some trigger_errors / error_log when returning false?
140 * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
141 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
142 * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster
143 * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
145 public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array())
147 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
149 if (is_string($callable) && strpos($callable, '::') !== false) {
150 $callable = explode('::', $callable);
152 if (is_array($callable)) {
153 if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
154 error_log('XML-RPC: syntax for function to be wrapped is wrong');
157 if (is_string($callable[0])) {
158 $plainFuncName = implode('::', $callable);
159 } elseif (is_object($callable[0])) {
160 $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
162 $exists = method_exists($callable[0], $callable[1]);
163 } else if ($callable instanceof \Closure) {
164 $plainFuncName = 'Closure';
168 $plainFuncName = $callable;
169 $exists = function_exists($callable);
173 error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName);
177 $funcDesc = $this->introspectFunction($callable, $plainFuncName);
182 $funcSigs = $this->buildMethodSignatures($funcDesc);
186 eval($code . '$allOK=1;');
188 //$xmlrpcFuncName = create_function('$m', $innerCode);
191 error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap php function ' . $plainFuncName);
195 $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null);
198 $newFuncName =$this->newFunctionName($callable, $newFuncName, $extraOptions);
199 $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
200 // replace the original callable to be set in the results
201 $callable = $newFuncName;
204 /// @todo examine if $paramDocs matches $parsVariations and build array for
205 /// usage as method signature, plus put together a nice string for docs
208 'function' => $callable,
209 'signature' => $funcSigs['sigs'],
210 'docstring' => $funcDesc['desc'],
211 'signature_docs' => $funcSigs['pSigs'],
219 * Introspect a php callable and its phpdoc block and extract information about its signature
221 * @param callable $callable
222 * @param string $plainFuncName
223 * @return array|false
225 protected function introspectFunction($callable, $plainFuncName)
227 // start to introspect PHP code
228 if (is_array($callable)) {
229 $func = new \ReflectionMethod($callable[0], $callable[1]);
230 if ($func->isPrivate()) {
231 error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName);
235 if ($func->isProtected()) {
236 error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName);
240 if ($func->isConstructor()) {
241 error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName);
245 if ($func->isDestructor()) {
246 error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName);
250 if ($func->isAbstract()) {
251 error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName);
255 /// @todo add more checks for static vs. nonstatic?
257 $func = new \ReflectionFunction($callable);
259 if ($func->isInternal()) {
260 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
261 // instead of getparameters to fully reflect internal php functions ?
262 error_log('XML-RPC: function to be wrapped is internal: ' . $plainFuncName);
267 // retrieve parameter names, types and description from javadoc comments
269 // function description
271 // type of return val: by default 'any'
272 $returns = Value::$xmlrpcValue;
273 // desc of return val
275 // type + name of function parameters
276 $paramDocs = array();
278 $docs = $func->getDocComment();
280 $docs = explode("\n", $docs);
282 foreach ($docs as $doc) {
283 $doc = trim($doc, " \r\t/*");
284 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
289 } elseif (strpos($doc, '@param') === 0) {
290 // syntax: @param type [$name] desc
291 if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
292 if (strpos($matches[1], '|')) {
293 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
294 $paramDocs[$i]['type'] = 'mixed';
296 $paramDocs[$i]['type'] = $matches[1];
298 $paramDocs[$i]['name'] = trim($matches[2]);
299 $paramDocs[$i]['doc'] = $matches[3];
302 } elseif (strpos($doc, '@return') === 0) {
303 // syntax: @return type desc
304 //$returns = preg_split('/\s+/', $doc);
305 if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
306 $returns = $this->php_2_xmlrpc_type($matches[1]);
307 if (isset($matches[2])) {
308 $returnsDocs = $matches[2];
315 // execute introspection of actual function prototype
318 foreach ($func->getParameters() as $paramObj) {
319 $params[$i] = array();
320 $params[$i]['name'] = '$' . $paramObj->getName();
321 $params[$i]['isoptional'] = $paramObj->isOptional();
329 'paramsDocs' => $paramDocs,
330 'returns' => $returns,
331 'returnsDocs' =>$returnsDocs,
336 * Given the method description given by introspection, create method signature data
338 * @param array $funcDesc as generated by self::introspectFunction()
342 protected function buildMethodSignatures($funcDesc)
345 $parsVariations = array();
347 $pNum = count($funcDesc['params']);
348 foreach ($funcDesc['params'] as $param) {
349 if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] &&
350 strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) {
351 // param name from phpdoc info does not match param definition!
352 $funcDesc['paramDocs'][$i]['type'] = 'mixed';
355 if ($param['isoptional']) {
356 // this particular parameter is optional. save as valid previous list of parameters
357 $parsVariations[] = $pars;
363 // last allowed parameters combination
364 $parsVariations[] = $pars;
368 if (count($parsVariations) == 0) {
369 // only known good synopsis = no parameters
370 $parsVariations[] = array();
375 foreach ($parsVariations as $pars) {
376 // build a 'generic' signature (only use an appropriate return type)
377 $sig = array($funcDesc['returns']);
378 $pSig = array($funcDesc['returnsDocs']);
379 for ($i = 0; $i < count($pars); $i++) {
380 if (isset($funcDesc['paramDocs'][$i]['type'])) {
381 $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$i]['type']);
383 $sig[] = Value::$xmlrpcValue;
385 $pSig[] = isset($funcDesc['paramDocs'][$i]['doc']) ? $funcDesc['paramDocs'][$i]['doc'] : '';
398 * Creates a closure that will execute $callable
399 * @todo use namespace, options to encode/decode objects, validate params
402 * @param array $extraOptions
403 * @param string $plainFuncName
404 * @param string $funcDesc
407 protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
409 $function = function($req) use($callable, $extraOptions)
411 $encoder = new \PhpXmlRpc\Encoder();
412 $params = $encoder->decode($req);
414 $result = call_user_func_array($callable, $params);
416 if (! $result instanceof \PhpXmlRpc\Response) {
417 $result = new \PhpXmlRpc\Response($encoder->encode($result));
426 * Return a name for the new function
428 * @param string $newFuncName
431 protected function newFunctionName($callable, $newFuncName, $extraOptions)
433 // determine name of new php function
435 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
437 if ($newFuncName == '') {
438 if (is_array($callable)) {
439 if (is_string($callable[0])) {
440 $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
442 $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
445 if ($callable instanceof \Closure) {
446 $xmlrpcFuncName = "{$prefix}_closure";
448 $xmlrpcFuncName = "{$prefix}_$callable";
452 $xmlrpcFuncName = $newFuncName;
455 while (function_exists($xmlrpcFuncName)) {
456 $xmlrpcFuncName .= 'x';
459 return $xmlrpcFuncName;
464 * @param string $newFuncName
465 * @param array $extraOptions
466 * @param string $plainFuncName
467 * @param array $funcDesc
470 protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
472 $namespace = '\\PhpXmlRpc\\';
473 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
474 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
475 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
476 $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
478 // build body of new function
480 $innerCode = "\$encoder = new {$namespace}Encoder();\n";
482 $parsVariations = array();
484 $pNum = count($funcDesc['params']);
485 foreach ($funcDesc['params'] as $param) {
486 if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] &&
487 strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) {
488 // param name from phpdoc info does not match param definition!
489 $funcDesc['paramDocs'][$i]['type'] = 'mixed';
492 if ($param['isoptional']) {
493 // this particular parameter is optional. save as valid previous list of parameters
494 $innerCode .= "if (\$paramcount > $i) {\n";
495 $parsVariations[] = $pars;
497 $innerCode .= "\$p$i = \$req->getParam($i);\n";
498 if ($decodePhpObjects) {
499 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n";
501 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n";
506 if ($param['isoptional']) {
510 // last allowed parameters combination
511 $parsVariations[] = $pars;
515 if (count($parsVariations) == 0) {
516 // only known good synopsis = no parameters
517 $parsVariations[] = array();
520 $minPars = count($parsVariations[0]);
524 // add to code the check for min params number
525 // NB: this check needs to be done BEFORE decoding param values
526 $innerCode = "\$paramcount = \$req->getNumParams();\n" .
527 "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n" . $innerCode;
529 $innerCode = "\$paramcount = \$req->getNumParams();\n" . $innerCode;
532 $innerCode .= "\$np = false;\n";
533 // since there are no closures in php, if we are given an object instance,
534 // we store a pointer to it in a global var...
535 if (is_array($callable) && is_object($callable[0])) {
536 $GLOBALS['xmlrpcWPFObjHolder'][$newFuncName] = &$callable[0];
537 $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$newFuncName'];\n";
538 $realFuncName = '$obj->' . $callable[1];
540 $realFuncName = $plainFuncName;
542 foreach ($parsVariations as $pars) {
543 $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n";
545 $innerCode .= "\$np = true;\n";
546 $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "'); else {\n";
547 //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
548 $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
549 if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
550 $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
552 if ($encodePhpObjects) {
553 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
555 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
558 // shall we exclude functions returning by ref?
559 // if($func->returnsReference())
562 $code = "function $newFuncName(\$req) {\n" . $innerCode . "}\n}";
568 * Given a user-defined PHP class or php object, map its methods onto a list of
569 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
570 * object and called from remote clients (as well as their corresponding signature info).
572 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
573 * @param array $extraOptions see the docs for wrap_php_method for more options
574 * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
576 * @return array or false on failure
578 * @todo get_class_methods will return both static and non-static methods.
579 * we have to differentiate the action, depending on whether we received a class name or object
581 public function wrap_php_class($classname, $extraOptions = array())
583 $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
584 $methodtype = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
587 $mlist = get_class_methods($classname);
588 foreach ($mlist as $mname) {
589 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
591 $func = new \ReflectionMethod($classname, $mname);
592 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
593 if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
594 (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
596 $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extraOptions);
598 $result[$methodwrap['function']] = $methodwrap['function'];
609 * Given an xmlrpc client and a method name, register a php wrapper function
610 * that will call it and return results using native php types for both
611 * params and results. The generated php function will return a Response
612 * object for failed xmlrpc calls.
615 * - server must support system.methodsignature for the wanted xmlrpc method
616 * - for methods that expose many signatures, only one can be picked (we
617 * could in principle check if signatures differ only by number of params
618 * and not by type, but it would be more complication than we can spare time)
619 * - nested xmlrpc params: the caller of the generated php function has to
620 * encode on its own the params passed to the php function if these are structs
621 * or arrays whose (sub)members include values of type datetime or base64
623 * Notes: the connection properties of the given client will be copied
624 * and reused for the connection used during the call to the generated
626 * Calling the generated php function 'might' be slow: a new xmlrpc client
627 * is created on every invocation and an xmlrpc-connection opened+closed.
628 * An extra 'debug' param is appended to param list of xmlrpc method, useful
629 * for debugging purposes.
631 * @param Client $client an xmlrpc client set up correctly to communicate with target server
632 * @param string $methodName the xmlrpc method to be mapped to a php function
633 * @param array $extraOptions array of options that specify conversion details. valid options include
634 * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
635 * integer timeout timeout (in secs) to be used when executing function/calling remote method
636 * string protocol 'http' (default), 'http11' or 'https'
637 * string new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
638 * string return_source if true return php code w. function definition instead fo function name
639 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
640 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
641 * 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
642 * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
644 * @return string the name of the generated php function (or false) - OR AN ARRAY...
646 public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $timeout = 0, $protocol = '', $newFuncName = '')
648 // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
649 // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
650 if (!is_array($extraOptions)) {
651 $signum = $extraOptions;
652 $extraOptions = array();
654 $signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
655 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
656 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
657 $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
659 //$encodePhpObjects = in_array('encode_php_objects', $extraOptions);
660 //$verbatimClientCopy = in_array('simple_client_copy', $extraOptions) ? 1 :
661 // in_array('build_class_code', $extraOptions) ? 2 : 0;
663 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
664 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
665 // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
666 $simpleClientCopy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
667 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
668 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
669 $namespace = '\\PhpXmlRpc\\';
670 if (isset($extraOptions['return_on_fault'])) {
672 $faultResponse = $extraOptions['return_on_fault'];
674 $decodeFault = false;
677 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
679 $msgclass = $namespace . 'Request';
680 $valclass = $namespace . 'Value';
681 $decoderClass = $namespace . 'Encoder';
683 $msg = new $msgclass('system.methodSignature');
684 $msg->addparam(new $valclass($methodName));
685 $client->setDebug($debug);
686 $response = $client->send($msg, $timeout, $protocol);
687 if ($response->faultCode()) {
688 error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName);
692 $msig = $response->value();
693 if ($client->return_type != 'phpvals') {
694 $decoder = new $decoderClass();
695 $msig = $decoder->decode($msig);
697 if (!is_array($msig) || count($msig) <= $signum) {
698 error_log('XML-RPC: could not retrieve method signature nr.' . $signum . ' from remote server for method ' . $methodName);
702 // pick a suitable name for the new function, avoiding collisions
703 if ($newFuncName != '') {
704 $xmlrpcFuncName = $newFuncName;
706 // take care to insure that methodname is translated to valid
708 $xmlrpcFuncName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
709 array('_', ''), $methodName);
711 while ($buildIt && function_exists($xmlrpcFuncName)) {
712 $xmlrpcFuncName .= 'x';
715 $msig = $msig[$signum];
717 // if in 'offline' mode, get method description too.
718 // in online mode, favour speed of operation
720 $msg = new $msgclass('system.methodHelp');
721 $msg->addparam(new $valclass($methodName));
722 $response = $client->send($msg, $timeout, $protocol);
723 if (!$response->faultCode()) {
724 $mdesc = $response->value();
725 if ($client->return_type != 'phpvals') {
726 $mdesc = $mdesc->scalarval();
731 $results = $this->build_remote_method_wrapper_code($client, $methodName,
732 $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simpleClientCopy,
733 $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
734 $faultResponse, $namespace);
738 eval($results['source'] . '$allOK=1;');
740 //$xmlrpcFuncName = create_function('$m', $innerCode);
742 return $xmlrpcFuncName;
744 error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap remote method ' . $methodName);
749 $results['function'] = $xmlrpcFuncName;
758 * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
759 * all xmlrpc methods exposed by the remote server as own methods.
760 * For more details see wrap_xmlrpc_method.
762 * @param Client $client the client obj all set to query the desired server
763 * @param array $extraOptions list of options for wrapped code
770 * - simple_client_copy
774 * @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options)
776 public function wrap_xmlrpc_server($client, $extraOptions = array())
778 $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
779 //$signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
780 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
781 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
782 $newclassname = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
783 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
784 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
785 $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
786 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
787 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
788 $namespace = '\\PhpXmlRpc\\';
790 $msgclass = $namespace . 'Request';
791 //$valclass = $prefix.'val';
792 $decoderClass = $namespace . 'Encoder';
794 $msg = new $msgclass('system.listMethods');
795 $response = $client->send($msg, $timeout, $protocol);
796 if ($response->faultCode()) {
797 error_log('XML-RPC: could not retrieve method list from remote server');
801 $mlist = $response->value();
802 if ($client->return_type != 'phpvals') {
803 $decoder = new $decoderClass();
804 $mlist = $decoder->decode($mlist);
806 if (!is_array($mlist) || !count($mlist)) {
807 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
811 // pick a suitable name for the new function, avoiding collisions
812 if ($newclassname != '') {
813 $xmlrpcClassName = $newclassname;
815 $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
816 array('_', ''), $client->server) . '_client';
818 while ($buildIt && class_exists($xmlrpcClassName)) {
819 $xmlrpcClassName .= 'x';
822 /// @todo add function setdebug() to new class, to enable/disable debugging
823 $source = "class $xmlrpcClassName\n{\nvar \$client;\n\n";
824 $source .= "function __construct()\n{\n";
825 $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace);
826 $source .= "\$this->client = \$client;\n}\n\n";
827 $opts = array('simple_client_copy' => 2, 'return_source' => true,
828 'timeout' => $timeout, 'protocol' => $protocol,
829 'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix,
830 'decode_php_objs' => $decodePhpObjects,
832 /// @todo build phpdoc for class definition, too
833 foreach ($mlist as $mname) {
834 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
835 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
836 array('_', ''), $mname);
837 $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts);
840 $source .= $methodwrap['docstring'];
842 $source .= $methodwrap['source'] . "\n";
844 error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
851 eval($source . '$allOK=1;');
853 //$xmlrpcFuncName = create_function('$m', $innerCode);
855 return $xmlrpcClassName;
857 error_log('XML-RPC: could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
862 return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
869 * Given the necessary info, build php code that creates a new function to
870 * invoke a remote xmlrpc method.
871 * Take care that no full checking of input parameters is done to ensure that
872 * valid php code is emitted.
873 * Note: real spaghetti code follows...
875 public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName,
876 $msig, $mdesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc',
877 $decodePhpObjects = false, $encodePhpObjects = false, $decdoeFault = false,
878 $faultResponse = '', $namespace = '\\PhpXmlRpc\\')
880 $code = "function $xmlrpcFuncName (";
881 if ($clientCopyMode < 2) {
882 // client copy mode 0 or 1 == partial / full client copy in emitted code
883 $innerCode = $this->build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace);
884 $innerCode .= "\$client->setDebug(\$debug);\n";
887 // client copy mode 2 == no client copy in emitted code
891 $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
894 // take care that PHP comment is not terminated unwillingly by method description
895 $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
897 $mdesc = "/**\nFunction $xmlrpcFuncName\n";
901 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
903 $pcount = count($msig);
904 for ($i = 1; $i < $pcount; $i++) {
907 if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
908 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
910 // only build directly xmlrpc values when type is known and scalar
911 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n";
913 if ($encodePhpObjects) {
914 $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
916 $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
919 $innerCode .= "\$req->addparam(\$p$i);\n";
920 $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
922 if ($clientCopyMode < 2) {
923 $plist[] = '$debug=0';
924 $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
926 $plist = implode(', ', $plist);
927 $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
929 $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
931 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
932 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
934 $respCode = var_export($faultResponse, true);
939 if ($decodePhpObjects) {
940 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
942 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
945 $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
947 return array('source' => $code, 'docstring' => $mdesc);
951 * Given necessary info, generate php code that will rebuild a client object
952 * Take care that no full checking of input parameters is done to ensure that
953 * valid php code is emitted.
954 * @param Client $client
955 * @param bool $verbatimClientCopy
956 * @param string $prefix
957 * @param string $namespace
961 protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
963 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
964 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
966 // copy all client fields to the client that will be generated runtime
967 // (this provides for future expansion or subclassing of client obj)
968 if ($verbatimClientCopy) {
969 foreach ($client as $fld => $val) {
970 if ($fld != 'debug' && $fld != 'return_type') {
971 $val = var_export($val, true);
972 $code .= "\$client->$fld = $val;\n";
976 // only make sure that client always returns the correct data type
977 $code .= "\$client->return_type = '{$prefix}vals';\n";
978 //$code .= "\$client->setDebug(\$debug);\n";