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