Passed
Push — master ( 251b1a...cf6e60 )
by Gaetano
08:24
created

src/Wrapper.php (2 issues)

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