Fix: allow library to receive calls/responses where LATIN-1 charset is set in http...
[plcapi.git] / lib / xmlrpc.inc
index a4c9ef2..a1d0ca8 100644 (file)
@@ -1,7 +1,6 @@
 <?php\r
 // by Edd Dumbill (C) 1999-2002\r
 // <edd@usefulinc.com>\r
-// $Id: xmlrpc.inc,v 1.174 2009/03/16 19:36:38 ggiunta Exp $\r
 \r
 // Copyright (c) 1999,2000,2002 Edd Dumbill.\r
 // All rights reserved.\r
        $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';\r
 \r
        $GLOBALS['xmlrpcName']='XML-RPC for PHP';\r
-       $GLOBALS['xmlrpcVersion']='3.0.0.beta';\r
+       $GLOBALS['xmlrpcVersion']='3.0.0';\r
 \r
        // let user errors start at 800\r
        $GLOBALS['xmlrpcerruser']=800;\r
 \r
        // set to TRUE to enable encoding of php NULL values to <EX:NIL/> instead of <NIL/>\r
        $GLOBALS['xmlrpc_null_apache_encoding']=false;\r
+       $GLOBALS['xmlrpc_null_apache_encoding_ns']='http://ws.apache.org/xmlrpc/namespaces/extensions';\r
 \r
        // used to store state during parsing\r
        // quick explanation of components:\r
                                else\r
                                {\r
                                        $GLOBALS['_xh']['rt'] = strtolower($name);\r
+                                       $GLOBALS['_xh']['rt'] = strtolower($name);\r
                                }\r
                        }\r
                        else\r
                var $proxy_pass='';\r
                var $proxy_authtype=1;\r
                var $cookies=array();\r
+               var $extracurlopts=array();\r
+\r
                /**\r
                * List of http compression methods accepted by the client for responses.\r
                * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib\r
                * http://curl.haxx.se/docs/faq.html#7.3)\r
                */\r
                var $xmlrpc_curl_handle = null;\r
-               /// Wheter to use persistent connections for http 1.1 and https\r
+               /// Whether to use persistent connections for http 1.1 and https\r
                var $keepalive = false;\r
                /// Charset encodings that can be decoded without problems by the client\r
                var $accepted_charset_encodings = array();\r
                * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'\r
                */\r
                var $return_type = 'xmlrpcvals';\r
+               /**\r
+               * Sent to servers in http headers\r
+               */\r
+               var $user_agent;\r
 \r
                /**\r
                * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php\r
                                $this->accepted_compression = array('gzip', 'deflate');\r
                        }\r
 \r
-                       // keepalives: enabled by default ONLY for PHP >= 4.3.8\r
+                       // keepalives: enabled by default\r
                        $this->keepalive = true;\r
 \r
                        // by default the xml parser can support these 3 charset encodings\r
                        $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');\r
+\r
+                       // initialize user_agent string\r
+                       $this->user_agent = $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'];\r
                }\r
 \r
                /**\r
                * Enables/disables the echoing to screen of the xmlrpc responses received\r
-               * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)\r
+               * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)\r
                * @access public\r
                */\r
                function setDebug($in)\r
 \r
                /**\r
                * Add a CA certificate to verify server with (see man page about\r
-               * CURLOPT_CAINFO for more details\r
+               * CURLOPT_CAINFO for more details)\r
                * @param string $cacert certificate file name (or dir holding certificates)\r
                * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false\r
                * @access public\r
                        if ($compmethod == 'any')\r
                                $this->accepted_compression = array('gzip', 'deflate');\r
                        else\r
-                               $this->accepted_compression = array($compmethod);\r
+                               if ($compmethod == false )\r
+                                       $this->accepted_compression = array();\r
+                               else\r
+                                       $this->accepted_compression = array($compmethod);\r
                }\r
 \r
                /**\r
                        }\r
                }\r
 \r
+               /**\r
+               * Directly set cURL options, for extra flexibility\r
+               * It allows eg. to bind client to a specific IP interface / address\r
+               * @param array $options\r
+               */\r
+               function SetCurlOptions( $options )\r
+               {\r
+                       $this->extracurlopts = $options;\r
+               }\r
+\r
+               /**\r
+               * Set user-agent string that will be used by this client instance\r
+               * in http headers sent to the server\r
+               */\r
+               function SetUserAgent( $agentstring )\r
+               {\r
+                       $this->user_agent = $agentstring;\r
+               }\r
+\r
                /**\r
                * Send an xmlrpc request\r
                * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request\r
                                $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";\r
                                if ($authtype != 1)\r
                                {\r
-                                       error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');\r
+                                       error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0');\r
                                }\r
                        }\r
 \r
                                {\r
                                        if ($proxyauthtype != 1)\r
                                        {\r
-                                               error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');\r
+                                               error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0');\r
                                        }\r
                                        $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";\r
                                }\r
                                $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";\r
                        }\r
 \r
+                       // omit port if 80\r
+                       $port = ($port == 80) ? '' : (':' . $port);\r
+\r
                        $op= 'POST ' . $uri. " HTTP/1.0\r\n" .\r
-                               'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" .\r
-                               'Host: '. $server . ':' . $port . "\r\n" .\r
+                               'User-Agent: ' . $this->user_agent . "\r\n" .\r
+                               'Host: '. $server . $port . "\r\n" .\r
                                $credentials .\r
                                $proxy_credentials .\r
                                $accepted_encoding .\r
 \r
                        if(!fputs($fp, $op, strlen($op)))\r
                        {\r
-                       fclose($fp);\r
+                               fclose($fp);\r
                                $this->errstr='Write error';\r
                                $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);\r
                                return $r;\r
                        }\r
                        else\r
                        {\r
-                               // reset errno and errstr on succesful socket connection\r
+                               // reset errno and errstr on successful socket connection\r
                                $this->errstr = '';\r
                        }\r
                        // G. Giunta 2005/10/24: close socket before parsing.\r
-                       // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)\r
+                       // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)\r
                        $ipd='';\r
                        do\r
                        {\r
                        {\r
                                curl_setopt($curl, CURLOPT_VERBOSE, 1);\r
                        }\r
-                       curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);\r
+                       curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);\r
                        // required for XMLRPC: post the data\r
                        curl_setopt($curl, CURLOPT_POST, 1);\r
                        // the data\r
                        // return the header too\r
                        curl_setopt($curl, CURLOPT_HEADER, 1);\r
 \r
-                       // will only work with PHP >= 5.0\r
                        // NB: if we set an empty string, CURL will add http header indicating\r
                        // ALL methods it is supporting. This is possibly a better option than\r
                        // letting the user tell what curl can / cannot do...\r
                                }\r
                                else if ($authtype != 1)\r
                                {\r
-                                       error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');\r
+                                       error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install');\r
                                }\r
                        }\r
 \r
                                {\r
                                        curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);\r
                                }\r
+\r
+                               // Upgrade transparently to more stringent check for versions of php which do not support otherwise.\r
+                               // Doing it in constructor would be cleaner; doing it here saves us a couple of function calls\r
+                               if($this->verifyhost == 1 && $info = curl_version() && version_compare($info['version'], '7.28.1') >= 0)\r
+                               {\r
+                                       $this->verifyhost = 2;\r
+                               }\r
                                // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used\r
                                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);\r
                        }\r
                                        }\r
                                        else if ($proxyauthtype != 1)\r
                                        {\r
-                                               error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');\r
+                                               error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install');\r
                                        }\r
                                }\r
                        }\r
                                curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));\r
                        }\r
 \r
+                       foreach ($this->extracurlopts as $opt => $val)\r
+                       {\r
+                               curl_setopt($curl, $opt, $val);\r
+                       }\r
+\r
                        $result = curl_exec($curl);\r
 \r
                        if ($this->debug > 1)\r
                        {\r
                                print "<PRE>\n---CURL INFO---\n";\r
                                foreach(curl_getinfo($curl) as $name => $val)\r
-                                        print $name . ': ' . htmlentities($val). "\n";\r
+                               {\r
+                                       if (is_array($val))\r
+                                       {\r
+                                               $val = implode("\n", $val);\r
+                                       }\r
+                                       print $name . ': ' . htmlentities($val) . "\n";\r
+                               }\r
+\r
                                print "---END---\n</PRE>";\r
                        }\r
 \r
                                        curl_close($curl);\r
                                }\r
                                $resp =& $msg->parseResponse($result, true, $this->return_type);\r
+                               // if we got back a 302, we can not reuse the curl handle for later calls\r
+                               if($resp->faultCode() == $GLOBALS['xmlrpcerr']['http_error'] && $keepalive)\r
+                               {\r
+                                       curl_close($curl);\r
+                                       $this->xmlrpc_curl_handle = null;\r
+                               }\r
                        }\r
                        return $resp;\r
                }\r
                * @param array $msgs an array of xmlrpcmsg objects\r
                * @param integer $timeout connection timeout (in seconds)\r
                * @param string $method the http protocol variant to be used\r
-               * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted\r
+               * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted\r
                * @return array\r
                * @access public\r
                */\r
                * with attributes being e.g. 'expires', 'path', domain'.\r
                * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)\r
                * are still present in the array. It is up to the user-defined code to decide\r
-               * how to use the received cookies, and wheter they have to be sent back with the next\r
+               * how to use the received cookies, and whether they have to be sent back with the next\r
                * request to the server (using xmlrpc_client::setCookie) or not\r
                * @return array array of cookies received from the server\r
                * @access public\r
                                $this->content_type = 'text/xml; charset=' . $charset_encoding;\r
                        else\r
                                $this->content_type = 'text/xml';\r
+                       if ($GLOBALS['xmlrpc_null_apache_encoding'])\r
+                       {\r
+                               $result = "<methodResponse xmlns:ex=\"".$GLOBALS['xmlrpc_null_apache_encoding_ns']."\">\n";\r
+                       }\r
+                       else\r
+                       {\r
                        $result = "<methodResponse>\n";\r
+                       }\r
                        if($this->errno)\r
                        {\r
                                // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients\r
@@ -2055,7 +2121,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
 \r
                /**\r
                * @param string $meth the name of the method to invoke\r
-               * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)\r
+               * @param array $pars array of parameters to be passed to the method (xmlrpcval objects)\r
                */\r
                function xmlrpcmsg($meth, $pars=0)\r
                {\r
@@ -2110,7 +2176,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        else\r
                                $this->content_type = 'text/xml';\r
                        $this->payload=$this->xml_header($charset_encoding);\r
-                       $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";\r
+                       $this->payload.='<methodName>' . xmlrpc_encode_entitites($this->methodname, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</methodName>\n";\r
                        $this->payload.="<params>\n";\r
                        for($i=0; $i<count($this->params); $i++)\r
                        {\r
@@ -2139,6 +2205,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
 \r
                /**\r
                * Returns xml representation of the message. XML prologue included\r
+               * @param string $charset_encoding\r
                * @return string the xml representation of the message, xml prologue included\r
                * @access public\r
                */\r
@@ -2187,11 +2254,12 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                * Given an open file handle, read all data available and parse it as axmlrpc response.\r
                * NB: the file handle is not closed by this function.\r
                * NNB: might have trouble in rare cases to work on network streams, as we\r
-        *      check for a read of 0 bytes instead of feof($fp).\r
+               *      check for a read of 0 bytes instead of feof($fp).\r
                *      But since checking for feof(null) returns false, we would risk an\r
                *      infinite loop in that case, because we cannot trust the caller\r
                *      to give us a valid pointer to an open file...\r
                * @access public\r
+               * @param resource $fp stream pointer\r
                * @return xmlrpcresp\r
                * @todo add 2nd & 3rd param to be passed to ParseResponse() ???\r
                */\r
@@ -2244,7 +2312,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                        }\r
                                        else\r
                                        {\r
-                                               error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed');\r
+                                               error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');\r
                                                $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');\r
                                                return $r;\r
                                        }\r
@@ -2265,7 +2333,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))\r
                                {\r
                                        $errstr= substr($data, 0, strpos($data, "\n")-1);\r
-                                       error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);\r
+                                       error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);\r
                                        $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');\r
                                        return $r;\r
                                }\r
@@ -2390,7 +2458,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                        {\r
                                                if(!$data = decode_chunked($data))\r
                                                {\r
-                                                       error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');\r
+                                                       error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');\r
                                                        $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);\r
                                                        return $r;\r
                                                }\r
@@ -2420,14 +2488,14 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                                                }\r
                                                                else\r
                                                                {\r
-                                                                       error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');\r
+                                                                       error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');\r
                                                                        $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);\r
                                                                        return $r;\r
                                                                }\r
                                                        }\r
                                                        else\r
                                                        {\r
-                                                               error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');\r
+                                                               error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');\r
                                                                $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);\r
                                                                return $r;\r
                                                        }\r
@@ -2435,7 +2503,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                        }\r
                                } // end of 'if needed, de-chunk, re-inflate response'\r
 \r
-                               // real stupid hack to avoid PHP complaining about returning NULL by ref\r
+                               // real stupid hack to avoid PHP complaining about returning NULL by ref\r
                                $r = null;\r
                                $r =& $r;\r
                                return $r;\r
@@ -2459,7 +2527,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
 \r
                        if($data == '')\r
                        {\r
-                               error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');\r
+                               error_log('XML-RPC: '.__METHOD__.': no response received from server.');\r
                                $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);\r
                                return $r;\r
                        }\r
@@ -2504,17 +2572,10 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
 \r
                        // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)\r
                        // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib\r
-                       $bd = false;\r
-                       // Poor man's version of strrpos for php 4...\r
-                       $pos = strpos($data, '</methodResponse>');\r
-                       while($pos || is_int($pos))\r
+                       $pos = strrpos($data, '</methodResponse>');\r
+                       if($pos !== false)\r
                        {\r
-                               $bd = $pos+17;\r
-                               $pos = strpos($data, '</methodResponse>', $bd);\r
-                       }\r
-                       if($bd)\r
-                       {\r
-                               $data = substr($data, 0, $bd);\r
+                               $data = substr($data, 0, $pos+17);\r
                        }\r
 \r
                        // if user wants back raw xml, give it to him\r
@@ -2538,17 +2599,24 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        $GLOBALS['_xh']['isf_reason']='';\r
                        $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'\r
 \r
-                       // if response charset encoding is not known / supported, try to use\r
-                       // the default encoding and parse the xml anyway, but log a warning...\r
-                       if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       // the following code might be better for mb_string enabled installs, but\r
+                       // Since parsing will fail if charset is not specified in the xml prologue,\r
+                       // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...\r
+                       // The following code might be better for mb_string enabled installs, but\r
                        // makes the lib about 200% slower...\r
-                       //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       {\r
-                               error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);\r
-                               $resp_encoding = $GLOBALS['xmlrpc_defencoding'];\r
+                       //if (!is_valid_charset($resp_encoding, array('UTF-8')))\r
+                       if (!in_array($resp_encoding, array('UTF-8', 'US-ASCII')) && !has_encoding($data)) {\r
+                               if ($resp_encoding == 'ISO-8859-1') {\r
+                                       $data = utf8_encode($data);\r
+                               } else {\r
+                                       if (extension_loaded('mbstring')) {\r
+                                               $data = mb_convert_encoding($data, 'UTF-8', $resp_encoding);\r
+                                       } else {\r
+                                               error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $resp_encoding);\r
+                                       }\r
+                               }\r
                        }\r
-                       $parser = xml_parser_create($resp_encoding);\r
+\r
+                       $parser = xml_parser_create();\r
                        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
                        // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell\r
                        // the xml parser to give us back data in the expected charset.\r
@@ -2720,7 +2788,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                                $this->me['struct']=$val;\r
                                                break;\r
                                        default:\r
-                                               error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");\r
+                                               error_log("XML-RPC: ".__METHOD__.": not a known type ($type)");\r
                                }\r
                                /*if($type=='')\r
                                {\r
@@ -2752,13 +2820,13 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        $typeof=@$GLOBALS['xmlrpcTypes'][$type];\r
                        if($typeof!=1)\r
                        {\r
-                               error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");\r
+                               error_log("XML-RPC: ".__METHOD__.": not a scalar type ($type)");\r
                                return 0;\r
                        }\r
 \r
                        // coerce booleans into correct values\r
-                       // NB: we should iether do it for datetimes, integers and doubles, too,\r
-                       // or just plain remove this check, implemnted on booleans only...\r
+                       // NB: we should either do it for datetimes, integers and doubles, too,\r
+                       // or just plain remove this check, implemented on booleans only...\r
                        if($type==$GLOBALS['xmlrpcBoolean'])\r
                        {\r
                                if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))\r
@@ -2774,10 +2842,10 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        switch($this->mytype)\r
                        {\r
                                case 1:\r
-                                       error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');\r
+                                       error_log('XML-RPC: '.__METHOD__.': scalar xmlrpcval can have only one value');\r
                                        return 0;\r
                                case 3:\r
-                                       error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');\r
+                                       error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval');\r
                                        return 0;\r
                                case 2:\r
                                        // we're adding a scalar value to an array here\r
@@ -2819,7 +2887,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        }\r
                        else\r
                        {\r
-                               error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']');\r
+                               error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');\r
                                return 0;\r
                        }\r
                }\r
@@ -2848,7 +2916,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                        }\r
                        else\r
                        {\r
-                               error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']');\r
+                               error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');\r
                                return 0;\r
                        }\r
                }\r
@@ -2920,22 +2988,41 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                                        $rs.="<${typ}>".(int)$val."</${typ}>";\r
                                                        break;\r
                                                case $GLOBALS['xmlrpcDouble']:\r
-                                               // avoid using standard conversion of float to string because it is locale-dependent,\r
-                                               // and also because the xmlrpc spec forbids exponential notation\r
-                                               // sprintf('%F') would be most likely ok but it is only available since PHP 4.3.10 and PHP 5.0.3.\r
-                                               // The code below tries its best at keeping max precision while avoiding exp notation,\r
-                                               // but there is of course no limit in the number of decimal places to be used...\r
-                                               $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";\r
+                                                       // avoid using standard conversion of float to string because it is locale-dependent,\r
+                                                       // and also because the xmlrpc spec forbids exponential notation.\r
+                                                       // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.\r
+                                                       // The code below tries its best at keeping max precision while avoiding exp notation,\r
+                                                       // but there is of course no limit in the number of decimal places to be used...\r
+                                                       $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";\r
+                                                       break;\r
+                                               case $GLOBALS['xmlrpcDateTime']:\r
+                                                       if (is_string($val))\r
+                                                       {\r
+                                                               $rs.="<${typ}>${val}</${typ}>";\r
+                                                       }\r
+                                                       else if(is_a($val, 'DateTime'))\r
+                                                       {\r
+                                                               $rs.="<${typ}>".$val->format('Ymd\TH:i:s')."</${typ}>";\r
+                                                       }\r
+                                                       else if(is_int($val))\r
+                                                       {\r
+                                                               $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val)."</${typ}>";\r
+                                                       }\r
+                                                       else\r
+                                                       {\r
+                                                               // not really a good idea here: but what shall we output anyway? left for backward compat...\r
+                                                               $rs.="<${typ}>${val}</${typ}>";\r
+                                                       }\r
                                                        break;\r
                                                case $GLOBALS['xmlrpcNull']:\r
-                                                   if ($GLOBALS['xmlrpc_null_apache_encoding'])\r
-                                                   {\r
-                                                       $rs.="<ex:nil/>";\r
-                                                   }\r
-                                                   else\r
-                            {\r
-                                $rs.="<nil/>";\r
-                            }\r
+                                                       if ($GLOBALS['xmlrpc_null_apache_encoding'])\r
+                                                       {\r
+                                                               $rs.="<ex:nil/>";\r
+                                                       }\r
+                                                       else\r
+                                                       {\r
+                                                               $rs.="<nil/>";\r
+                                                       }\r
                                                        break;\r
                                                default:\r
                                                        // no standard type value should arrive here, but provide a possibility\r
@@ -3009,7 +3096,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                }\r
 \r
                /**\r
-               * Checks wheter a struct member with a given name is present.\r
+               * Checks whether a struct member with a given name is present.\r
                * Works only on xmlrpcvals of type struct.\r
                * @param string $m the name of the struct member to be looked up\r
                * @return boolean\r
@@ -3235,7 +3322,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
        * @author Dan Libby (dan@libby.com)\r
        *\r
        * @param xmlrpcval $xmlrpc_val\r
-       * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects\r
+       * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is\r
        * @return mixed\r
        */\r
        function php_xmlrpc_decode($xmlrpc_val, $options=array())\r
@@ -3262,6 +3349,27 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                                        return $xmlrpc_val->scalarval();\r
                                        }\r
                                }\r
+                               if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601')\r
+                               {\r
+                                       // we return a Datetime object instead of a string\r
+                                       // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes,\r
+                                       // we cater to all 3 cases here\r
+                                       $out = $xmlrpc_val->scalarval();\r
+                                       if (is_string($out))\r
+                                       {\r
+                                               $out = strtotime($out);\r
+                                       }\r
+                                       if (is_int($out))\r
+                                       {\r
+                                               $result = new Datetime();\r
+                                               $result->setTimestamp($out);\r
+                                               return $result;\r
+                                       }\r
+                                       elseif (is_a($out, 'Datetime'))\r
+                                       {\r
+                                               return $out;\r
+                                       }\r
+                               }\r
                                return $xmlrpc_val->scalarval();\r
                        case 'array':\r
                                $size = $xmlrpc_val->arraysize();\r
@@ -3336,7 +3444,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
        * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'\r
        * @return xmlrpcval\r
        */\r
-       function &php_xmlrpc_encode($php_val, $options=array())\r
+       function php_xmlrpc_encode($php_val, $options=array())\r
        {\r
                $type = gettype($php_val);\r
                switch($type)\r
@@ -3370,7 +3478,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                $ko = false;\r
                                foreach($php_val as $key => $val)\r
                                {\r
-                                       $arr[$key] =& php_xmlrpc_encode($val, $options);\r
+                                       $arr[$key] = php_xmlrpc_encode($val, $options);\r
                                        if(!$ko && $key !== $j)\r
                                        {\r
                                                $ko = true;\r
@@ -3391,9 +3499,14 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                {\r
                                        $xmlrpc_val = $php_val;\r
                                }\r
+                               else if(is_a($php_val, 'DateTime'))\r
+                               {\r
+                                       $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $GLOBALS['xmlrpcStruct']);\r
+                               }\r
                                else\r
                                {\r
                                        $arr = array();\r
+                                       reset($php_val);\r
                                        while(list($k,$v) = each($php_val))\r
                                        {\r
                                                $arr[$k] = php_xmlrpc_encode($v, $options);\r
@@ -3460,8 +3573,28 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                $GLOBALS['_xh']['isf_reason'] = '';\r
                $GLOBALS['_xh']['method'] = false;\r
                $GLOBALS['_xh']['rt'] = '';\r
-               /// @todo 'guestimate' encoding\r
-               $parser = xml_parser_create();\r
+\r
+               // 'guestimate' encoding\r
+               $val_encoding = guess_encoding('', $xml_val);\r
+\r
+               // Since parsing will fail if charset is not specified in the xml prologue,\r
+               // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...\r
+               // The following code might be better for mb_string enabled installs, but\r
+               // makes the lib about 200% slower...\r
+               //if (!is_valid_charset($val_encoding, array('UTF-8')))\r
+               if (!in_array($val_encoding, array('UTF-8', 'US-ASCII')) && !has_encoding($xml_val)) {\r
+                       if ($val_encoding == 'ISO-8859-1') {\r
+                               $xml_val = utf8_encode($xml_val);\r
+                       } else {\r
+                               if (extension_loaded('mbstring')) {\r
+                                       $xml_val = mb_convert_encoding($xml_val, 'UTF-8', $val_encoding);\r
+                               } else {\r
+                                       error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $val_encoding);\r
+                               }\r
+                       }\r
+               }\r
+\r
+        $parser = xml_parser_create();\r
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
                // What if internal encoding is not in one of the 3 allowed?\r
                // we use the broadest one, ie. utf8!\r
@@ -3582,9 +3715,10 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
        * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,\r
        * which will be most probably using UTF-8 anyway...\r
        *\r
-       * @param string $httpheaders the http Content-type header\r
+       * @param string $httpheader the http Content-type header\r
        * @param string $xmlchunk xml content buffer\r
        * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)\r
+       * @return string\r
        *\r
        * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!\r
        */\r
@@ -3602,7 +3736,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                // Note: we do not check for invalid chars in VALUE:\r
                //   this had better be done using pure ereg as below\r
                // Note 2: we might be removing whitespace/tabs that ought to be left in if\r
-        //   the received charset is a quoted string. But nobody uses such charset names...\r
+               //   the received charset is a quoted string. But nobody uses such charset names...\r
 \r
                /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?\r
                $matches = array();\r
@@ -3672,11 +3806,49 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                }\r
        }\r
 \r
+       /**\r
+        * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)\r
+        *\r
+        * @param string $xmlChunk\r
+        * @return bool\r
+        */\r
+       function has_encoding($xmlChunk)\r
+       {\r
+               // scan the first bytes of the data for a UTF-16 (or other) BOM pattern\r
+               //       (source: http://www.w3.org/TR/2000/REC-xml-20001006)\r
+               if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk))\r
+               {\r
+                       return true;\r
+               }\r
+               elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk))\r
+               {\r
+                       return true;\r
+               }\r
+               elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk))\r
+               {\r
+                       return true;\r
+               }\r
+\r
+               // test if encoding is specified in the xml declaration\r
+               // Details:\r
+               // SPACE:                (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+\r
+               // EQ:                  SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*\r
+               if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .\r
+                       '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",\r
+                       $xmlChunk, $matches))\r
+               {\r
+                       return true;\r
+               }\r
+\r
+               return false;\r
+       }\r
+\r
        /**\r
        * Checks if a given charset encoding is present in a list of encodings or\r
        * if it is a valid subset of any encoding in the list\r
        * @param string $encoding charset to be tested\r
        * @param mixed $validlist comma separated list of valid charsets (or array of charsets)\r
+       * @return bool\r
        */\r
        function is_valid_charset($encoding, $validlist)\r
        {\r
@@ -3697,7 +3869,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
                                foreach ($validlist as $allowed)\r
                                        if (in_array($allowed, $charset_supersets[$encoding]))\r
                                                return true;\r
-                               return false;\r
+                       return false;\r
                }\r
        }\r
 \r