first commit

This commit is contained in:
2026-02-07 09:46:32 +08:00
commit 5fcd5dc646
443 changed files with 89466 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
<?php
namespace PhpXmlRpc;
/**
* In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
* For usage, see any file in the demo/client directory
*/
class Autoloader
{
/**
* Registers PhpXmlRpc\Autoloader as an SPL autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function register($prepend = false)
{
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
}
/**
* Handles autoloading of classes.
*
* @param string $class A class name.
*/
public static function autoload($class)
{
if (0 !== strpos($class, 'PhpXmlRpc\\')) {
return;
}
if (is_file($file = __DIR__ . str_replace(array('PhpXmlRpc\\', '\\'), '/', $class).'.php')) {
require $file;
}
}
}

1188
lib/phpxmlrpc/src/Client.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,317 @@
<?php
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\XMLParser;
/**
* A helper class to easily convert between Value objects and php native values
*/
class Encoder
{
/**
* Takes an xmlrpc value in object format and translates it into native PHP types.
*
* Works with xmlrpc requests objects as input, too.
*
* Given proper options parameter, can rebuild generic php object instances
* (provided those have been encoded to xmlrpc format using a corresponding
* option in php_xmlrpc_encode())
* PLEASE NOTE that rebuilding php objects involves calling their constructor function.
* This means that the remote communication end can decide which php code will
* get executed on your server, leaving the door possibly open to 'php-injection'
* style of attacks (provided you have some classes defined on your server that
* might wreak havoc if instances are built outside an appropriate context).
* Make sure you trust the remote server/client before eanbling this!
*
* @author Dan Libby (dan@libby.com)
*
* @param Value|Request $xmlrpcVal
* @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
*
* @return mixed
*/
public function decode($xmlrpcVal, $options = array())
{
switch ($xmlrpcVal->kindOf()) {
case 'scalar':
if (in_array('extension_api', $options)) {
reset($xmlrpcVal->me);
list($typ, $val) = each($xmlrpcVal->me);
switch ($typ) {
case 'dateTime.iso8601':
$xmlrpcVal->scalar = $val;
$xmlrpcVal->type = 'datetime';
$xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val);
return $xmlrpcVal;
case 'base64':
$xmlrpcVal->scalar = $val;
$xmlrpcVal->type = $typ;
return $xmlrpcVal;
default:
return $xmlrpcVal->scalarval();
}
}
if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
// we return a Datetime object instead of a string
// since now the constructor of xmlrpc value accepts safely strings, ints and datetimes,
// we cater to all 3 cases here
$out = $xmlrpcVal->scalarval();
if (is_string($out)) {
$out = strtotime($out);
}
if (is_int($out)) {
$result = new \Datetime();
$result->setTimestamp($out);
return $result;
} elseif (is_a($out, 'Datetime')) {
return $out;
}
}
return $xmlrpcVal->scalarval();
case 'array':
$arr = array();
foreach($xmlrpcVal as $value) {
$arr[] = $this->decode($value, $options);
}
return $arr;
case 'struct':
// If user said so, try to rebuild php objects for specific struct vals.
/// @todo should we raise a warning for class not found?
// shall we check for proper subclass of xmlrpc value instead of
// presence of _php_class to detect what we can do?
if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
&& class_exists($xmlrpcVal->_php_class)
) {
$obj = @new $xmlrpcVal->_php_class();
foreach ($xmlrpcVal as $key => $value) {
$obj->$key = $this->decode($value, $options);
}
return $obj;
} else {
$arr = array();
foreach ($xmlrpcVal as $key => $value) {
$arr[$key] = $this->decode($value, $options);
}
return $arr;
}
case 'msg':
$paramCount = $xmlrpcVal->getNumParams();
$arr = array();
for ($i = 0; $i < $paramCount; $i++) {
$arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
}
return $arr;
}
}
/**
* Takes native php types and encodes them into xmlrpc PHP object format.
* It will not re-encode xmlrpc value objects.
*
* Feature creep -- could support more types via optional type argument
* (string => datetime support has been added, ??? => base64 not yet)
*
* If given a proper options parameter, php object instances will be encoded
* into 'special' xmlrpc values, that can later be decoded into php objects
* by calling php_xmlrpc_decode() with a corresponding option
*
* @author Dan Libby (dan@libby.com)
*
* @param mixed $phpVal the value to be converted into an xmlrpc value object
* @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
*
* @return \PhpXmlrpc\Value
*/
public function encode($phpVal, $options = array())
{
$type = gettype($phpVal);
switch ($type) {
case 'string':
if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
} else {
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
}
break;
case 'integer':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
break;
case 'double':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
break;
// <G_Giunta_2001-02-29>
// Add support for encoding/decoding of booleans, since they are supported in PHP
case 'boolean':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
break;
// </G_Giunta_2001-02-29>
case 'array':
// PHP arrays can be encoded to either xmlrpc structs or arrays,
// depending on wheter they are hashes or plain 0..n integer indexed
// A shorter one-liner would be
// $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
// but execution time skyrockets!
$j = 0;
$arr = array();
$ko = false;
foreach ($phpVal as $key => $val) {
$arr[$key] = $this->encode($val, $options);
if (!$ko && $key !== $j) {
$ko = true;
}
$j++;
}
if ($ko) {
$xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
} else {
$xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
}
break;
case 'object':
if (is_a($phpVal, 'PhpXmlRpc\Value')) {
$xmlrpcVal = $phpVal;
} elseif (is_a($phpVal, 'DateTime')) {
$xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
} else {
$arr = array();
reset($phpVal);
while (list($k, $v) = each($phpVal)) {
$arr[$k] = $this->encode($v, $options);
}
$xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
if (in_array('encode_php_objs', $options)) {
// let's save original class name into xmlrpc value:
// might be useful later on...
$xmlrpcVal->_php_class = get_class($phpVal);
}
}
break;
case 'NULL':
if (in_array('extension_api', $options)) {
$xmlrpcVal = new Value('', Value::$xmlrpcString);
} elseif (in_array('null_extension', $options)) {
$xmlrpcVal = new Value('', Value::$xmlrpcNull);
} else {
$xmlrpcVal = new Value();
}
break;
case 'resource':
if (in_array('extension_api', $options)) {
$xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
} else {
$xmlrpcVal = new Value();
}
// catch "user function", "unknown type"
default:
// giancarlo pinerolo <ping@alt.it>
// it has to return
// an empty object in case, not a boolean.
$xmlrpcVal = new Value();
break;
}
return $xmlrpcVal;
}
/**
* Convert the xml representation of a method response, method request or single
* xmlrpc value into the appropriate object (a.k.a. deserialize).
*
* @param string $xmlVal
* @param array $options
*
* @return mixed false on error, or an instance of either Value, Request or Response
*/
public function decodeXml($xmlVal, $options = array())
{
// 'guestimate' encoding
$valEncoding = XMLParser::guessEncoding('', $xmlVal);
if ($valEncoding != '') {
// Since parsing will fail if charset is not specified in the xml prologue,
// the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
// The following code might be better for mb_string enabled installs, but
// makes the lib about 200% slower...
//if (!is_valid_charset($valEncoding, array('UTF-8'))
if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
if ($valEncoding == 'ISO-8859-1') {
$xmlVal = utf8_encode($xmlVal);
} else {
if (extension_loaded('mbstring')) {
$xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
} else {
error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
}
}
}
}
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
// What if internal encoding is not in one of the 3 allowed?
// we use the broadest one, ie. utf8!
if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
} else {
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
}
$xmlRpcParser = new XMLParser();
xml_set_object($parser, $xmlRpcParser);
xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
xml_set_character_data_handler($parser, 'xmlrpc_cd');
xml_set_default_handler($parser, 'xmlrpc_dh');
if (!xml_parse($parser, $xmlVal, 1)) {
$errstr = sprintf('XML error: %s at line %d, column %d',
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser), xml_get_current_column_number($parser));
error_log($errstr);
xml_parser_free($parser);
return false;
}
xml_parser_free($parser);
if ($xmlRpcParser->_xh['isf'] > 1) {
// test that $xmlrpc->_xh['value'] is an obj, too???
error_log($xmlRpcParser->_xh['isf_reason']);
return false;
}
switch ($xmlRpcParser->_xh['rt']) {
case 'methodresponse':
$v = &$xmlRpcParser->_xh['value'];
if ($xmlRpcParser->_xh['isf'] == 1) {
$vc = $v['faultCode'];
$vs = $v['faultString'];
$r = new Response(0, $vc->scalarval(), $vs->scalarval());
} else {
$r = new Response($v);
}
return $r;
case 'methodcall':
$req = new Request($xmlRpcParser->_xh['method']);
for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
$req->addParam($xmlRpcParser->_xh['params'][$i]);
}
return $req;
case 'value':
return $xmlRpcParser->_xh['value'];
default:
return false;
}
}
}

View File

@@ -0,0 +1,273 @@
<?php
namespace PhpXmlRpc\Helper;
use PhpXmlRpc\PhpXmlRpc;
class Charset
{
// tables used for transcoding different charsets into us-ascii xml
protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
protected $xml_iso88591_utf8 = array("in" => array(), "out" => array());
/// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
/// These will NOT be present in true ISO-8859-1, but will save the unwary
/// windows user from sending junk (though no luck when receiving them...)
/*
protected $xml_cp1252_Entities = array('in' => array(), out' => array(
'&#x20AC;', '?', '&#x201A;', '&#x0192;',
'&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
'&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
'&#x0152;', '?', '&#x017D;', '?',
'?', '&#x2018;', '&#x2019;', '&#x201C;',
'&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
'&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
'&#x0153;', '?', '&#x017E;', '&#x0178;'
));
*/
protected $charset_supersets = array(
'US-ASCII' => array('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',),
);
protected static $instance = null;
/**
* This class is singleton for performance reasons.
*
* @return Charset
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
for ($i = 0; $i < 32; $i++) {
$this->xml_iso88591_Entities["in"][] = chr($i);
$this->xml_iso88591_Entities["out"][] = "&#{$i};";
}
for ($i = 160; $i < 256; $i++) {
$this->xml_iso88591_Entities["in"][] = chr($i);
$this->xml_iso88591_Entities["out"][] = "&#{$i};";
}
/*for ($i = 128; $i < 160; $i++)
{
$this->xml_cp1252_Entities['in'][] = chr($i);
}*/
}
/**
* Convert a string to the correct XML representation in a target charset.
*
* To help correct communication of non-ascii chars inside strings, regardless of the charset used when sending
* requests, parsing them, sending responses and parsing responses, an option is to convert all non-ascii chars
* present in the message into their equivalent 'charset entity'. Charset entities enumerated this way are
* independent of the charset encoding used to transmit them, and all XML parsers are bound to understand them.
* Note that in the std case we are not sending a charset encoding mime type along with http headers, so we are
* bound by RFC 3023 to emit strict us-ascii.
*
* @todo do a bit of basic benchmarking (strtr vs. str_replace)
* @todo make usage of iconv() or recode_string() or mb_string() where available
*
* @param string $data
* @param string $srcEncoding
* @param string $destEncoding
*
* @return string
*/
public function encodeEntities($data, $srcEncoding = '', $destEncoding = '')
{
if ($srcEncoding == '') {
// lame, but we know no better...
$srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding;
}
$conversion = strtoupper($srcEncoding . '_' . $destEncoding);
switch ($conversion) {
case 'ISO-8859-1_':
case 'ISO-8859-1_US-ASCII':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
$escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData);
break;
case 'ISO-8859-1_UTF-8':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
$escapedData = utf8_encode($escapedData);
break;
case 'ISO-8859-1_ISO-8859-1':
case 'US-ASCII_US-ASCII':
case 'US-ASCII_UTF-8':
case 'US-ASCII_':
case 'US-ASCII_ISO-8859-1':
case 'UTF-8_UTF-8':
//case 'CP1252_CP1252':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
break;
case 'UTF-8_':
case 'UTF-8_US-ASCII':
case 'UTF-8_ISO-8859-1':
// NB: this will choke on invalid UTF-8, going most likely beyond EOF
$escapedData = '';
// be kind to users creating string xmlrpc values out of different php types
$data = (string)$data;
$ns = strlen($data);
for ($nn = 0; $nn < $ns; $nn++) {
$ch = $data[$nn];
$ii = ord($ch);
// 7 bits: 0bbbbbbb (127)
if ($ii < 128) {
/// @todo shall we replace this with a (supposedly) faster str_replace?
switch ($ii) {
case 34:
$escapedData .= '&quot;';
break;
case 38:
$escapedData .= '&amp;';
break;
case 39:
$escapedData .= '&apos;';
break;
case 60:
$escapedData .= '&lt;';
break;
case 62:
$escapedData .= '&gt;';
break;
default:
$escapedData .= $ch;
} // switch
} // 11 bits: 110bbbbb 10bbbbbb (2047)
elseif ($ii >> 5 == 6) {
$b1 = ($ii & 31);
$ii = ord($data[$nn + 1]);
$b2 = ($ii & 63);
$ii = ($b1 * 64) + $b2;
$ent = sprintf('&#%d;', $ii);
$escapedData .= $ent;
$nn += 1;
} // 16 bits: 1110bbbb 10bbbbbb 10bbbbbb
elseif ($ii >> 4 == 14) {
$b1 = ($ii & 15);
$ii = ord($data[$nn + 1]);
$b2 = ($ii & 63);
$ii = ord($data[$nn + 2]);
$b3 = ($ii & 63);
$ii = ((($b1 * 64) + $b2) * 64) + $b3;
$ent = sprintf('&#%d;', $ii);
$escapedData .= $ent;
$nn += 2;
} // 21 bits: 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
elseif ($ii >> 3 == 30) {
$b1 = ($ii & 7);
$ii = ord($data[$nn + 1]);
$b2 = ($ii & 63);
$ii = ord($data[$nn + 2]);
$b3 = ($ii & 63);
$ii = ord($data[$nn + 3]);
$b4 = ($ii & 63);
$ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
$ent = sprintf('&#%d;', $ii);
$escapedData .= $ent;
$nn += 3;
}
}
// when converting to latin-1, do not be so eager with using entities for characters 160-255
if ($conversion == 'UTF-8_ISO-8859-1') {
$escapedData = str_replace(array_slice($this->xml_iso88591_Entities['out'], 32), array_slice($this->xml_iso88591_Entities['in'], 32), $escapedData);
}
break;
/*
case 'CP1252_':
case 'CP1252_US-ASCII':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
$escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData);
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
break;
case 'CP1252_UTF-8':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
/// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
$escapedData = utf8_encode($escapedData);
break;
case 'CP1252_ISO-8859-1':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
// we might as well replace all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
break;
*/
default:
$escapedData = '';
error_log('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
}
return $escapedData;
}
/**
* Checks if a given charset encoding is present in a list of encodings or
* if it is a valid subset of any encoding in the list.
*
* @param string $encoding charset to be tested
* @param string|array $validList comma separated list of valid charsets (or array of charsets)
*
* @return bool
*/
public function isValidCharset($encoding, $validList)
{
if (is_string($validList)) {
$validList = explode(',', $validList);
}
if (@in_array(strtoupper($encoding), $validList)) {
return true;
} else {
if (array_key_exists($encoding, $this->charset_supersets)) {
foreach ($validList as $allowed) {
if (in_array($allowed, $this->charset_supersets[$encoding])) {
return true;
}
}
}
return false;
}
}
/**
* Used only for backwards compatibility
* @deprecated
*
* @param string $charset
*
* @return array
*
* @throws \Exception for unknown/unsupported charsets
*/
public function getEntities($charset)
{
switch ($charset)
{
case 'iso88591':
return $this->xml_iso88591_Entities;
default:
throw new \Exception('Unsupported charset: ' . $charset);
}
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace PhpXmlRpc\Helper;
class Date
{
/**
* Given a timestamp, return the corresponding ISO8601 encoded string.
*
* Really, timezones ought to be supported
* but the XML-RPC spec says:
*
* "Don't assume a timezone. It should be specified by the server in its
* documentation what assumptions it makes about timezones."
*
* These routines always assume localtime unless
* $utc is set to 1, in which case UTC is assumed
* and an adjustment for locale is made when encoding
*
* @param int $timet (timestamp)
* @param int $utc (0 or 1)
*
* @return string
*/
public static function iso8601Encode($timet, $utc = 0)
{
if (!$utc) {
$t = strftime("%Y%m%dT%H:%M:%S", $timet);
} else {
if (function_exists('gmstrftime')) {
// gmstrftime doesn't exist in some versions
// of PHP
$t = gmstrftime("%Y%m%dT%H:%M:%S", $timet);
} else {
$t = strftime("%Y%m%dT%H:%M:%S", $timet - date('Z'));
}
}
return $t;
}
/**
* Given an ISO8601 date string, return a timet in the localtime, or UTC.
*
* @param string $idate
* @param int $utc either 0 or 1
*
* @return int (datetime)
*/
public static function iso8601Decode($idate, $utc = 0)
{
$t = 0;
if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs)) {
if ($utc) {
$t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
} else {
$t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
}
}
return $t;
}
}

View File

@@ -0,0 +1,245 @@
<?php
namespace PhpXmlRpc\Helper;
use PhpXmlRpc\PhpXmlRpc;
class Http
{
/**
* Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6
* Code shamelessly stolen from nusoap library by Dietrich Ayala.
*
* @param string $buffer the string to be decoded
*
* @return string
*/
public static function decodeChunked($buffer)
{
// length := 0
$length = 0;
$new = '';
// read chunk-size, chunk-extension (if any) and crlf
// get the position of the linebreak
$chunkEnd = strpos($buffer, "\r\n") + 2;
$temp = substr($buffer, 0, $chunkEnd);
$chunkSize = hexdec(trim($temp));
$chunkStart = $chunkEnd;
while ($chunkSize > 0) {
$chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
// just in case we got a broken connection
if ($chunkEnd == false) {
$chunk = substr($buffer, $chunkStart);
// append chunk-data to entity-body
$new .= $chunk;
$length += strlen($chunk);
break;
}
// read chunk-data and crlf
$chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
// append chunk-data to entity-body
$new .= $chunk;
// length := length + chunk-size
$length += strlen($chunk);
// read chunk-size and crlf
$chunkStart = $chunkEnd + 2;
$chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
if ($chunkEnd == false) {
break; //just in case we got a broken connection
}
$temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
$chunkSize = hexdec(trim($temp));
$chunkStart = $chunkEnd;
}
return $new;
}
/**
* Parses HTTP an http response headers and separates them from the body.
*
* @param string $data the http response,headers and body. It will be stripped of headers
* @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
*
* @return array with keys 'headers' and 'cookies'
* @throws \Exception
*/
public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
{
$httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
// Support "web-proxy-tunelling" connections for https through proxies
if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
// Look for CR/LF or simple LF as line separator,
// (even though it is not valid http)
$pos = strpos($data, "\r\n\r\n");
if ($pos || is_int($pos)) {
$bd = $pos + 4;
} else {
$pos = strpos($data, "\n\n");
if ($pos || is_int($pos)) {
$bd = $pos + 2;
} else {
// No separation between response headers and body: fault?
$bd = 0;
}
}
if ($bd) {
// this filters out all http headers from proxy.
// maybe we could take them into account, too?
$data = substr($data, $bd);
} else {
error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
}
}
// Strip HTTP 1.1 100 Continue header if present
while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
$pos = strpos($data, 'HTTP', 12);
// server sent a Continue header without any (valid) content following...
// give the client a chance to know it
if (!$pos && !is_int($pos)) {
// works fine in php 3, 4 and 5
break;
}
$data = substr($data, $pos);
}
if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
$errstr = substr($data, 0, strpos($data, "\n") - 1);
error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']);
}
// be tolerant to usage of \n instead of \r\n to separate headers and data
// (even though it is not valid http)
$pos = strpos($data, "\r\n\r\n");
if ($pos || is_int($pos)) {
$bd = $pos + 4;
} else {
$pos = strpos($data, "\n\n");
if ($pos || is_int($pos)) {
$bd = $pos + 2;
} else {
// No separation between response headers and body: fault?
// we could take some action here instead of going on...
$bd = 0;
}
}
// be tolerant to line endings, and extra empty lines
$ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
while (list(, $line) = @each($ar)) {
// take care of multi-line headers and cookies
$arr = explode(':', $line, 2);
if (count($arr) > 1) {
$headerName = strtolower(trim($arr[0]));
/// @todo some other headers (the ones that allow a CSV list of values)
/// do allow many values to be passed using multiple header lines.
/// We should add content to $xmlrpc->_xh['headers'][$headerName]
/// instead of replacing it for those...
if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
if ($headerName == 'set-cookie2') {
// version 2 cookies:
// there could be many cookies on one line, comma separated
$cookies = explode(',', $arr[1]);
} else {
$cookies = array($arr[1]);
}
foreach ($cookies as $cookie) {
// glue together all received cookies, using a comma to separate them
// (same as php does with getallheaders())
if (isset($httpResponse['headers'][$headerName])) {
$httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
} else {
$httpResponse['headers'][$headerName] = trim($cookie);
}
// parse cookie attributes, in case user wants to correctly honour them
// feature creep: only allow rfc-compliant cookie attributes?
// @todo support for server sending multiple time cookie with same name, but using different PATHs
$cookie = explode(';', $cookie);
foreach ($cookie as $pos => $val) {
$val = explode('=', $val, 2);
$tag = trim($val[0]);
$val = trim(@$val[1]);
/// @todo with version 1 cookies, we should strip leading and trailing " chars
if ($pos == 0) {
$cookiename = $tag;
$httpResponse['cookies'][$tag] = array();
$httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
} else {
if ($tag != 'value') {
$httpResponse['cookies'][$cookiename][$tag] = $val;
}
}
}
}
} else {
$httpResponse['headers'][$headerName] = trim($arr[1]);
}
} elseif (isset($headerName)) {
/// @todo version1 cookies might span multiple lines, thus breaking the parsing above
$httpResponse['headers'][$headerName] .= ' ' . trim($line);
}
}
$data = substr($data, $bd);
if ($debug && count($httpResponse['headers'])) {
$msg = '';
foreach ($httpResponse['headers'] as $header => $value) {
$msg .= "HEADER: $header: $value\n";
}
foreach ($httpResponse['cookies'] as $header => $value) {
$msg .= "COOKIE: $header={$value['value']}\n";
}
Logger::instance()->debugMessage($msg);
}
// if CURL was used for the call, http headers have been processed,
// and dechunking + reinflating have been carried out
if (!$headersProcessed) {
// Decode chunked encoding sent by http 1.1 servers
if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
if (!$data = Http::decodeChunked($data)) {
error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']);
}
}
// Decode gzip-compressed stuff
// code shamelessly inspired from nusoap library by Dietrich Ayala
if (isset($httpResponse['headers']['content-encoding'])) {
$httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
// if decoding works, use it. else assume data wasn't gzencoded
if (function_exists('gzinflate')) {
if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
$data = $degzdata;
if ($debug) {
Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
}
} elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
$data = $degzdata;
if ($debug) {
Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
}
} else {
error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']);
}
} else {
error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']);
}
}
}
} // end of 'if needed, de-chunk, re-inflate response'
return $httpResponse;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace PhpXmlRpc\Helper;
class Logger
{
protected static $instance = null;
/**
* This class is singleton, so that later we can move to DI patterns.
*
* @return Logger
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Echoes a debug message, taking care of escaping it when not in console mode.
* NB: if the encoding of the message is not known or wrong, and we are working in web mode, there is no guarantee
* of 100% accuracy, which kind of defeats the purpose of debugging
*
* @param string $message
* @param string $encoding
*/
public function debugMessage($message, $encoding=null)
{
// US-ASCII is a warning for PHP and a fatal for HHVM
if ($encoding == 'US-ASCII') {
$encoding = 'UTF-8';
}
if (PHP_SAPI != 'cli') {
$flags = ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE;
if ($encoding != null) {
print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
} else {
print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
}
} else {
print "\n$message\n";
}
// let the user see this now in case there's a time out later...
flush();
}
}

View File

@@ -0,0 +1,561 @@
<?php
namespace PhpXmlRpc\Helper;
use PhpXmlRpc\PhpXmlRpc;
use PhpXmlRpc\Value;
/**
* Deals with parsing the XML.
*/
class XMLParser
{
// used to store state during parsing
// quick explanation of components:
// ac - used to accumulate values
// stack - array with genealogy of xml elements names:
// used to validate nesting of xmlrpc elements
// valuestack - array used for parsing arrays and structs
// lv - used to indicate "looking for a value": implements
// the logic to allow values with no types to be strings
// isf - used to indicate a parsing fault (2) or xmlrpc response fault (1)
// isf_reason - used for storing xmlrpc response fault string
// method - used to store method name
// params - used to store parameters in method calls
// pt - used to store the type of each received parameter. Useful if parameters are automatically decoded to php values
// rt - 'methodcall or 'methodresponse'
public $_xh = array(
'ac' => '',
'stack' => array(),
'valuestack' => array(),
'isf' => 0,
'isf_reason' => '',
'method' => false, // so we can check later if we got a methodname or not
'params' => array(),
'pt' => array(),
'rt' => '',
);
public $xmlrpc_valid_parents = array(
'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
'BOOLEAN' => array('VALUE'),
'I4' => array('VALUE'),
'I8' => array('VALUE'),
'EX:I8' => array('VALUE'),
'INT' => array('VALUE'),
'STRING' => array('VALUE'),
'DOUBLE' => array('VALUE'),
'DATETIME.ISO8601' => array('VALUE'),
'BASE64' => array('VALUE'),
'MEMBER' => array('STRUCT'),
'NAME' => array('MEMBER'),
'DATA' => array('ARRAY'),
'ARRAY' => array('VALUE'),
'STRUCT' => array('VALUE'),
'PARAM' => array('PARAMS'),
'METHODNAME' => array('METHODCALL'),
'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
'FAULT' => array('METHODRESPONSE'),
'NIL' => array('VALUE'), // only used when extension activated
'EX:NIL' => array('VALUE'), // only used when extension activated
);
/**
* xml parser handler function for opening element tags.
*/
public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false)
{
// if invalid xmlrpc already detected, skip all processing
if ($this->_xh['isf'] < 2) {
// check for correct element nesting
// top level element can only be of 2 types
/// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
/// there is only a single top level element in xml anyway
if (count($this->_xh['stack']) == 0) {
if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
$name != 'VALUE' && !$acceptSingleVals)
) {
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = 'missing top level xmlrpc element';
return;
} else {
$this->_xh['rt'] = strtolower($name);
}
} else {
// not top level element: see if parent is OK
$parent = end($this->_xh['stack']);
if (!array_key_exists($name, $this->xmlrpc_valid_parents) || !in_array($parent, $this->xmlrpc_valid_parents[$name])) {
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
return;
}
}
switch ($name) {
// optimize for speed switch cases: most common cases first
case 'VALUE':
/// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
$this->_xh['vt'] = 'value'; // indicator: no value found yet
$this->_xh['ac'] = '';
$this->_xh['lv'] = 1;
$this->_xh['php_class'] = null;
break;
case 'I8':
case 'EX:I8':
if (PHP_INT_SIZE === 4) {
/// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "Received i8 element but php is compiled in 32 bit mode";
return;
}
// fall through voluntarily
case 'I4':
case 'INT':
case 'STRING':
case 'BOOLEAN':
case 'DOUBLE':
case 'DATETIME.ISO8601':
case 'BASE64':
if ($this->_xh['vt'] != 'value') {
// two data elements inside a value: an error occurred!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
return;
}
$this->_xh['ac'] = ''; // reset the accumulator
break;
case 'STRUCT':
case 'ARRAY':
if ($this->_xh['vt'] != 'value') {
//two data elements inside a value: an error occurred!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
return;
}
// create an empty array to hold child values, and push it onto appropriate stack
$curVal = array();
$curVal['values'] = array();
$curVal['type'] = $name;
// check for out-of-band information to rebuild php objs
// and in case it is found, save it
if (@isset($attrs['PHP_CLASS'])) {
$curVal['php_class'] = $attrs['PHP_CLASS'];
}
$this->_xh['valuestack'][] = $curVal;
$this->_xh['vt'] = 'data'; // be prepared for a data element next
break;
case 'DATA':
if ($this->_xh['vt'] != 'data') {
//two data elements inside a value: an error occurred!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "found two data elements inside an array element";
return;
}
case 'METHODCALL':
case 'METHODRESPONSE':
case 'PARAMS':
// valid elements that add little to processing
break;
case 'METHODNAME':
case 'NAME':
/// @todo we could check for 2 NAME elements inside a MEMBER element
$this->_xh['ac'] = '';
break;
case 'FAULT':
$this->_xh['isf'] = 1;
break;
case 'MEMBER':
$this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = ''; // set member name to null, in case we do not find in the xml later on
//$this->_xh['ac']='';
// Drop trough intentionally
case 'PARAM':
// clear value type, so we can check later if no value has been passed for this param/member
$this->_xh['vt'] = null;
break;
case 'NIL':
case 'EX:NIL':
if (PhpXmlRpc::$xmlrpc_null_extension) {
if ($this->_xh['vt'] != 'value') {
//two data elements inside a value: an error occurred!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
return;
}
$this->_xh['ac'] = ''; // reset the accumulator
break;
}
// we do not support the <NIL/> extension, so
// drop through intentionally
default:
/// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
$this->_xh['isf'] = 2;
$this->_xh['isf_reason'] = "found not-xmlrpc xml element $name";
break;
}
// Save current element name to stack, to validate nesting
$this->_xh['stack'][] = $name;
/// @todo optimization creep: move this inside the big switch() above
if ($name != 'VALUE') {
$this->_xh['lv'] = 0;
}
}
}
/**
* Used in decoding xml chunks that might represent single xmlrpc values.
*/
public function xmlrpc_se_any($parser, $name, $attrs)
{
$this->xmlrpc_se($parser, $name, $attrs, true);
}
/**
* xml parser handler function for close element tags.
*/
public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true)
{
if ($this->_xh['isf'] < 2) {
// push this element name from stack
// NB: if XML validates, correct opening/closing is guaranteed and
// we do not have to check for $name == $currElem.
// we also checked for proper nesting at start of elements...
$currElem = array_pop($this->_xh['stack']);
switch ($name) {
case 'VALUE':
// This if() detects if no scalar was inside <VALUE></VALUE>
if ($this->_xh['vt'] == 'value') {
$this->_xh['value'] = $this->_xh['ac'];
$this->_xh['vt'] = Value::$xmlrpcString;
}
if ($rebuildXmlrpcvals) {
// build the xmlrpc val out of the data received, and substitute it
$temp = new Value($this->_xh['value'], $this->_xh['vt']);
// in case we got info about underlying php class, save it
// in the object we're rebuilding
if (isset($this->_xh['php_class'])) {
$temp->_php_class = $this->_xh['php_class'];
}
// check if we are inside an array or struct:
// if value just built is inside an array, let's move it into array on the stack
$vscount = count($this->_xh['valuestack']);
if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
$this->_xh['valuestack'][$vscount - 1]['values'][] = $temp;
} else {
$this->_xh['value'] = $temp;
}
} else {
/// @todo this needs to treat correctly php-serialized objects,
/// since std deserializing is done by php_xmlrpc_decode,
/// which we will not be calling...
if (isset($this->_xh['php_class'])) {
}
// check if we are inside an array or struct:
// if value just built is inside an array, let's move it into array on the stack
$vscount = count($this->_xh['valuestack']);
if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
$this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value'];
}
}
break;
case 'BOOLEAN':
case 'I4':
case 'I8':
case 'EX:I8':
case 'INT':
case 'STRING':
case 'DOUBLE':
case 'DATETIME.ISO8601':
case 'BASE64':
$this->_xh['vt'] = strtolower($name);
/// @todo: optimization creep - remove the if/elseif cycle below
/// since the case() in which we are already did that
if ($name == 'STRING') {
$this->_xh['value'] = $this->_xh['ac'];
} elseif ($name == 'DATETIME.ISO8601') {
if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->_xh['ac'])) {
error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in DATETIME: ' . $this->_xh['ac']);
}
$this->_xh['vt'] = Value::$xmlrpcDateTime;
$this->_xh['value'] = $this->_xh['ac'];
} elseif ($name == 'BASE64') {
/// @todo check for failure of base64 decoding / catch warnings
$this->_xh['value'] = base64_decode($this->_xh['ac']);
} elseif ($name == 'BOOLEAN') {
// special case here: we translate boolean 1 or 0 into PHP
// constants true or false.
// Strings 'true' and 'false' are accepted, even though the
// spec never mentions them (see eg. Blogger api docs)
// NB: this simple checks helps a lot sanitizing input, ie no
// security problems around here
if ($this->_xh['ac'] == '1' || strcasecmp($this->_xh['ac'], 'true') == 0) {
$this->_xh['value'] = true;
} else {
// log if receiving something strange, even though we set the value to false anyway
if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) {
error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']);
}
$this->_xh['value'] = false;
}
} elseif ($name == 'DOUBLE') {
// we have a DOUBLE
// we must check that only 0123456789-.<space> are characters here
// NOTE: regexp could be much stricter than this...
if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) {
/// @todo: find a better way of throwing an error than this!
error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in DOUBLE: ' . $this->_xh['ac']);
$this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
} else {
// it's ok, add it on
$this->_xh['value'] = (double)$this->_xh['ac'];
}
} else {
// we have an I4/I8/INT
// we must check that only 0123456789-<space> are characters here
if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) {
/// @todo find a better way of throwing an error than this!
error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in INT: ' . $this->_xh['ac']);
$this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
} else {
// it's ok, add it on
$this->_xh['value'] = (int)$this->_xh['ac'];
}
}
$this->_xh['lv'] = 3; // indicate we've found a value
break;
case 'NAME':
$this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac'];
break;
case 'MEMBER':
// add to array in the stack the last element built,
// unless no VALUE was found
if ($this->_xh['vt']) {
$vscount = count($this->_xh['valuestack']);
$this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value'];
} else {
error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml');
}
break;
case 'DATA':
$this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty
break;
case 'STRUCT':
case 'ARRAY':
// fetch out of stack array of values, and promote it to current value
$currVal = array_pop($this->_xh['valuestack']);
$this->_xh['value'] = $currVal['values'];
$this->_xh['vt'] = strtolower($name);
if (isset($currVal['php_class'])) {
$this->_xh['php_class'] = $currVal['php_class'];
}
break;
case 'PARAM':
// add to array of params the current value,
// unless no VALUE was found
if ($this->_xh['vt']) {
$this->_xh['params'][] = $this->_xh['value'];
$this->_xh['pt'][] = $this->_xh['vt'];
} else {
error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml');
}
break;
case 'METHODNAME':
$this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']);
break;
case 'NIL':
case 'EX:NIL':
if (PhpXmlRpc::$xmlrpc_null_extension) {
$this->_xh['vt'] = 'null';
$this->_xh['value'] = null;
$this->_xh['lv'] = 3;
break;
}
// drop through intentionally if nil extension not enabled
case 'PARAMS':
case 'FAULT':
case 'METHODCALL':
case 'METHORESPONSE':
break;
default:
// End of INVALID ELEMENT!
// shall we add an assert here for unreachable code???
break;
}
}
}
/**
* Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values.
*/
public function xmlrpc_ee_fast($parser, $name)
{
$this->xmlrpc_ee($parser, $name, false);
}
/**
* xml parser handler function for character data.
*/
public function xmlrpc_cd($parser, $data)
{
// skip processing if xml fault already detected
if ($this->_xh['isf'] < 2) {
// "lookforvalue==3" means that we've found an entire value
// and should discard any further character data
if ($this->_xh['lv'] != 3) {
$this->_xh['ac'] .= $data;
}
}
}
/**
* xml parser handler function for 'other stuff', ie. not char data or
* element start/end tag. In fact it only gets called on unknown entities...
*/
public function xmlrpc_dh($parser, $data)
{
// skip processing if xml fault already detected
if ($this->_xh['isf'] < 2) {
if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') {
$this->_xh['ac'] .= $data;
}
}
return true;
}
/**
* xml charset encoding guessing helper function.
* Tries to determine the charset encoding of an XML chunk received over HTTP.
* NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
* we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of non conforming (legacy?) clients/servers,
* which will be most probably using UTF-8 anyway...
* In order of importance checks:
* 1. http headers
* 2. BOM
* 3. XML declaration
* 4. guesses using mb_detect_encoding()
*
* @param string $httpHeader the http Content-type header
* @param string $xmlChunk xml content buffer
* @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled).
* This can also be set globally using PhpXmlRpc::$xmlrpc_detectencodings
* @return string the encoding determined. Null if it can't be determined and mbstring is enabled,
* PhpXmlRpc::$xmlrpc_defencoding if it can't be determined and mbstring is not enabled
*
* @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
*/
public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
{
// discussion: see http://www.yale.edu/pclt/encoding/
// 1 - test if encoding is specified in HTTP HEADERS
// Details:
// LWS: (\13\10)?( |\t)+
// token: (any char but excluded stuff)+
// quoted string: " (any char but double quotes and control chars)* "
// header: Content-type = ...; charset=value(; ...)*
// where value is of type token, no LWS allowed between 'charset' and value
// Note: we do not check for invalid chars in VALUE:
// this had better be done using pure ereg as below
// Note 2: we might be removing whitespace/tabs that ought to be left in if
// the received charset is a quoted string. But nobody uses such charset names...
/// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
$matches = array();
if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
return strtoupper(trim($matches[1], " \t\""));
}
// 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
// (source: http://www.w3.org/TR/2000/REC-xml-20001006)
// NOTE: actually, according to the spec, even if we find the BOM and determine
// an encoding, we should check if there is an encoding specified
// in the xml declaration, and verify if they match.
/// @todo implement check as described above?
/// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
return 'UCS-4';
} elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
return 'UTF-16';
} elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
return 'UTF-8';
}
// 3 - test if encoding is specified in the xml declaration
// Details:
// SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
// EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
'\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
$xmlChunk, $matches)) {
return strtoupper(substr($matches[2], 1, -1));
}
// 4 - if mbstring is available, let it do the guesswork
if (extension_loaded('mbstring')) {
if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) {
$encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings;
}
if ($encodingPrefs) {
$enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
} else {
$enc = mb_detect_encoding($xmlChunk);
}
// NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
// IANA also likes better US-ASCII, so go with it
if ($enc == 'ASCII') {
$enc = 'US-' . $enc;
}
return $enc;
} else {
// no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
// Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
// this should be the standard. And we should be getting text/xml as request and response.
// BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
return PhpXmlRpc::$xmlrpc_defencoding;
}
}
/**
* Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)
*
* @param string $xmlChunk
* @return bool
*/
public static function hasEncoding($xmlChunk)
{
// scan the first bytes of the data for a UTF-16 (or other) BOM pattern
// (source: http://www.w3.org/TR/2000/REC-xml-20001006)
if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
return true;
} elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
return true;
} elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
return true;
}
// test if encoding is specified in the xml declaration
// Details:
// SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
// EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
'\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
$xmlChunk, $matches)) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,150 @@
<?php
namespace PhpXmlRpc;
/**
* Manages global configuration for operation of the library.
*/
class PhpXmlRpc
{
static public $xmlrpcerr = array(
'unknown_method' => 1,
'invalid_return' => 2,
'incorrect_params' => 3,
'introspect_unknown' => 4,
'http_error' => 5,
'no_data' => 6,
'no_ssl' => 7,
'curl_fail' => 8,
'invalid_request' => 15,
'no_curl' => 16,
'server_error' => 17,
'multicall_error' => 18,
'multicall_notstruct' => 9,
'multicall_nomethod' => 10,
'multicall_notstring' => 11,
'multicall_recursion' => 12,
'multicall_noparams' => 13,
'multicall_notarray' => 14,
'cannot_decompress' => 103,
'decompress_fail' => 104,
'dechunk_fail' => 105,
'server_cannot_decompress' => 106,
'server_decompress_fail' => 107,
);
static public $xmlrpcstr = array(
'unknown_method' => 'Unknown method',
'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload',
'incorrect_params' => 'Incorrect parameters passed to method',
'introspect_unknown' => "Can't introspect: method unknown",
'http_error' => "Didn't receive 200 OK from remote server.",
'no_data' => 'No data received from server.',
'no_ssl' => 'No SSL support compiled in.',
'curl_fail' => 'CURL error',
'invalid_request' => 'Invalid request payload',
'no_curl' => 'No CURL support compiled in.',
'server_error' => 'Internal server error',
'multicall_error' => 'Received from server invalid multicall response',
'multicall_notstruct' => 'system.multicall expected struct',
'multicall_nomethod' => 'missing methodName',
'multicall_notstring' => 'methodName is not a string',
'multicall_recursion' => 'recursive system.multicall forbidden',
'multicall_noparams' => 'missing params',
'multicall_notarray' => 'params is not an array',
'cannot_decompress' => 'Received from server compressed HTTP and cannot decompress',
'decompress_fail' => 'Received from server invalid compressed HTTP',
'dechunk_fail' => 'Received from server invalid chunked HTTP',
'server_cannot_decompress' => 'Received from client compressed HTTP request and cannot decompress',
'server_decompress_fail' => 'Received from client invalid compressed HTTP request',
);
// The charset encoding used by the server for received requests and
// by the client for received responses when received charset cannot be determined
// and mbstring extension is not enabled
public static $xmlrpc_defencoding = "UTF-8";
// The list of encodings used by the server for requests and by the client for responses
// to detect the charset of the received payload when
// - the charset cannot be determined by looking at http headers, xml declaration or BOM
// - mbstring extension is enabled
public static $xmlrpc_detectencodings = array();
// The encoding used internally by PHP.
// String values received as xml will be converted to this, and php strings will be converted to xml
// as if having been coded with this.
// Valid also when defining names of xmlrpc methods
public static $xmlrpc_internalencoding = "UTF-8";
public static $xmlrpcName = "XML-RPC for PHP";
public static $xmlrpcVersion = "4.1.0";
// let user errors start at 800
public static $xmlrpcerruser = 800;
// let XML parse errors start at 100
public static $xmlrpcerrxml = 100;
// set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values
public static $xmlrpc_null_extension = false;
// set to TRUE to enable encoding of php NULL values to <EX:NIL/> instead of <NIL/>
public static $xmlrpc_null_apache_encoding = false;
public static $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions";
/**
* A function to be used for compatibility with legacy code: it creates all global variables which used to be declared,
* such as library version etc...
*/
public static function exportGlobals()
{
$reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc');
foreach ($reflection->getStaticProperties() as $name => $value) {
$GLOBALS[$name] = $value;
}
// NB: all the variables exported into the global namespace below here do NOT guarantee 100%
// compatibility, as they are NOT reimported back during calls to importGlobals()
$reflection = new \ReflectionClass('PhpXmlRpc\Value');
foreach ($reflection->getStaticProperties() as $name => $value) {
$GLOBALS[$name] = $value;
}
$parser = new Helper\XMLParser();
$reflection = new \ReflectionClass('PhpXmlRpc\Helper\XMLParser');
foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $name => $value) {
if (in_array($value->getName(), array('xmlrpc_valid_parents')))
{
$GLOBALS[$value->getName()] = $value->getValue($parser);
}
}
$charset = Helper\Charset::instance();
$GLOBALS['xml_iso88591_Entities'] = $charset->getEntities('iso88591');
}
/**
* A function to be used for compatibility with legacy code: it gets the values of all global variables which used
* to be declared, such as library version etc... and sets them to php classes.
* It should be used by code which changed the values of those global variables to alter the working of the library.
* Example code:
* 1. include xmlrpc.inc
* 2. set the values, e.g. $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
* 3. import them: PhpXmlRpc\PhpXmlRpc::importGlobals();
* 4. run your own code.
*/
public static function importGlobals()
{
$reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc');
$staticProperties = $reflection->getStaticProperties();
foreach ($staticProperties as $name => $value) {
if (isset($GLOBALS[$name])) {
self::$$name = $GLOBALS[$name];
}
}
}
}

View File

@@ -0,0 +1,389 @@
<?php
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
use PhpXmlRpc\Helper\Http;
use PhpXmlRpc\Helper\Logger;
use PhpXmlRpc\Helper\XMLParser;
/**
* This class provides the representation of a request to an XML-RPC server.
* A client sends a PhpXmlrpc\Request to a server, and receives back an PhpXmlrpc\Response.
*/
class Request
{
/// @todo: do these need to be public?
public $payload;
public $methodname;
public $params = array();
public $debug = 0;
public $content_type = 'text/xml';
// holds data while parsing the response. NB: Not a full Response object
protected $httpResponse = array();
/**
* @param string $methodName the name of the method to invoke
* @param Value[] $params array of parameters to be passed to the method (NB: Value objects, not plain php values)
*/
public function __construct($methodName, $params = array())
{
$this->methodname = $methodName;
foreach ($params as $param) {
$this->addParam($param);
}
}
public function xml_header($charsetEncoding = '')
{
if ($charsetEncoding != '') {
return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
} else {
return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
}
}
public function xml_footer()
{
return '</methodCall>';
}
public function createPayload($charsetEncoding = '')
{
if ($charsetEncoding != '') {
$this->content_type = 'text/xml; charset=' . $charsetEncoding;
} else {
$this->content_type = 'text/xml';
}
$this->payload = $this->xml_header($charsetEncoding);
$this->payload .= '<methodName>' . Charset::instance()->encodeEntities(
$this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
$this->payload .= "<params>\n";
foreach ($this->params as $p) {
$this->payload .= "<param>\n" . $p->serialize($charsetEncoding) .
"</param>\n";
}
$this->payload .= "</params>\n";
$this->payload .= $this->xml_footer();
}
/**
* Gets/sets the xmlrpc method to be invoked.
*
* @param string $methodName the method to be set (leave empty not to set it)
*
* @return string the method that will be invoked
*/
public function method($methodName = '')
{
if ($methodName != '') {
$this->methodname = $methodName;
}
return $this->methodname;
}
/**
* Returns xml representation of the message. XML prologue included.
*
* @param string $charsetEncoding
*
* @return string the xml representation of the message, xml prologue included
*/
public function serialize($charsetEncoding = '')
{
$this->createPayload($charsetEncoding);
return $this->payload;
}
/**
* Add a parameter to the list of parameters to be used upon method invocation.
*
* Checks that $params is actually a Value object and not a plain php value.
*
* @param Value $param
*
* @return boolean false on failure
*/
public function addParam($param)
{
// add check: do not add to self params which are not xmlrpc values
if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
$this->params[] = $param;
return true;
} else {
return false;
}
}
/**
* Returns the nth parameter in the request. The index zero-based.
*
* @param integer $i the index of the parameter to fetch (zero based)
*
* @return Value the i-th parameter
*/
public function getParam($i)
{
return $this->params[$i];
}
/**
* Returns the number of parameters in the message.
*
* @return integer the number of parameters currently set
*/
public function getNumParams()
{
return count($this->params);
}
/**
* Given an open file handle, read all data available and parse it as an xmlrpc response.
*
* NB: the file handle is not closed by this function.
* NNB: might have trouble in rare cases to work on network streams, as we check for a read of 0 bytes instead of
* feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case,
* because we cannot trust the caller to give us a valid pointer to an open file...
*
* @param resource $fp stream pointer
*
* @return Response
*
* @todo add 2nd & 3rd param to be passed to ParseResponse() ???
*/
public function parseResponseFile($fp)
{
$ipd = '';
while ($data = fread($fp, 32768)) {
$ipd .= $data;
}
return $this->parseResponse($ipd);
}
/**
* Parse the xmlrpc response contained in the string $data and return a Response object.
*
* When $this->debug has been set to a value greater than 0, will echo debug messages to screen while decoding.
*
* @param string $data the xmlrpc response, possibly including http headers
* @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and
* consequent decoding
* @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or
* 'phpvals'
*
* @return Response
*/
public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals')
{
if ($this->debug) {
Logger::instance()->debugMessage("---GOT---\n$data\n---END---");
}
$this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
if ($data == '') {
error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
}
// parse the HTTP headers of the response, if present, and separate them from data
if (substr($data, 0, 4) == 'HTTP') {
$httpParser = new Http();
try {
$this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
} catch(\Exception $e) {
$r = new Response(0, $e->getCode(), $e->getMessage());
// failed processing of HTTP response headers
// save into response obj the full payload received, for debugging
$r->raw_data = $data;
return $r;
}
}
// be tolerant of extra whitespace in response body
$data = trim($data);
/// @todo return an error msg if $data=='' ?
// be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
// idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
$pos = strrpos($data, '</methodResponse>');
if ($pos !== false) {
$data = substr($data, 0, $pos + 17);
}
// try to 'guestimate' the character encoding of the received response
$respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data);
if ($this->debug) {
$start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
if ($start) {
$start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
$end = strpos($data, '-->', $start);
$comments = substr($data, $start, $end - $start);
Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
}
}
// if user wants back raw xml, give it to him
if ($returnType == 'xml') {
$r = new Response($data, 0, '', 'xml');
$r->hdrs = $this->httpResponse['headers'];
$r->_cookies = $this->httpResponse['cookies'];
$r->raw_data = $this->httpResponse['raw_data'];
return $r;
}
if ($respEncoding != '') {
// Since parsing will fail if charset is not specified in the xml prologue,
// the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
// The following code might be better for mb_string enabled installs, but
// makes the lib about 200% slower...
//if (!is_valid_charset($respEncoding, array('UTF-8')))
if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
if ($respEncoding == 'ISO-8859-1') {
$data = utf8_encode($data);
} else {
if (extension_loaded('mbstring')) {
$data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
} else {
error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding);
}
}
}
}
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
// G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
// the xml parser to give us back data in the expected charset.
// What if internal encoding is not in one of the 3 allowed?
// we use the broadest one, ie. utf8
// This allows to send data which is native in various charset,
// by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
} else {
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
}
$xmlRpcParser = new XMLParser();
xml_set_object($parser, $xmlRpcParser);
if ($returnType == 'phpvals') {
xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
} else {
xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
}
xml_set_character_data_handler($parser, 'xmlrpc_cd');
xml_set_default_handler($parser, 'xmlrpc_dh');
// first error check: xml not well formed
if (!xml_parse($parser, $data, count($data))) {
// thanks to Peter Kocks <peter.kocks@baygate.com>
if ((xml_get_current_line_number($parser)) == 1) {
$errStr = 'XML error at line 1, check URL';
} else {
$errStr = sprintf('XML error: %s at line %d, column %d',
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser), xml_get_current_column_number($parser));
}
error_log($errStr);
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errStr . ')');
xml_parser_free($parser);
if ($this->debug) {
print $errStr;
}
$r->hdrs = $this->httpResponse['headers'];
$r->_cookies = $this->httpResponse['cookies'];
$r->raw_data = $this->httpResponse['raw_data'];
return $r;
}
xml_parser_free($parser);
// second error check: xml well formed but not xml-rpc compliant
if ($xmlRpcParser->_xh['isf'] > 1) {
if ($this->debug) {
/// @todo echo something for user?
}
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
}
// third error check: parsing of the response has somehow gone boink.
// NB: shall we omit this check, since we trust the parsing code?
elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
// something odd has happened
// and it's time to generate a client side error
// indicating something odd went on
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
PhpXmlRpc::$xmlrpcstr['invalid_return']);
} else {
if ($this->debug > 1) {
Logger::instance()->debugMessage(
"---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
);
}
// note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
$v = &$xmlRpcParser->_xh['value'];
if ($xmlRpcParser->_xh['isf']) {
/// @todo we should test here if server sent an int and a string, and/or coerce them into such...
if ($returnType == 'xmlrpcvals') {
$errNo_v = $v['faultCode'];
$errStr_v = $v['faultString'];
$errNo = $errNo_v->scalarval();
$errStr = $errStr_v->scalarval();
} else {
$errNo = $v['faultCode'];
$errStr = $v['faultString'];
}
if ($errNo == 0) {
// FAULT returned, errno needs to reflect that
$errNo = -1;
}
$r = new Response(0, $errNo, $errStr);
} else {
$r = new Response($v, 0, '', $returnType);
}
}
$r->hdrs = $this->httpResponse['headers'];
$r->_cookies = $this->httpResponse['cookies'];
$r->raw_data = $this->httpResponse['raw_data'];
return $r;
}
/**
* Kept the old name even if Request class was renamed, for compatibility.
*
* @return string
*/
public function kindOf()
{
return 'msg';
}
/**
* Enables/disables the echoing to screen of the xmlrpc responses received.
*
* @param integer $in values 0, 1, 2 are supported
*/
public function setDebug($in)
{
$this->debug = $in;
}
}

View File

@@ -0,0 +1,158 @@
<?php
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
/**
* This class provides the representation of the response of an XML-RPC server.
* Server-side, a server method handler will construct a Response and pass it as its return value.
* An identical Response object will be returned by the result of an invocation of the send() method of the Client class.
*/
class Response
{
/// @todo: do these need to be public?
public $val = 0;
public $valtyp;
public $errno = 0;
public $errstr = '';
public $payload;
public $hdrs = array();
public $_cookies = array();
public $content_type = 'text/xml';
public $raw_data = '';
/**
* @param mixed $val either a Value object, a php value or the xml serialization of an xmlrpc value (a string)
* @param integer $fCode set it to anything but 0 to create an error response. In that case, $val is discarded
* @param string $fString the error string, in case of an error response
* @param string $valType The type of $val passed in. Either 'xmlrpcvals', 'phpvals' or 'xml'. Leave empty to let
* the code guess the correct type.
*
* @todo add check that $val / $fCode / $fString is of correct type???
* NB: as of now we do not do it, since it might be either an xmlrpc value or a plain php val, or a complete
* xml chunk, depending on usage of Client::send() inside which creator is called...
*/
public function __construct($val, $fCode = 0, $fString = '', $valType = '')
{
if ($fCode != 0) {
// error response
$this->errno = $fCode;
$this->errstr = $fString;
} else {
// successful response
$this->val = $val;
if ($valType == '') {
// user did not declare type of response value: try to guess it
if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
$this->valtyp = 'xmlrpcvals';
} elseif (is_string($this->val)) {
$this->valtyp = 'xml';
} else {
$this->valtyp = 'phpvals';
}
} else {
// user declares type of resp value: believe him
$this->valtyp = $valType;
}
}
}
/**
* Returns the error code of the response.
*
* @return integer the error code of this response (0 for not-error responses)
*/
public function faultCode()
{
return $this->errno;
}
/**
* Returns the error code of the response.
*
* @return string the error string of this response ('' for not-error responses)
*/
public function faultString()
{
return $this->errstr;
}
/**
* Returns the value received by the server. If the Response's faultCode is non-zero then the value returned by this
* method should not be used (it may not even be an object).
*
* @return Value|string|mixed the Value object returned by the server. Might be an xml string or plain php value
* depending on the convention adopted when creating the Response
*/
public function value()
{
return $this->val;
}
/**
* Returns an array with the cookies received from the server.
* Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 => $val2, ...)
* with attributes being e.g. 'expires', 'path', domain'.
* NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past) are still present in the array.
* It is up to the user-defined code to decide how to use the received cookies, and whether they have to be sent back
* with the next request to the server (using Client::setCookie) or not.
*
* @return array array of cookies received from the server
*/
public function cookies()
{
return $this->_cookies;
}
/**
* Returns xml representation of the response. XML prologue not included.
*
* @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed
*
* @return string the xml representation of the response
*
* @throws \Exception
*/
public function serialize($charsetEncoding = '')
{
if ($charsetEncoding != '') {
$this->content_type = 'text/xml; charset=' . $charsetEncoding;
} else {
$this->content_type = 'text/xml';
}
if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
$result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
} else {
$result = "<methodResponse>\n";
}
if ($this->errno) {
// G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
// by xml-encoding non ascii chars
$result .= "<fault>\n" .
"<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
"</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
Charset::instance()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</string></value>\n</member>\n" .
"</struct>\n</value>\n</fault>";
} else {
if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) {
if (is_string($this->val) && $this->valtyp == 'xml') {
$result .= "<params>\n<param>\n" .
$this->val .
"</param>\n</params>";
} else {
/// @todo try to build something serializable?
throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values');
}
} else {
$result .= "<params>\n<param>\n" .
$this->val->serialize($charsetEncoding) .
"</param>\n</params>";
}
}
$result .= "\n</methodResponse>";
$this->payload = $result;
return $result;
}
}

1068
lib/phpxmlrpc/src/Server.php Normal file

File diff suppressed because it is too large Load Diff

599
lib/phpxmlrpc/src/Value.php Normal file
View File

@@ -0,0 +1,599 @@
<?php
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
/**
* This class enables the creation of values for XML-RPC, by encapsulating plain php values.
*/
class Value implements \Countable, \IteratorAggregate, \ArrayAccess
{
public static $xmlrpcI4 = "i4";
public static $xmlrpcI8 = "i8";
public static $xmlrpcInt = "int";
public static $xmlrpcBoolean = "boolean";
public static $xmlrpcDouble = "double";
public static $xmlrpcString = "string";
public static $xmlrpcDateTime = "dateTime.iso8601";
public static $xmlrpcBase64 = "base64";
public static $xmlrpcArray = "array";
public static $xmlrpcStruct = "struct";
public static $xmlrpcValue = "undefined";
public static $xmlrpcNull = "null";
public static $xmlrpcTypes = array(
"i4" => 1,
"i8" => 1,
"int" => 1,
"boolean" => 1,
"double" => 1,
"string" => 1,
"dateTime.iso8601" => 1,
"base64" => 1,
"array" => 2,
"struct" => 3,
"null" => 1,
);
/// @todo: do these need to be public?
public $me = array();
public $mytype = 0;
public $_php_class = null;
/**
* Build an xmlrpc value.
*
* When no value or type is passed in, the value is left uninitialized, and the value can be added later.
*
* @param mixed $val if passing in an array, all array elements should be PhpXmlRpc\Value themselves
* @param string $type any valid xmlrpc type name (lowercase): i4, int, boolean, string, double, dateTime.iso8601,
* base64, array, struct, null.
* If null, 'string' is assumed.
* You should refer to http://www.xmlrpc.com/spec for more information on what each of these mean.
*/
public function __construct($val = -1, $type = '')
{
// optimization creep - do not call addXX, do it all inline.
// downside: booleans will not be coerced anymore
if ($val !== -1 || $type != '') {
switch ($type) {
case '':
$this->mytype = 1;
$this->me['string'] = $val;
break;
case 'i4':
case 'i8':
case 'int':
case 'double':
case 'string':
case 'boolean':
case 'dateTime.iso8601':
case 'base64':
case 'null':
$this->mytype = 1;
$this->me[$type] = $val;
break;
case 'array':
$this->mytype = 2;
$this->me['array'] = $val;
break;
case 'struct':
$this->mytype = 3;
$this->me['struct'] = $val;
break;
default:
error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
}
}
}
/**
* Add a single php value to an xmlrpc value.
*
* If the xmlrpc value is an array, the php value is added as its last element.
* If the xmlrpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
* Fails if the xmlrpc value is not an array and already initialized.
*
* @param mixed $val
* @param string $type allowed values: i4, i8, int, boolean, string, double, dateTime.iso8601, base64, null.
*
* @return int 1 or 0 on failure
*/
public function addScalar($val, $type = 'string')
{
$typeOf = null;
if (isset(static::$xmlrpcTypes[$type])) {
$typeOf = static::$xmlrpcTypes[$type];
}
if ($typeOf !== 1) {
error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
return 0;
}
// coerce booleans into correct values
// NB: we should either do it for datetimes, integers, i8 and doubles, too,
// or just plain remove this check, implemented on booleans only...
if ($type == static::$xmlrpcBoolean) {
if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
$val = true;
} else {
$val = false;
}
}
switch ($this->mytype) {
case 1:
error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
return 0;
case 3:
error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
return 0;
case 2:
// we're adding a scalar value to an array here
$this->me['array'][] = new Value($val, $type);
return 1;
default:
// a scalar, so set the value and remember we're scalar
$this->me[$type] = $val;
$this->mytype = $typeOf;
return 1;
}
}
/**
* Add an array of xmlrpc value objects to an xmlrpc value.
*
* If the xmlrpc value is an array, the elements are appended to the existing ones.
* If the xmlrpc value is empty (uninitialized), this method makes it an array value, and sets that value.
* Fails otherwise.
*
* @param Value[] $values
*
* @return int 1 or 0 on failure
*
* @todo add some checking for $values to be an array of xmlrpc values?
*/
public function addArray($values)
{
if ($this->mytype == 0) {
$this->mytype = static::$xmlrpcTypes['array'];
$this->me['array'] = $values;
return 1;
} elseif ($this->mytype == 2) {
// we're adding to an array here
$this->me['array'] = array_merge($this->me['array'], $values);
return 1;
} else {
error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
return 0;
}
}
/**
* Merges an array of named xmlrpc value objects into an xmlrpc value.
*
* If the xmlrpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
* If the xmlrpc value is empty (uninitialized), this method makes it a struct value, and sets that value.
* Fails otherwise.
*
* @param Value[] $values
*
* @return int 1 or 0 on failure
*
* @todo add some checking for $values to be an array?
*/
public function addStruct($values)
{
if ($this->mytype == 0) {
$this->mytype = static::$xmlrpcTypes['struct'];
$this->me['struct'] = $values;
return 1;
} elseif ($this->mytype == 3) {
// we're adding to a struct here
$this->me['struct'] = array_merge($this->me['struct'], $values);
return 1;
} else {
error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
return 0;
}
}
/**
* Returns a string containing either "struct", "array", "scalar" or "undef", describing the base type of the value.
*
* @return string
*/
public function kindOf()
{
switch ($this->mytype) {
case 3:
return 'struct';
break;
case 2:
return 'array';
break;
case 1:
return 'scalar';
break;
default:
return 'undef';
}
}
protected function serializedata($typ, $val, $charsetEncoding = '')
{
$rs = '';
if (!isset(static::$xmlrpcTypes[$typ])) {
return $rs;
}
switch (static::$xmlrpcTypes[$typ]) {
case 1:
switch ($typ) {
case static::$xmlrpcBase64:
$rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
break;
case static::$xmlrpcBoolean:
$rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
break;
case static::$xmlrpcString:
// G. Giunta 2005/2/13: do NOT use htmlentities, since
// it will produce named html entities, which are invalid xml
$rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
break;
case static::$xmlrpcInt:
case static::$xmlrpcI4:
case static::$xmlrpcI8:
$rs .= "<${typ}>" . (int)$val . "</${typ}>";
break;
case static::$xmlrpcDouble:
// avoid using standard conversion of float to string because it is locale-dependent,
// and also because the xmlrpc spec forbids exponential notation.
// sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
// The code below tries its best at keeping max precision while avoiding exp notation,
// but there is of course no limit in the number of decimal places to be used...
$rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
break;
case static::$xmlrpcDateTime:
if (is_string($val)) {
$rs .= "<${typ}>${val}</${typ}>";
} elseif (is_a($val, 'DateTime')) {
$rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
} elseif (is_int($val)) {
$rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
} else {
// not really a good idea here: but what shall we output anyway? left for backward compat...
$rs .= "<${typ}>${val}</${typ}>";
}
break;
case static::$xmlrpcNull:
if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
$rs .= "<ex:nil/>";
} else {
$rs .= "<nil/>";
}
break;
default:
// no standard type value should arrive here, but provide a possibility
// for xmlrpc values of unknown type...
$rs .= "<${typ}>${val}</${typ}>";
}
break;
case 3:
// struct
if ($this->_php_class) {
$rs .= '<struct php_class="' . $this->_php_class . "\">\n";
} else {
$rs .= "<struct>\n";
}
$charsetEncoder = Charset::instance();
foreach ($val as $key2 => $val2) {
$rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
//$rs.=$this->serializeval($val2);
$rs .= $val2->serialize($charsetEncoding);
$rs .= "</member>\n";
}
$rs .= '</struct>';
break;
case 2:
// array
$rs .= "<array>\n<data>\n";
foreach ($val as $element) {
//$rs.=$this->serializeval($val[$i]);
$rs .= $element->serialize($charsetEncoding);
}
$rs .= "</data>\n</array>";
break;
default:
break;
}
return $rs;
}
/**
* Returns the xml representation of the value. XML prologue not included.
*
* @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
*
* @return string
*/
public function serialize($charsetEncoding = '')
{
reset($this->me);
list($typ, $val) = $this->each($this->me);
return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
}
public function each(&$array)
{
$res = array();
$key = key($array);
if($key !== null){
next($array);
$res[1] = $res['value'] = $array[$key];
$res[0] = $res['key'] = $key;
}else{
$res = false;
}
return $res;
}
/**
* Checks whether a struct member with a given name is present.
*
* Works only on xmlrpc values of type struct.
*
* @param string $key the name of the struct member to be looked up
*
* @return boolean
*
* @deprecated use array access, e.g. isset($val[$key])
*/
public function structmemexists($key)
{
return array_key_exists($key, $this->me['struct']);
}
/**
* Returns the value of a given struct member (an xmlrpc value object in itself).
* Will raise a php warning if struct member of given name does not exist.
*
* @param string $key the name of the struct member to be looked up
*
* @return Value
*
* @deprecated use array access, e.g. $val[$key]
*/
public function structmem($key)
{
return $this->me['struct'][$key];
}
/**
* Reset internal pointer for xmlrpc values of type struct.
* @deprecated iterate directly over the object using foreach instead
*/
public function structreset()
{
reset($this->me['struct']);
}
/**
* Return next member element for xmlrpc values of type struct.
*
* @return Value
*
* @deprecated iterate directly over the object using foreach instead
*/
public function structeach()
{
return $this->each($this->me['struct']);
}
/**
* Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
*
* @return mixed
*/
public function scalarval()
{
reset($this->me);
list(, $b) = $this->each($this->me);
return $b;
}
/**
* Returns the type of the xmlrpc value.
*
* For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
*
* @return string
*/
public function scalartyp()
{
reset($this->me);
list($a,) = $this->each($this->me);
if ($a == static::$xmlrpcI4) {
$a = static::$xmlrpcInt;
}
return $a;
}
/**
* Returns the m-th member of an xmlrpc value of array type.
*
* @param integer $key the index of the value to be retrieved (zero based)
*
* @return Value
*
* @deprecated use array access, e.g. $val[$key]
*/
public function arraymem($key)
{
return $this->me['array'][$key];
}
/**
* Returns the number of members in an xmlrpc value of array type.
*
* @return integer
*
* @deprecated use count() instead
*/
public function arraysize()
{
return count($this->me['array']);
}
/**
* Returns the number of members in an xmlrpc value of struct type.
*
* @return integer
*
* @deprecated use count() instead
*/
public function structsize()
{
return count($this->me['struct']);
}
/**
* Returns the number of members in an xmlrpc value:
* - 0 for uninitialized values
* - 1 for scalar values
* - the number of elements for struct and array values
*
* @return integer
*/
public function count()
{
switch ($this->mytype) {
case 3:
return count($this->me['struct']);
case 2:
return count($this->me['array']);
case 1:
return 1;
default:
return 0;
}
}
/**
* Implements the IteratorAggregate interface
*
* @return ArrayIterator
*/
public function getIterator() {
switch ($this->mytype) {
case 3:
return new \ArrayIterator($this->me['struct']);
case 2:
return new \ArrayIterator($this->me['array']);
case 1:
return new \ArrayIterator($this->me);
default:
return new \ArrayIterator();
}
return new \ArrayIterator();
}
public function offsetSet($offset, $value) {
switch ($this->mytype) {
case 3:
if (!($value instanceof \PhpXmlRpc\Value)) {
throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
}
if (is_null($offset)) {
// disallow struct members with empty names
throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
} else {
$this->me['struct'][$offset] = $value;
}
return;
case 2:
if (!($value instanceof \PhpXmlRpc\Value)) {
throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
}
if (is_null($offset)) {
$this->me['array'][] = $value;
} else {
// nb: we are not checking that $offset is above the existing array range...
$this->me['array'][$offset] = $value;
}
return;
case 1:
// todo: handle i4 vs int
reset($this->me);
list($type,) = $this->each($this->me);
if ($type != $offset) {
throw new \Exception('');
}
$this->me[$type] = $value;
return;
default:
// it would be nice to allow empty values to be be turned into non-empty ones this way, but we miss info to do so
throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be set using array index");
}
}
public function offsetExists($offset) {
switch ($this->mytype) {
case 3:
return isset($this->me['struct'][$offset]);
case 2:
return isset($this->me['array'][$offset]);
case 1:
// todo: handle i4 vs int
return $offset == $this->scalartyp();
default:
return false;
}
}
public function offsetUnset($offset) {
switch ($this->mytype) {
case 3:
unset($this->me['struct'][$offset]);
return;
case 2:
unset($this->me['array'][$offset]);
return;
case 1:
// can not remove value from a scalar
throw new \Exception("XML-RPC Value is of type 'scalar' and its value can not be unset using array index");
default:
throw new \Exception("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
}
}
public function offsetGet($offset) {
switch ($this->mytype) {
case 3:
return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
case 2:
return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
case 1:
// on bad type: null or exception?
reset($this->me);
list($type, $value) = $this->each($this->me);
return $type == $offset ? $value : null;
default:
// return null or exception?
throw new \Exception("XML-RPC Value is of type 'undef' and can not be accessed using array index");
}
}
}

File diff suppressed because it is too large Load Diff