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