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 separate introspection from code generation for func-2-method wrapping
16 * @todo use some better templating system for code generation?
17 * @todo implement method wrapping with preservation of php objs in calls
18 * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
23 * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
24 * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
25 * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
26 * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
27 * for php arrays always return array, even though arrays sometimes serialize as json structs.
29 * @param string $phpType
33 public function php_2_xmlrpc_type($phpType)
35 switch (strtolower($phpType)) {
37 return Value::$xmlrpcString;
39 case Value::$xmlrpcInt: // 'int'
40 case Value::$xmlrpcI4:
41 return Value::$xmlrpcInt;
43 return Value::$xmlrpcDouble;
45 return Value::$xmlrpcBoolean;
47 return Value::$xmlrpcArray;
49 return Value::$xmlrpcStruct;
50 case Value::$xmlrpcBase64:
51 case Value::$xmlrpcStruct:
52 return strtolower($phpType);
56 if (class_exists($phpType)) {
57 return Value::$xmlrpcStruct;
59 // unknown: might be any 'extended' xmlrpc type
60 return Value::$xmlrpcValue;
66 * Given a string defining a phpxmlrpc type return corresponding php type.
68 * @param string $xmlrpcType
72 public function xmlrpc_2_php_type($xmlrpcType)
74 switch (strtolower($xmlrpcType)) {
76 case 'datetime.iso8601':
78 return Value::$xmlrpcString;
92 // unknown: might be any xmlrpc type
93 return strtolower($xmlrpcType);
98 * Given a user-defined PHP function, create a PHP 'wrapper' function that can
99 * be exposed as xmlrpc method from an xmlrpc server object and called from remote
100 * clients (as well as its corresponding signature info).
102 * Since php is a typeless language, to infer types of input and output parameters,
103 * it relies on parsing the javadoc-style comment block associated with the given
104 * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
105 * in the @param tag is also allowed, if you need the php function to receive/send
106 * data in that particular format (note that base64 encoding/decoding is transparently
107 * carried out by the lib, while datetime vals are passed around as strings)
110 * - only works for user-defined functions, not for PHP internal functions
111 * (reflection does not support retrieving number/type of params for those)
112 * - functions returning php objects will generate special xmlrpc responses:
113 * when the xmlrpc decoding of those responses is carried out by this same lib, using
114 * the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
115 * In short: php objects can be serialized, too (except for their resource members),
116 * using this function.
117 * Other libs might choke on the very same xml that will be generated in this case
118 * (i.e. it has a nonstandard attribute on struct element tags)
119 * - usage of javadoc @param tags using param names in a different order from the
120 * function prototype is not considered valid (to be fixed?)
122 * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
123 * php functions (ie. functions not expecting a single Request obj as parameter)
124 * is by making use of the functions_parameters_type class member.
126 * @param string $funcName the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
127 * @param string $newFuncName (optional) name for function to be created
128 * @param array $extraOptions (optional) array of options for conversion. valid values include:
129 * bool return_source when true, php code w. function definition will be returned, not evaluated
130 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
131 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
132 * bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
134 * @return false on error, or an array containing the name of the new php function,
135 * its signature and docs, to be used in the server dispatch map
137 * @todo decide how to deal with params passed by ref: bomb out or allow?
138 * @todo finish using javadoc info to build method sig if all params are named but out of order
139 * @todo add a check for params of 'resource' type
140 * @todo add some trigger_errors / error_log when returning false?
141 * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
142 * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
143 * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster
144 * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
146 public function wrap_php_function($funcName, $newFuncName = '', $extraOptions = array())
148 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
149 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
150 $namespace = '\\PhpXmlRpc\\';
151 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
152 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
153 $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
155 if (is_string($funcName) && strpos($funcName, '::') !== false) {
156 $funcName = explode('::', $funcName);
158 if (is_array($funcName)) {
159 if (count($funcName) < 2 || (!is_string($funcName[0]) && !is_object($funcName[0]))) {
160 error_log('XML-RPC: syntax for function to be wrapped is wrong');
164 if (is_string($funcName[0])) {
165 $plainFuncName = implode('::', $funcName);
166 } elseif (is_object($funcName[0])) {
167 $plainFuncName = get_class($funcName[0]) . '->' . $funcName[1];
169 $exists = method_exists($funcName[0], $funcName[1]);
171 $plainFuncName = $funcName;
172 $exists = function_exists($funcName);
176 error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName);
180 // determine name of new php function
181 if ($newFuncName == '') {
182 if (is_array($funcName)) {
183 if (is_string($funcName[0])) {
184 $xmlrpcFuncName = "{$prefix}_" . implode('_', $funcName);
186 $xmlrpcFuncName = "{$prefix}_" . get_class($funcName[0]) . '_' . $funcName[1];
189 $xmlrpcFuncName = "{$prefix}_$funcName";
192 $xmlrpcFuncName = $newFuncName;
194 while ($buildIt && function_exists($xmlrpcFuncName)) {
195 $xmlrpcFuncName .= 'x';
198 // start to introspect PHP code
199 if (is_array($funcName)) {
200 $func = new \ReflectionMethod($funcName[0], $funcName[1]);
201 if ($func->isPrivate()) {
202 error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName);
206 if ($func->isProtected()) {
207 error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName);
211 if ($func->isConstructor()) {
212 error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName);
216 if ($func->isDestructor()) {
217 error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName);
221 if ($func->isAbstract()) {
222 error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName);
226 /// @todo add more checks for static vs. nonstatic?
228 $func = new \ReflectionFunction($funcName);
230 if ($func->isInternal()) {
231 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
232 // instead of getparameters to fully reflect internal php functions ?
233 error_log('XML-RPC: function to be wrapped is internal: ' . $plainFuncName);
238 // retrieve parameter names, types and description from javadoc comments
240 // function description
242 // type of return val: by default 'any'
243 $returns = Value::$xmlrpcValue;
244 // desc of return val
246 // type + name of function parameters
247 $paramDocs = array();
249 $docs = $func->getDocComment();
251 $docs = explode("\n", $docs);
253 foreach ($docs as $doc) {
254 $doc = trim($doc, " \r\t/*");
255 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
260 } elseif (strpos($doc, '@param') === 0) {
261 // syntax: @param type [$name] desc
262 if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
263 if (strpos($matches[1], '|')) {
264 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
265 $paramDocs[$i]['type'] = 'mixed';
267 $paramDocs[$i]['type'] = $matches[1];
269 $paramDocs[$i]['name'] = trim($matches[2]);
270 $paramDocs[$i]['doc'] = $matches[3];
273 } elseif (strpos($doc, '@return') === 0) {
274 // syntax: @return type desc
275 //$returns = preg_split('/\s+/', $doc);
276 if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
277 $returns = php_2_xmlrpc_type($matches[1]);
278 if (isset($matches[2])) {
279 $returnsDocs = $matches[2];
286 // execute introspection of actual function prototype
289 foreach ($func->getParameters() as $paramObj) {
290 $params[$i] = array();
291 $params[$i]['name'] = '$' . $paramObj->getName();
292 $params[$i]['isoptional'] = $paramObj->isOptional();
296 // start building of PHP code to be eval'd
298 $innerCode = "\$encoder = new {$namespace}Encoder();\n";
300 $parsVariations = array();
302 $pNum = count($params);
303 foreach ($params as $param) {
304 if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name'])) {
305 // param name from phpdoc info does not match param definition!
306 $paramDocs[$i]['type'] = 'mixed';
309 if ($param['isoptional']) {
310 // this particular parameter is optional. save as valid previous list of parameters
311 $innerCode .= "if (\$paramcount > $i) {\n";
312 $parsVariations[] = $pars;
314 $innerCode .= "\$p$i = \$msg->getParam($i);\n";
315 if ($decodePhpObjects) {
316 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n";
318 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n";
323 if ($param['isoptional']) {
327 // last allowed parameters combination
328 $parsVariations[] = $pars;
334 if (count($parsVariations) == 0) {
335 // only known good synopsis = no parameters
336 $parsVariations[] = array();
339 $minPars = count($parsVariations[0]);
343 // add to code the check for min params number
344 // NB: this check needs to be done BEFORE decoding param values
345 $innerCode = "\$paramcount = \$msg->getNumParams();\n" .
346 "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innerCode;
348 $innerCode = "\$paramcount = \$msg->getNumParams();\n" . $innerCode;
351 $innerCode .= "\$np = false;\n";
352 // since there are no closures in php, if we are given an object instance,
353 // we store a pointer to it in a global var...
354 if (is_array($funcName) && is_object($funcName[0])) {
355 $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcFuncName] = &$funcName[0];
356 $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcFuncName'];\n";
357 $realFuncName = '$obj->' . $funcName[1];
359 $realFuncName = $plainFuncName;
361 foreach ($parsVariations as $pars) {
362 $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n";
363 // build a 'generic' signature (only use an appropriate return type)
364 $sig = array($returns);
365 $pSig = array($returnsDocs);
366 for ($i = 0; $i < count($pars); $i++) {
367 if (isset($paramDocs[$i]['type'])) {
368 $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
370 $sig[] = Value::$xmlrpcValue;
372 $pSig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
377 $innerCode .= "\$np = true;\n";
378 $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n";
379 //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
380 $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
381 if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) {
382 $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));";
384 if ($encodePhpObjects) {
385 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
387 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
390 // shall we exclude functions returning by ref?
391 // if($func->returnsReference())
393 $code = "function $xmlrpcFuncName(\$msg) {\n" . $innerCode . "}\n}";
397 eval($code . '$allOK=1;');
399 //$xmlrpcFuncName = create_function('$m', $innerCode);
402 error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap php function ' . $plainFuncName);
408 /// @todo examine if $paramDocs matches $parsVariations and build array for
409 /// usage as method signature, plus put together a nice string for docs
411 $ret = array('function' => $xmlrpcFuncName, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $pSigs, 'source' => $code);
418 * Given a user-defined PHP class or php object, map its methods onto a list of
419 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
420 * object and called from remote clients (as well as their corresponding signature info).
422 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
423 * @param array $extraOptions see the docs for wrap_php_method for more options
424 * 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
426 * @return array or false on failure
428 * @todo get_class_methods will return both static and non-static methods.
429 * we have to differentiate the action, depending on wheter we recived a class name or object
431 public function wrap_php_class($classname, $extraOptions = array())
433 $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
434 $methodtype = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
437 $mlist = get_class_methods($classname);
438 foreach ($mlist as $mname) {
439 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
441 $func = new \ReflectionMethod($classname, $mname);
442 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
443 if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
444 (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
446 $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extraOptions);
448 $result[$methodwrap['function']] = $methodwrap['function'];
459 * Given an xmlrpc client and a method name, register a php wrapper function
460 * that will call it and return results using native php types for both
461 * params and results. The generated php function will return a Response
462 * object for failed xmlrpc calls.
465 * - server must support system.methodsignature for the wanted xmlrpc method
466 * - for methods that expose many signatures, only one can be picked (we
467 * could in principle check if signatures differ only by number of params
468 * and not by type, but it would be more complication than we can spare time)
469 * - nested xmlrpc params: the caller of the generated php function has to
470 * encode on its own the params passed to the php function if these are structs
471 * or arrays whose (sub)members include values of type datetime or base64
473 * Notes: the connection properties of the given client will be copied
474 * and reused for the connection used during the call to the generated
476 * Calling the generated php function 'might' be slow: a new xmlrpc client
477 * is created on every invocation and an xmlrpc-connection opened+closed.
478 * An extra 'debug' param is appended to param list of xmlrpc method, useful
479 * for debugging purposes.
481 * @param Client $client an xmlrpc client set up correctly to communicate with target server
482 * @param string $methodName the xmlrpc method to be mapped to a php function
483 * @param array $extraOptions array of options that specify conversion details. valid options include
484 * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
485 * integer timeout timeout (in secs) to be used when executing function/calling remote method
486 * string protocol 'http' (default), 'http11' or 'https'
487 * string new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
488 * string return_source if true return php code w. function definition instead fo function name
489 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
490 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
491 * 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
492 * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
494 * @return string the name of the generated php function (or false) - OR AN ARRAY...
496 public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $timeout = 0, $protocol = '', $newFuncName = '')
498 // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
499 // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
500 if (!is_array($extraOptions)) {
501 $signum = $extraOptions;
502 $extraOptions = array();
504 $signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
505 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
506 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
507 $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
509 //$encodePhpObjects = in_array('encode_php_objects', $extraOptions);
510 //$verbatimClientCopy = in_array('simple_client_copy', $extraOptions) ? 1 :
511 // in_array('build_class_code', $extraOptions) ? 2 : 0;
513 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
514 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
515 // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
516 $simpleClientCopy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
517 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
518 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
519 $namespace = '\\PhpXmlRpc\\';
520 if (isset($extraOptions['return_on_fault'])) {
522 $faultResponse = $extraOptions['return_on_fault'];
524 $decodeFault = false;
527 $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
529 $msgclass = $namespace . 'Request';
530 $valclass = $namespace . 'Value';
531 $decoderClass = $namespace . 'Encoder';
533 $msg = new $msgclass('system.methodSignature');
534 $msg->addparam(new $valclass($methodName));
535 $client->setDebug($debug);
536 $response = $client->send($msg, $timeout, $protocol);
537 if ($response->faultCode()) {
538 error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName);
542 $msig = $response->value();
543 if ($client->return_type != 'phpvals') {
544 $decoder = new $decoderClass();
545 $msig = $decoder->decode($msig);
547 if (!is_array($msig) || count($msig) <= $signum) {
548 error_log('XML-RPC: could not retrieve method signature nr.' . $signum . ' from remote server for method ' . $methodName);
552 // pick a suitable name for the new function, avoiding collisions
553 if ($newFuncName != '') {
554 $xmlrpcFuncName = $newFuncName;
556 // take care to insure that methodname is translated to valid
558 $xmlrpcFuncName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
559 array('_', ''), $methodName);
561 while ($buildIt && function_exists($xmlrpcFuncName)) {
562 $xmlrpcFuncName .= 'x';
565 $msig = $msig[$signum];
567 // if in 'offline' mode, get method description too.
568 // in online mode, favour speed of operation
570 $msg = new $msgclass('system.methodHelp');
571 $msg->addparam(new $valclass($methodName));
572 $response = $client->send($msg, $timeout, $protocol);
573 if (!$response->faultCode()) {
574 $mdesc = $response->value();
575 if ($client->return_type != 'phpvals') {
576 $mdesc = $mdesc->scalarval();
581 $results = $this->build_remote_method_wrapper_code($client, $methodName,
582 $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simpleClientCopy,
583 $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
584 $faultResponse, $namespace);
588 eval($results['source'] . '$allOK=1;');
590 //$xmlrpcFuncName = create_function('$m', $innerCode);
592 return $xmlrpcFuncName;
594 error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap remote method ' . $methodName);
599 $results['function'] = $xmlrpcFuncName;
608 * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
609 * all xmlrpc methods exposed by the remote server as own methods.
610 * For more details see wrap_xmlrpc_method.
612 * @param Client $client the client obj all set to query the desired server
613 * @param array $extraOptions list of options for wrapped code
615 * @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)
617 public function wrap_xmlrpc_server($client, $extraOptions = array())
619 $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
620 //$signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
621 $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
622 $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
623 $newclassname = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
624 $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
625 $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
626 $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
627 $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
628 $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
629 $namespace = '\\PhpXmlRpc\\';
631 $msgclass = $namespace . 'Request';
632 //$valclass = $prefix.'val';
633 $decoderClass = $namespace . 'Encoder';
635 $msg = new $msgclass('system.listMethods');
636 $response = $client->send($msg, $timeout, $protocol);
637 if ($response->faultCode()) {
638 error_log('XML-RPC: could not retrieve method list from remote server');
642 $mlist = $response->value();
643 if ($client->return_type != 'phpvals') {
644 $decoder = new $decoderClass();
645 $mlist = $decoder->decode($mlist);
647 if (!is_array($mlist) || !count($mlist)) {
648 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
652 // pick a suitable name for the new function, avoiding collisions
653 if ($newclassname != '') {
654 $xmlrpcClassName = $newclassname;
656 $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
657 array('_', ''), $client->server) . '_client';
659 while ($buildIt && class_exists($xmlrpcClassName)) {
660 $xmlrpcClassName .= 'x';
663 /// @todo add function setdebug() to new class, to enable/disable debugging
664 $source = "class $xmlrpcClassName\n{\nvar \$client;\n\n";
665 $source .= "function __construct()\n{\n";
666 $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace);
667 $source .= "\$this->client = \$client;\n}\n\n";
668 $opts = array('simple_client_copy' => 2, 'return_source' => true,
669 'timeout' => $timeout, 'protocol' => $protocol,
670 'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix,
671 'decode_php_objs' => $decodePhpObjects,
673 /// @todo build javadoc for class definition, too
674 foreach ($mlist as $mname) {
675 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
676 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
677 array('_', ''), $mname);
678 $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts);
681 $source .= $methodwrap['docstring'];
683 $source .= $methodwrap['source'] . "\n";
685 error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
692 eval($source . '$allOK=1;');
694 //$xmlrpcFuncName = create_function('$m', $innerCode);
696 return $xmlrpcClassName;
698 error_log('XML-RPC: could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
703 return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
710 * Given the necessary info, build php code that creates a new function to
711 * invoke a remote xmlrpc method.
712 * Take care that no full checking of input parameters is done to ensure that
713 * valid php code is emitted.
714 * Note: real spaghetti code follows...
716 public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName,
717 $msig, $mdesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc',
718 $decodePhpObjects = false, $encodePhpObjects = false, $decdoeFault = false,
719 $faultResponse = '', $namespace = '\\PhpXmlRpc\\')
721 $code = "function $xmlrpcFuncName (";
722 if ($clientCopyMode < 2) {
723 // client copy mode 0 or 1 == partial / full client copy in emitted code
724 $innerCode = $this->build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace);
725 $innerCode .= "\$client->setDebug(\$debug);\n";
728 // client copy mode 2 == no client copy in emitted code
732 $innerCode .= "\$msg = new {$namespace}Request('$methodName');\n";
735 // take care that PHP comment is not terminated unwillingly by method description
736 $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
738 $mdesc = "/**\nFunction $xmlrpcFuncName\n";
742 $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
744 $pcount = count($msig);
745 for ($i = 1; $i < $pcount; $i++) {
748 if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
749 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
751 // only build directly xmlrpc values when type is known and scalar
752 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n";
754 if ($encodePhpObjects) {
755 $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
757 $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
760 $innerCode .= "\$msg->addparam(\$p$i);\n";
761 $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
763 if ($clientCopyMode < 2) {
764 $plist[] = '$debug=0';
765 $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
767 $plist = implode(', ', $plist);
768 $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
770 $innerCode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
772 if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
773 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
775 $respCode = var_export($faultResponse, true);
780 if ($decodePhpObjects) {
781 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
783 $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
786 $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
788 return array('source' => $code, 'docstring' => $mdesc);
792 * Given necessary info, generate php code that will rebuild a client object
793 * Take care that no full checking of input parameters is done to ensure that
794 * valid php code is emitted.
795 * @param Client $client
796 * @param bool $verbatimClientCopy
797 * @param string $prefix
798 * @param string $namespace
801 protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
803 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
804 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
806 // copy all client fields to the client that will be generated runtime
807 // (this provides for future expansion or subclassing of client obj)
808 if ($verbatimClientCopy) {
809 foreach ($client as $fld => $val) {
810 if ($fld != 'debug' && $fld != 'return_type') {
811 $val = var_export($val, true);
812 $code .= "\$client->$fld = $val;\n";
816 // only make sure that client always returns the correct data type
817 $code .= "\$client->return_type = '{$prefix}vals';\n";
818 //$code .= "\$client->setDebug(\$debug);\n";