Improve generation of methods signature by the Wrapper class
[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 vice-versa.
13  * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies.
14  *
15  * @todo use some better templating system for code generation?
16  * @todo implement method wrapping with preservation of php objs in calls
17  * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
18  */
19 class Wrapper
20 {
21     /**
22      * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
23      * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
24      * NB: for php 'resource' types returns empty string, since resources cannot be serialized;
25      * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
26      * for php arrays always return array, even though arrays sometimes serialize as json structs.
27      *
28      * @param string $phpType
29      *
30      * @return string
31      */
32     public function php_2_xmlrpc_type($phpType)
33     {
34         switch (strtolower($phpType)) {
35             case 'string':
36                 return Value::$xmlrpcString;
37             case 'integer':
38             case Value::$xmlrpcInt: // 'int'
39             case Value::$xmlrpcI4:
40                 return Value::$xmlrpcInt;
41             case 'double':
42                 return Value::$xmlrpcDouble;
43             case 'boolean':
44                 return Value::$xmlrpcBoolean;
45             case 'array':
46                 return Value::$xmlrpcArray;
47             case 'object':
48                 return Value::$xmlrpcStruct;
49             case Value::$xmlrpcBase64:
50             case Value::$xmlrpcStruct:
51                 return strtolower($phpType);
52             case 'resource':
53                 return '';
54             default:
55                 if (class_exists($phpType)) {
56                     return Value::$xmlrpcStruct;
57                 } else {
58                     // unknown: might be any 'extended' xmlrpc type
59                     return Value::$xmlrpcValue;
60                 }
61         }
62     }
63
64     /**
65      * Given a string defining a phpxmlrpc type return corresponding php type.
66      *
67      * @param string $xmlrpcType
68      *
69      * @return string
70      */
71     public function xmlrpc_2_php_type($xmlrpcType)
72     {
73         switch (strtolower($xmlrpcType)) {
74             case 'base64':
75             case 'datetime.iso8601':
76             case 'string':
77                 return Value::$xmlrpcString;
78             case 'int':
79             case 'i4':
80                 return 'integer';
81             case 'struct':
82             case 'array':
83                 return 'array';
84             case 'double':
85                 return 'float';
86             case 'undefined':
87                 return 'mixed';
88             case 'boolean':
89             case 'null':
90             default:
91                 // unknown: might be any xmlrpc type
92                 return strtolower($xmlrpcType);
93         }
94     }
95
96     /**
97      * Given a user-defined PHP function, create a PHP 'wrapper' function that can
98      * be exposed as xmlrpc method from an xmlrpc server object and called from remote
99      * clients (as well as its corresponding signature info).
100      *
101      * Since php is a typeless language, to infer types of input and output parameters,
102      * it relies on parsing the javadoc-style comment block associated with the given
103      * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
104      * in the @param tag is also allowed, if you need the php function to receive/send
105      * data in that particular format (note that base64 encoding/decoding is transparently
106      * carried out by the lib, while datetime vals are passed around as strings)
107      *
108      * Known limitations:
109      * - only works for user-defined functions, not for PHP internal functions
110      *   (reflection does not support retrieving number/type of params for those)
111      * - functions returning php objects will generate special xmlrpc responses:
112      *   when the xmlrpc decoding of those responses is carried out by this same lib, using
113      *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
114      *   In short: php objects can be serialized, too (except for their resource members),
115      *   using this function.
116      *   Other libs might choke on the very same xml that will be generated in this case
117      *   (i.e. it has a nonstandard attribute on struct element tags)
118      * - usage of javadoc @param tags using param names in a different order from the
119      *   function prototype is not considered valid (to be fixed?)
120      *
121      * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
122      * php functions (ie. functions not expecting a single Request obj as parameter)
123      * is by making use of the functions_parameters_type class member.
124      *
125      * @param string|array $callable the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
126      * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
127      * @param array $extraOptions (optional) array of options for conversion. valid values include:
128      *                            bool return_source when true, php code w. function definition will be returned, not evaluated
129      *                            bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
130      *                            bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
131      *                            bool suppress_warnings  remove from produced xml any runtime warnings due to the php function being invoked
132      *
133      * @return array|false false on error, or an array containing the name of the new php function,
134      *                     its signature and docs, to be used in the server dispatch map
135      *
136      * @todo decide how to deal with params passed by ref: bomb out or allow?
137      * @todo finish using phpdoc info to build method sig if all params are named but out of order
138      * @todo add a check for params of 'resource' type
139      * @todo add some trigger_errors / error_log when returning false?
140      * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
141      * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
142      * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster
143      * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
144      */
145     public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array())
146     {
147         $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
148
149         if (is_string($callable) && strpos($callable, '::') !== false) {
150             $callable = explode('::', $callable);
151         }
152         if (is_array($callable)) {
153             if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
154                 error_log('XML-RPC: syntax for function to be wrapped is wrong');
155                 return false;
156             }
157             if (is_string($callable[0])) {
158                 $plainFuncName = implode('::', $callable);
159             } elseif (is_object($callable[0])) {
160                 $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
161             }
162             $exists = method_exists($callable[0], $callable[1]);
163         } else if ($callable instanceof \Closure) {
164             $plainFuncName = 'Closure';
165             $exists = true;
166         }
167         else {
168             $plainFuncName = $callable;
169             $exists = function_exists($callable);
170         }
171
172         if (!$exists) {
173             error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName);
174             return false;
175         }
176
177         $funcDesc = $this->introspectFunction($callable, $plainFuncName);
178         if (!$funcDesc) {
179             return false;
180         }
181
182         $funcSigs = $this->buildMethodSignatures($funcDesc);
183
184         if ($buildIt) {
185             /*$allOK = 0;
186             eval($code . '$allOK=1;');
187             // alternative
188             //$xmlrpcFuncName = create_function('$m', $innerCode);
189
190             if (!$allOK) {
191                 error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap php function ' . $plainFuncName);
192
193                 return false;
194             }*/
195             $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null);
196             $code = '';
197         } else {
198             $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
199             $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
200             // replace the original callable to be set in the results
201             $callable = $newFuncName;
202         }
203
204         /// @todo examine if $paramDocs matches $parsVariations and build array for
205         /// usage as method signature, plus put together a nice string for docs
206
207         $ret = array(
208             'function' => $callable,
209             'signature' => $funcSigs['sigs'],
210             'docstring' => $funcDesc['desc'],
211             'signature_docs' => $funcSigs['sigsDocs'],
212             'source' => $code
213         );
214
215         return $ret;
216     }
217
218     /**
219      * Introspect a php callable and its phpdoc block and extract information about its signature
220      *
221      * @param callable $callable
222      * @param string $plainFuncName
223      * @return array|false
224      */
225     protected function introspectFunction($callable, $plainFuncName)
226     {
227         // start to introspect PHP code
228         if (is_array($callable)) {
229             $func = new \ReflectionMethod($callable[0], $callable[1]);
230             if ($func->isPrivate()) {
231                 error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName);
232
233                 return false;
234             }
235             if ($func->isProtected()) {
236                 error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName);
237
238                 return false;
239             }
240             if ($func->isConstructor()) {
241                 error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName);
242
243                 return false;
244             }
245             if ($func->isDestructor()) {
246                 error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName);
247
248                 return false;
249             }
250             if ($func->isAbstract()) {
251                 error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName);
252
253                 return false;
254             }
255             /// @todo add more checks for static vs. nonstatic?
256         } else {
257             $func = new \ReflectionFunction($callable);
258         }
259         if ($func->isInternal()) {
260             // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
261             // instead of getparameters to fully reflect internal php functions ?
262             error_log('XML-RPC: function to be wrapped is internal: ' . $plainFuncName);
263
264             return false;
265         }
266
267         // retrieve parameter names, types and description from javadoc comments
268
269         // function description
270         $desc = '';
271         // type of return val: by default 'any'
272         $returns = Value::$xmlrpcValue;
273         // desc of return val
274         $returnsDocs = '';
275         // type + name of function parameters
276         $paramDocs = array();
277
278         $docs = $func->getDocComment();
279         if ($docs != '') {
280             $docs = explode("\n", $docs);
281             $i = 0;
282             foreach ($docs as $doc) {
283                 $doc = trim($doc, " \r\t/*");
284                 if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
285                     if ($desc) {
286                         $desc .= "\n";
287                     }
288                     $desc .= $doc;
289                 } elseif (strpos($doc, '@param') === 0) {
290                     // syntax: @param type [$name] desc
291                     if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) {
292                         if ($matches[2] == '' && substr($matches[3], 0, 1) == '$') {
293                             // syntax: @param type $name
294                             $name = strtolower(trim($matches[3]));
295                             $paramDocs[$name]['name'] = trim($matches[3]);
296                             $paramDocs[$name]['doc'] = '';
297                         } else {
298                             $name = strtolower(trim($matches[2]));
299                             $paramDocs[$name]['name'] = trim($matches[2]);
300                             $paramDocs[$name]['doc'] = $matches[3];
301                         }
302
303                         $paramDocs[$name]['type'] = $matches[1];
304                     }
305                     $i++;
306                 } elseif (strpos($doc, '@return') === 0) {
307                     // syntax: @return type [desc]
308                     if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
309                         $returns = $matches[1];
310                         if (isset($matches[2])) {
311                             $returnsDocs = trim($matches[2]);
312                         }
313                     }
314                 }
315             }
316         }
317
318         // execute introspection of actual function prototype
319         $params = array();
320         $i = 0;
321         foreach ($func->getParameters() as $paramObj) {
322             $params[$i] = array();
323             $params[$i]['name'] = '$' . $paramObj->getName();
324             $params[$i]['isoptional'] = $paramObj->isOptional();
325             $i++;
326         }
327
328         return array(
329             'desc' => $desc,
330             'docs' => $docs,
331             'params' => $params,
332             'paramDocs' => $paramDocs,
333             'returns' => $returns,
334             'returnsDocs' =>$returnsDocs,
335         );
336     }
337
338     /**
339      * Given the method description given by introspection, create method signature data
340      *
341      * @todo support better docs with multiple types separated by pipes by creating multiple signatures
342      *
343      * @param array $funcDesc as generated by self::introspectFunction()
344      *
345      * @return array
346      */
347     protected function buildMethodSignatures($funcDesc)
348     {
349         $i = 0;
350         $parsVariations = array();
351         $pars = array();
352         $pNum = count($funcDesc['params']);
353         foreach ($funcDesc['params'] as $param) {
354             /* // match by name real param and documented params
355             $name = strtolower($param['name']);
356             if (!isset($funcDesc['paramDocs'][$name])) {
357                 $funcDesc['paramDocs'][$name] = array();
358             }
359             if (!isset($funcDesc['paramDocs'][$name]['type'])) {
360                 $funcDesc['paramDocs'][$name]['type'] = 'mixed';
361             }*/
362
363             if ($param['isoptional']) {
364                 // this particular parameter is optional. save as valid previous list of parameters
365                 $parsVariations[] = $pars;
366             }
367
368             $pars[] = "\$p$i";
369             $i++;
370             if ($i == $pNum) {
371                 // last allowed parameters combination
372                 $parsVariations[] = $pars;
373             }
374         }
375
376         if (count($parsVariations) == 0) {
377             // only known good synopsis = no parameters
378             $parsVariations[] = array();
379         }
380
381         $sigs = array();
382         $sigsDocs = array();
383         foreach ($parsVariations as $pars) {
384             // build a signature
385             $sig = array($this->php_2_xmlrpc_type($funcDesc['returns']));
386             $pSig = array($funcDesc['returnsDocs']);
387             for ($i = 0; $i < count($pars); $i++) {
388                 $name = strtolower($funcDesc['params'][$i]['name']);
389                 if (isset($funcDesc['paramDocs'][$name]['type'])) {
390                     $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$name]['type']);
391                 } else {
392                     $sig[] = Value::$xmlrpcValue;
393                 }
394                 $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
395             }
396             $sigs[] = $sig;
397             $sigsDocs[] = $pSig;
398         }
399
400         return array(
401             'sigs' => $sigs,
402             'sigsDocs' => $sigsDocs
403         );
404     }
405
406     /**
407      * Creates a closure that will execute $callable
408      * @todo validate params
409      *
410      * @param $callable
411      * @param array $extraOptions
412      * @param string $plainFuncName
413      * @param string $funcDesc
414      * @return callable
415      */
416     protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
417     {
418         $function = function($req) use($callable, $extraOptions)
419         {
420             $nameSpace = '\\PhpXmlRpc\\';
421             $encoderClass = $nameSpace.'Encoder';
422             $responseClass = $nameSpace.'Response';
423
424             $encoder = new $encoderClass();
425             $options = array();
426             if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
427                 $options[] = 'decode_php_objs';
428             }
429             $params = $encoder->decode($req, $options);
430
431             $result = call_user_func_array($callable, $params);
432
433             if (! is_a($result, $responseClass)) {
434                 $options = array();
435                 if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
436                     $options[] = 'encode_php_objs';
437                 }
438                 $result = new $responseClass($encoder->encode($result, $options));
439             }
440
441             return $result;
442         };
443
444         return $function;
445     }
446
447     /**
448      * Return a name for the new function
449      * @param $callable
450      * @param string $newFuncName
451      * @return string
452      */
453     protected function newFunctionName($callable, $newFuncName, $extraOptions)
454     {
455         // determine name of new php function
456
457         $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
458
459         if ($newFuncName == '') {
460             if (is_array($callable)) {
461                 if (is_string($callable[0])) {
462                     $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
463                 } else {
464                     $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
465                 }
466             } else {
467                 if ($callable instanceof \Closure) {
468                     $xmlrpcFuncName = "{$prefix}_closure";
469                 } else {
470                     $xmlrpcFuncName = "{$prefix}_$callable";
471                 }
472             }
473         } else {
474             $xmlrpcFuncName = $newFuncName;
475         }
476
477         while (function_exists($xmlrpcFuncName)) {
478             $xmlrpcFuncName .= 'x';
479         }
480
481         return $xmlrpcFuncName;
482     }
483
484     /**
485      * @param $callable
486      * @param string $newFuncName
487      * @param array $extraOptions
488      * @param string $plainFuncName
489      * @param array $funcDesc
490      * @return array
491      */
492     protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
493     {
494         $namespace = '\\PhpXmlRpc\\';
495         $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
496         $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
497         $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
498         $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
499
500         // build body of new function
501
502         $innerCode = "\$encoder = new {$namespace}Encoder();\n";
503         $i = 0;
504         $parsVariations = array();
505         $pars = array();
506         $pNum = count($funcDesc['params']);
507         foreach ($funcDesc['params'] as $param) {
508             if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] &&
509                 strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) {
510                 // param name from phpdoc info does not match param definition!
511                 $funcDesc['paramDocs'][$i]['type'] = 'mixed';
512             }
513
514             if ($param['isoptional']) {
515                 // this particular parameter is optional. save as valid previous list of parameters
516                 $innerCode .= "if (\$paramcount > $i) {\n";
517                 $parsVariations[] = $pars;
518             }
519             $innerCode .= "\$p$i = \$req->getParam($i);\n";
520             if ($decodePhpObjects) {
521                 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n";
522             } else {
523                 $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n";
524             }
525
526             $pars[] = "\$p$i";
527             $i++;
528             if ($param['isoptional']) {
529                 $innerCode .= "}\n";
530             }
531             if ($i == $pNum) {
532                 // last allowed parameters combination
533                 $parsVariations[] = $pars;
534             }
535         }
536
537         if (count($parsVariations) == 0) {
538             // only known good synopsis = no parameters
539             $parsVariations[] = array();
540             $minPars = 0;
541         } else {
542             $minPars = count($parsVariations[0]);
543         }
544
545         if ($minPars) {
546             // add to code the check for min params number
547             // NB: this check needs to be done BEFORE decoding param values
548             $innerCode = "\$paramcount = \$req->getNumParams();\n" .
549                 "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n" . $innerCode;
550         } else {
551             $innerCode = "\$paramcount = \$req->getNumParams();\n" . $innerCode;
552         }
553
554         $innerCode .= "\$np = false;\n";
555         // since there are no closures in php, if we are given an object instance,
556         // we store a pointer to it in a global var...
557         if (is_array($callable) && is_object($callable[0])) {
558             $GLOBALS['xmlrpcWPFObjHolder'][$newFuncName] = &$callable[0];
559             $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$newFuncName'];\n";
560             $realFuncName = '$obj->' . $callable[1];
561         } else {
562             $realFuncName = $plainFuncName;
563         }
564         foreach ($parsVariations as $pars) {
565             $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n";
566         }
567         $innerCode .= "\$np = true;\n";
568         $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "'); else {\n";
569         //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
570         $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
571         if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
572             $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
573         } else {
574             if ($encodePhpObjects) {
575                 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
576             } else {
577                 $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
578             }
579         }
580         // shall we exclude functions returning by ref?
581         // if($func->returnsReference())
582         //     return false;
583
584         $code = "function $newFuncName(\$req) {\n" . $innerCode . "}\n}";
585
586         return $code;
587     }
588
589     /**
590      * Given a user-defined PHP class or php object, map its methods onto a list of
591      * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
592      * object and called from remote clients (as well as their corresponding signature info).
593      *
594      * @param mixed $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
595      * @param array $extraOptions see the docs for wrap_php_method for basic options, plus
596      *                            - string method_type: 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance
597      *                            - string method_filter: a regexp used to filter methods to wrap based on their names
598      *                            - string $prefix/ used for the names of the xmlrpc methods created
599      *
600      * @return array or false on failure
601      *
602      * @todo get_class_methods will return both static and non-static methods.
603      *       we have to differentiate the action, depending on whether we received a class name or object
604      */
605     public function wrap_php_class($className, $extraOptions = array())
606     {
607         $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
608         $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
609         $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
610
611         $results = array();
612         $mList = get_class_methods($className);
613         foreach ($mList as $mName) {
614             if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
615                 $func = new \ReflectionMethod($className, $mName);
616                 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
617                     if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
618                         (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
619                     ) {
620                         $methodWrap = $this->wrap_php_function(array($className, $mName), '', $extraOptions);
621                         if ($methodWrap) {
622                             if (is_object($className)) {
623                                 $realClassName = get_class($className);
624                             }else {
625                                 $realClassName = $className;
626                             }
627                             $results[$prefix."$realClassName.$mName"] = $methodWrap;
628                         }
629                     }
630                 }
631             }
632         }
633
634         return $results;
635     }
636
637     /**
638      * Given an xmlrpc client and a method name, register a php wrapper function
639      * that will call it and return results using native php types for both
640      * params and results. The generated php function will return a Response
641      * object for failed xmlrpc calls.
642      *
643      * Known limitations:
644      * - server must support system.methodsignature for the wanted xmlrpc method
645      * - for methods that expose many signatures, only one can be picked (we
646      *   could in principle check if signatures differ only by number of params
647      *   and not by type, but it would be more complication than we can spare time)
648      * - nested xmlrpc params: the caller of the generated php function has to
649      *   encode on its own the params passed to the php function if these are structs
650      *   or arrays whose (sub)members include values of type datetime or base64
651      *
652      * Notes: the connection properties of the given client will be copied
653      * and reused for the connection used during the call to the generated
654      * php function.
655      * Calling the generated php function 'might' be slow: a new xmlrpc client
656      * is created on every invocation and an xmlrpc-connection opened+closed.
657      * An extra 'debug' param is appended to param list of xmlrpc method, useful
658      * for debugging purposes.
659      *
660      * @todo in case user wants back a function, return a closure instead of using eval
661      *
662      * @param Client $client an xmlrpc client set up correctly to communicate with target server
663      * @param string $methodName the xmlrpc method to be mapped to a php function
664      * @param array $extraOptions array of options that specify conversion details. valid options include
665      *                              integer       signum      the index of the method signature to use in mapping (if method exposes many sigs)
666      *                              integer       timeout     timeout (in secs) to be used when executing function/calling remote method
667      *                              string        protocol    'http' (default), 'http11' or 'https'
668      *                              string        new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name
669      *                              string        return_source if true return php code w. function definition instead fo function name
670      *                              bool          encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
671      *                              bool          decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
672      *                              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
673      *                              bool          debug        set it to 1 or 2 to see debug results of querying server for method synopsis
674      *
675      * @return string the name of the generated php function (or false) - OR AN ARRAY...
676      */
677     public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $timeout = 0, $protocol = '', $newFuncName = '')
678     {
679         // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
680         // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
681         if (!is_array($extraOptions)) {
682             $sigNum = $extraOptions;
683             $extraOptions = array();
684         } else {
685             $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
686             $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
687             $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
688             $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
689         }
690         //$encodePhpObjects = in_array('encode_php_objects', $extraOptions);
691         //$verbatimClientCopy = in_array('simple_client_copy', $extraOptions) ? 1 :
692         //      in_array('build_class_code', $extraOptions) ? 2 : 0;
693
694         $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
695         $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
696         // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...
697         $simpleClientCopy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
698         $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
699         $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
700         $namespace = '\\PhpXmlRpc\\';
701         if (isset($extraOptions['return_on_fault'])) {
702             $decodeFault = true;
703             $faultResponse = $extraOptions['return_on_fault'];
704         } else {
705             $decodeFault = false;
706             $faultResponse = '';
707         }
708         $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
709
710         $msgClass = $namespace . 'Request';
711         $valClass = $namespace . 'Value';
712         $decoderClass = $namespace . 'Encoder';
713
714         $msg = new $msgClass('system.methodSignature');
715         $msg->addparam(new $valClass($methodName));
716         $client->setDebug($debug);
717         $response = $client->send($msg, $timeout, $protocol);
718         if ($response->faultCode()) {
719             error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName);
720
721             return false;
722         } else {
723             $mSig = $response->value();
724             if ($client->return_type != 'phpvals') {
725                 $decoder = new $decoderClass();
726                 $mSig = $decoder->decode($mSig);
727             }
728             if (!is_array($mSig) || count($mSig) <= $sigNum) {
729                 error_log('XML-RPC: could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
730
731                 return false;
732             } else {
733                 // pick a suitable name for the new function, avoiding collisions
734                 if ($newFuncName != '') {
735                     $xmlrpcFuncName = $newFuncName;
736                 } else {
737                     // take care to insure that methodname is translated to valid
738                     // php function name
739                     $xmlrpcFuncName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
740                             array('_', ''), $methodName);
741                 }
742                 while ($buildIt && function_exists($xmlrpcFuncName)) {
743                     $xmlrpcFuncName .= 'x';
744                 }
745
746                 $mSig = $mSig[$sigNum];
747                 $mDesc = '';
748                 // if in 'offline' mode, get method description too.
749                 // in online mode, favour speed of operation
750                 if (!$buildIt) {
751                     $msg = new $msgClass('system.methodHelp');
752                     $msg->addparam(new $valClass($methodName));
753                     $response = $client->send($msg, $timeout, $protocol);
754                     if (!$response->faultCode()) {
755                         $mDesc = $response->value();
756                         if ($client->return_type != 'phpvals') {
757                             $mDesc = $mDesc->scalarval();
758                         }
759                     }
760                 }
761
762                 $results = $this->build_remote_method_wrapper_code($client, $methodName,
763                     $xmlrpcFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
764                     $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
765                     $faultResponse, $namespace);
766
767                 if ($buildIt) {
768                     $allOK = 0;
769                     eval($results['source'] . '$allOK=1;');
770                     // alternative
771                     //$xmlrpcFuncName = create_function('$m', $innerCode);
772                     if ($allOK) {
773                         return $xmlrpcFuncName;
774                     } else {
775                         error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap remote method ' . $methodName);
776
777                         return false;
778                     }
779                 } else {
780                     $results['function'] = $xmlrpcFuncName;
781
782                     return $results;
783                 }
784             }
785         }
786     }
787
788     /**
789      * Similar to wrap_xmlrpc_method, but will generate a php class that wraps
790      * all xmlrpc methods exposed by the remote server as own methods.
791      * For more details see wrap_xmlrpc_method.
792      *
793      * NB: for a slimmer alternative, see the code in demo/client/proxy.php
794      *
795      * @param Client $client the client obj all set to query the desired server
796      * @param array $extraOptions list of options for wrapped code
797      *              - method_filter
798      *              - timeout
799      *              - protocol
800      *              - new_class_name
801      *              - encode_php_objs
802      *              - decode_php_objs
803      *              - simple_client_copy
804      *              - return_source
805      *              - prefix
806      *
807      * @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)
808      */
809     public function wrap_xmlrpc_server($client, $extraOptions = array())
810     {
811         $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
812         //$sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
813         $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
814         $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
815         $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
816         $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
817         $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
818         $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
819         $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
820         $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
821         $namespace = '\\PhpXmlRpc\\';
822
823         $msgClass = $namespace . 'Request';
824         //$valClass = $prefix.'val';
825         $decoderClass = $namespace . 'Encoder';
826
827         $msg = new $msgClass('system.listMethods');
828         $response = $client->send($msg, $timeout, $protocol);
829         if ($response->faultCode()) {
830             error_log('XML-RPC: could not retrieve method list from remote server');
831
832             return false;
833         } else {
834             $mList = $response->value();
835             if ($client->return_type != 'phpvals') {
836                 $decoder = new $decoderClass();
837                 $mList = $decoder->decode($mList);
838             }
839             if (!is_array($mList) || !count($mList)) {
840                 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
841
842                 return false;
843             } else {
844                 // pick a suitable name for the new function, avoiding collisions
845                 if ($newClassName != '') {
846                     $xmlrpcClassName = $newClassName;
847                 } else {
848                     $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
849                             array('_', ''), $client->server) . '_client';
850                 }
851                 while ($buildIt && class_exists($xmlrpcClassName)) {
852                     $xmlrpcClassName .= 'x';
853                 }
854
855                 /// @todo add function setdebug() to new class, to enable/disable debugging
856                 $source = "class $xmlrpcClassName\n{\nvar \$client;\n\n";
857                 $source .= "function __construct()\n{\n";
858                 $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace);
859                 $source .= "\$this->client = \$client;\n}\n\n";
860                 $opts = array('simple_client_copy' => 2, 'return_source' => true,
861                     'timeout' => $timeout, 'protocol' => $protocol,
862                     'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix,
863                     'decode_php_objs' => $decodePhpObjects,
864                 );
865                 /// @todo build phpdoc for class definition, too
866                 foreach ($mList as $mName) {
867                     if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
868                         // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
869                         $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
870                             array('_', ''), $mName);
871                         $methodWrap = $this->wrap_xmlrpc_method($client, $mName, $opts);
872                         if ($methodWrap) {
873                             if (!$buildIt) {
874                                 $source .= $methodWrap['docstring'];
875                             }
876                             $source .= $methodWrap['source'] . "\n";
877                         } else {
878                             error_log('XML-RPC: will not create class method to wrap remote method ' . $mName);
879                         }
880                     }
881                 }
882                 $source .= "}\n";
883                 if ($buildIt) {
884                     $allOK = 0;
885                     eval($source . '$allOK=1;');
886                     // alternative
887                     //$xmlrpcFuncName = create_function('$m', $innerCode);
888                     if ($allOK) {
889                         return $xmlrpcClassName;
890                     } else {
891                         error_log('XML-RPC: could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
892
893                         return false;
894                     }
895                 } else {
896                     return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
897                 }
898             }
899         }
900     }
901
902     /**
903      * Given the necessary info, build php code that creates a new function to
904      * invoke a remote xmlrpc method.
905      * Take care that no full checking of input parameters is done to ensure that
906      * valid php code is emitted.
907      * Note: real spaghetti code follows...
908      */
909     public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName,
910                                                         $mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc',
911                                                         $decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false,
912                                                         $faultResponse = '', $namespace = '\\PhpXmlRpc\\')
913     {
914         $code = "function $xmlrpcFuncName (";
915         if ($clientCopyMode < 2) {
916             // client copy mode 0 or 1 == partial / full client copy in emitted code
917             $innerCode = $this->build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace);
918             $innerCode .= "\$client->setDebug(\$debug);\n";
919             $this_ = '';
920         } else {
921             // client copy mode 2 == no client copy in emitted code
922             $innerCode = '';
923             $this_ = 'this->';
924         }
925         $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
926
927         if ($mDesc != '') {
928             // take care that PHP comment is not terminated unwillingly by method description
929             $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
930         } else {
931             $mDesc = "/**\nFunction $xmlrpcFuncName\n";
932         }
933
934         // param parsing
935         $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
936         $plist = array();
937         $pcount = count($mSig);
938         for ($i = 1; $i < $pcount; $i++) {
939             $plist[] = "\$p$i";
940             $ptype = $mSig[$i];
941             if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
942                 $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null'
943             ) {
944                 // only build directly xmlrpc values when type is known and scalar
945                 $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n";
946             } else {
947                 if ($encodePhpObjects) {
948                     $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
949                 } else {
950                     $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
951                 }
952             }
953             $innerCode .= "\$req->addparam(\$p$i);\n";
954             $mDesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
955         }
956         if ($clientCopyMode < 2) {
957             $plist[] = '$debug=0';
958             $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
959         }
960         $plist = implode(', ', $plist);
961         $mDesc .= '* @return ' . $this->xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
962
963         $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
964         if ($decodeFault) {
965             if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
966                 $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
967             } else {
968                 $respCode = var_export($faultResponse, true);
969             }
970         } else {
971             $respCode = '$res';
972         }
973         if ($decodePhpObjects) {
974             $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
975         } else {
976             $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
977         }
978
979         $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
980
981         return array('source' => $code, 'docstring' => $mDesc);
982     }
983
984     /**
985      * Given necessary info, generate php code that will rebuild a client object
986      * Take care that no full checking of input parameters is done to ensure that
987      * valid php code is emitted.
988      * @param Client $client
989      * @param bool $verbatimClientCopy
990      * @param string $prefix
991      * @param string $namespace
992      *
993      * @return string
994      */
995     protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
996     {
997         $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
998             "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
999
1000         // copy all client fields to the client that will be generated runtime
1001         // (this provides for future expansion or subclassing of client obj)
1002         if ($verbatimClientCopy) {
1003             foreach ($client as $fld => $val) {
1004                 if ($fld != 'debug' && $fld != 'return_type') {
1005                     $val = var_export($val, true);
1006                     $code .= "\$client->$fld = $val;\n";
1007                 }
1008             }
1009         }
1010         // only make sure that client always returns the correct data type
1011         $code .= "\$client->return_type = '{$prefix}vals';\n";
1012         //$code .= "\$client->setDebug(\$debug);\n";
1013         return $code;
1014     }
1015 }