Move debugger to new api and add basic unit tests for it
[plcapi.git] / src / Wrapper.php
1 <?php
2 /**
3  * @author Gaetano Giunta
4  * @copyright (C) 2006-2015 G. Giunta
5  * @license code licensed under the BSD License: see file license.txt
6  */
7
8 namespace PhpXmlRpc;
9
10 /**
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.
14  *
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)
19  */
20 class Wrapper
21 {
22     /**
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.
28      *
29      * @param string $phptype
30      *
31      * @return string
32      */
33     public function php_2_xmlrpc_type($phptype)
34     {
35         switch (strtolower($phptype)) {
36             case 'string':
37                 return Value::$xmlrpcString;
38             case 'integer':
39             case Value::$xmlrpcInt: // 'int'
40             case Value::$xmlrpcI4:
41                 return Value::$xmlrpcInt;
42             case 'double':
43                 return Value::$xmlrpcDouble;
44             case 'boolean':
45                 return Value::$xmlrpcBoolean;
46             case 'array':
47                 return Value::$xmlrpcArray;
48             case 'object':
49                 return Value::$xmlrpcStruct;
50             case Value::$xmlrpcBase64:
51             case Value::$xmlrpcStruct:
52                 return strtolower($phptype);
53             case 'resource':
54                 return '';
55             default:
56                 if (class_exists($phptype)) {
57                     return Value::$xmlrpcStruct;
58                 } else {
59                     // unknown: might be any 'extended' xmlrpc type
60                     return Value::$xmlrpcValue;
61                 }
62         }
63     }
64
65     /**
66      * Given a string defining a phpxmlrpc type return corresponding php type.
67      *
68      * @param string $xmlrpctype
69      *
70      * @return string
71      */
72     public function xmlrpc_2_php_type($xmlrpctype)
73     {
74         switch (strtolower($xmlrpctype)) {
75             case 'base64':
76             case 'datetime.iso8601':
77             case 'string':
78                 return Value::$xmlrpcString;
79             case 'int':
80             case 'i4':
81                 return 'integer';
82             case 'struct':
83             case 'array':
84                 return 'array';
85             case 'double':
86                 return 'float';
87             case 'undefined':
88                 return 'mixed';
89             case 'boolean':
90             case 'null':
91             default:
92                 // unknown: might be any xmlrpc type
93                 return strtolower($xmlrpctype);
94         }
95     }
96
97     /**
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).
101      *
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)
108      *
109      * Known limitations:
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?)
121      *
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.
125      *
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
133      *
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
136      *
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?
145      */
146     public function wrap_php_function($funcname, $newfuncname = '', $extra_options = array())
147     {
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'] ? '@' : '';
154
155         $exists = false;
156         if (is_string($funcname) && strpos($funcname, '::') !== false) {
157             $funcname = explode('::', $funcname);
158         }
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');
162
163                 return false;
164             }
165             if (is_string($funcname[0])) {
166                 $plainfuncname = implode('::', $funcname);
167             } elseif (is_object($funcname[0])) {
168                 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
169             }
170             $exists = method_exists($funcname[0], $funcname[1]);
171         } else {
172             $plainfuncname = $funcname;
173             $exists = function_exists($funcname);
174         }
175
176         if (!$exists) {
177             error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname);
178
179             return false;
180         } else {
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);
186                     } else {
187                         $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1];
188                     }
189                 } else {
190                     $xmlrpcfuncname = "{$prefix}_$funcname";
191                 }
192             } else {
193                 $xmlrpcfuncname = $newfuncname;
194             }
195             while ($buildit && function_exists($xmlrpcfuncname)) {
196                 $xmlrpcfuncname .= 'x';
197             }
198
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);
204
205                     return false;
206                 }
207                 if ($func->isProtected()) {
208                     error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname);
209
210                     return false;
211                 }
212                 if ($func->isConstructor()) {
213                     error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname);
214
215                     return false;
216                 }
217                 if ($func->isDestructor()) {
218                     error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname);
219
220                     return false;
221                 }
222                 if ($func->isAbstract()) {
223                     error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname);
224
225                     return false;
226                 }
227                 /// @todo add more checks for static vs. nonstatic?
228             } else {
229                 $func = new \ReflectionFunction($funcname);
230             }
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);
235
236                 return false;
237             }
238
239             // retrieve parameter names, types and description from javadoc comments
240
241             // function description
242             $desc = '';
243             // type of return val: by default 'any'
244             $returns = Value::$xmlrpcValue;
245             // desc of return val
246             $returnsDocs = '';
247             // type + name of function parameters
248             $paramDocs = array();
249
250             $docs = $func->getDocComment();
251             if ($docs != '') {
252                 $docs = explode("\n", $docs);
253                 $i = 0;
254                 foreach ($docs as $doc) {
255                     $doc = trim($doc, " \r\t/*");
256                     if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
257                         if ($desc) {
258                             $desc .= "\n";
259                         }
260                         $desc .= $doc;
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';
267                             } else {
268                                 $paramDocs[$i]['type'] = $matches[1];
269                             }
270                             $paramDocs[$i]['name'] = trim($matches[2]);
271                             $paramDocs[$i]['doc'] = $matches[3];
272                         }
273                         $i++;
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];
281                             }
282                         }
283                     }
284                 }
285             }
286
287             // execute introspection of actual function prototype
288             $params = array();
289             $i = 0;
290             foreach ($func->getParameters() as $paramobj) {
291                 $params[$i] = array();
292                 $params[$i]['name'] = '$' . $paramobj->getName();
293                 $params[$i]['isoptional'] = $paramobj->isOptional();
294                 $i++;
295             }
296
297             // start  building of PHP code to be eval'd
298
299             $innercode = "\$encoder = new {$namespace}Encoder();\n";
300             $i = 0;
301             $parsvariations = array();
302             $pars = 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';
308                 }
309
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;
314                 }
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";
318                 } else {
319                     $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n";
320                 }
321
322                 $pars[] = "\$p$i";
323                 $i++;
324                 if ($param['isoptional']) {
325                     $innercode .= "}\n";
326                 }
327                 if ($i == $pnum) {
328                     // last allowed parameters combination
329                     $parsvariations[] = $pars;
330                 }
331             }
332
333             $sigs = array();
334             $psigs = array();
335             if (count($parsvariations) == 0) {
336                 // only known good synopsis = no parameters
337                 $parsvariations[] = array();
338                 $minpars = 0;
339             } else {
340                 $minpars = count($parsvariations[0]);
341             }
342
343             if ($minpars) {
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;
348             } else {
349                 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
350             }
351
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];
359             } else {
360                 $realfuncname = $plainfuncname;
361             }
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']);
370                     } else {
371                         $sig[] = Value::$xmlrpcValue;
372                     }
373                     $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
374                 }
375                 $sigs[] = $sig;
376                 $psigs[] = $psig;
377             }
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'));";
384             } else {
385                 if ($encode_php_objects) {
386                     $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
387                 } else {
388                     $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
389                 }
390             }
391             // shall we exclude functions returning by ref?
392             // if($func->returnsReference())
393             //     return false;
394             $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
395             //print_r($code);
396             if ($buildit) {
397                 $allOK = 0;
398                 eval($code . '$allOK=1;');
399                 // alternative
400                 //$xmlrpcfuncname = create_function('$m', $innercode);
401
402                 if (!$allOK) {
403                     error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname);
404
405                     return false;
406                 }
407             }
408
409             /// @todo examine if $paramDocs matches $parsvariations and build array for
410             /// usage as method signature, plus put together a nice string for docs
411
412             $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
413
414             return $ret;
415         }
416     }
417
418     /**
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).
422      *
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
426      *
427      * @return array or false on failure
428      *
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
431      */
432     public function wrap_php_class($classname, $extra_options = array())
433     {
434         $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
435         $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
436
437         $result = array();
438         $mlist = get_class_methods($classname);
439         foreach ($mlist as $mname) {
440             if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
441                 // echo $mlist."\n";
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))))
446                     ) {
447                         $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extra_options);
448                         if ($methodwrap) {
449                             $result[$methodwrap['function']] = $methodwrap['function'];
450                         }
451                     }
452                 }
453             }
454         }
455
456         return $result;
457     }
458
459     /**
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.
464      *
465      * Known limitations:
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
473      *
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
476      * php function.
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.
481      *
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
494      *
495      * @return string the name of the generated php function (or false) - OR AN ARRAY...
496      */
497     public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $timeout = 0, $protocol = '', $newfuncname = '')
498     {
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();
504         } else {
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'] : '';
509         }
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;
513
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'];
524         } else {
525             $decode_fault = false;
526             $fault_response = '';
527         }
528         $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
529
530         $msgclass = $namespace . 'Request';
531         $valclass = $namespace . 'Value';
532         $decoderClass = $namespace . 'Encoder';
533
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);
540
541             return false;
542         } else {
543             $msig = $response->value();
544             if ($client->return_type != 'phpvals') {
545                 $decoder = new $decoderClass();
546                 $msig = $decoder->decode($msig);
547             }
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);
550
551                 return false;
552             } else {
553                 // pick a suitable name for the new function, avoiding collisions
554                 if ($newfuncname != '') {
555                     $xmlrpcfuncname = $newfuncname;
556                 } else {
557                     // take care to insure that methodname is translated to valid
558                     // php function name
559                     $xmlrpcfuncname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
560                             array('_', ''), $methodname);
561                 }
562                 while ($buildit && function_exists($xmlrpcfuncname)) {
563                     $xmlrpcfuncname .= 'x';
564                 }
565
566                 $msig = $msig[$signum];
567                 $mdesc = '';
568                 // if in 'offline' mode, get method description too.
569                 // in online mode, favour speed of operation
570                 if (!$buildit) {
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();
578                         }
579                     }
580                 }
581
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);
586                 //print_r($code);
587                 if ($buildit) {
588                     $allOK = 0;
589                     eval($results['source'] . '$allOK=1;');
590                     // alternative
591                     //$xmlrpcfuncname = create_function('$m', $innercode);
592                     if ($allOK) {
593                         return $xmlrpcfuncname;
594                     } else {
595                         error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname);
596
597                         return false;
598                     }
599                 } else {
600                     $results['function'] = $xmlrpcfuncname;
601
602                     return $results;
603                 }
604             }
605         }
606     }
607
608     /**
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.
612      *
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
615      *
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)
617      */
618     public function wrap_xmlrpc_server($client, $extra_options = array())
619     {
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\\';
631
632         $msgclass = $namespace . 'Request';
633         //$valclass = $prefix.'val';
634         $decoderClass = $namespace . 'Encoder';
635
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');
640
641             return false;
642         } else {
643             $mlist = $response->value();
644             if ($client->return_type != 'phpvals') {
645                 $decoder = new $decoderClass();
646                 $mlist = $decoder->decode($mlist);
647             }
648             if (!is_array($mlist) || !count($mlist)) {
649                 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
650
651                 return false;
652             } else {
653                 // pick a suitable name for the new function, avoiding collisions
654                 if ($newclassname != '') {
655                     $xmlrpcclassname = $newclassname;
656                 } else {
657                     $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
658                             array('_', ''), $client->server) . '_client';
659                 }
660                 while ($buildit && class_exists($xmlrpcclassname)) {
661                     $xmlrpcclassname .= 'x';
662                 }
663
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,
673                 );
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);
680                         if ($methodwrap) {
681                             if (!$buildit) {
682                                 $source .= $methodwrap['docstring'];
683                             }
684                             $source .= $methodwrap['source'] . "\n";
685                         } else {
686                             error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
687                         }
688                     }
689                 }
690                 $source .= "}\n";
691                 if ($buildit) {
692                     $allOK = 0;
693                     eval($source . '$allOK=1;');
694                     // alternative
695                     //$xmlrpcfuncname = create_function('$m', $innercode);
696                     if ($allOK) {
697                         return $xmlrpcclassname;
698                     } else {
699                         error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server);
700
701                         return false;
702                     }
703                 } else {
704                     return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
705                 }
706             }
707         }
708     }
709
710     /**
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...
716      */
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\\')
721     {
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";
727             $this_ = '';
728         } else {
729             // client copy mode 2 == no client copy in emitted code
730             $innercode = '';
731             $this_ = 'this->';
732         }
733         $innercode .= "\$msg = new {$namespace}Request('$methodname');\n";
734
735         if ($mdesc != '') {
736             // take care that PHP comment is not terminated unwillingly by method description
737             $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
738         } else {
739             $mdesc = "/**\nFunction $xmlrpcfuncname\n";
740         }
741
742         // param parsing
743         $innercode .= "\$encoder = new {$namespace}Encoder();\n";
744         $plist = array();
745         $pcount = count($msig);
746         for ($i = 1; $i < $pcount; $i++) {
747             $plist[] = "\$p$i";
748             $ptype = $msig[$i];
749             if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
750                 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
751             ) {
752                 // only build directly xmlrpc values when type is known and scalar
753                 $innercode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n";
754             } else {
755                 if ($encode_php_objects) {
756                     $innercode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
757                 } else {
758                     $innercode .= "\$p$i = \$encoder->encode(\$p$i);\n";
759                 }
760             }
761             $innercode .= "\$msg->addparam(\$p$i);\n";
762             $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
763         }
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";
767         }
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";
770
771         $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
772         if ($decode_fault) {
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) . "')";
775             } else {
776                 $respcode = var_export($fault_response, true);
777             }
778         } else {
779             $respcode = '$res';
780         }
781         if ($decode_php_objects) {
782             $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
783         } else {
784             $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value());";
785         }
786
787         $code = $code . $plist . ") {\n" . $innercode . "\n}\n";
788
789         return array('source' => $code, 'docstring' => $mdesc);
790     }
791
792     /**
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.
796      */
797     protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
798     {
799         $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
800             "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
801
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";
809                 }
810             }
811         }
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";
815         return $code;
816     }
817 }