Passed
Push — master ( 57812a...5787f8 )
by Gaetano
03:38
created

Wrapper::php2XmlrpcType()   D

Complexity

Conditions 19
Paths 19

Size

Total Lines 36
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 23.156

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 19
eloc 32
c 2
b 0
f 0
nc 19
nop 1
dl 0
loc 36
ccs 24
cts 31
cp 0.7742
crap 23.156
rs 4.5166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @author Gaetano Giunta
4
 * @copyright (C) 2006-2020 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
 */
21
class Wrapper
22
{
23
    /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode
24
    public static $objHolder = array();
25
26
    /**
27
     * Given a string defining a php type or phpxmlrpc type (loosely defined: strings
28
     * accepted come from javadoc blocks), return corresponding phpxmlrpc type.
29
     * Notes:
30
     * - for php 'resource' types returns empty string, since resources cannot be serialized;
31
     * - for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
32
     * - for php arrays always return array, even though arrays sometimes serialize as structs...
33
     * - for 'void' and 'null' returns 'undefined'
34
     *
35
     * @param string $phpType
36
     *
37
     * @return string
38
     *
39
     * @todo support notation `something[]` as 'array'
40
     */
41 488
    public function php2XmlrpcType($phpType)
42
    {
43 488
        switch (strtolower($phpType)) {
44 488
            case 'string':
45 488
                return Value::$xmlrpcString;
46 488
            case 'integer':
47 488
            case Value::$xmlrpcInt: // 'int'
48 488
            case Value::$xmlrpcI4:
49 488
            case Value::$xmlrpcI8:
50 488
                return Value::$xmlrpcInt;
51 488
            case Value::$xmlrpcDouble: // 'double'
52
                return Value::$xmlrpcDouble;
53 488
            case 'bool':
54 488
            case Value::$xmlrpcBoolean: // 'boolean'
55 488
            case 'false':
56 488
            case 'true':
57
                return Value::$xmlrpcBoolean;
58 488
            case Value::$xmlrpcArray: // 'array':
59 488
            case 'array[]';
60
                return Value::$xmlrpcArray;
61 488
            case 'object':
62 488
            case Value::$xmlrpcStruct: // 'struct'
63
                return Value::$xmlrpcStruct;
64 488
            case Value::$xmlrpcBase64:
65
                return Value::$xmlrpcBase64;
66 488
            case 'resource':
67
                return '';
68
            default:
69 488
                if (class_exists($phpType)) {
70 488
                    if (is_a($phpType, 'DateTimeInterface')) {
71
                        return Value::$xmlrpcDateTime;
72
                    }
73 488
                    return Value::$xmlrpcStruct;
74
                } else {
75
                    // unknown: might be any 'extended' xmlrpc type
76 488
                    return Value::$xmlrpcValue;
77
                }
78
        }
79
    }
80
81
    /**
82
     * Given a string defining a phpxmlrpc type return the corresponding php type.
83
     *
84
     * @param string $xmlrpcType
85
     *
86
     * @return string
87
     */
88 77
    public function xmlrpc2PhpType($xmlrpcType)
89
    {
90 77
        switch (strtolower($xmlrpcType)) {
91 77
            case 'base64':
92 77
            case 'datetime.iso8601':
93 77
            case 'string':
94 58
                return Value::$xmlrpcString;
95 77
            case 'int':
96 20
            case 'i4':
97 20
            case 'i8':
98 58
                return 'integer';
99 20
            case 'struct':
100 20
            case 'array':
101
                return 'array';
102 20
            case 'double':
103
                return 'float';
104 20
            case 'undefined':
105 20
                return 'mixed';
106
            case 'boolean':
107
            case 'null':
108
            default:
109
                // unknown: might be any xmlrpc type
110
                return strtolower($xmlrpcType);
111
        }
112
    }
113
114
    /**
115
     * Given a user-defined PHP function, create a PHP 'wrapper' function that can
116
     * be exposed as xmlrpc method from an xmlrpc server object and called from remote
117
     * clients (as well as its corresponding signature info).
118
     *
119
     * Since php is a typeless language, to infer types of input and output parameters,
120
     * it relies on parsing the javadoc-style comment block associated with the given
121
     * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
122
     * in the '@param' tag is also allowed, if you need the php function to receive/send
123
     * data in that particular format (note that base64 encoding/decoding is transparently
124
     * carried out by the lib, while datetime vals are passed around as strings)
125
     *
126
     * Known limitations:
127
     * - only works for user-defined functions, not for PHP internal functions
128
     *   (reflection does not support retrieving number/type of params for those)
129
     * - functions returning php objects will generate special structs in xmlrpc responses:
130
     *   when the xmlrpc decoding of those responses is carried out by this same lib, using
131
     *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
132
     *   In short: php objects can be serialized, too (except for their resource members),
133
     *   using this function.
134
     *   Other libs might choke on the very same xml that will be generated in this case
135
     *   (i.e. it has a nonstandard attribute on struct element tags)
136
     *
137
     * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
138
     * php functions (ie. functions not expecting a single Request obj as parameter)
139
     * is by making use of the functions_parameters_type class member.
140
     *
141
     * @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
142
     * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true
143
     * @param array $extraOptions (optional) array of options for conversion. valid values include:
144
     *                            - bool return_source     when true, php code w. function definition will be returned, instead of a closure
145
     *                            - bool encode_php_objs   let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
146
     *                            - bool decode_php_objs   --- WARNING !!! possible security hazard. only use it with trusted servers ---
147
     *                            - bool suppress_warnings remove from produced xml any warnings generated at runtime by the php function being invoked
148
     *
149
     * @return array|false false on error, or an array containing the name of the new php function,
150
     *                     its signature and docs, to be used in the server dispatch map
151
     *
152
     * @todo decide how to deal with params passed by ref in function definition: bomb out or allow?
153
     * @todo finish using phpdoc info to build method sig if all params are named but out of order
154
     * @todo add a check for params of 'resource' type
155
     * @todo add some trigger_errors / error_log when returning false?
156
     * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value...
157
     * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
158
     * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance?
159
     * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway
160
     */
161 488
    public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
162
    {
163 488
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
164
165 488
        if (is_string($callable) && strpos($callable, '::') !== false) {
166 488
            $callable = explode('::', $callable);
167
        }
168 488
        if (is_array($callable)) {
169 488
            if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
170
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
171
                return false;
172
            }
173 488
            if (is_string($callable[0])) {
174 488
                $plainFuncName = implode('::', $callable);
175 488
            } elseif (is_object($callable[0])) {
176 488
                $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
177
            }
178 488
            $exists = method_exists($callable[0], $callable[1]);
179 488
        } else if ($callable instanceof \Closure) {
180
            // we do not support creating code which wraps closures, as php does not allow to serialize them
181 488
            if (!$buildIt) {
182
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code');
183
                return false;
184
            }
185
186 488
            $plainFuncName = 'Closure';
187 488
            $exists = true;
188
        } else {
189 488
            $plainFuncName = $callable;
190 488
            $exists = function_exists($callable);
0 ignored issues
show
Bug introduced by
$callable of type callable is incompatible with the type string expected by parameter $function_name of function_exists(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

190
            $exists = function_exists(/** @scrutinizer ignore-type */ $callable);
Loading history...
191
        }
192
193 488
        if (!$exists) {
194
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $plainFuncName does not seem to be defined for all execution paths leading up to this point.
Loading history...
195
            return false;
196
        }
197
198 488
        $funcDesc = $this->introspectFunction($callable, $plainFuncName);
199 488
        if (!$funcDesc) {
200
            return false;
201
        }
202
203 488
        $funcSigs = $this->buildMethodSignatures($funcDesc);
204
205 488
        if ($buildIt) {
206 488
            $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
207
        } else {
208 488
            $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
209 488
            $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
210
        }
211
212
        $ret = array(
213 488
            'function' => $callable,
214 488
            'signature' => $funcSigs['sigs'],
215 488
            'docstring' => $funcDesc['desc'],
216 488
            'signature_docs' => $funcSigs['sigsDocs'],
217
        );
218 488
        if (!$buildIt) {
219 488
            $ret['function'] = $newFuncName;
220 488
            $ret['source'] = $code;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $code does not seem to be defined for all execution paths leading up to this point.
Loading history...
221
        }
222 488
        return $ret;
223
    }
224
225
    /**
226
     * Introspect a php callable and its phpdoc block and extract information about its signature
227
     *
228
     * @param callable $callable
229
     * @param string $plainFuncName
230
     * @return array|false
231
     */
232 488
    protected function introspectFunction($callable, $plainFuncName)
233
    {
234
        // start to introspect PHP code
235 488
        if (is_array($callable)) {
236 488
            $func = new \ReflectionMethod($callable[0], $callable[1]);
237 488
            if ($func->isPrivate()) {
238
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName);
239
                return false;
240
            }
241 488
            if ($func->isProtected()) {
242
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
243
                return false;
244
            }
245 488
            if ($func->isConstructor()) {
246
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
247
                return false;
248
            }
249 488
            if ($func->isDestructor()) {
250
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
251
                return false;
252
            }
253 488
            if ($func->isAbstract()) {
254
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName);
255
                return false;
256
            }
257
            /// @todo add more checks for static vs. nonstatic?
258
        } else {
259 488
            $func = new \ReflectionFunction($callable);
260
        }
261 488
        if ($func->isInternal()) {
262
            // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
263
            // instead of getparameters to fully reflect internal php functions ?
264
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName);
265
            return false;
266
        }
267
268
        // retrieve parameter names, types and description from javadoc comments
269
270
        // function description
271 488
        $desc = '';
272
        // type of return val: by default 'any'
273 488
        $returns = Value::$xmlrpcValue;
274
        // desc of return val
275 488
        $returnsDocs = '';
276
        // type + name of function parameters
277 488
        $paramDocs = array();
278
279 488
        $docs = $func->getDocComment();
280 488
        if ($docs != '') {
281 488
            $docs = explode("\n", $docs);
282 488
            $i = 0;
283 488
            foreach ($docs as $doc) {
284 488
                $doc = trim($doc, " \r\t/*");
285 488
                if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
286 488
                    if ($desc) {
287 488
                        $desc .= "\n";
288
                    }
289 488
                    $desc .= $doc;
290 488
                } elseif (strpos($doc, '@param') === 0) {
291
                    // syntax: @param type $name [desc]
292 488
                    if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) {
293 488
                        $name = strtolower(trim($matches[2]));
294
                        //$paramDocs[$name]['name'] = trim($matches[2]);
295 488
                        $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
296 488
                        $paramDocs[$name]['type'] = $matches[1];
297
                    }
298 488
                    $i++;
299 488
                } elseif (strpos($doc, '@return') === 0) {
300
                    // syntax: @return type [desc]
301 488
                    if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
302 488
                        $returns = $matches[1];
303 488
                        if (isset($matches[2])) {
304 488
                            $returnsDocs = trim($matches[2]);
305
                        }
306
                    }
307
                }
308
            }
309
        }
310
311
        // execute introspection of actual function prototype
312 488
        $params = array();
313 488
        $i = 0;
314 488
        foreach ($func->getParameters() as $paramObj) {
315 488
            $params[$i] = array();
316 488
            $params[$i]['name'] = '$' . $paramObj->getName();
317 488
            $params[$i]['isoptional'] = $paramObj->isOptional();
318 488
            $i++;
319
        }
320
321
        return array(
322 488
            'desc' => $desc,
323 488
            'docs' => $docs,
324 488
            'params' => $params, // array, positionally indexed
325 488
            'paramDocs' => $paramDocs, // array, indexed by name
326 488
            'returns' => $returns,
327 488
            'returnsDocs' =>$returnsDocs,
328
        );
329
    }
330
331
    /**
332
     * Given the method description given by introspection, create method signature data
333
     *
334
     * @todo support better docs with multiple types separated by pipes by creating multiple signatures
335
     *       (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences)
336
     *
337
     * @param array $funcDesc as generated by self::introspectFunction()
338
     *
339
     * @return array
340
     */
341 488
    protected function buildMethodSignatures($funcDesc)
342
    {
343 488
        $i = 0;
344 488
        $parsVariations = array();
345 488
        $pars = array();
346 488
        $pNum = count($funcDesc['params']);
347 488
        foreach ($funcDesc['params'] as $param) {
348
            /* // match by name real param and documented params
349
            $name = strtolower($param['name']);
350
            if (!isset($funcDesc['paramDocs'][$name])) {
351
                $funcDesc['paramDocs'][$name] = array();
352
            }
353
            if (!isset($funcDesc['paramDocs'][$name]['type'])) {
354
                $funcDesc['paramDocs'][$name]['type'] = 'mixed';
355
            }*/
356
357 488
            if ($param['isoptional']) {
358
                // this particular parameter is optional. save as valid previous list of parameters
359
                $parsVariations[] = $pars;
360
            }
361
362 488
            $pars[] = "\$p$i";
363 488
            $i++;
364 488
            if ($i == $pNum) {
365
                // last allowed parameters combination
366 488
                $parsVariations[] = $pars;
367
            }
368
        }
369
370 488
        if (count($parsVariations) == 0) {
371
            // only known good synopsis = no parameters
372 488
            $parsVariations[] = array();
373
        }
374
375 488
        $sigs = array();
376 488
        $sigsDocs = array();
377 488
        foreach ($parsVariations as $pars) {
378
            // build a signature
379 488
            $sig = array($this->php2XmlrpcType($funcDesc['returns']));
380 488
            $pSig = array($funcDesc['returnsDocs']);
381 488
            for ($i = 0; $i < count($pars); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
382 488
                $name = strtolower($funcDesc['params'][$i]['name']);
383 488
                if (isset($funcDesc['paramDocs'][$name]['type'])) {
384 488
                    $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
385
                } else {
386 488
                    $sig[] = Value::$xmlrpcValue;
387
                }
388 488
                $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
389
            }
390 488
            $sigs[] = $sig;
391 488
            $sigsDocs[] = $pSig;
392
        }
393
394
        return array(
395 488
            'sigs' => $sigs,
396 488
            'sigsDocs' => $sigsDocs
397
        );
398
    }
399
400
    /**
401
     * Creates a closure that will execute $callable
402
     * @todo validate params? In theory all validation is left to the dispatch map...
403
     * @todo add support for $catchWarnings
404
     *
405
     * @param $callable
406
     * @param array $extraOptions
407
     * @param string $plainFuncName
408
     * @param array $funcDesc
409
     * @return \Closure
410
     */
411 488
    protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
412
    {
413
        /**
414
         * @param Request $req
415
         * @return mixed
416
         */
417
        $function = function($req) use($callable, $extraOptions, $funcDesc)
418
        {
419 79
            $nameSpace = '\\PhpXmlRpc\\';
420 79
            $encoderClass = $nameSpace.'Encoder';
421 79
            $responseClass = $nameSpace.'Response';
422 79
            $valueClass = $nameSpace.'Value';
423
424
            // validate number of parameters received
425
            // this should be optional really, as we assume the server does the validation
426 79
            $minPars = count($funcDesc['params']);
427 79
            $maxPars = $minPars;
428 79
            foreach ($funcDesc['params'] as $i => $param) {
429 79
                if ($param['isoptional']) {
430
                    // this particular parameter is optional. We assume later ones are as well
431
                    $minPars = $i;
432
                    break;
433
                }
434
            }
435 79
            $numPars = $req->getNumParams();
436 79
            if ($numPars < $minPars || $numPars > $maxPars) {
437
                return new $responseClass(0, 3, 'Incorrect parameters passed to method');
438
            }
439
440 79
            $encoder = new $encoderClass();
441 79
            $options = array();
442 79
            if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) {
443
                $options[] = 'decode_php_objs';
444
            }
445 79
            $params = $encoder->decode($req, $options);
446
447 79
            $result = call_user_func_array($callable, $params);
448
449 79
            if (! is_a($result, $responseClass)) {
450 79
                if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
451
                    $result = new $valueClass($result, $funcDesc['returns']);
452
                } else {
453 79
                    $options = array();
454 79
                    if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) {
455 1
                        $options[] = 'encode_php_objs';
456
                    }
457
458 79
                    $result = $encoder->encode($result, $options);
459
                }
460 79
                $result = new $responseClass($result);
461
            }
462
463 79
            return $result;
464 488
        };
465
466 488
        return $function;
467
    }
468
469
    /**
470
     * Return a name for a new function, based on $callable, insuring its uniqueness
471
     * @param mixed $callable a php callable, or the name of an xmlrpc method
472
     * @param string $newFuncName when not empty, it is used instead of the calculated version
473
     * @return string
474
     */
475 564
    protected function newFunctionName($callable, $newFuncName, $extraOptions)
476
    {
477
        // determine name of new php function
478
479 564
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
480
481 564
        if ($newFuncName == '') {
482 545
            if (is_array($callable)) {
483 488
                if (is_string($callable[0])) {
484 488
                    $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable);
485
                } else {
486 488
                    $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1];
487
                }
488
            } else {
489 545
                if ($callable instanceof \Closure) {
490
                    $xmlrpcFuncName = "{$prefix}_closure";
491
                } else {
492 545
                    $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
493 545
                        array('_', ''), $callable);
494 545
                    $xmlrpcFuncName = "{$prefix}_$callable";
495
                }
496
            }
497
        } else {
498 20
            $xmlrpcFuncName = $newFuncName;
499
        }
500
501 564
        while (function_exists($xmlrpcFuncName)) {
502 543
            $xmlrpcFuncName .= 'x';
503
        }
504
505 564
        return $xmlrpcFuncName;
506
    }
507
508
    /**
509
     * @param $callable
510
     * @param string $newFuncName
511
     * @param array $extraOptions
512
     * @param string $plainFuncName
513
     * @param array $funcDesc
514
     * @return string
515
     *
516
     * @todo add a nice phpdoc block in the generated source
517
     */
518 488
    protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
519
    {
520 488
        $namespace = '\\PhpXmlRpc\\';
521
522 488
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
523 488
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
524 488
        $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : '';
525
526 488
        $i = 0;
527 488
        $parsVariations = array();
528 488
        $pars = array();
529 488
        $pNum = count($funcDesc['params']);
530 488
        foreach ($funcDesc['params'] as $param) {
531
532 488
            if ($param['isoptional']) {
533
                // this particular parameter is optional. save as valid previous list of parameters
534
                $parsVariations[] = $pars;
535
            }
536
537 488
            $pars[] = "\$p[$i]";
538 488
            $i++;
539 488
            if ($i == $pNum) {
540
                // last allowed parameters combination
541 488
                $parsVariations[] = $pars;
542
            }
543
        }
544
545 488
        if (count($parsVariations) == 0) {
546
            // only known good synopsis = no parameters
547
            $parsVariations[] = array();
548
            $minPars = 0;
549
            $maxPars = 0;
550
        } else {
551 488
            $minPars = count($parsVariations[0]);
552 488
            $maxPars = count($parsVariations[count($parsVariations)-1]);
553
        }
554
555
        // build body of new function
556
557 488
        $innerCode = "\$paramCount = \$req->getNumParams();\n";
558 488
        $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n";
559
560 488
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
561 488
        if ($decodePhpObjects) {
562
            $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n";
563
        } else {
564 488
            $innerCode .= "\$p = \$encoder->decode(\$req);\n";
565
        }
566
567
        // since we are building source code for later use, if we are given an object instance,
568
        // we go out of our way and store a pointer to it in a static class var var...
569 488
        if (is_array($callable) && is_object($callable[0])) {
570 488
            self::$objHolder[$newFuncName] = $callable[0];
571 488
            $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
572 488
            $realFuncName = '$obj->' . $callable[1];
573
        } else {
574 488
            $realFuncName = $plainFuncName;
575
        }
576 488
        foreach ($parsVariations as $i => $pars) {
577 488
            $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n";
578 488
            if ($i < (count($parsVariations) - 1))
579
                $innerCode .= "else\n";
580
        }
581 488
        $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n";
582 488
        if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) {
583
            $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));";
584
        } else {
585 488
            if ($encodePhpObjects) {
586
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n";
587
            } else {
588 488
                $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n";
589
            }
590
        }
591
        // shall we exclude functions returning by ref?
592
        // if($func->returnsReference())
593
        //     return false;
594
595 488
        $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}";
596
597 488
        return $code;
598
    }
599
600
    /**
601
     * Given a user-defined PHP class or php object, map its methods onto a list of
602
     * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
603
     * object and called from remote clients (as well as their corresponding signature info).
604
     *
605
     * @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
606
     * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
607
     *                            - 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
608
     *                            - string method_filter  a regexp used to filter methods to wrap based on their names
609
     *                            - string prefix         used for the names of the xmlrpc methods created
610
     *
611
     * @return array|false false on failure
612
     */
613 488
    public function wrapPhpClass($className, $extraOptions = array())
614
    {
615 488
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
616 488
        $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
617 488
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
618
619 488
        $results = array();
620 488
        $mList = get_class_methods($className);
621 488
        foreach ($mList as $mName) {
622 488
            if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
623 488
                $func = new \ReflectionMethod($className, $mName);
624 488
                if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
625 488
                    if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) ||
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($func->isStatic() && $m...& is_object($className), Probably Intended Meaning: $func->isStatic() && ($m... is_object($className))
Loading history...
626 488
                        (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className))))
627
                    ) {
628 488
                        $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
629 488
                        if ($methodWrap) {
630 488
                            if (is_object($className)) {
631 488
                                $realClassName = get_class($className);
632
                            }else {
633
                                $realClassName = $className;
634
                            }
635 488
                            $results[$prefix."$realClassName.$mName"] = $methodWrap;
636
                        }
637
                    }
638
                }
639
            }
640
        }
641
642 488
        return $results;
643
    }
644
645
    /**
646
     * Given an xmlrpc client and a method name, register a php wrapper function
647
     * that will call it and return results using native php types for both
648
     * params and results. The generated php function will return a Response
649
     * object for failed xmlrpc calls.
650
     *
651
     * Known limitations:
652
     * - server must support system.methodsignature for the wanted xmlrpc method
653
     * - for methods that expose many signatures, only one can be picked (we
654
     *   could in principle check if signatures differ only by number of params
655
     *   and not by type, but it would be more complication than we can spare time)
656
     * - nested xmlrpc params: the caller of the generated php function has to
657
     *   encode on its own the params passed to the php function if these are structs
658
     *   or arrays whose (sub)members include values of type datetime or base64
659
     *
660
     * Notes: the connection properties of the given client will be copied
661
     * and reused for the connection used during the call to the generated
662
     * php function.
663
     * Calling the generated php function 'might' be slow: a new xmlrpc client
664
     * is created on every invocation and an xmlrpc-connection opened+closed.
665
     * An extra 'debug' param is appended to param list of xmlrpc method, useful
666
     * for debugging purposes.
667
     *
668
     * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it'
669
     * @todo if we can not retrieve method signature, create a php function with varargs
670
     * @todo allow the created function to throw exceptions on method calls failures
671
     * @todo if caller did not specify a specific sig, shall we support all of them?
672
     *       It might be hard (hence slow) to match based on type and number of arguments...
673
     *
674
     * @param Client $client an xmlrpc client set up correctly to communicate with target server
675
     * @param string $methodName the xmlrpc method to be mapped to a php function
676
     * @param array $extraOptions array of options that specify conversion details. Valid options include
677
     *                            - integer signum              the index of the method signature to use in mapping (if method exposes many sigs)
678
     *                            - integer timeout             timeout (in secs) to be used when executing function/calling remote method
679
     *                            - string  protocol            'http' (default), 'http11' or 'https'
680
     *                            - string  new_function_name   the name of php function to create, when return_source is used. If unspecified, lib will pick an appropriate name
681
     *                            - string  return_source       if true return php code w. function definition instead of function itself (closure)
682
     *                            - bool    encode_php_objs     let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
683
     *                            - bool    decode_php_objs     --- WARNING !!! possible security hazard. only use it with trusted servers ---
684
     *                            - 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
685
     *                            - bool    debug               set it to 1 or 2 to see debug results of querying server for method synopsis
686
     *                            - 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)
687
     *
688
     * @return \closure|string[]|false false on failure, closure by default and array for return_source = true
689
     */
690 78
    public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
691
    {
692 78
        $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
693
694 78
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
695
696 78
        $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
697 78
        if (!$mSig) {
698
            return false;
699
        }
700
701 78
        if ($buildIt) {
702 1
            return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
703
        } else {
704
            // if in 'offline' mode, retrieve method description too.
705
            // in online mode, favour speed of operation
706 77
            $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions);
707
708 77
            $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions);
709
710 77
            $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc);
711
            /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName,
712
                $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy,
713
                $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault,
714
                $faultResponse, $namespace);*/
715
716 77
            $results['function'] = $newFuncName;
717
718 77
            return $results;
719
        }
720
721
    }
722
723
    /**
724
     * Retrieves an xmlrpc method signature from a server which supports system.methodSignature
725
     * @param Client $client
726
     * @param string $methodName
727
     * @param array $extraOptions
728
     * @return false|array
729
     */
730 78
    protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array())
731
    {
732 78
        $namespace = '\\PhpXmlRpc\\';
733 78
        $reqClass = $namespace . 'Request';
734 78
        $valClass = $namespace . 'Value';
735 78
        $decoderClass = $namespace . 'Encoder';
736
737 78
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
738 78
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
739 78
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
740 78
        $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0;
741
742 78
        $req = new $reqClass('system.methodSignature');
743 78
        $req->addparam(new $valClass($methodName));
744 78
        $client->setDebug($debug);
745 78
        $response = $client->send($req, $timeout, $protocol);
746 78
        if ($response->faultCode()) {
747
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName);
748
            return false;
749
        }
750
751 78
        $mSig = $response->value();
752 78
        if ($client->return_type != 'phpvals') {
753 77
            $decoder = new $decoderClass();
754 77
            $mSig = $decoder->decode($mSig);
755
        }
756
757 78
        if (!is_array($mSig) || count($mSig) <= $sigNum) {
758
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
759
            return false;
760
        }
761
762 78
        return $mSig[$sigNum];
763
    }
764
765
    /**
766
     * @param Client $client
767
     * @param string $methodName
768
     * @param array $extraOptions
769
     * @return string in case of any error, an empty string is returned, no warnings generated
770
     */
771 77
    protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array())
772
    {
773 77
        $namespace = '\\PhpXmlRpc\\';
774 77
        $reqClass = $namespace . 'Request';
775 77
        $valClass = $namespace . 'Value';
776
777 77
        $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0;
778 77
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
779 77
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
780
781 77
        $mDesc = '';
782
783 77
        $req = new $reqClass('system.methodHelp');
784 77
        $req->addparam(new $valClass($methodName));
785 77
        $client->setDebug($debug);
786 77
        $response = $client->send($req, $timeout, $protocol);
787 77
        if (!$response->faultCode()) {
788 77
            $mDesc = $response->value();
789 77
            if ($client->return_type != 'phpvals') {
790 77
                $mDesc = $mDesc->scalarval();
0 ignored issues
show
Bug introduced by
The method scalarval() does not exist on integer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

790
                /** @scrutinizer ignore-call */ 
791
                $mDesc = $mDesc->scalarval();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
791
            }
792
        }
793
794 77
        return $mDesc;
795
    }
796
797
    /**
798
     * @param Client $client
799
     * @param string $methodName
800
     * @param array $extraOptions
801
     * @param array $mSig
802
     * @return \Closure
803
     *
804
     * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case?
805
     */
806 1
    protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig)
807
    {
808
        // we clone the client, so that we can modify it a bit independently of the original
809 1
        $clientClone = clone $client;
810
        $function = function() use($clientClone, $methodName, $extraOptions, $mSig)
811
        {
812 1
            $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
813 1
            $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
814 1
            $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
815 1
            $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
816 1
            if (isset($extraOptions['return_on_fault'])) {
817
                $decodeFault = true;
818
                $faultResponse = $extraOptions['return_on_fault'];
819
            } else {
820 1
                $decodeFault = false;
821
            }
822
823 1
            $namespace = '\\PhpXmlRpc\\';
824 1
            $reqClass = $namespace . 'Request';
825 1
            $encoderClass = $namespace . 'Encoder';
826 1
            $valueClass = $namespace . 'Value';
827
828 1
            $encoder = new $encoderClass();
829 1
            $encodeOptions = array();
830 1
            if ($encodePhpObjects) {
831
                $encodeOptions[] = 'encode_php_objs';
832
            }
833 1
            $decodeOptions = array();
834 1
            if ($decodePhpObjects) {
835
                $decodeOptions[] = 'decode_php_objs';
836
            }
837
838
            /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not...
839
840
            // support one extra parameter: debug
841 1
            $maxArgs = count($mSig)-1; // 1st element is the return type
842 1
            $currentArgs = func_get_args();
843 1
            if (func_num_args() == ($maxArgs+1)) {
844 1
                $debug = array_pop($currentArgs);
845 1
                $clientClone->setDebug($debug);
846
            }
847
848 1
            $xmlrpcArgs = array();
849 1
            foreach($currentArgs as $i => $arg) {
850 1
                if ($i == $maxArgs) {
851
                    break;
852
                }
853 1
                $pType = $mSig[$i+1];
854 1
                if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
855
                    $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
856
                ) {
857
                    // by building directly xmlrpc values when type is known and scalar (instead of encode() calls),
858
                    // we make sure to honour the xmlrpc signature
859 1
                    $xmlrpcArgs[] = new $valueClass($arg, $pType);
860
                } else {
861
                    $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions);
862
                }
863
            }
864
865 1
            $req = new $reqClass($methodName, $xmlrpcArgs);
866
            // use this to get the maximum decoding flexibility
867 1
            $clientClone->return_type = 'xmlrpcvals';
868 1
            $resp = $clientClone->send($req, $timeout, $protocol);
869 1
            if ($resp->faultcode()) {
870
                if ($decodeFault) {
871
                    if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) ||
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $faultResponse does not seem to be defined for all execution paths leading up to this point.
Loading history...
872
                            (strpos($faultResponse, '%faultString%') !== false))) {
873
                        $faultResponse = str_replace(array('%faultCode%', '%faultString%'),
874
                            array($resp->faultCode(), $resp->faultString()), $faultResponse);
875
                    }
876
                    return $faultResponse;
877
                } else {
878
                    return $resp;
879
                }
880
            } else {
881 1
                return $encoder->decode($resp->value(), $decodeOptions);
882
            }
883 1
        };
884
885 1
        return $function;
886
    }
887
888
    /**
889
     * @param Client $client
890
     * @param string $methodName
891
     * @param array $extraOptions
892
     * @param string $newFuncName
893
     * @param array $mSig
894
     * @param string $mDesc
895
     * @return string[] keys: source, docstring
896
     */
897 77
    public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='')
898
    {
899 77
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
900 77
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
901 77
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
902 77
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
903 77
        $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0;
904 77
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
905 77
        if (isset($extraOptions['return_on_fault'])) {
906
            $decodeFault = true;
907
            $faultResponse = $extraOptions['return_on_fault'];
908
        } else {
909 77
            $decodeFault = false;
910 77
            $faultResponse = '';
911
        }
912
913 77
        $namespace = '\\PhpXmlRpc\\';
914
915 77
        $code = "function $newFuncName (";
916 77
        if ($clientCopyMode < 2) {
917
            // client copy mode 0 or 1 == full / partial client copy in emitted code
918 58
            $verbatimClientCopy = !$clientCopyMode;
919 58
            $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
920 58
            $innerCode .= "\$client->setDebug(\$debug);\n";
921 58
            $this_ = '';
922
        } else {
923
            // client copy mode 2 == no client copy in emitted code
924 20
            $innerCode = '';
925 20
            $this_ = 'this->';
926
        }
927 77
        $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
928
929 77
        if ($mDesc != '') {
930
            // take care that PHP comment is not terminated unwillingly by method description
931 77
            $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
932
        } else {
933
            $mDesc = "/**\nFunction $newFuncName\n";
934
        }
935
936
        // param parsing
937 77
        $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
938 77
        $plist = array();
939 77
        $pCount = count($mSig);
940 77
        for ($i = 1; $i < $pCount; $i++) {
941 58
            $plist[] = "\$p$i";
942 58
            $pType = $mSig[$i];
943 58
            if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
944 58
                $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
945
            ) {
946
                // only build directly xmlrpc values when type is known and scalar
947 58
                $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
948
            } else {
949
                if ($encodePhpObjects) {
950
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
951
                } else {
952
                    $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
953
                }
954
            }
955 58
            $innerCode .= "\$req->addparam(\$p$i);\n";
956 58
            $mDesc .= '* @param ' . $this->xmlrpc2PhpType($pType) . " \$p$i\n";
957
        }
958 77
        if ($clientCopyMode < 2) {
959 58
            $plist[] = '$debug=0';
960 58
            $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
961
        }
962 77
        $plist = implode(', ', $plist);
963 77
        $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
964
965 77
        $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
966 77
        if ($decodeFault) {
967
            if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
968
                $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
969
            } else {
970
                $respCode = var_export($faultResponse, true);
971
            }
972
        } else {
973 77
            $respCode = '$res';
974
        }
975 77
        if ($decodePhpObjects) {
976 20
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
977
        } else {
978 58
            $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
979
        }
980
981 77
        $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
982
983 77
        return array('source' => $code, 'docstring' => $mDesc);
984
    }
985
986
    /**
987
     * Similar to wrapXmlrpcMethod, but will generate a php class that wraps
988
     * all xmlrpc methods exposed by the remote server as own methods.
989
     * For more details see wrapXmlrpcMethod.
990
     *
991
     * For a slimmer alternative, see the code in demo/client/proxy.php
992
     *
993
     * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes...
994
     *
995
     * @param Client $client the client obj all set to query the desired server
996
     * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus
997
     *              - string method_filter      regular expression
998
     *              - string new_class_name
999
     *              - string prefix
1000
     *              - bool   simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class
1001
     *
1002
     * @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)
1003
     */
1004 20
    public function wrapXmlrpcServer($client, $extraOptions = array())
1005
    {
1006 20
        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
1007 20
        $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0;
1008 20
        $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : '';
1009 20
        $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : '';
1010 20
        $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false;
1011 20
        $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false;
1012 20
        $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true;
1013 20
        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
1014 20
        $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc';
1015 20
        $namespace = '\\PhpXmlRpc\\';
1016
1017 20
        $reqClass = $namespace . 'Request';
1018 20
        $decoderClass = $namespace . 'Encoder';
1019
1020 20
        $req = new $reqClass('system.listMethods');
1021 20
        $response = $client->send($req, $timeout, $protocol);
1022 20
        if ($response->faultCode()) {
1023
            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
1024
1025
            return false;
1026
        } else {
1027 20
            $mList = $response->value();
1028 20
            if ($client->return_type != 'phpvals') {
1029 20
                $decoder = new $decoderClass();
1030 20
                $mList = $decoder->decode($mList);
1031
            }
1032 20
            if (!is_array($mList) || !count($mList)) {
1033
                Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server');
1034
1035
                return false;
1036
            } else {
1037
                // pick a suitable name for the new function, avoiding collisions
1038 20
                if ($newClassName != '') {
1039
                    $xmlrpcClassName = $newClassName;
1040
                } else {
1041 20
                    $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1042 20
                            array('_', ''), $client->server) . '_client';
1043
                }
1044 20
                while ($buildIt && class_exists($xmlrpcClassName)) {
1045 19
                    $xmlrpcClassName .= 'x';
1046
                }
1047
1048
                /// @todo add function setdebug() to new class, to enable/disable debugging
1049 20
                $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n";
1050 20
                $source .= "function __construct()\n{\n";
1051 20
                $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
1052 20
                $source .= "\$this->client = \$client;\n}\n\n";
1053
                $opts = array(
1054 20
                    'return_source' => true,
1055 20
                    'simple_client_copy' => 2, // do not produce code to copy the client object
1056 20
                    'timeout' => $timeout,
1057 20
                    'protocol' => $protocol,
1058 20
                    'encode_php_objs' => $encodePhpObjects,
1059 20
                    'decode_php_objs' => $decodePhpObjects,
1060 20
                    'prefix' => $prefix,
1061
                );
1062
                /// @todo build phpdoc for class definition, too
1063 20
                foreach ($mList as $mName) {
1064 20
                    if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
1065
                        // note: this will fail if server exposes 2 methods called f.e. do.something and do_something
1066 20
                        $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
1067 20
                            array('_', ''), $mName);
1068 20
                        $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts);
1069 20
                        if ($methodWrap) {
1070 20
                            if (!$buildIt) {
1071
                                $source .= $methodWrap['docstring'];
1072
                            }
1073 20
                            $source .= $methodWrap['source'] . "\n";
1074
                        } else {
1075
                            Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
1076
                        }
1077
                    }
1078
                }
1079 20
                $source .= "}\n";
1080 20
                if ($buildIt) {
1081 20
                    $allOK = 0;
1082 20
                    eval($source . '$allOK=1;');
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
1083 20
                    if ($allOK) {
1084 20
                        return $xmlrpcClassName;
1085
                    } else {
1086
                        Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
1087
                        return false;
1088
                    }
1089
                } else {
1090
                    return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
1091
                }
1092
            }
1093
        }
1094
    }
1095
1096
    /**
1097
     * Given necessary info, generate php code that will build a client object just like the given one.
1098
     * Take care that no full checking of input parameters is done to ensure that
1099
     * valid php code is emitted.
1100
     * @param Client $client
1101
     * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type'
1102
     * @param string $prefix used for the return_type of the created client
1103
     * @param string $namespace
1104
     *
1105
     * @return string
1106
     */
1107 77
    protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' )
1108
    {
1109 77
        $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) .
1110 77
            "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
1111
1112
        // copy all client fields to the client that will be generated runtime
1113
        // (this provides for future expansion or subclassing of client obj)
1114 77
        if ($verbatimClientCopy) {
1115 77
            foreach ($client as $fld => $val) {
1116
                /// @todo in php 8.0, curl handles became objects, but they have no __set_state, thus var_export will
1117
                ///        fail for xmlrpc_curl_handle. So we disabled copying it.
1118
                ///        We should examine in depth if this change can have side effects - at first sight if the
1119
                ///        client's curl handle is not set, all curl options are (re)set on each http call, so there
1120
                ///        should be no loss of state...
1121 77
                if ($fld != 'debug' && $fld != 'return_type' && $fld != 'xmlrpc_curl_handle') {
1122 77
                    $val = var_export($val, true);
1123 77
                    $code .= "\$client->$fld = $val;\n";
1124
                }
1125
            }
1126
        }
1127
        // only make sure that client always returns the correct data type
1128 77
        $code .= "\$client->return_type = '{$prefix}vals';\n";
1129
        //$code .= "\$client->setDebug(\$debug);\n";
1130 77
        return $code;
1131
    }
1132
}
1133