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