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