fdcd620042a4e34228617a1b3d90a3eefc419b9a
[plcapi.git] / src / Server.php
1 <?php
2
3 namespace PhpXmlRpc;
4
5 use PhpXmlRpc\Helper\XMLParser;
6 use PhpXmlRpc\Helper\Charset;
7
8 class Server
9 {
10     /**
11      * Array defining php functions exposed as xmlrpc methods by this server.
12      */
13     protected $dmap = array();
14     /**
15      * Defines how functions in dmap will be invoked: either using an xmlrpc request object
16      * or plain php values.
17      * Valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
18      */
19     public $functions_parameters_type = 'xmlrpcvals';
20     /**
21      * Option used for fine-tuning the encoding the php values returned from
22      * functions registered in the dispatch map when the functions_parameters_types
23      * member is set to 'phpvals'
24      * @see Encoder::encode for a list of values
25      */
26     public $phpvals_encoding_options = array('auto_dates');
27     /**
28      * Controls whether the server is going to echo debugging messages back to the client as comments in response body.
29      * Valid values: 0,1,2,3
30      */
31     public $debug = 1;
32     /**
33      * Controls behaviour of server when the invoked user function throws an exception:
34      * 0 = catch it and return an 'internal error' xmlrpc response (default)
35      * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
36      * 2 = allow the exception to float to the upper layers
37      */
38     public $exception_handling = 0;
39     /**
40      * When set to true, it will enable HTTP compression of the response, in case
41      * the client has declared its support for compression in the request.
42      * Set at constructor time.
43      */
44     public $compress_response = false;
45     /**
46      * List of http compression methods accepted by the server for requests. Set at constructor time.
47      * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
48      */
49     public $accepted_compression = array();
50     /// shall we serve calls to system.* methods?
51     public $allow_system_funcs = true;
52     /**
53      * List of charset encodings natively accepted for requests.
54      *  Set at constructor time.
55      */
56     public $accepted_charset_encodings = array();
57     /**
58      * charset encoding to be used for response.
59      * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
60      * Can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
61      * null (leave unspecified in response, convert output stream to US_ASCII),
62      * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
63      * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway).
64      * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
65      */
66     public $response_charset_encoding = '';
67     /**
68      * Storage for internal debug info.
69      */
70     protected $debug_info = '';
71     /**
72      * Extra data passed at runtime to method handling functions. Used only by EPI layer
73      */
74     public $user_data = null;
75
76     protected static $_xmlrpc_debuginfo = '';
77     protected static $_xmlrpcs_occurred_errors = '';
78     protected static $_xmlrpcs_prev_ehandler = '';
79
80     /**
81      * @param array $dispatchMap the dispatch map with definition of exposed services
82      * @param boolean $serviceNow set to false to prevent the server from running upon construction
83      */
84     public function __construct($dispatchMap = null, $serviceNow = true)
85     {
86         // if ZLIB is enabled, let the server by default accept compressed requests,
87         // and compress responses sent to clients that support them
88         if (function_exists('gzinflate')) {
89             $this->accepted_compression = array('gzip', 'deflate');
90             $this->compress_response = true;
91         }
92
93         // by default the xml parser can support these 3 charset encodings
94         $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
95
96         // dispMap is a dispatch array of methods mapped to function names and signatures.
97         // If a method doesn't appear in the map then an unknown method error is generated
98         /* milosch - changed to make passing dispMap optional.
99         * instead, you can use the class add_to_map() function
100         * to add functions manually (borrowed from SOAPX4)
101         */
102         if ($dispatchMap) {
103             $this->dmap = $dispatchMap;
104             if ($serviceNow) {
105                 $this->service();
106             }
107         }
108     }
109
110     /**
111      * Set debug level of server.
112      *
113      * @param integer $level debug lvl: determines info added to xmlrpc responses (as xml comments)
114      *                    0 = no debug info,
115      *                    1 = msgs set from user with debugmsg(),
116      *                    2 = add complete xmlrpc request (headers and body),
117      *                    3 = add also all processing warnings happened during method processing
118      *                    (NB: this involves setting a custom error handler, and might interfere
119      *                    with the standard processing of the php function exposed as method. In
120      *                    particular, triggering an USER_ERROR level error will not halt script
121      *                    execution anymore, but just end up logged in the xmlrpc response)
122      *                    Note that info added at level 2 and 3 will be base64 encoded
123      */
124     public function setDebug($level)
125     {
126         $this->debug = $level;
127     }
128
129     /**
130      * Add a string to the debug info that can be later serialized by the server
131      * as part of the response message.
132      * Note that for best compatibility, the debug string should be encoded using
133      * the PhpXmlRpc::$xmlrpc_internalencoding character set.
134      *
135      * @param string $msg
136      * @access public
137      */
138     public static function xmlrpc_debugmsg($msg)
139     {
140         static::$_xmlrpc_debuginfo .= $msg . "\n";
141     }
142
143     public static function error_occurred($msg)
144     {
145         static::$_xmlrpcs_occurred_errors .= $msg . "\n";
146     }
147
148     /**
149      * Return a string with the serialized representation of all debug info.
150      *
151      * @param string $charsetEncoding the target charset encoding for the serialization
152      *
153      * @return string an XML comment (or two)
154      */
155     public function serializeDebug($charsetEncoding = '')
156     {
157         // Tough encoding problem: which internal charset should we assume for debug info?
158         // It might contain a copy of raw data received from client, ie with unknown encoding,
159         // intermixed with php generated data and user generated data...
160         // so we split it: system debug is base 64 encoded,
161         // user debug info should be encoded by the end user using the INTERNAL_ENCODING
162         $out = '';
163         if ($this->debug_info != '') {
164             $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n" . base64_encode($this->debug_info) . "\n-->\n";
165         }
166         if (static::$_xmlrpc_debuginfo != '') {
167             $out .= "<!-- DEBUG INFO:\n" . Charset::instance()->encodeEntities(str_replace('--', '_-', static::$_xmlrpc_debuginfo), PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n-->\n";
168             // NB: a better solution MIGHT be to use CDATA, but we need to insert it
169             // into return payload AFTER the beginning tag
170             //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n";
171         }
172
173         return $out;
174     }
175
176     /**
177      * Execute the xmlrpc request, printing the response.
178      *
179      * @param string $data the request body. If null, the http POST request will be examined
180      * @param bool $returnPayload When true, return the response but do not echo it or any http header
181      *
182      * @return Response the response object (usually not used by caller...)
183      */
184     public function service($data = null, $returnPayload = false)
185     {
186         if ($data === null) {
187             $data = file_get_contents('php://input');
188         }
189         $rawData = $data;
190
191         // reset internal debug info
192         $this->debug_info = '';
193
194         // Echo back what we received, before parsing it
195         if ($this->debug > 1) {
196             $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
197         }
198
199         $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding);
200         if (!$r) {
201             $r = $this->parseRequest($data, $reqCharset);
202         }
203
204         // save full body of request into response, for more debugging usages
205         $r->raw_data = $rawData;
206
207         if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) {
208             $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
209                 static::$_xmlrpcs_occurred_errors . "+++END+++");
210         }
211
212         $payload = $this->xml_header($respCharset);
213         if ($this->debug > 0) {
214             $payload = $payload . $this->serializeDebug($respCharset);
215         }
216
217         // G. Giunta 2006-01-27: do not create response serialization if it has
218         // already happened. Helps building json magic
219         if (empty($r->payload)) {
220             $r->serialize($respCharset);
221         }
222         $payload = $payload . $r->payload;
223
224         if ($returnPayload) {
225             return $payload;
226         }
227
228         // if we get a warning/error that has output some text before here, then we cannot
229         // add a new header. We cannot say we are sending xml, either...
230         if (!headers_sent()) {
231             header('Content-Type: ' . $r->content_type);
232             // we do not know if client actually told us an accepted charset, but if he did
233             // we have to tell him what we did
234             header("Vary: Accept-Charset");
235
236             // http compression of output: only
237             // if we can do it, and we want to do it, and client asked us to,
238             // and php ini settings do not force it already
239             $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
240             if ($this->compress_response && function_exists('gzencode') && $respEncoding != ''
241                 && $phpNoSelfCompress
242             ) {
243                 if (strpos($respEncoding, 'gzip') !== false) {
244                     $payload = gzencode($payload);
245                     header("Content-Encoding: gzip");
246                     header("Vary: Accept-Encoding");
247                 } elseif (strpos($respEncoding, 'deflate') !== false) {
248                     $payload = gzcompress($payload);
249                     header("Content-Encoding: deflate");
250                     header("Vary: Accept-Encoding");
251                 }
252             }
253
254             // do not output content-length header if php is compressing output for us:
255             // it will mess up measurements
256             if ($phpNoSelfCompress) {
257                 header('Content-Length: ' . (int)strlen($payload));
258             }
259         } else {
260             error_log('XML-RPC: ' . __METHOD__ . ': http headers already sent before response is fully generated. Check for php warning or error messages');
261         }
262
263         print $payload;
264
265         // return request, in case subclasses want it
266         return $r;
267     }
268
269     /**
270      * Add a method to the dispatch map.
271      *
272      * @param string $methodName the name with which the method will be made available
273      * @param string $function the php function that will get invoked
274      * @param array $sig the array of valid method signatures
275      * @param string $doc method documentation
276      * @param array $sigDoc the array of valid method signatures docs (one string per param, one for return type)
277      */
278     public function add_to_map($methodName, $function, $sig = null, $doc = false, $sigDoc = false)
279     {
280         $this->dmap[$methodName] = array(
281             'function' => $function,
282             'docstring' => $doc,
283         );
284         if ($sig) {
285             $this->dmap[$methodName]['signature'] = $sig;
286         }
287         if ($sigDoc) {
288             $this->dmap[$methodName]['signature_docs'] = $sigDoc;
289         }
290     }
291
292     /**
293      * Verify type and number of parameters received against a list of known signatures.
294      *
295      * @param array|Request $in array of either xmlrpc value objects or xmlrpc type definitions
296      * @param array $sigs array of known signatures to match against
297      *
298      * @return array
299      */
300     protected function verifySignature($in, $sigs)
301     {
302         // check each possible signature in turn
303         if (is_object($in)) {
304             $numParams = $in->getNumParams();
305         } else {
306             $numParams = count($in);
307         }
308         foreach ($sigs as $curSig) {
309             if (count($curSig) == $numParams + 1) {
310                 $itsOK = 1;
311                 for ($n = 0; $n < $numParams; $n++) {
312                     if (is_object($in)) {
313                         $p = $in->getParam($n);
314                         if ($p->kindOf() == 'scalar') {
315                             $pt = $p->scalartyp();
316                         } else {
317                             $pt = $p->kindOf();
318                         }
319                     } else {
320                         $pt = $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
321                     }
322
323                     // param index is $n+1, as first member of sig is return type
324                     if ($pt != $curSig[$n + 1] && $curSig[$n + 1] != Value::$xmlrpcValue) {
325                         $itsOK = 0;
326                         $pno = $n + 1;
327                         $wanted = $curSig[$n + 1];
328                         $got = $pt;
329                         break;
330                     }
331                 }
332                 if ($itsOK) {
333                     return array(1, '');
334                 }
335             }
336         }
337         if (isset($wanted)) {
338             return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
339         } else {
340             return array(0, "No method signature matches number of parameters");
341         }
342     }
343
344     /**
345      * Parse http headers received along with xmlrpc request. If needed, inflate request.
346      *
347      * @return mixed null on success or a Response
348      */
349     protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression)
350     {
351         // check if $_SERVER is populated: it might have been disabled via ini file
352         // (this is true even when in CLI mode)
353         if (count($_SERVER) == 0) {
354             error_log('XML-RPC: ' . __METHOD__ . ': cannot parse request headers as $_SERVER is not populated');
355         }
356
357         if ($this->debug > 1) {
358             if (function_exists('getallheaders')) {
359                 $this->debugmsg(''); // empty line
360                 foreach (getallheaders() as $name => $val) {
361                     $this->debugmsg("HEADER: $name: $val");
362                 }
363             }
364         }
365
366         if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) {
367             $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
368         } else {
369             $contentEncoding = '';
370         }
371
372         // check if request body has been compressed and decompress it
373         if ($contentEncoding != '' && strlen($data)) {
374             if ($contentEncoding == 'deflate' || $contentEncoding == 'gzip') {
375                 // if decoding works, use it. else assume data wasn't gzencoded
376                 if (function_exists('gzinflate') && in_array($contentEncoding, $this->accepted_compression)) {
377                     if ($contentEncoding == 'deflate' && $degzdata = @gzuncompress($data)) {
378                         $data = $degzdata;
379                         if ($this->debug > 1) {
380                             $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
381                         }
382                     } elseif ($contentEncoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
383                         $data = $degzdata;
384                         if ($this->debug > 1) {
385                             $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
386                         }
387                     } else {
388                         $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
389
390                         return $r;
391                     }
392                 } else {
393                     //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
394                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']);
395
396                     return $r;
397                 }
398             }
399         }
400
401         // check if client specified accepted charsets, and if we know how to fulfill
402         // the request
403         if ($this->response_charset_encoding == 'auto') {
404             $respEncoding = '';
405             if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
406                 // here we should check if we can match the client-requested encoding
407                 // with the encodings we know we can generate.
408                 /// @todo we should parse q=0.x preferences instead of getting first charset specified...
409                 $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
410                 // Give preference to internal encoding
411                 $knownCharsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
412                 foreach ($knownCharsets as $charset) {
413                     foreach ($clientAcceptedCharsets as $accepted) {
414                         if (strpos($accepted, $charset) === 0) {
415                             $respEncoding = $charset;
416                             break;
417                         }
418                     }
419                     if ($respEncoding) {
420                         break;
421                     }
422                 }
423             }
424         } else {
425             $respEncoding = $this->response_charset_encoding;
426         }
427
428         if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
429             $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING'];
430         } else {
431             $respCompression = '';
432         }
433
434         // 'guestimate' request encoding
435         /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
436         $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
437             $data);
438
439         return;
440     }
441
442     /**
443      * Parse an xml chunk containing an xmlrpc request and execute the corresponding
444      * php function registered with the server.
445      *
446      * @param string $data the xml request
447      * @param string $reqEncoding (optional) the charset encoding of the xml request
448      *
449      * @return Response
450      */
451     public function parseRequest($data, $reqEncoding = '')
452     {
453         // decompose incoming XML into request structure
454
455         if ($reqEncoding != '') {
456             // Since parsing will fail if charset is not specified in the xml prologue,
457             // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
458             // The following code might be better for mb_string enabled installs, but
459             // makes the lib about 200% slower...
460             //if (!is_valid_charset($reqEncoding, array('UTF-8')))
461             if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
462                 if ($reqEncoding == 'ISO-8859-1') {
463                     $data = utf8_encode($data);
464                 } else {
465                     if (extension_loaded('mbstring')) {
466                         $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding);
467                     } else {
468                         error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding);
469                     }
470                 }
471             }
472         }
473
474         $parser = xml_parser_create();
475         xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
476         // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
477         // the xml parser to give us back data in the expected charset
478         // What if internal encoding is not in one of the 3 allowed?
479         // we use the broadest one, ie. utf8
480         // This allows to send data which is native in various charset,
481         // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
482         if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
483             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
484         } else {
485             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
486         }
487
488         $xmlRpcParser = new XMLParser();
489         xml_set_object($parser, $xmlRpcParser);
490
491         if ($this->functions_parameters_type != 'xmlrpcvals') {
492             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
493         } else {
494             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
495         }
496         xml_set_character_data_handler($parser, 'xmlrpc_cd');
497         xml_set_default_handler($parser, 'xmlrpc_dh');
498         if (!xml_parse($parser, $data, 1)) {
499             // return XML error as a faultCode
500             $r = new Response(0,
501                 PhpXmlRpc::$xmlrpcerrxml + xml_get_error_code($parser),
502                 sprintf('XML error: %s at line %d, column %d',
503                     xml_error_string(xml_get_error_code($parser)),
504                     xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
505             xml_parser_free($parser);
506         } elseif ($xmlRpcParser->_xh['isf']) {
507             xml_parser_free($parser);
508             $r = new Response(0,
509                 PhpXmlRpc::$xmlrpcerr['invalid_request'],
510                 PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
511         } else {
512             xml_parser_free($parser);
513             // small layering violation in favor of speed and memory usage:
514             // we should allow the 'execute' method handle this, but in the
515             // most common scenario (xmlrpc values type server with some methods
516             // registered as phpvals) that would mean a useless encode+decode pass
517             if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) {
518                 if ($this->debug > 1) {
519                     $this->debugmsg("\n+++PARSED+++\n" . var_export($xmlRpcParser->_xh['params'], true) . "\n+++END+++");
520                 }
521                 $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']);
522             } else {
523                 // build a Request object with data parsed from xml
524                 $req = new Request($xmlRpcParser->_xh['method']);
525                 // now add parameters in
526                 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
527                     $req->addParam($xmlRpcParser->_xh['params'][$i]);
528                 }
529
530                 if ($this->debug > 1) {
531                     $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++");
532                 }
533                 $r = $this->execute($req);
534             }
535         }
536
537         return $r;
538     }
539
540     /**
541      * Execute a method invoked by the client, checking parameters used.
542      *
543      * @param mixed $req either a Request obj or a method name
544      * @param array $params array with method parameters as php types (if m is method name only)
545      * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only)
546      *
547      * @return Response
548      *
549      * @throws \Exception in case the executed method does throw an exception (and depending on )
550      */
551     protected function execute($req, $params = null, $paramTypes = null)
552     {
553         if (is_object($req)) {
554             $methName = $req->method();
555         } else {
556             $methName = $req;
557         }
558         $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
559         $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
560
561         if (!isset($dmap[$methName]['function'])) {
562             // No such method
563             return new Response(0,
564                 PhpXmlRpc::$xmlrpcerr['unknown_method'],
565                 PhpXmlRpc::$xmlrpcstr['unknown_method']);
566         }
567
568         // Check signature
569         if (isset($dmap[$methName]['signature'])) {
570             $sig = $dmap[$methName]['signature'];
571             if (is_object($req)) {
572                 list($ok, $errStr) = $this->verifySignature($req, $sig);
573             } else {
574                 list($ok, $errStr) = $this->verifySignature($paramTypes, $sig);
575             }
576             if (!$ok) {
577                 // Didn't match.
578                 return new Response(
579                     0,
580                     PhpXmlRpc::$xmlrpcerr['incorrect_params'],
581                     PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errStr}"
582                 );
583             }
584         }
585
586         $func = $dmap[$methName]['function'];
587         // let the 'class::function' syntax be accepted in dispatch maps
588         if (is_string($func) && strpos($func, '::')) {
589             $func = explode('::', $func);
590         }
591
592         if (is_array($func)) {
593             if (is_object($func[0])) {
594                 $funcName = get_class($func[0]) . '->' . $func[1];
595             } else {
596                 $funcName = implode('::', $func);
597             }
598         } else if ($func instanceof \Closure) {
599             $funcName = 'Closure';
600         } else {
601             $funcName = $func;
602         }
603
604         // verify that function to be invoked is in fact callable
605         if (!is_callable($func)) {
606             error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable");
607
608             return new Response(
609                 0,
610                 PhpXmlRpc::$xmlrpcerr['server_error'],
611                 PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method"
612             );
613         }
614
615         // If debug level is 3, we should catch all errors generated during
616         // processing of user function, and log them as part of response
617         if ($this->debug > 2) {
618             self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'));
619         }
620         try {
621             // Allow mixed-convention servers
622             if (is_object($req)) {
623                 if ($sysCall) {
624                     $r = call_user_func($func, $this, $req);
625                 } else {
626                     $r = call_user_func($func, $req);
627                 }
628                 if (!is_a($r, 'PhpXmlRpc\Response')) {
629                     error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler does not return an xmlrpc response object but a " . gettype($r));
630                     if (is_a($r, 'PhpXmlRpc\Value')) {
631                         $r = new Response($r);
632                     } else {
633                         $r = new Response(
634                             0,
635                             PhpXmlRpc::$xmlrpcerr['server_error'],
636                             PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response object"
637                         );
638                     }
639                 }
640             } else {
641                 // call a 'plain php' function
642                 if ($sysCall) {
643                     array_unshift($params, $this);
644                     $r = call_user_func_array($func, $params);
645                 } else {
646                     // 3rd API convention for method-handling functions: EPI-style
647                     if ($this->functions_parameters_type == 'epivals') {
648                         $r = call_user_func_array($func, array($methName, $params, $this->user_data));
649                         // mimic EPI behaviour: if we get an array that looks like an error, make it
650                         // an eror response
651                         if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) {
652                             $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']);
653                         } else {
654                             // functions using EPI api should NOT return resp objects,
655                             // so make sure we encode the return type correctly
656                             $r = new Response(php_xmlrpc_encode($r, array('extension_api')));
657                         }
658                     } else {
659                         $r = call_user_func_array($func, $params);
660                     }
661                 }
662                 // the return type can be either a Response object or a plain php value...
663                 if (!is_a($r, '\PhpXmlRpc\Response')) {
664                     // what should we assume here about automatic encoding of datetimes
665                     // and php classes instances???
666                     $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
667                 }
668             }
669         } catch (\Exception $e) {
670             // (barring errors in the lib) an uncatched exception happened
671             // in the called function, we wrap it in a proper error-response
672             switch ($this->exception_handling) {
673                 case 2:
674                     throw $e;
675                     break;
676                 case 1:
677                     $r = new Response(0, $e->getCode(), $e->getMessage());
678                     break;
679                 default:
680                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']);
681             }
682         }
683         if ($this->debug > 2) {
684             // note: restore the error handler we found before calling the
685             // user func, even if it has been changed inside the func itself
686             if (self::$_xmlrpcs_prev_ehandler) {
687                 set_error_handler(self::$_xmlrpcs_prev_ehandler);
688             } else {
689                 restore_error_handler();
690             }
691         }
692
693         return $r;
694     }
695
696     /**
697      * add a string to the 'internal debug message' (separate from 'user debug message').
698      *
699      * @param string $string
700      */
701     protected function debugmsg($string)
702     {
703         $this->debug_info .= $string . "\n";
704     }
705
706     protected function xml_header($charsetEncoding = '')
707     {
708         if ($charsetEncoding != '') {
709             return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
710         } else {
711             return "<?xml version=\"1.0\"?" . ">\n";
712         }
713     }
714
715     /* Functions that implement system.XXX methods of xmlrpc servers */
716
717     public function getSystemDispatchMap()
718     {
719         return array(
720             'system.listMethods' => array(
721                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods',
722                 // listMethods: signature was either a string, or nothing.
723                 // The useless string variant has been removed
724                 'signature' => array(array(Value::$xmlrpcArray)),
725                 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch',
726                 'signature_docs' => array(array('list of method names')),
727             ),
728             'system.methodHelp' => array(
729                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp',
730                 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)),
731                 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string',
732                 'signature_docs' => array(array('method description', 'name of the method to be described')),
733             ),
734             'system.methodSignature' => array(
735                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature',
736                 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)),
737                 'docstring' => 'Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)',
738                 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')),
739             ),
740             'system.multicall' => array(
741                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall',
742                 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)),
743                 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details',
744                 'signature_docs' => array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"')),
745             ),
746             'system.getCapabilities' => array(
747                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities',
748                 'signature' => array(array(Value::$xmlrpcStruct)),
749                 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to',
750                 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')),
751             ),
752         );
753     }
754
755     public static function _xmlrpcs_getCapabilities($server, $req = null)
756     {
757         $outAr = array(
758             // xmlrpc spec: always supported
759             'xmlrpc' => new Value(array(
760                 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'),
761                 'specVersion' => new Value(1, 'int'),
762             ), 'struct'),
763             // if we support system.xxx functions, we always support multicall, too...
764             // Note that, as of 2006/09/17, the following URL does not respond anymore
765             'system.multicall' => new Value(array(
766                 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
767                 'specVersion' => new Value(1, 'int'),
768             ), 'struct'),
769             // introspection: version 2! we support 'mixed', too
770             'introspection' => new Value(array(
771                 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
772                 'specVersion' => new Value(2, 'int'),
773             ), 'struct'),
774         );
775
776         // NIL extension
777         if (PhpXmlRpc::$xmlrpc_null_extension) {
778             $outAr['nil'] = new Value(array(
779                 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
780                 'specVersion' => new Value(1, 'int'),
781             ), 'struct');
782         }
783
784         return new Response(new Value($outAr, 'struct'));
785     }
786
787     public static function _xmlrpcs_listMethods($server, $req = null) // if called in plain php values mode, second param is missing
788     {
789         $outAr = array();
790         foreach ($server->dmap as $key => $val) {
791             $outAr[] = new Value($key, 'string');
792         }
793         if ($server->allow_system_funcs) {
794             foreach ($server->getSystemDispatchMap() as $key => $val) {
795                 $outAr[] = new Value($key, 'string');
796             }
797         }
798
799         return new Response(new Value($outAr, 'array'));
800     }
801
802     public static function _xmlrpcs_methodSignature($server, $req)
803     {
804         // let accept as parameter both an xmlrpc value or string
805         if (is_object($req)) {
806             $methName = $req->getParam(0);
807             $methName = $methName->scalarval();
808         } else {
809             $methName = $req;
810         }
811         if (strpos($methName, "system.") === 0) {
812             $dmap = $server->getSystemDispatchMap();
813         } else {
814             $dmap = $server->dmap;
815         }
816         if (isset($dmap[$methName])) {
817             if (isset($dmap[$methName]['signature'])) {
818                 $sigs = array();
819                 foreach ($dmap[$methName]['signature'] as $inSig) {
820                     $curSig = array();
821                     foreach ($inSig as $sig) {
822                         $curSig[] = new Value($sig, 'string');
823                     }
824                     $sigs[] = new Value($curSig, 'array');
825                 }
826                 $r = new Response(new Value($sigs, 'array'));
827             } else {
828                 // NB: according to the official docs, we should be returning a
829                 // "none-array" here, which means not-an-array
830                 $r = new Response(new Value('undef', 'string'));
831             }
832         } else {
833             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
834         }
835
836         return $r;
837     }
838
839     public static function _xmlrpcs_methodHelp($server, $req)
840     {
841         // let accept as parameter both an xmlrpc value or string
842         if (is_object($req)) {
843             $methName = $req->getParam(0);
844             $methName = $methName->scalarval();
845         } else {
846             $methName = $req;
847         }
848         if (strpos($methName, "system.") === 0) {
849             $dmap = $server->getSystemDispatchMap();
850         } else {
851             $dmap = $server->dmap;
852         }
853         if (isset($dmap[$methName])) {
854             if (isset($dmap[$methName]['docstring'])) {
855                 $r = new Response(new Value($dmap[$methName]['docstring']), 'string');
856             } else {
857                 $r = new Response(new Value('', 'string'));
858             }
859         } else {
860             $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
861         }
862
863         return $r;
864     }
865
866     public static function _xmlrpcs_multicall_error($err)
867     {
868         if (is_string($err)) {
869             $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
870             $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"];
871         } else {
872             $code = $err->faultCode();
873             $str = $err->faultString();
874         }
875         $struct = array();
876         $struct['faultCode'] = new Value($code, 'int');
877         $struct['faultString'] = new Value($str, 'string');
878
879         return new Value($struct, 'struct');
880     }
881
882     public static function _xmlrpcs_multicall_do_call($server, $call)
883     {
884         if ($call->kindOf() != 'struct') {
885             return static::_xmlrpcs_multicall_error('notstruct');
886         }
887         $methName = @$call->structmem('methodName');
888         if (!$methName) {
889             return static::_xmlrpcs_multicall_error('nomethod');
890         }
891         if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') {
892             return static::_xmlrpcs_multicall_error('notstring');
893         }
894         if ($methName->scalarval() == 'system.multicall') {
895             return static::_xmlrpcs_multicall_error('recursion');
896         }
897
898         $params = @$call->structmem('params');
899         if (!$params) {
900             return static::_xmlrpcs_multicall_error('noparams');
901         }
902         if ($params->kindOf() != 'array') {
903             return static::_xmlrpcs_multicall_error('notarray');
904         }
905         $numParams = $params->arraysize();
906
907         $req = new Request($methName->scalarval());
908         for ($i = 0; $i < $numParams; $i++) {
909             if (!$req->addParam($params->arraymem($i))) {
910                 $i++;
911
912                 return static::_xmlrpcs_multicall_error(new Response(0,
913                     PhpXmlRpc::$xmlrpcerr['incorrect_params'],
914                     PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
915             }
916         }
917
918         $result = $server->execute($req);
919
920         if ($result->faultCode() != 0) {
921             return static::_xmlrpcs_multicall_error($result); // Method returned fault.
922         }
923
924         return new Value(array($result->value()), 'array');
925     }
926
927     public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
928     {
929         if (!is_array($call)) {
930             return static::_xmlrpcs_multicall_error('notstruct');
931         }
932         if (!array_key_exists('methodName', $call)) {
933             return static::_xmlrpcs_multicall_error('nomethod');
934         }
935         if (!is_string($call['methodName'])) {
936             return static::_xmlrpcs_multicall_error('notstring');
937         }
938         if ($call['methodName'] == 'system.multicall') {
939             return static::_xmlrpcs_multicall_error('recursion');
940         }
941         if (!array_key_exists('params', $call)) {
942             return static::_xmlrpcs_multicall_error('noparams');
943         }
944         if (!is_array($call['params'])) {
945             return static::_xmlrpcs_multicall_error('notarray');
946         }
947
948         // this is a real dirty and simplistic hack, since we might have received a
949         // base64 or datetime values, but they will be listed as strings here...
950         $numParams = count($call['params']);
951         $pt = array();
952         $wrapper = new Wrapper();
953         foreach ($call['params'] as $val) {
954             $pt[] = $wrapper->php_2_xmlrpc_type(gettype($val));
955         }
956
957         $result = $server->execute($call['methodName'], $call['params'], $pt);
958
959         if ($result->faultCode() != 0) {
960             return static::_xmlrpcs_multicall_error($result); // Method returned fault.
961         }
962
963         return new Value(array($result->value()), 'array');
964     }
965
966     public static function _xmlrpcs_multicall($server, $req)
967     {
968         $result = array();
969         // let accept a plain list of php parameters, beside a single xmlrpc msg object
970         if (is_object($req)) {
971             $calls = $req->getParam(0);
972             $numCalls = $calls->arraysize();
973             for ($i = 0; $i < $numCalls; $i++) {
974                 $call = $calls->arraymem($i);
975                 $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call);
976             }
977         } else {
978             $numCalls = count($req);
979             for ($i = 0; $i < $numCalls; $i++) {
980                 $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]);
981             }
982         }
983
984         return new Response(new Value($result, 'array'));
985     }
986
987     /**
988      * Error handler used to track errors that occur during server-side execution of PHP code.
989      * This allows to report back to the client whether an internal error has occurred or not
990      * using an xmlrpc response object, instead of letting the client deal with the html junk
991      * that a PHP execution error on the server generally entails.
992      *
993      * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
994      */
995     public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = null, $lineNo = null, $context = null)
996     {
997         // obey the @ protocol
998         if (error_reporting() == 0) {
999             return;
1000         }
1001
1002         //if($errCode != E_NOTICE && $errCode != E_WARNING && $errCode != E_USER_NOTICE && $errCode != E_USER_WARNING)
1003         if ($errCode != E_STRICT) {
1004             \PhpXmlRpc\Server::error_occurred($errString);
1005         }
1006         // Try to avoid as much as possible disruption to the previous error handling
1007         // mechanism in place
1008         if (self::$_xmlrpcs_prev_ehandler == '') {
1009             // The previous error handler was the default: all we should do is log error
1010             // to the default error log (if level high enough)
1011             if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) {
1012                 error_log($errString);
1013             }
1014         } else {
1015             // Pass control on to previous error handler, trying to avoid loops...
1016             if (self::$_xmlrpcs_prev_ehandler != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) {
1017                 if (is_array(self::$_xmlrpcs_prev_ehandler)) {
1018                     // the following works both with static class methods and plain object methods as error handler
1019                     call_user_func_array(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context));
1020                 } else {
1021                     $method = self::$_xmlrpcs_prev_ehandler;
1022                     $method($errCode, $errString, $filename, $lineNo, $context);
1023                 }
1024             }
1025         }
1026     }
1027 }