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 viceversa.
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 $extra_options (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 = '', $extra_options = array())
148 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
149 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
150 $namespace = '\\PhpXmlRpc\\';
151 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
152 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
153 $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
156 if (is_string($funcname) && strpos($funcname, '::') !== false) {
157 $funcname = explode('::', $funcname);
159 if (is_array($funcname)) {
160 if (count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) {
161 error_log('XML-RPC: syntax for function to be wrapped is wrong');
165 if (is_string($funcname[0])) {
166 $plainfuncname = implode('::', $funcname);
167 } elseif (is_object($funcname[0])) {
168 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
170 $exists = method_exists($funcname[0], $funcname[1]);
172 $plainfuncname = $funcname;
173 $exists = function_exists($funcname);
177 error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname);
181 // determine name of new php function
182 if ($newfuncname == '') {
183 if (is_array($funcname)) {
184 if (is_string($funcname[0])) {
185 $xmlrpcfuncname = "{$prefix}_" . implode('_', $funcname);
187 $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1];
190 $xmlrpcfuncname = "{$prefix}_$funcname";
193 $xmlrpcfuncname = $newfuncname;
195 while ($buildit && function_exists($xmlrpcfuncname)) {
196 $xmlrpcfuncname .= 'x';
199 // start to introspect PHP code
200 if (is_array($funcname)) {
201 $func = new \ReflectionMethod($funcname[0], $funcname[1]);
202 if ($func->isPrivate()) {
203 error_log('XML-RPC: method to be wrapped is private: ' . $plainfuncname);
207 if ($func->isProtected()) {
208 error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname);
212 if ($func->isConstructor()) {
213 error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname);
217 if ($func->isDestructor()) {
218 error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname);
222 if ($func->isAbstract()) {
223 error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname);
227 /// @todo add more checks for static vs. nonstatic?
229 $func = new \ReflectionFunction($funcname);
231 if ($func->isInternal()) {
232 // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
233 // instead of getparameters to fully reflect internal php functions ?
234 error_log('XML-RPC: function to be wrapped is internal: ' . $plainfuncname);
239 // retrieve parameter names, types and description from javadoc comments
241 // function description
243 // type of return val: by default 'any'
244 $returns = Value::$xmlrpcValue;
245 // desc of return val
247 // type + name of function parameters
248 $paramDocs = array();
250 $docs = $func->getDocComment();
252 $docs = explode("\n", $docs);
254 foreach ($docs as $doc) {
255 $doc = trim($doc, " \r\t/*");
256 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
261 } elseif (strpos($doc, '@param') === 0) {
262 // syntax: @param type [$name] desc
263 if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
264 if (strpos($matches[1], '|')) {
265 //$paramDocs[$i]['type'] = explode('|', $matches[1]);
266 $paramDocs[$i]['type'] = 'mixed';
268 $paramDocs[$i]['type'] = $matches[1];
270 $paramDocs[$i]['name'] = trim($matches[2]);
271 $paramDocs[$i]['doc'] = $matches[3];
274 } elseif (strpos($doc, '@return') === 0) {
275 // syntax: @return type desc
276 //$returns = preg_split('/\s+/', $doc);
277 if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
278 $returns = php_2_xmlrpc_type($matches[1]);
279 if (isset($matches[2])) {
280 $returnsDocs = $matches[2];
287 // execute introspection of actual function prototype
290 foreach ($func->getParameters() as $paramobj) {
291 $params[$i] = array();
292 $params[$i]['name'] = '$' . $paramobj->getName();
293 $params[$i]['isoptional'] = $paramobj->isOptional();
297 // start building of PHP code to be eval'd
299 $innercode = "\$encoder = new {$namespace}Encoder();\n";
301 $parsvariations = array();
303 $pnum = count($params);
304 foreach ($params as $param) {
305 if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name'])) {
306 // param name from phpdoc info does not match param definition!
307 $paramDocs[$i]['type'] = 'mixed';
310 if ($param['isoptional']) {
311 // this particular parameter is optional. save as valid previous list of parameters
312 $innercode .= "if (\$paramcount > $i) {\n";
313 $parsvariations[] = $pars;
315 $innercode .= "\$p$i = \$msg->getParam($i);\n";
316 if ($decode_php_objects) {
317 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n";
319 $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n";
324 if ($param['isoptional']) {
328 // last allowed parameters combination
329 $parsvariations[] = $pars;
335 if (count($parsvariations) == 0) {
336 // only known good synopsis = no parameters
337 $parsvariations[] = array();
340 $minpars = count($parsvariations[0]);
344 // add to code the check for min params number
345 // NB: this check needs to be done BEFORE decoding param values
346 $innercode = "\$paramcount = \$msg->getNumParams();\n" .
347 "if (\$paramcount < $minpars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode;
349 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
352 $innercode .= "\$np = false;\n";
353 // since there are no closures in php, if we are given an object instance,
354 // we store a pointer to it in a global var...
355 if (is_array($funcname) && is_object($funcname[0])) {
356 $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] = &$funcname[0];
357 $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
358 $realfuncname = '$obj->' . $funcname[1];
360 $realfuncname = $plainfuncname;
362 foreach ($parsvariations as $pars) {
363 $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
364 // build a 'generic' signature (only use an appropriate return type)
365 $sig = array($returns);
366 $psig = array($returnsDocs);
367 for ($i = 0; $i < count($pars); $i++) {
368 if (isset($paramDocs[$i]['type'])) {
369 $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
371 $sig[] = Value::$xmlrpcValue;
373 $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
378 $innercode .= "\$np = true;\n";
379 $innercode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n";
380 //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
381 $innercode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
382 if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) {
383 $innercode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));";
385 if ($encode_php_objects) {
386 $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
388 $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
391 // shall we exclude functions returning by ref?
392 // if($func->returnsReference())
394 $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
398 eval($code . '$allOK=1;');
400 //$xmlrpcfuncname = create_function('$m', $innercode);
403 error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname);
409 /// @todo examine if $paramDocs matches $parsvariations and build array for
410 /// usage as method signature, plus put together a nice string for docs
412 $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
419 * Given a user-defined PHP class or php object, map its methods onto a list of
420 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
421 * object and called from remote clients (as well as their corresponding signature info).
423 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
424 * @param array $extra_options see the docs for wrap_php_method for more options
425 * 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
427 * @return array or false on failure
429 * @todo get_class_methods will return both static and non-static methods.
430 * we have to differentiate the action, depending on wheter we recived a class name or object
432 public function wrap_php_class($classname, $extra_options = array())
434 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
435 $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
438 $mlist = get_class_methods($classname);
439 foreach ($mlist as $mname) {
440 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
442 $func = new \ReflectionMethod($classname, $mname);
443 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
444 if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
445 (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
447 $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extra_options);
449 $result[$methodwrap['function']] = $methodwrap['function'];
460 * Given an xmlrpc client and a method name, register a php wrapper function
461 * that will call it and return results using native php types for both
462 * params and results. The generated php function will return a Response
463 * object for failed xmlrpc calls.
466 * - server must support system.methodsignature for the wanted xmlrpc method
467 * - for methods that expose many signatures, only one can be picked (we
468 * could in principle check if signatures differ only by number of params
469 * and not by type, but it would be more complication than we can spare time)
470 * - nested xmlrpc params: the caller of the generated php function has to
471 * encode on its own the params passed to the php function if these are structs
472 * or arrays whose (sub)members include values of type datetime or base64
474 * Notes: the connection properties of the given client will be copied
475 * and reused for the connection used during the call to the generated
477 * Calling the generated php function 'might' be slow: a new xmlrpc client
478 * is created on every invocation and an xmlrpc-connection opened+closed.
479 * An extra 'debug' param is appended to param list of xmlrpc method, useful
480 * for debugging purposes.
482 * @param Client $client an xmlrpc client set up correctly to communicate with target server
483 * @param string $methodname the xmlrpc method to be mapped to a php function
484 * @param array $extra_options array of options that specify conversion details. valid options include
485 * integer signum the index of the method signature to use in mapping (if method exposes many sigs)
486 * integer timeout timeout (in secs) to be used when executing function/calling remote method
487 * string protocol 'http' (default), 'http11' or 'https'
488 * string new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
489 * string return_source if true return php code w. function definition instead fo function name
490 * bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
491 * bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
492 * 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
493 * bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
495 * @return string the name of the generated php function (or false) - OR AN ARRAY...
497 public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $timeout = 0, $protocol = '', $newfuncname = '')
499 // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
500 // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
501 if (!is_array($extra_options)) {
502 $signum = $extra_options;
503 $extra_options = array();
505 $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
506 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
507 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
508 $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
510 //$encode_php_objects = in_array('encode_php_objects', $extra_options);
511 //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
512 // in_array('build_class_code', $extra_options) ? 2 : 0;
514 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
515 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
516 // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
517 $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
518 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
519 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
520 $namespace = '\\PhpXmlRpc\\';
521 if (isset($extra_options['return_on_fault'])) {
522 $decode_fault = true;
523 $fault_response = $extra_options['return_on_fault'];
525 $decode_fault = false;
526 $fault_response = '';
528 $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
530 $msgclass = $namespace . 'Request';
531 $valclass = $namespace . 'Value';
532 $decoderClass = $namespace . 'Encoder';
534 $msg = new $msgclass('system.methodSignature');
535 $msg->addparam(new $valclass($methodname));
536 $client->setDebug($debug);
537 $response = $client->send($msg, $timeout, $protocol);
538 if ($response->faultCode()) {
539 error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodname);
543 $msig = $response->value();
544 if ($client->return_type != 'phpvals') {
545 $decoder = new $decoderClass();
546 $msig = $decoder->decode($msig);
548 if (!is_array($msig) || count($msig) <= $signum) {
549 error_log('XML-RPC: could not retrieve method signature nr.' . $signum . ' from remote server for method ' . $methodname);
553 // pick a suitable name for the new function, avoiding collisions
554 if ($newfuncname != '') {
555 $xmlrpcfuncname = $newfuncname;
557 // take care to insure that methodname is translated to valid
559 $xmlrpcfuncname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
560 array('_', ''), $methodname);
562 while ($buildit && function_exists($xmlrpcfuncname)) {
563 $xmlrpcfuncname .= 'x';
566 $msig = $msig[$signum];
568 // if in 'offline' mode, get method description too.
569 // in online mode, favour speed of operation
571 $msg = new $msgclass('system.methodHelp');
572 $msg->addparam(new $valclass($methodname));
573 $response = $client->send($msg, $timeout, $protocol);
574 if (!$response->faultCode()) {
575 $mdesc = $response->value();
576 if ($client->return_type != 'phpvals') {
577 $mdesc = $mdesc->scalarval();
582 $results = $this->build_remote_method_wrapper_code($client, $methodname,
583 $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
584 $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
585 $fault_response, $namespace);
589 eval($results['source'] . '$allOK=1;');
591 //$xmlrpcfuncname = create_function('$m', $innercode);
593 return $xmlrpcfuncname;
595 error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname);
600 $results['function'] = $xmlrpcfuncname;
609 * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
610 * all xmlrpc methods exposed by the remote server as own methods.
611 * For more details see wrap_xmlrpc_method.
613 * @param Client $client the client obj all set to query the desired server
614 * @param array $extra_options list of options for wrapped code
616 * @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)
618 public function wrap_xmlrpc_server($client, $extra_options = array())
620 $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
621 //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
622 $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
623 $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
624 $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
625 $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
626 $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
627 $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
628 $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
629 $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
630 $namespace = '\\PhpXmlRpc\\';
632 $msgclass = $namespace . 'Request';
633 //$valclass = $prefix.'val';
634 $decoderClass = $namespace . 'Encoder';
636 $msg = new $msgclass('system.listMethods');
637 $response = $client->send($msg, $timeout, $protocol);
638 if ($response->faultCode()) {
639 error_log('XML-RPC: could not retrieve method list from remote server');
643 $mlist = $response->value();
644 if ($client->return_type != 'phpvals') {
645 $decoder = new $decoderClass();
646 $mlist = $decoder->decode($mlist);
648 if (!is_array($mlist) || !count($mlist)) {
649 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
653 // pick a suitable name for the new function, avoiding collisions
654 if ($newclassname != '') {
655 $xmlrpcclassname = $newclassname;
657 $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
658 array('_', ''), $client->server) . '_client';
660 while ($buildit && class_exists($xmlrpcclassname)) {
661 $xmlrpcclassname .= 'x';
664 /// @todo add function setdebug() to new class, to enable/disable debugging
665 $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
666 $source .= "function __construct()\n{\n";
667 $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix, $namespace);
668 $source .= "\$this->client = \$client;\n}\n\n";
669 $opts = array('simple_client_copy' => 2, 'return_source' => true,
670 'timeout' => $timeout, 'protocol' => $protocol,
671 'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
672 'decode_php_objs' => $decode_php_objects,
674 /// @todo build javadoc for class definition, too
675 foreach ($mlist as $mname) {
676 if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
677 $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
678 array('_', ''), $mname);
679 $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts);
682 $source .= $methodwrap['docstring'];
684 $source .= $methodwrap['source'] . "\n";
686 error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
693 eval($source . '$allOK=1;');
695 //$xmlrpcfuncname = create_function('$m', $innercode);
697 return $xmlrpcclassname;
699 error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server);
704 return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
711 * Given the necessary info, build php code that creates a new function to
712 * invoke a remote xmlrpc method.
713 * Take care that no full checking of input parameters is done to ensure that
714 * valid php code is emitted.
715 * Note: real spaghetti code follows...
717 public function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
718 $msig, $mdesc = '', $timeout = 0, $protocol = '', $client_copy_mode = 0, $prefix = 'xmlrpc',
719 $decode_php_objects = false, $encode_php_objects = false, $decode_fault = false,
720 $fault_response = '', $namespace = '\\PhpXmlRpc\\')
722 $code = "function $xmlrpcfuncname (";
723 if ($client_copy_mode < 2) {
724 // client copy mode 0 or 1 == partial / full client copy in emitted code
725 $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix, $namespace);
726 $innercode .= "\$client->setDebug(\$debug);\n";
729 // client copy mode 2 == no client copy in emitted code
733 $innercode .= "\$msg = new {$namespace}Request('$methodname');\n";
736 // take care that PHP comment is not terminated unwillingly by method description
737 $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
739 $mdesc = "/**\nFunction $xmlrpcfuncname\n";
743 $innercode .= "\$encoder = new {$namespace}Encoder();\n";
745 $pcount = count($msig);
746 for ($i = 1; $i < $pcount; $i++) {
749 if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
750 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
752 // only build directly xmlrpc values when type is known and scalar
753 $innercode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n";
755 if ($encode_php_objects) {
756 $innercode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
758 $innercode .= "\$p$i = \$encoder->encode(\$p$i);\n";
761 $innercode .= "\$msg->addparam(\$p$i);\n";
762 $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
764 if ($client_copy_mode < 2) {
765 $plist[] = '$debug=0';
766 $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
768 $plist = implode(', ', $plist);
769 $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
771 $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
773 if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false))) {
774 $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $fault_response) . "')";
776 $respcode = var_export($fault_response, true);
781 if ($decode_php_objects) {
782 $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
784 $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value());";
787 $code = $code . $plist . ") {\n" . $innercode . "\n}\n";
789 return array('source' => $code, 'docstring' => $mdesc);
793 * Given necessary info, generate php code that will rebuild a client object
794 * Take care that no full checking of input parameters is done to ensure that
795 * valid php code is emitted.
797 protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
799 $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
800 "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
802 // copy all client fields to the client that will be generated runtime
803 // (this provides for future expansion or subclassing of client obj)
804 if ($verbatim_client_copy) {
805 foreach ($client as $fld => $val) {
806 if ($fld != 'debug' && $fld != 'return_type') {
807 $val = var_export($val, true);
808 $code .= "\$client->$fld = $val;\n";
812 // only make sure that client always returns the correct data type
813 $code .= "\$client->return_type = '{$prefix}vals';\n";
814 //$code .= "\$client->setDebug(\$debug);\n";