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