5 use PhpXmlRpc\Helper\Charset;
6 use PhpXmlRpc\Helper\Logger;
7 use PhpXmlRpc\Helper\XMLParser;
10 * Allows effortless implementation of XML-RPC servers
14 protected static $logger;
15 protected static $parser;
16 protected static $charsetEncoder;
19 * Defines how functions in dmap will be invoked: either using an xmlrpc request object
20 * or plain php values.
21 * Valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
22 * @todo create class constants for these
24 public $functions_parameters_type = 'xmlrpcvals';
27 * Option used for fine-tuning the encoding the php values returned from
28 * functions registered in the dispatch map when the functions_parameters_types
29 * member is set to 'phpvals'
30 * @see Encoder::encode for a list of values
32 public $phpvals_encoding_options = array('auto_dates');
35 * Controls whether the server is going to echo debugging messages back to the client as comments in response body.
36 * Valid values: 0,1,2,3
41 * Controls behaviour of server when the invoked user function throws an exception:
42 * 0 = catch it and return an 'internal error' xmlrpc response (default)
43 * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
44 * 2 = allow the exception to float to the upper layers
46 public $exception_handling = 0;
49 * When set to true, it will enable HTTP compression of the response, in case
50 * the client has declared its support for compression in the request.
51 * Set at constructor time.
53 public $compress_response = false;
56 * List of http compression methods accepted by the server for requests. Set at constructor time.
57 * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
59 public $accepted_compression = array();
61 /// Shall we serve calls to system.* methods?
62 public $allow_system_funcs = true;
65 * List of charset encodings natively accepted for requests.
66 * Set at constructor time.
69 public $accepted_charset_encodings = array();
72 * Charset encoding to be used for response.
73 * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
74 * Can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
75 * null (leave unspecified in response, convert output stream to US_ASCII),
76 * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
77 * 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).
78 * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
80 public $response_charset_encoding = '';
83 * Extra data passed at runtime to method handling functions. Used only by EPI layer
85 public $user_data = null;
88 * Array defining php functions exposed as xmlrpc methods by this server.
91 protected $dmap = array();
94 * Storage for internal debug info.
96 protected $debug_info = '';
98 protected static $_xmlrpc_debuginfo = '';
99 protected static $_xmlrpcs_occurred_errors = '';
100 protected static $_xmlrpcs_prev_ehandler = '';
102 public function getLogger()
104 if (self::$logger === null) {
105 self::$logger = Logger::instance();
107 return self::$logger;
110 public static function setLogger($logger)
112 self::$logger = $logger;
115 public function getParser()
117 if (self::$parser === null) {
118 self::$parser = new XMLParser();
120 return self::$parser;
123 public static function setParser($parser)
125 self::$parser = $parser;
128 public function getCharsetEncoder()
130 if (self::$charsetEncoder === null) {
131 self::$charsetEncoder = Charset::instance();
133 return self::$charsetEncoder;
136 public function setCharsetEncoder($charsetEncoder)
138 self::$charsetEncoder = $charsetEncoder;
142 * @param array[] $dispatchMap the dispatch map with definition of exposed services
143 * Array keys are the names of the method names.
144 * Each array value is an array with the following members:
145 * - function (callable)
146 * - docstring (optional)
147 * - signature (array, optional)
148 * - signature_docs (array, optional)
149 * - parameters_type (string, optional)
150 * @param boolean $serviceNow set to false to prevent the server from running upon construction
152 public function __construct($dispatchMap = null, $serviceNow = true)
154 // if ZLIB is enabled, let the server by default accept compressed requests,
155 // and compress responses sent to clients that support them
156 if (function_exists('gzinflate')) {
157 $this->accepted_compression = array('gzip', 'deflate');
158 $this->compress_response = true;
161 // by default the xml parser can support these 3 charset encodings
162 $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
164 // dispMap is a dispatch array of methods mapped to function names and signatures.
165 // If a method doesn't appear in the map then an unknown method error is generated
166 /* milosch - changed to make passing dispMap optional.
167 * instead, you can use the class add_to_map() function
168 * to add functions manually (borrowed from SOAPX4)
171 $this->dmap = $dispatchMap;
179 * Set debug level of server.
181 * @param integer $level debug lvl: determines info added to xmlrpc responses (as xml comments)
183 * 1 = msgs set from user with debugmsg(),
184 * 2 = add complete xmlrpc request (headers and body),
185 * 3 = add also all processing warnings happened during method processing
186 * (NB: this involves setting a custom error handler, and might interfere
187 * with the standard processing of the php function exposed as method. In
188 * particular, triggering an USER_ERROR level error will not halt script
189 * execution anymore, but just end up logged in the xmlrpc response)
190 * Note that info added at level 2 and 3 will be base64 encoded
192 public function setDebug($level)
194 $this->debug = $level;
198 * Add a string to the debug info that can be later serialized by the server as part of the response message.
199 * Note that for best compatibility, the debug string should be encoded using the PhpXmlRpc::$xmlrpc_internalencoding
204 public static function xmlrpc_debugmsg($msg)
206 static::$_xmlrpc_debuginfo .= $msg . "\n";
210 * Add a string to the debug info that will be later serialized by the server as part of the response message
211 * (base64 encoded, only when debug level >= 2)
216 public static function error_occurred($msg)
218 static::$_xmlrpcs_occurred_errors .= $msg . "\n";
222 * Return a string with the serialized representation of all debug info.
224 * @param string $charsetEncoding the target charset encoding for the serialization
226 * @return string an XML comment (or two)
228 public function serializeDebug($charsetEncoding = '')
230 // Tough encoding problem: which internal charset should we assume for debug info?
231 // It might contain a copy of raw data received from client, ie with unknown encoding,
232 // intermixed with php generated data and user generated data...
233 // so we split it: system debug is base 64 encoded,
234 // user debug info should be encoded by the end user using the INTERNAL_ENCODING
236 if ($this->debug_info != '') {
237 $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n" . base64_encode($this->debug_info) . "\n-->\n";
239 if (static::$_xmlrpc_debuginfo != '') {
240 $out .= "<!-- DEBUG INFO:\n" . $this->getCharsetEncoder()->encodeEntities(str_replace('--', '_-', static::$_xmlrpc_debuginfo), PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n-->\n";
241 // NB: a better solution MIGHT be to use CDATA, but we need to insert it
242 // into return payload AFTER the beginning tag
243 //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n";
250 * Execute the xmlrpc request, printing the response.
252 * @param string $data the request body. If null, the http POST request will be examined
253 * @param bool $returnPayload When true, return the response but do not echo it or any http header
255 * @return Response|string the response object (usually not used by caller...) or its xml serialization
257 * @throws \Exception in case the executed method does throw an exception (and depending on server configuration)
259 public function service($data = null, $returnPayload = false)
261 if ($data === null) {
262 $data = file_get_contents('php://input');
266 // reset internal debug info
267 $this->debug_info = '';
269 // Save what we received, before parsing it
270 if ($this->debug > 1) {
271 $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
274 $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding);
276 // this actually executes the request
277 $r = $this->parseRequest($data, $reqCharset);
280 // save full body of request into response, for more debugging usages
281 $r->raw_data = $rawData;
283 if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) {
284 $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
285 static::$_xmlrpcs_occurred_errors . "+++END+++");
288 $payload = $this->xml_header($respCharset);
289 if ($this->debug > 0) {
290 $payload = $payload . $this->serializeDebug($respCharset);
293 // Do not create response serialization if it has already happened. Helps building json magic
294 if (empty($r->payload)) {
295 $r->serialize($respCharset);
297 $payload = $payload . $r->payload;
299 if ($returnPayload) {
303 // if we get a warning/error that has output some text before here, then we cannot
304 // add a new header. We cannot say we are sending xml, either...
305 if (!headers_sent()) {
306 header('Content-Type: ' . $r->content_type);
307 // we do not know if client actually told us an accepted charset, but if he did
308 // we have to tell him what we did
309 header("Vary: Accept-Charset");
311 // http compression of output: only
312 // if we can do it, and we want to do it, and client asked us to,
313 // and php ini settings do not force it already
314 /// @todo check separately for gzencode and gzcompress functions, in case of polyfills
315 $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
316 if ($this->compress_response && function_exists('gzencode') && $respEncoding != ''
317 && $phpNoSelfCompress
319 if (strpos($respEncoding, 'gzip') !== false) {
320 $payload = gzencode($payload);
321 header("Content-Encoding: gzip");
322 header("Vary: Accept-Encoding");
323 } elseif (strpos($respEncoding, 'deflate') !== false) {
324 $payload = gzcompress($payload);
325 header("Content-Encoding: deflate");
326 header("Vary: Accept-Encoding");
330 // Do not output content-length header if php is compressing output for us:
331 // it will mess up measurements.
332 // Note that Apache/mod_php will add (and even alter!) the Content-Length header on its own, but only for
333 // responses up to 8000 bytes
334 if ($phpNoSelfCompress) {
335 header('Content-Length: ' . (int)strlen($payload));
338 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': http headers already sent before response is fully generated. Check for php warning or error messages');
343 // return request, in case subclasses want it
348 * Add a method to the dispatch map.
350 * @param string $methodName the name with which the method will be made available
351 * @param callable $function the php function that will get invoked
352 * @param array[] $sig the array of valid method signatures.
353 * Each element is one signature: an array of strings with at least one element
354 * First element = type of returned value. Elements 2..N = types of parameters 1..N
355 * @param string $doc method documentation
356 * @param array[] $sigDoc the array of valid method signatures docs, following the format of $sig but with
357 * descriptions instead of types (one string for return type, one per param)
359 * @todo raise a warning if the user tries to register a 'system.' method
360 * @todo allow setting parameters_type
362 public function add_to_map($methodName, $function, $sig = null, $doc = false, $sigDoc = false)
364 $this->dmap[$methodName] = array(
365 'function' => $function,
369 $this->dmap[$methodName]['signature'] = $sig;
372 $this->dmap[$methodName]['signature_docs'] = $sigDoc;
377 * Verify type and number of parameters received against a list of known signatures.
379 * @param array|Request $in array of either xmlrpc value objects or xmlrpc type definitions
380 * @param array $sigs array of known signatures to match against
382 * @return array int, string
384 protected function verifySignature($in, $sigs)
386 // check each possible signature in turn
387 if (is_object($in)) {
388 $numParams = $in->getNumParams();
390 $numParams = count($in);
392 foreach ($sigs as $curSig) {
393 if (count($curSig) == $numParams + 1) {
395 for ($n = 0; $n < $numParams; $n++) {
396 if (is_object($in)) {
397 $p = $in->getParam($n);
398 if ($p->kindOf() == 'scalar') {
399 $pt = $p->scalartyp();
404 $pt = ($in[$n] == 'i4') ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
407 // param index is $n+1, as first member of sig is return type
408 if ($pt != $curSig[$n + 1] && $curSig[$n + 1] != Value::$xmlrpcValue) {
411 $wanted = $curSig[$n + 1];
421 if (isset($wanted)) {
422 return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
424 return array(0, "No method signature matches number of parameters");
429 * Parse http headers received along with xmlrpc request. If needed, inflate request.
431 * @return mixed Response|null on success or an error Response
433 protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression)
435 // check if $_SERVER is populated: it might have been disabled via ini file
436 // (this is true even when in CLI mode)
437 if (count($_SERVER) == 0) {
438 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': cannot parse request headers as $_SERVER is not populated');
441 if ($this->debug > 1) {
442 if (function_exists('getallheaders')) {
443 $this->debugmsg(''); // empty line
444 foreach (getallheaders() as $name => $val) {
445 $this->debugmsg("HEADER: $name: $val");
450 if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) {
451 $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
453 $contentEncoding = '';
456 // check if request body has been compressed and decompress it
457 if ($contentEncoding != '' && strlen($data)) {
458 if ($contentEncoding == 'deflate' || $contentEncoding == 'gzip') {
459 // if decoding works, use it. else assume data wasn't gzencoded
460 if (function_exists('gzinflate') && in_array($contentEncoding, $this->accepted_compression)) {
461 if ($contentEncoding == 'deflate' && $degzdata = @gzuncompress($data)) {
463 if ($this->debug > 1) {
464 $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
466 } elseif ($contentEncoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
468 if ($this->debug > 1) {
469 $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
472 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
477 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']);
484 // check if client specified accepted charsets, and if we know how to fulfill
486 if ($this->response_charset_encoding == 'auto') {
488 if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
489 // here we should check if we can match the client-requested encoding
490 // with the encodings we know we can generate.
491 /// @todo we should parse q=0.x preferences instead of getting first charset specified...
492 $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
493 // Give preference to internal encoding
494 $knownCharsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
495 foreach ($knownCharsets as $charset) {
496 foreach ($clientAcceptedCharsets as $accepted) {
497 if (strpos($accepted, $charset) === 0) {
498 $respEncoding = $charset;
508 $respEncoding = $this->response_charset_encoding;
511 if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
512 $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING'];
514 $respCompression = '';
517 // 'guestimate' request encoding
518 /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
519 $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
526 * Parse an xml chunk containing an xmlrpc request and execute the corresponding
527 * php function registered with the server.
529 * @param string $data the xml request
530 * @param string $reqEncoding (optional) the charset encoding of the xml request
534 * @throws \Exception in case the executed method does throw an exception (and depending on server configuration)
536 * @internal this function will become protected in the future
537 * @todo either rename this function or move the 'execute' part out of it...
539 public function parseRequest($data, $reqEncoding = '')
541 // decompose incoming XML into request structure
543 if ($reqEncoding != '') {
544 // Since parsing will fail if
545 // - charset is not specified in the xml prologue,
546 // - the encoding is not UTF8 and
547 // - there are non-ascii chars in the text,
548 // we try to work round that...
549 // The following code might be better for mb_string enabled installs, but
550 // makes the lib about 200% slower...
551 //if (!is_valid_charset($reqEncoding, array('UTF-8')))
552 if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
553 if ($reqEncoding == 'ISO-8859-1') {
554 $data = utf8_encode($data);
556 if (extension_loaded('mbstring')) {
557 $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding);
559 $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding);
565 // PHP internally might use ISO-8859-1, so we have to tell the xml parser to give us back data in the expected charset.
566 // What if internal encoding is not in one of the 3 allowed? We use the broadest one, ie. utf8
567 // This allows to send data which is native in various charset,
568 // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
569 if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
570 /// @todo emit a warning
571 $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
573 $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
576 $xmlRpcParser = $this->getParser();
577 $xmlRpcParser->parse($data, $this->functions_parameters_type, XMLParser::ACCEPT_REQUEST, $options);
578 if ($xmlRpcParser->_xh['isf'] > 2) {
579 // (BC) we return XML error as a faultCode
580 preg_match('/^XML error ([0-9]+)/', $xmlRpcParser->_xh['isf_reason'], $matches);
582 PhpXmlRpc::$xmlrpcerrxml + $matches[1],
583 $xmlRpcParser->_xh['isf_reason']);
584 } elseif ($xmlRpcParser->_xh['isf']) {
586 PhpXmlRpc::$xmlrpcerr['invalid_request'],
587 PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
589 // small layering violation in favor of speed and memory usage:
590 // we should allow the 'execute' method handle this, but in the
591 // most common scenario (xmlrpc values type server with some methods
592 // registered as phpvals) that would mean a useless encode+decode pass
593 if ($this->functions_parameters_type != 'xmlrpcvals' ||
594 (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) &&
595 ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] != 'xmlrpcvals')
598 if ($this->debug > 1) {
599 $this->debugmsg("\n+++PARSED+++\n" . var_export($xmlRpcParser->_xh['params'], true) . "\n+++END+++");
601 $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']);
603 // build a Request object with data parsed from xml
604 $req = new Request($xmlRpcParser->_xh['method']);
605 // now add parameters in
606 for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
607 $req->addParam($xmlRpcParser->_xh['params'][$i]);
610 if ($this->debug > 1) {
611 $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++");
613 $r = $this->execute($req);
621 * Execute a method invoked by the client, checking parameters used.
623 * @param Request|string $req either a Request obj or a method name
624 * @param mixed[] $params array with method parameters as php types (only if m is method name)
625 * @param string[] $paramTypes array with xmlrpc types of method parameters (only if m is method name)
629 * @throws \Exception in case the executed method does throw an exception (and depending on server configuration)
631 protected function execute($req, $params = null, $paramTypes = null)
633 static::$_xmlrpcs_occurred_errors = '';
634 static::$_xmlrpc_debuginfo = '';
636 if (is_object($req)) {
637 $methName = $req->method();
641 $sysCall = $this->isSyscall($methName);
642 $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
644 if (!isset($dmap[$methName]['function'])) {
646 return new Response(0,
647 PhpXmlRpc::$xmlrpcerr['unknown_method'],
648 PhpXmlRpc::$xmlrpcstr['unknown_method']);
652 if (isset($dmap[$methName]['signature'])) {
653 $sig = $dmap[$methName]['signature'];
654 if (is_object($req)) {
655 list($ok, $errStr) = $this->verifySignature($req, $sig);
657 list($ok, $errStr) = $this->verifySignature($paramTypes, $sig);
663 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
664 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errStr}"
669 $func = $dmap[$methName]['function'];
670 // let the 'class::function' syntax be accepted in dispatch maps
671 if (is_string($func) && strpos($func, '::')) {
672 $func = explode('::', $func);
675 if (is_array($func)) {
676 if (is_object($func[0])) {
677 $funcName = get_class($func[0]) . '->' . $func[1];
679 $funcName = implode('::', $func);
681 } else if ($func instanceof \Closure) {
682 $funcName = 'Closure';
687 // verify that function to be invoked is in fact callable
688 if (!is_callable($func)) {
689 $this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable");
692 PhpXmlRpc::$xmlrpcerr['server_error'],
693 PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method"
697 // If debug level is 3, we should catch all errors generated during
698 // processing of user function, and log them as part of response
699 if ($this->debug > 2) {
700 self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'));
704 // Allow mixed-convention servers
705 if (is_object($req)) {
707 $r = call_user_func($func, $this, $req);
709 $r = call_user_func($func, $req);
711 if (!is_a($r, 'PhpXmlRpc\Response')) {
712 $this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler does not return an xmlrpc response object but a " . gettype($r));
713 if (is_a($r, 'PhpXmlRpc\Value')) {
714 $r = new Response($r);
718 PhpXmlRpc::$xmlrpcerr['server_error'],
719 PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response object"
724 // call a 'plain php' function
726 array_unshift($params, $this);
727 $r = call_user_func_array($func, $params);
729 // 3rd API convention for method-handling functions: EPI-style
730 if ($this->functions_parameters_type == 'epivals') {
731 $r = call_user_func_array($func, array($methName, $params, $this->user_data));
732 // mimic EPI behaviour: if we get an array that looks like an error, make it
734 if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) {
735 $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']);
737 // functions using EPI api should NOT return resp objects,
738 // so make sure we encode the return type correctly
739 $encoder = new Encoder();
740 $r = new Response($encoder->encode($r, array('extension_api')));
743 $r = call_user_func_array($func, $params);
746 // the return type can be either a Response object or a plain php value...
747 if (!is_a($r, '\PhpXmlRpc\Response')) {
748 // what should we assume here about automatic encoding of datetimes
749 // and php classes instances???
750 $encoder = new Encoder();
751 $r = new Response($encoder->encode($r, $this->phpvals_encoding_options));
754 } catch (\Exception $e) {
755 // (barring errors in the lib) an uncatched exception happened
756 // in the called function, we wrap it in a proper error-response
757 switch ($this->exception_handling) {
759 if ($this->debug > 2) {
760 if (self::$_xmlrpcs_prev_ehandler) {
761 set_error_handler(self::$_xmlrpcs_prev_ehandler);
763 restore_error_handler();
768 $r = new Response(0, $e->getCode(), $e->getMessage());
771 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']);
774 if ($this->debug > 2) {
775 // note: restore the error handler we found before calling the
776 // user func, even if it has been changed inside the func itself
777 if (self::$_xmlrpcs_prev_ehandler) {
778 set_error_handler(self::$_xmlrpcs_prev_ehandler);
780 restore_error_handler();
788 * Add a string to the 'internal debug message' (separate from 'user debug message').
790 * @param string $string
792 protected function debugmsg($string)
794 $this->debug_info .= $string . "\n";
798 * @param string $charsetEncoding
801 protected function xml_header($charsetEncoding = '')
803 if ($charsetEncoding != '') {
804 return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
806 return "<?xml version=\"1.0\"?" . ">\n";
811 * @param string $methName
814 protected function isSyscall($methName)
816 return (strpos($methName, "system.") === 0);
822 public function getDispatchMap()
830 public function getSystemDispatchMap()
832 if (!$this->allow_system_funcs) {
837 'system.listMethods' => array(
838 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods',
839 // listMethods: signature was either a string, or nothing.
840 // The useless string variant has been removed
841 'signature' => array(array(Value::$xmlrpcArray)),
842 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch',
843 'signature_docs' => array(array('list of method names')),
845 'system.methodHelp' => array(
846 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp',
847 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)),
848 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string',
849 'signature_docs' => array(array('method description', 'name of the method to be described')),
851 'system.methodSignature' => array(
852 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature',
853 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)),
854 '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)',
855 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')),
857 'system.multicall' => array(
858 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall',
859 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)),
860 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details',
861 '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"')),
863 'system.getCapabilities' => array(
864 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities',
865 'signature' => array(array(Value::$xmlrpcStruct)),
866 'docstring' => 'This method lists all the capabilities that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to',
867 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')),
872 /* Functions that implement system.XXX methods of xmlrpc servers */
877 public function getCapabilities()
880 // xmlrpc spec: always supported
882 'specUrl' => 'http://www.xmlrpc.com/spec',
885 // if we support system.xxx functions, we always support multicall, too...
886 // Note that, as of 2006/09/17, the following URL does not respond anymore
887 'system.multicall' => array(
888 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
891 // introspection: version 2! we support 'mixed', too
892 'introspection' => array(
893 'specUrl' => 'http://phpxmlrpc.sourceforge.net/doc-2/ch10.html',
899 if (PhpXmlRpc::$xmlrpc_null_extension) {
900 $outAr['nil'] = array(
901 'specUrl' => 'http://www.ontosys.com/xml-rpc/extensions.php',
910 * @param Server $server
911 * @param Request $req
914 public static function _xmlrpcs_getCapabilities($server, $req = null)
916 $encoder = new Encoder();
917 return new Response($encoder->encode($server->getCapabilities()));
921 * @param Server $server
922 * @param Request $req if called in plain php values mode, second param is missing
925 public static function _xmlrpcs_listMethods($server, $req = null)
928 foreach ($server->dmap as $key => $val) {
929 $outAr[] = new Value($key, 'string');
931 foreach ($server->getSystemDispatchMap() as $key => $val) {
932 $outAr[] = new Value($key, 'string');
935 return new Response(new Value($outAr, 'array'));
939 * @param Server $server
940 * @param Request $req
943 public static function _xmlrpcs_methodSignature($server, $req)
945 // let accept as parameter both an xmlrpc value or string
946 if (is_object($req)) {
947 $methName = $req->getParam(0);
948 $methName = $methName->scalarval();
952 if ($server->isSyscall($methName)) {
953 $dmap = $server->getSystemDispatchMap();
955 $dmap = $server->dmap;
957 if (isset($dmap[$methName])) {
958 if (isset($dmap[$methName]['signature'])) {
960 foreach ($dmap[$methName]['signature'] as $inSig) {
962 foreach ($inSig as $sig) {
963 $curSig[] = new Value($sig, 'string');
965 $sigs[] = new Value($curSig, 'array');
967 $r = new Response(new Value($sigs, 'array'));
969 // NB: according to the official docs, we should be returning a
970 // "none-array" here, which means not-an-array
971 $r = new Response(new Value('undef', 'string'));
974 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
981 * @param Server $server
982 * @param Request $req
985 public static function _xmlrpcs_methodHelp($server, $req)
987 // let accept as parameter both an xmlrpc value or string
988 if (is_object($req)) {
989 $methName = $req->getParam(0);
990 $methName = $methName->scalarval();
994 if ($server->isSyscall($methName)) {
995 $dmap = $server->getSystemDispatchMap();
997 $dmap = $server->dmap;
999 if (isset($dmap[$methName])) {
1000 if (isset($dmap[$methName]['docstring'])) {
1001 $r = new Response(new Value($dmap[$methName]['docstring'], 'string'));
1003 $r = new Response(new Value('', 'string'));
1006 $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
1012 public static function _xmlrpcs_multicall_error($err)
1014 if (is_string($err)) {
1015 $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
1016 $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"];
1018 $code = $err->faultCode();
1019 $str = $err->faultString();
1022 $struct['faultCode'] = new Value($code, 'int');
1023 $struct['faultString'] = new Value($str, 'string');
1025 return new Value($struct, 'struct');
1029 * @param Server $server
1030 * @param Value $call
1033 public static function _xmlrpcs_multicall_do_call($server, $call)
1035 if ($call->kindOf() != 'struct') {
1036 return static::_xmlrpcs_multicall_error('notstruct');
1038 $methName = @$call['methodName'];
1040 return static::_xmlrpcs_multicall_error('nomethod');
1042 if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') {
1043 return static::_xmlrpcs_multicall_error('notstring');
1045 if ($methName->scalarval() == 'system.multicall') {
1046 return static::_xmlrpcs_multicall_error('recursion');
1049 $params = @$call['params'];
1051 return static::_xmlrpcs_multicall_error('noparams');
1053 if ($params->kindOf() != 'array') {
1054 return static::_xmlrpcs_multicall_error('notarray');
1057 $req = new Request($methName->scalarval());
1058 foreach($params as $i => $param) {
1059 if (!$req->addParam($param)) {
1060 $i++; // for error message, we count params from 1
1061 return static::_xmlrpcs_multicall_error(new Response(0,
1062 PhpXmlRpc::$xmlrpcerr['incorrect_params'],
1063 PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
1067 $result = $server->execute($req);
1069 if ($result->faultCode() != 0) {
1070 return static::_xmlrpcs_multicall_error($result); // Method returned fault.
1073 return new Value(array($result->value()), 'array');
1077 * @param Server $server
1078 * @param Value $call
1081 public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
1083 if (!is_array($call)) {
1084 return static::_xmlrpcs_multicall_error('notstruct');
1086 if (!array_key_exists('methodName', $call)) {
1087 return static::_xmlrpcs_multicall_error('nomethod');
1089 if (!is_string($call['methodName'])) {
1090 return static::_xmlrpcs_multicall_error('notstring');
1092 if ($call['methodName'] == 'system.multicall') {
1093 return static::_xmlrpcs_multicall_error('recursion');
1095 if (!array_key_exists('params', $call)) {
1096 return static::_xmlrpcs_multicall_error('noparams');
1098 if (!is_array($call['params'])) {
1099 return static::_xmlrpcs_multicall_error('notarray');
1102 // this is a simplistic hack, since we might have received
1103 // base64 or datetime values, but they will be listed as strings here...
1105 $wrapper = new Wrapper();
1106 foreach ($call['params'] as $val) {
1107 // support EPI-encoded base64 and datetime values
1108 if ($val instanceof \stdClass && isset($val->xmlrpc_type)) {
1109 $pt[] = $val->xmlrpc_type == 'datetime' ? Value::$xmlrpcDateTime : $val->xmlrpc_type;
1111 $pt[] = $wrapper->php2XmlrpcType(gettype($val));
1115 $result = $server->execute($call['methodName'], $call['params'], $pt);
1117 if ($result->faultCode() != 0) {
1118 return static::_xmlrpcs_multicall_error($result); // Method returned fault.
1121 return new Value(array($result->value()), 'array');
1125 * @param Server $server
1126 * @param Request|array $req
1129 public static function _xmlrpcs_multicall($server, $req)
1132 // let accept a plain list of php parameters, beside a single xmlrpc msg object
1133 if (is_object($req)) {
1134 $calls = $req->getParam(0);
1135 foreach($calls as $call) {
1136 $result[] = static::_xmlrpcs_multicall_do_call($server, $call);
1139 $numCalls = count($req);
1140 for ($i = 0; $i < $numCalls; $i++) {
1141 $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]);
1145 return new Response(new Value($result, 'array'));
1149 * Error handler used to track errors that occur during server-side execution of PHP code.
1150 * This allows to report back to the client whether an internal error has occurred or not
1151 * using an xmlrpc response object, instead of letting the client deal with the html junk
1152 * that a PHP execution error on the server generally entails.
1154 * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
1156 public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = null, $lineNo = null, $context = null)
1158 // obey the @ protocol
1159 if (error_reporting() == 0) {
1163 //if($errCode != E_NOTICE && $errCode != E_WARNING && $errCode != E_USER_NOTICE && $errCode != E_USER_WARNING)
1164 if ($errCode != E_STRICT) {
1165 \PhpXmlRpc\Server::error_occurred($errString);
1167 // Try to avoid as much as possible disruption to the previous error handling
1168 // mechanism in place
1169 if (self::$_xmlrpcs_prev_ehandler == '') {
1170 // The previous error handler was the default: all we should do is log error
1171 // to the default error log (if level high enough)
1172 if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) {
1173 if (self::$logger === null) {
1174 self::$logger = Logger::instance();
1176 self::$logger->errorLog($errString);
1179 // Pass control on to previous error handler, trying to avoid loops...
1180 if (self::$_xmlrpcs_prev_ehandler != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) {
1181 if (is_array(self::$_xmlrpcs_prev_ehandler)) {
1182 // the following works both with static class methods and plain object methods as error handler
1183 call_user_func_array(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context));
1185 $method = self::$_xmlrpcs_prev_ehandler;
1186 $method($errCode, $errString, $filename, $lineNo, $context);