Merge branch 'master_MDL-76929' of https://github.com/mattporritt/moodle

This commit is contained in:
Ilya Tregubov
2023-04-26 09:27:58 +08:00
35 changed files with 5060 additions and 2538 deletions
+1458 -752
View File
File diff suppressed because it is too large Load Diff
+113 -103
View File
@@ -2,73 +2,54 @@
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Logger;
use PhpXmlRpc\Helper\XMLParser;
use PhpXmlRpc\Traits\LoggerAware;
use PhpXmlRpc\Traits\ParserAware;
/**
* A helper class to easily convert between Value objects and php native values
* A helper class to easily convert between Value objects and php native values.
*
* @todo implement an interface
* @todo add class constants for the options values
*/
class Encoder
{
protected static $logger;
protected static $parser;
public function getLogger()
{
if (self::$logger === null) {
self::$logger = Logger::instance();
}
return self::$logger;
}
public static function setLogger($logger)
{
self::$logger = $logger;
}
public function getParser()
{
if (self::$parser === null) {
self::$parser = new XMLParser();
}
return self::$parser;
}
public static function setParser($parser)
{
self::$parser = $parser;
}
use LoggerAware;
use ParserAware;
/**
* Takes an xmlrpc value in object format and translates it into native PHP types.
*
* Works with xmlrpc requests objects as input, too.
*
* Takes an xml-rpc Value in object instance and translates it into native PHP types, recursively.
* Works with xml-rpc Request objects as input, too.
* Xmlrpc dateTime values will be converted to strings or DateTime objects depending on an $options parameter
* Supports i8 and NIL xml-rpc values without the need for specific options.
* Both xml-rpc arrays and structs are decoded into PHP arrays, with the exception described below:
* 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())
* xml-rpc 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 enabling this!
*
* @author Dan Libby ([email protected])
* @author Dan Libby
*
* @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
*
* @param array $options accepted elements:
* - 'decode_php_objs': if set in the options array, xml-rpc structs can be decoded into php
* objects, see the details above;
* - 'dates_as_objects': when set xml-rpc dateTimes are decoded as php DateTime objects
* - 'extension_api': reserved for usage by phpxmlrpc-polyfill
* @return mixed
*
* Feature creep -- add an option to allow converting xml-rpc dateTime values to unix timestamps (integers)
*/
public function decode($xmlrpcVal, $options = array())
{
switch ($xmlrpcVal->kindOf()) {
case 'scalar':
if (in_array('extension_api', $options)) {
$val = reset($xmlrpcVal->me);
$typ = key($xmlrpcVal->me);
$val = $xmlrpcVal->scalarVal();
$typ = $xmlrpcVal->scalarTyp();
switch ($typ) {
case 'dateTime.iso8601':
$xmlrpcVal = array(
@@ -85,38 +66,48 @@ class Encoder
return (object)$xmlrpcVal;
case 'string':
if (isset($options['extension_api_encoding'])) {
$dval = @iconv('UTF-8', $options['extension_api_encoding'], $val);
// if iconv is not available, we use mb_convert_encoding
if (function_exists('iconv')) {
$dval = @iconv('UTF-8', $options['extension_api_encoding'], $val);
} elseif (function_exists('mb_convert_encoding')) {
/// @todo check for discrepancies between the supported charset names
$dval = @mb_convert_encoding($val, $options['extension_api_encoding'], 'UTF-8');
} else {
$dval = false;
}
if ($dval !== false) {
return $dval;
}
}
//return $val;
// break through voluntarily
default:
return $val;
}
}
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 (in_array('dates_as_objects', $options) && $xmlrpcVal->scalarTyp() == 'dateTime.iso8601') {
// we return a Datetime object instead of a string; since now the constructor of xml-rpc value accepts
// safely string, int and DateTimeInterface, we cater to all 3 cases here
$out = $xmlrpcVal->scalarVal();
if (is_string($out)) {
$out = strtotime($out);
// NB: if the string does not convert into a timestamp, this will return false.
// We avoid logging an error here, as we presume it was already done when parsing the xml
/// @todo we could return null, to be more in line with what the XMLParser does...
}
if (is_int($out)) {
$result = new \DateTime();
$result->setTimestamp($out);
return $result;
} elseif (is_a($out, 'DateTimeInterface')) {
} elseif (is_a($out, 'DateTimeInterface') || is_a($out, 'DateTime')) {
return $out;
}
}
return $xmlrpcVal->scalarval();
return $xmlrpcVal->scalarVal();
case 'array':
$arr = array();
foreach($xmlrpcVal as $value) {
foreach ($xmlrpcVal as $value) {
$arr[] = $this->decode($value, $options);
}
return $arr;
@@ -124,7 +115,7 @@ class Encoder
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
// shall we check for proper subclass of xml-rpc 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)
@@ -155,29 +146,41 @@ class Encoder
}
/**
* Takes native php types and encodes them into xmlrpc PHP object format.
* It will not re-encode xmlrpc value objects.
* Takes native php types and encodes them into xml-rpc Value objects, recursively.
* PHP strings, integers, floats and booleans have a straightforward encoding - note that integers will _not_ be
* converted to xml-rpc <i8> elements, even if they exceed the 32-bit range.
* PHP arrays will be encoded to either xml-rpc structs or arrays, depending on whether they are hashes
* or plain 0..N integer indexed.
* PHP objects will be encoded into xml-rpc structs, except if they implement DateTimeInterface, in which case they
* will be encoded as dateTime values.
* PhpXmlRpc\Value objects will not be double-encoded - which makes it possible to pass in a pre-created base64 Value
* as part of a php array.
* If given a proper $options parameter, php object instances will be encoded into 'special' xml-rpc values, that can
* later be decoded into php object instances by calling php_xmlrpc_decode() with a corresponding option.
* PHP resource and NULL variables will be converted into uninitialized Value objects (which will lead to invalid
* xml-rpc when later serialized); to support encoding of the latter use the appropriate $options parameter.
*
* 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 ([email protected])
*
* @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'
* @author Dan Libby
*
* @param mixed $phpVal the value to be converted into an xml-rpc value object
* @param array $options can include:
* - 'encode_php_objs' when set, some out-of-band info will be added to the xml produced by
* serializing the built Value, which can later be decoced by this library to rebuild an
* instance of the same php object
* - 'auto_dates': when set, any string which respects the xml-rpc datetime format will be converted to a dateTime Value
* - 'null_extension': when set, php NULL values will be converted to an xml-rpc <NIL> (or <EX:NIL>) Value
* - 'extension_api': reserved for usage by phpxmlrpc-polyfill
* @return Value
*
* Feature creep -- could support more types via optional type argument (string => datetime support has been added,
* ??? => base64 not yet). Also: allow auto-encoding of integers to i8 when too-big to fit into i4
*/
public function encode($phpVal, $options = array())
{
$type = gettype($phpVal);
switch ($type) {
case 'string':
/// @todo should we be stricter in the accepted dates (ie. reject more of invalid days & times)?
if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
if (in_array('auto_dates', $options) && preg_match(PhpXmlRpc::$xmlrpc_datetime_format, $phpVal)) {
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
} else {
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
@@ -189,15 +192,12 @@ class Encoder
case 'double':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
break;
// Add support for encoding/decoding of booleans, since they are supported in PHP
case 'boolean':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
break;
case 'array':
// PHP arrays can be encoded to either xmlrpc structs or arrays, depending on whether 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));
// $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
// but execution time skyrockets!
$j = 0;
$arr = array();
@@ -218,7 +218,8 @@ class Encoder
case 'object':
if (is_a($phpVal, 'PhpXmlRpc\Value')) {
$xmlrpcVal = $phpVal;
} elseif (is_a($phpVal, 'DateTimeInterface')) {
// DateTimeInterface is not present in php 5.4...
} elseif (is_a($phpVal, 'DateTimeInterface') || is_a($phpVal, 'DateTime')) {
$xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcDateTime);
} elseif (in_array('extension_api', $options) && $phpVal instanceof \stdClass && isset($phpVal->xmlrpc_type)) {
// Handle the 'pre-converted' base64 and datetime values
@@ -239,13 +240,12 @@ class Encoder
} else {
$arr = array();
foreach($phpVal as $k => $v) {
foreach ($phpVal as $k => $v) {
$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...
// let's save original class name into xml-rpc value: it might be useful later on...
$xmlrpcVal->_php_class = get_class($phpVal);
}
}
@@ -268,8 +268,7 @@ class Encoder
break;
// catch "user function", "unknown type"
default:
// giancarlo pinerolo <[email protected]>
// it has to return an empty object in case, not a boolean.
// it has to return an empty object in case, not a boolean. (giancarlo pinerolo)
$xmlrpcVal = new Value();
break;
}
@@ -279,15 +278,17 @@ class Encoder
/**
* Convert the xml representation of a method response, method request or single
* xmlrpc value into the appropriate object (a.k.a. deserialize).
*
* @todo is this a good name/class for this method? It does something quite different from 'decode' after all
* (returning objects vs returns plain php values)... In fact it belongs rather to a Parser class
* xml-rpc value into the appropriate object (a.k.a. deserialize).
*
* @param string $xmlVal
* @param array $options
*
* @param array $options unused atm
* @return Value|Request|Response|false false on error, or an instance of either Value, Request or Response
*
* @todo is this a good name/class for this method? It does something quite different from 'decode' after all
* (returning objects vs returns plain php values)... In fact, it belongs rather to a Parser class
* @todo feature creep -- we should allow an option to return php native types instead of PhpXmlRpc objects instances
* @todo feature creep -- allow source charset to be passed in as an option, in case the xml misses its declaration
* @todo feature creep -- allow expected type (val/req/resp) to be passed in as an option
*/
public function decodeXml($xmlVal, $options = array())
{
@@ -296,7 +297,7 @@ class Encoder
if ($valEncoding != '') {
// Since parsing will fail if
// - charset is not specified in the xml prologue,
// - charset is not specified in the xml declaration,
// - the encoding is not UTF8 and
// - there are non-ascii chars in the text,
// we try to work round that...
@@ -306,71 +307,80 @@ class Encoder
if (function_exists('mb_convert_encoding')) {
$xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
} else {
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
if ($valEncoding == 'ISO-8859-1') {
$xmlVal = utf8_encode($xmlVal);
} else {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
}
}
}
}
// 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'))) {
/// @todo emit a warning
$parserOptions = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
} else {
// What if internal encoding is not in one of the 3 allowed? We use the broadest one, i.e. utf8!
/// @todo with php < 5.6, this does not work. We should add a manual conversion of the xml string to UTF8
if (in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
$parserOptions = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
} else {
$parserOptions = array(XML_OPTION_TARGET_ENCODING => 'UTF-8', 'target_charset' => PhpXmlRpc::$xmlrpc_internalencoding);
}
$xmlRpcParser = $this->getParser();
$xmlRpcParser->parse(
$_xh = $xmlRpcParser->parse(
$xmlVal,
XMLParser::RETURN_XMLRPCVALS,
XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE | XMLParser::ACCEPT_FAULT,
$parserOptions
);
// BC
if (!is_array($_xh)) {
$_xh = $xmlRpcParser->_xh;
}
if ($xmlRpcParser->_xh['isf'] > 1) {
// test that $xmlrpc->_xh['value'] is an obj, too???
if ($_xh['isf'] > 1) {
// test that $_xh['value'] is an obj, too???
$this->getLogger()->errorLog($xmlRpcParser->_xh['isf_reason']);
$this->getLogger()->error('XML-RPC: ' . $_xh['isf_reason']);
return false;
}
switch ($xmlRpcParser->_xh['rt']) {
switch ($_xh['rt']) {
case 'methodresponse':
$v = $xmlRpcParser->_xh['value'];
if ($xmlRpcParser->_xh['isf'] == 1) {
$v = $_xh['value'];
if ($_xh['isf'] == 1) {
/** @var Value $vc */
$vc = $v['faultCode'];
/** @var Value $vs */
$vs = $v['faultString'];
$r = new Response(0, $vc->scalarval(), $vs->scalarval());
$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]);
$req = new Request($_xh['method']);
for ($i = 0; $i < count($_xh['params']); $i++) {
$req->addParam($_xh['params'][$i]);
}
return $req;
case 'value':
return $xmlRpcParser->_xh['value'];
return $_xh['value'];
case 'fault':
// EPI api emulation
$v = $xmlRpcParser->_xh['value'];
$v = $_xh['value'];
// use a known error code
/** @var Value $vc */
$vc = isset($v['faultCode']) ? $v['faultCode']->scalarval() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
$vc = isset($v['faultCode']) ? $v['faultCode']->scalarVal() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
/** @var Value $vs */
$vs = isset($v['faultString']) ? $v['faultString']->scalarval() : '';
$vs = isset($v['faultString']) ? $v['faultString']->scalarVal() : '';
if (!is_int($vc) || $vc == 0) {
$vc = PhpXmlRpc::$xmlrpcerr['invalid_return'];
}
return new Response(0, $vc, $vs);
default:
return false;
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace PhpXmlRpc;
class Exception extends \Exception
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* To be used when throwing exceptions instead of returning Response objects (future API?)
*/
class FaultResponseException extends BaseExtension
{
}
+4 -1
View File
@@ -2,7 +2,10 @@
namespace PhpXmlRpc\Exception;
class HttpException extends PhpXmlrpcException
/**
* To be used for all errors related to parsing HTTP requests and responses
*/
class HttpException extends TransportException
{
protected $statusCode;
@@ -0,0 +1,7 @@
<?php
namespace PhpXmlRpc\Exception;
class NoSuchMethodException extends ServerException
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* Base exception for errors while parsing xml-rpc requests/responses: charset issue, xml issues, xml-rpc issues
*/
class ParsingException extends BaseExtension
{
}
@@ -1,7 +1,4 @@
<?php
namespace PhpXmlRpc\Exception;
class PhpXmlrpcException extends \Exception
{
}
// deprecated. Kept around for BC
class_alias('PhpXmlRpc\Exception', 'PhpXmlRpc\Exception\PhpXmlRpcException');
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* Base exception for errors thrown by the server while trying to handle the requests, such as errors with the dispatch map
*/
class ServerException extends BaseExtension
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* Exception thrown when an object is in such a state that it can not fulfill execution of a method
*/
class StateErrorException extends BaseExtension
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* To be used for all errors related to the transport, which are not related to specifically to HTTP. Eg: can not open socket
*/
class TransportException extends BaseExtension
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* Exception thrown when an argument passed to a function or method has an unsupported type
*/
class TypeErrorException extends BaseExtension
{
}
@@ -0,0 +1,12 @@
<?php
namespace PhpXmlRpc\Exception;
use PhpXmlRpc\Exception as BaseExtension;
/**
* Exception thrown when an argument passed to a function or method has an unsupported value (but its type is ok)
*/
class ValueErrorException extends BaseExtension
{
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace PhpXmlRpc\Exception;
class XmlException extends ParsingException
{
}
@@ -0,0 +1,7 @@
<?php
namespace PhpXmlRpc\Exception;
class XmlRpcException extends ParsingException
{
}
+96 -30
View File
@@ -2,13 +2,17 @@
namespace PhpXmlRpc\Helper;
use PhpXmlRpc\Exception\ValueErrorException;
use PhpXmlRpc\PhpXmlRpc;
use PhpXmlRpc\Traits\DeprecationLogger;
/**
* @todo implement an interface
*/
class Charset
{
use DeprecationLogger;
// tables used for transcoding different charsets into us-ascii xml
protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
@@ -27,9 +31,10 @@ class Charset
/**
* This class is singleton for performance reasons.
* @todo should we just make $xml_iso88591_Entities a static variable instead ?
*
* @return Charset
*
* @todo should we just make $xml_iso88591_Entities a static variable instead ?
*/
public static function instance()
{
@@ -41,7 +46,7 @@ class Charset
}
/**
* Force usage as singleton
* Force usage as singleton.
*/
protected function __construct()
{
@@ -49,7 +54,10 @@ class Charset
/**
* @param string $tableName
* @throws \Exception for unsupported $tableName
* @return void
*
* @throws ValueErrorException for unsupported $tableName
*
* @todo add support for cp1252 as well as latin-2 .. latin-10
* Optimization creep: instead of building all those tables on load, keep them ready-made php files
* which are not even included until needed
@@ -58,12 +66,12 @@ class Charset
* (though no luck when receiving them...)
* Note also that, apparently, while 'ISO/IEC 8859-1' has no characters defined for bytes 128 to 159,
* IANA ISO-8859-1 does have well-defined 'C1' control codes for those - wikipedia's page on latin-1 says:
* "ISO-8859-1 is the IANA preferred name for this standard when supplemented with the C0 and C1 control codes from ISO/IEC 6429."
* Check what mbstring/iconv do by default with those?
* "ISO-8859-1 is the IANA preferred name for this standard when supplemented with the C0 and C1 control codes
* from ISO/IEC 6429." Check what mbstring/iconv do by default with those?
*/
protected function buildConversionTable($tableName)
{
switch($tableName) {
switch ($tableName) {
case 'xml_iso88591_Entities':
if (count($this->xml_iso88591_Entities['in'])) {
return;
@@ -103,7 +111,7 @@ class Charset
break;*/
default:
throw new \Exception('Unsupported table: ' . $tableName);
throw new ValueErrorException('Unsupported table: ' . $tableName);
}
}
@@ -111,7 +119,7 @@ class Charset
* Convert a string to the correct XML representation in a target charset.
* This involves:
* - character transformation for all characters which have a different representation in source and dest charsets
* - using 'charset entity' representation for all characters which are outside of the target charset
* - using 'charset entity' representation for all characters which are outside the 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
@@ -121,19 +129,19 @@ class Charset
* Note that when not sending a charset encoding mime type along with http headers, we are bound by RFC 3023 to emit
* strict us-ascii for 'text/xml' payloads (but we should review RFC 7303, which seems to have changed the rules...)
*
* @todo do a bit of basic benchmarking (strtr vs. str_replace)
* @todo make usage of iconv() or mb_string() where available
* @todo support aliases for charset names, eg ASCII, LATIN1, ISO-88591 (see f.e. polyfill-iconv for a list),
* but then take those into account as well in other methods, ie.isValidCharset)
* @todo when converting to ASCII, allow to choose whether to escape the range 0-31,127 (non-print chars) or not
* @todo allow picking different strategies to deal w. invalid chars? eg. source in latin-1 and chars 128-159
* @todo add support for escaping using CDATA sections? (add cdata start and end tokens, replace only ']]>' with ']]]]><![CDATA[>')
*
* @param string $data
* @param string $srcEncoding
* @param string $destEncoding
*
* @return string
*
* @todo do a bit of basic benchmarking: strtr vs. str_replace, str_replace vs htmlspecialchars, hand-coded conversion
* vs mbstring when that is enabled
* @todo make use of iconv when it is available and mbstring is not
* @todo support aliases for charset names, eg ASCII, LATIN1, ISO-88591 (see f.e. polyfill-iconv for a list),
* but then take those into account as well in other methods, ie. isValidCharset)
* @todo when converting to ASCII, allow to choose whether to escape the range 0-31,127 (non-print chars) or not
* @todo allow picking different strategies to deal w. invalid chars? eg. source in latin-1 and chars 128-159
* @todo add support for escaping using CDATA sections? (add cdata start and end tokens, replace only ']]>' with ']]]]><![CDATA[>')
*/
public function encodeEntities($data, $srcEncoding = '', $destEncoding = '')
{
@@ -146,6 +154,15 @@ class Charset
$destEncoding = 'US-ASCII';
}
// in case there is transcoding going on, let's upscale to UTF8
/// @todo we should do this as well when $srcEncoding == $destEncoding and the encoding is not supported by
/// htmlspecialchars
if (!in_array($srcEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')) && $srcEncoding != $destEncoding &&
function_exists('mb_convert_encoding')) {
$data = mb_convert_encoding($data, 'UTF-8', str_replace('US-ASCII', 'ASCII', $srcEncoding));
$srcEncoding = 'UTF-8';
}
$conversion = strtoupper($srcEncoding . '_' . $destEncoding);
// list ordered with (expected) most common scenarios first
@@ -163,7 +180,7 @@ class Charset
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
// be kind to users creating string xml-rpc values out of different php types
$data = (string)$data;
$ns = strlen($data);
for ($nn = 0; $nn < $ns; $nn++) {
@@ -235,8 +252,11 @@ class Charset
case 'ISO-8859-1_UTF-8':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
/// @todo if on php >= 8.2, prefer using mbstring or iconv. Also: suppress the warning!
if (function_exists('mb_convert_encoding')) {
$escapedData = mb_convert_encoding($escapedData, 'UTF-8', 'ISO-8859-1');
$escapedData = mb_convert_encoding($escapedData, 'UTF-8', 'ISO-8859-1');
} else {
$escapedData = utf8_encode($escapedData);
}
break;
@@ -258,7 +278,7 @@ class Charset
$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 alone will NOT convert them)
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
$escapedData = mb_convert_encoding($escapedData, 'UTF-8', 'ISO-8859-1');
$escapedData = utf8_encode($escapedData);
break;
case 'CP1252_ISO-8859-1':
$this->buildConversionTable('xml_cp1252_Entities');
@@ -269,28 +289,76 @@ class Charset
*/
default:
$escapedData = '';
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
if (function_exists('mb_convert_encoding')) {
// If reaching where, there are only 2 cases possible: UTF8->XXX or XXX->XXX
// If src is UTF8, we run htmlspecialchars before converting to the target charset, as
// htmlspecialchars has limited charset support, but it groks utf8
if ($srcEncoding === 'UTF-8') {
$data = htmlspecialchars($data, defined('ENT_XML1') ? ENT_XML1 | ENT_QUOTES : ENT_QUOTES, 'UTF-8');
}
if ($srcEncoding !== $destEncoding) {
try {
// php 7.4 and lower: a warning is generated. php 8.0 and up: an Error is thrown. So much for BC...
$data = @mb_convert_encoding($data, str_replace('US-ASCII', 'ASCII', $destEncoding), str_replace('US-ASCII', 'ASCII', $srcEncoding));
} catch (\ValueError $e) {
$data = false;
}
}
if ($data === false) {
$escapedData = '';
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding via mbstring: failed...");
} else {
if ($srcEncoding === 'UTF-8') {
$escapedData = $data;
} else {
$escapedData = htmlspecialchars($data, defined('ENT_XML1') ? ENT_XML1 | ENT_QUOTES : ENT_QUOTES, $destEncoding);
}
}
} else {
$escapedData = '';
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
}
}
return $escapedData;
}
/**
* @return string[]
*/
public function knownCharsets()
{
$knownCharsets = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
// Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
// http://www.iana.org/assignments/character-sets/character-sets.xhtml
if (function_exists('mb_list_encodings')) {
$knownCharsets = array_unique(array_merge($knownCharsets, array_diff(mb_list_encodings(), array(
'pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII', 'HTML-ENTITIES', 'Quoted-Printable',
'7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'
))));
}
return $knownCharsets;
}
// *** BC layer ***
/**
* 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.
* @deprecated kept around for BC, as it is not in use by the lib
*
* @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)
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
if (is_string($validList)) {
$validList = explode(',', $validList);
}
if (@in_array(strtoupper($encoding), $validList)) {
if (in_array(strtoupper($encoding), $validList)) {
return true;
} else {
if (array_key_exists($encoding, $this->charset_supersets)) {
@@ -306,25 +374,23 @@ class Charset
}
/**
* Used only for backwards compatibility
* Used only for backwards compatibility (the .inc shims).
* @deprecated
*
* @param string $charset
*
* @return array
*
* @throws \Exception for unknown/unsupported charsets
* @throws ValueErrorException for unknown/unsupported charsets
*/
public function getEntities($charset)
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
switch ($charset)
{
case 'iso88591':
return $this->xml_iso88591_Entities;
default:
throw new \Exception('Unsupported charset: ' . $charset);
throw new ValueErrorException('Unsupported charset: ' . $charset);
}
}
}
+18 -9
View File
@@ -2,6 +2,13 @@
namespace PhpXmlRpc\Helper;
use PhpXmlRpc\PhpXmlRpc;
/**
* Helps to convert timestamps to the xml-rpc date format.
*
* Feature creep -- add support for custom TZs
*/
class Date
{
/**
@@ -12,16 +19,18 @@ class Date
* "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)
* This routine always encodes to local time unless $utc is set to 1, in which case UTC output is produced and an
* adjustment for the local timezone's offset is made
*
* @param int|\DateTimeInterface $timet timestamp or datetime
* @param bool|int $utc (0 or 1)
* @return string
*/
public static function iso8601Encode($timet, $utc = 0)
{
if (is_a($timet, 'DateTimeInterface') || is_a($timet, 'DateTime')) {
$timet = $timet->getTimestamp();
}
if (!$utc) {
$t = date('Ymd\TH:i:s', $timet);
} else {
@@ -32,17 +41,17 @@ class Date
}
/**
* Given an ISO8601 date string, return a timet in the localtime, or UTC.
* Given an ISO8601 date string, return a timestamp in the localtime, or UTC.
*
* @param string $idate
* @param int $utc either 0 or 1
* @param bool|int $utc either 0 (assume date is in local time) or 1 (assume date is in UTC)
*
* @return int (datetime)
* @return int (timestamp) 0 if the source string does not match the xml-rpc dateTime format
*/
public static function iso8601Decode($idate, $utc = 0)
{
$t = 0;
if (preg_match('/([0-9]{4})([0-1][0-9])([0-3][0-9])T([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/', $idate, $regs)) {
if (preg_match(PhpXmlRpc::$xmlrpc_datetime_format, $idate, $regs)) {
if ($utc) {
$t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
} else {
+83 -65
View File
@@ -4,17 +4,19 @@ namespace PhpXmlRpc\Helper;
use PhpXmlRpc\Exception\HttpException;
use PhpXmlRpc\PhpXmlRpc;
use PhpXmlRpc\Traits\LoggerAware;
class Http
{
use LoggerAware;
/**
* Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6
* 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.
* @internal this function will become protected in the future
*
* @param string $buffer the string to be decoded
*
* @return string
* @internal this function will become protected in the future
*/
public static function decodeChunked($buffer)
{
@@ -51,7 +53,7 @@ class Http
$chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
if ($chunkEnd == false) {
break; //just in case we got a broken connection
break; // just in case we got a broken connection
}
$temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
$chunkSize = hexdec(trim($temp));
@@ -62,22 +64,24 @@ class Http
}
/**
* Parses HTTP an http response headers and separates them from the body.
* Parses HTTP an http response's 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
*
* @param int $debug when > 0, logs to screen messages detailing info about the parsed data
* @return array with keys 'headers', 'cookies', 'raw_data' and 'status_code'
* @throws HttpException
*
* @todo if $debug is < 0, we could avoid populating 'raw_data' and 'headers' in the returned value - but that would
* be a weird API...
*/
public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
public function parseResponseHeaders(&$data, $headersProcessed = false, $debug = 0)
{
$httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array(), 'status_code' => null);
// Support "web-proxy-tunnelling" 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)
// 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;
@@ -91,11 +95,10 @@ class Http
}
}
if ($bd) {
// this filters out all http headers from proxy.
// maybe we could take them into account, too?
// this filters out all http headers from proxy. maybe we could take them into account, too?
$data = substr($data, $bd);
} else {
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
}
}
@@ -114,10 +117,12 @@ class Http
}
// When using Curl to query servers using Digest Auth, we get back a double set of http headers.
// Same when following redirects
// We strip out the 1st...
if ($headersProcessed && preg_match('/^HTTP\/[0-9](?:\.[0-9])? 401 /', $data)) {
/// @todo we should let the caller know that there was a redirect involved
if ($headersProcessed && preg_match('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) /', $data)) {
if (preg_match('/(\r?\n){2}HTTP\/[0-9](?:\.[0-9])? 200 /', $data)) {
$data = preg_replace('/^HTTP\/[0-9](?:\.[0-9])? 401 .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
$data = preg_replace('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
}
}
@@ -128,12 +133,11 @@ class Http
if ($httpResponse['status_code'] !== '200') {
$errstr = substr($data, 0, strpos($data, "\n") - 1);
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error'], null, $httpResponse['status_code'] );
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error'], null, $httpResponse['status_code']);
}
// be tolerant to usage of \n instead of \r\n to separate headers and data
// (even though it is not valid http)
// 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;
@@ -151,57 +155,48 @@ class Http
// be tolerant to line endings, and extra empty lines
$ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
foreach($ar as $line) {
// take care of multi-line headers and cookies
foreach ($ar as $line) {
// take care of (multi-line) headers and cookies
$arr = explode(':', $line, 2);
if (count($arr) > 1) {
/// @todo according to https://www.rfc-editor.org/rfc/rfc7230#section-3.2.4, we should reject with error
/// 400 any messages where a space is present between the header name and colon
$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...
/// @todo should we drop support for rfc2965 (set-cookie2) cookies? It has been obsoleted since 2011
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]);
if ($headerName == 'set-cookie') {
$cookie = $arr[1];
// 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 {
$cookies = array($arr[1]);
$httpResponse['headers'][$headerName] = trim($cookie);
}
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 = isset($val[1]) ? 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;
}
// parse cookie attributes, in case user wants to correctly honour them
// @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 = isset($val[1]) ? trim($val[1]) : '';
if ($pos === 0) {
$cookieName = $tag;
// if present, we have strip leading and trailing " chars from $val
if (preg_match('/^"(.*)"$/', $val, $matches)) {
$val = $matches[1];
}
$httpResponse['cookies'][$cookieName] = array('value' => urldecode($val));
} else {
$httpResponse['cookies'][$cookieName][$tag] = $val;
}
}
} else {
/// @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...
$httpResponse['headers'][$headerName] = trim($arr[1]);
}
} elseif (isset($headerName)) {
/// @todo version1 cookies might span multiple lines, thus breaking the parsing above
/// @todo improve this: 1. check that the line starts with a space or tab; 2. according to
/// https://www.rfc-editor.org/rfc/rfc7230#section-3.2.4, we should flat out refuse these messages
$httpResponse['headers'][$headerName] .= ' ' . trim($line);
}
}
@@ -216,17 +211,16 @@ class Http
foreach ($httpResponse['cookies'] as $header => $value) {
$msg .= "COOKIE: $header={$value['value']}\n";
}
Logger::instance()->debugMessage($msg);
$this->getLogger()->debug($msg);
}
// if CURL was used for the call, http headers have been processed,
// and dechunking + reinflating have been carried out
// 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 = static::decodeChunked($data)) {
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
throw new HttpException(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail'], null, $httpResponse['status_code']);
}
}
@@ -241,19 +235,19 @@ class Http
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---");
$this->getLogger()->debug("---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---");
$this->getLogger()->debug("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
}
} else {
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
throw new HttpException(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail'], null, $httpResponse['status_code']);
}
} else {
Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
throw new HttpException(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress'], null, $httpResponse['status_code']);
}
}
@@ -262,4 +256,28 @@ class Http
return $httpResponse;
}
/**
* Parses one of the http headers which can have a list of values with quality param.
* @see https://www.rfc-editor.org/rfc/rfc7231#section-5.3.1
*
* @param string $header
* @return string[]
*/
public function parseAcceptHeader($header)
{
$accepted = array();
foreach(explode(',', $header) as $c) {
if (preg_match('/^([^;]+); *q=([0-9.]+)/', $c, $matches)) {
$c = $matches[1];
$w = $matches[2];
} else {
$c = preg_replace('/;.*/', '', $c);
$w = 1;
}
$accepted[(trim($c))] = $w;
}
arsort($accepted);
return array_keys($accepted);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace PhpXmlRpc\Helper;
/**
* A helper dedicated to support Interoperability features
*/
class Interop
{
/// @todo review - should we use the range -32099 .. -32000 for some server erors?
public static $xmlrpcerr = array(
'unknown_method' => -32601,
'invalid_return' => 2,
'incorrect_params' => -32602,
'introspect_unknown' => -32601, // this shares the same code but has a separate meaning from 'unknown_method'...
'http_error' => -32300,
'no_data' => -32700,
'no_ssl' => -32400,
'curl_fail' => -32400,
'invalid_request' => -32600,
'no_curl' => -32400,
'server_error' => -32500,
'multicall_error' => -32700,
'multicall_notstruct' => -32600,
'multicall_nomethod' => -32601,
'multicall_notstring' => -32600,
'multicall_recursion' => -32603,
'multicall_noparams' => -32602,
'multicall_notarray' => -32600,
'no_http2' => -32400,
'invalid_xml' => -32700,
'xml_not_compliant' => -32700,
'xml_parsing_error' => -32700,
'cannot_decompress' => -32400,
'decompress_fail' => -32300,
'dechunk_fail' => -32300,
'server_cannot_decompress' => -32300,
'server_decompress_fail' => -32300,
);
public static $xmlrpcerruser = -32000;
}
+55 -4
View File
@@ -11,7 +11,7 @@ class Logger
protected static $instance = null;
/**
* This class can be used as singleton, so that later we can move to DI patterns.
* This class can be used as singleton, so that later we can move to DI patterns (ish...)
*
* @return Logger
*/
@@ -24,13 +24,60 @@ class Logger
return self::$instance;
}
// *** Implement the same interface as PSR/LOG, for the sake of interoperability ***
/**
* NB: unlike other "traditional" loggers, this one echoes to screen the debug messages instead of logging them.
*
* @param string $message
* @param array $context known key: 'encoding'
* @return void
*/
public function debug($message, $context = array())
{
if (isset($context['encoding'])) {
$this->debugMessage($message, $context['encoding']);
} else {
$this->debugMessage($message);
}
}
/**
* Following the general principle of 'never break stdout', the default behaviour
*
* @param string $message
* @param $context
* @return void
*/
public function warning($message, $context = array())
{
$this->errorLog(preg_replace('/^XML-RPC :/', 'XML-RPC Warning: ', $message));
}
/**
* Triggers the writing of a message to php's error log
*
* @param string $message
* @param array $context
* @return void
*/
public function error($message, $context = array())
{
$this->errorLog(preg_replace('/^XML-RPC :/', 'XML-RPC Error: ', $message));
}
// BC interface
/**
* 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
* @param string $encoding deprecated
* @return void
*
* @internal left in purely for BC
*/
public function debugMessage($message, $encoding = null)
{
@@ -57,13 +104,17 @@ class Logger
print "\n$message\n";
}
// let the user see this now in case there's a time out later...
// let the user see this now in case there's a time-out later...
flush();
}
/**
* Writes a message to the error log
* Writes a message to the error log.
*
* @param string $message
* @return void
*
* @internal left in purely for BC
*/
public function errorLog($message)
{
File diff suppressed because it is too large Load Diff
+219 -54
View File
@@ -2,32 +2,48 @@
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
use PhpXmlRpc\Helper\Http;
use PhpXmlRpc\Helper\Interop;
use PhpXmlRpc\Helper\XMLParser;
/**
* 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,
'no_http2' => 15,
/**
* @var int[]
*/
public static $xmlrpcerr = array(
'unknown_method' => 1, // server
/// @deprecated. left in for BC
'invalid_return' => 2, // client
'incorrect_params' => 3, // server
'introspect_unknown' => 4, // server
'http_error' => 5, // client
'no_data' => 6, // client
'no_ssl' => 7, // client
'curl_fail' => 8, // client
'invalid_request' => 15, // server
'no_curl' => 16, // client
'server_error' => 17, // server
'multicall_error' => 18, // client
'multicall_notstruct' => 9, // client
'multicall_nomethod' => 10, // client
'multicall_notstring' => 11, // client
'multicall_recursion' => 12, // client
'multicall_noparams' => 13, // client
'multicall_notarray' => 14, // client
'no_http2' => 19, // client
'unsupported_option' => 20, // client
// the following 3 are meant to give greater insight than 'invalid_return'. They use the same code for BC,
// but you can override their value in your own code
'invalid_xml' => 2, // client
'xml_not_compliant' => 2, // client
'xml_parsing_error' => 2, // client
/// @todo verify: can these conflict with $xmlrpcerrxml?
'cannot_decompress' => 103,
'decompress_fail' => 104,
'dechunk_fail' => 105,
@@ -35,8 +51,12 @@ class PhpXmlRpc
'server_decompress_fail' => 107,
);
static public $xmlrpcstr = array(
/**
* @var string[]
*/
public static $xmlrpcstr = array(
'unknown_method' => 'Unknown method',
/// @deprecated. left in for BC
'invalid_return' => 'Invalid response payload (you can use the setDebug method to allow analysis of the response)',
'incorrect_params' => 'Incorrect parameters passed to method',
'introspect_unknown' => "Can't introspect: method unknown",
@@ -55,6 +75,12 @@ class PhpXmlRpc
'multicall_noparams' => 'Missing params',
'multicall_notarray' => 'params is not an array',
'no_http2' => 'No HTTP/2 support compiled in',
'unsupported_option' => 'Some client option is not supported with the transport method currently in use',
// the following 3 are meant to give greater insight than 'invalid_return'. They use the same string for BC,
// but you can override their value in your own code
'invalid_xml' => 'Invalid response payload (you can use the setDebug method to allow analysis of the response)',
'xml_not_compliant' => 'Invalid response payload (you can use the setDebug method to allow analysis of the response)',
'xml_parsing_error' => 'Invalid response payload (you can use the setDebug method to allow analysis of the response)',
'cannot_decompress' => 'Received from server compressed HTTP and cannot decompress',
'decompress_fail' => 'Received from server invalid compressed HTTP',
@@ -63,50 +89,182 @@ class PhpXmlRpc
'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
/**
* @var string
* 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
/**
* @var string[]
* The list of preferred 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
/**
* @var string
* 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 xml-rpc methods
*/
public static $xmlrpc_internalencoding = "UTF-8";
/**
* @var string
*/
public static $xmlrpcName = "XML-RPC for PHP";
public static $xmlrpcVersion = "4.8.1";
/**
* @var string
*/
public static $xmlrpcVersion = "4.10.1";
// let user errors start at 800
/**
* @var int
* Let user errors start at 800
*/
public static $xmlrpcerruser = 800;
// let XML parse errors start at 100
/**
* @var int
* Let XML parse errors start at 100
*/
public static $xmlrpcerrxml = 100;
// set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values
/**
* @var bool
* 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/>
/**
* @var bool
* Set to TRUE to make the library use DateTime objects instead of strings for all values parsed from incoming XML.
* NB: if the received strings are not parseable as dates, NULL will be returned. To prevent that, enable as
* well `xmlrpc_reject_invalid_values`, so that invalid dates will be rejected by the library
*/
public static $xmlrpc_return_datetimes = false;
/**
* @var bool
* Set to TRUE to make the library reject incoming xml which uses invalid data for xml-rpc elements, such
* as base64 strings which can not be decoded, dateTime strings which do not represent a valid date, invalid bools,
* floats and integers, method names with forbidden characters, or struct members missing the value or name
*/
public static $xmlrpc_reject_invalid_values = false;
/**
* @var bool
* 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";
// number of decimal digits used to serialize Double values
/**
* @var int
* Number of decimal digits used to serialize Double values.
* @todo rename :'-(
*/
public static $xmlpc_double_precision = 128;
/**
* @var string
* Used to validate received date values. Alter this if the server/client you are communicating with uses date
* formats non-conformant with the spec
* NB: the string should not match any data which php can not successfully use in a DateTime object constructor call
* NB: atm, the Date helper uses this regexp and expects to find matches in a specific order
*/
public static $xmlrpc_datetime_format = '/^([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9]|60)$/';
/**
* @var string
* Used to validate received integer values. Alter this if the server/client you are communicating with uses
* formats non-conformant with the spec.
* We keep in spaces for BC, even though they are forbidden by the spec.
* NB: the string should not match any data which php can not successfully cast to an integer
*/
public static $xmlrpc_int_format = '/^[ \t]*[+-]?[0-9]+[ \t]*$/';
/**
* @var string
* Used to validate received double values. Alter this if the server/client you are communicating with uses
* formats non-conformant with the spec, e.g. with leading/trailing spaces/tabs/newlines.
* We keep in spaces for BC, even though they are forbidden by the spec.
* NB: the string should not match any data which php can not successfully cast to a float
*/
public static $xmlrpc_double_format = '/^[ \t]*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?[ \t]*$/';
/**
* @var string
* Used to validate received methodname values.
* According to the spec: "The string may only contain identifier characters, upper and lower-case A-Z, the numeric
* characters, 0-9, underscore, dot, colon and slash".
* We keep in leading and trailing spaces for BC, even though they are forbidden by the spec.
* But what about "identifier characters"? Is that meant to be 'identifier characters: upper and lower-case A-Z, ...'
* or something else? If the latter, there is no consensus across programming languages about what is a valid
* identifier character. PHP has one of the most crazy definitions of what is a valid identifier character, allowing
* _bytes_ in range x80-xff, without even specifying a character set (and then lowercasing anyway in some cases)...
*/
public static $xmlrpc_methodname_format = '|^[ \t]*[a-zA-Z0-9_.:/]+[ \t]*$|';
/**
* @var bool
* Set this to false to have a warning added to the log whenever user code uses a deprecated method/parameter/property
*/
public static $xmlrpc_silence_deprecations = true;
// *** BC layer ***
/**
* Inject a logger into all classes of the PhpXmlRpc library which use one
*
* @param $logger
* @return void
*/
public static function setLogger($logger)
{
Charset::setLogger($logger);
Client::setLogger($logger);
Encoder::setLogger($logger);
Http::setLogger($logger);
Request::setLogger($logger);
Server::setLogger($logger);
Value::setLogger($logger);
Wrapper::setLogger($logger);
XMLParser::setLogger($logger);
}
/**
* Makes the library use the error codes detailed at https://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
*
* @return void
*
* @tofo feature creep - allow switching back to the original set of codes; querying the current mode
*/
public static function useInteropFaults()
{
self::$xmlrpcerr = Interop::$xmlrpcerr;
self::$xmlrpcerruser = -Interop::$xmlrpcerruser;
}
/**
* 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...
* @return void
*
* @deprecated
*/
public static function exportGlobals()
{
$reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc');
foreach ($reflection->getStaticProperties() as $name => $value) {
$GLOBALS[$name] = $value;
if (!in_array($name, array('xmlrpc_return_datetimes', 'xmlrpc_reject_invalid_values', 'xmlrpc_datetime_format',
'xmlrpc_int_format', 'xmlrpc_double_format', 'xmlrpc_methodname_format', 'xmlrpc_silence_deprecations'))) {
$GLOBALS[$name] = $value;
}
}
// NB: all the variables exported into the global namespace below here do NOT guarantee 100% compatibility,
@@ -114,19 +272,17 @@ class PhpXmlRpc
$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);
if (!in_array($name, array('logger', 'charsetEncoder'))) {
$GLOBALS[$name] = $value;
}
}
$charset = Helper\Charset::instance();
/// @todo mke it possible to inject the XMLParser and Charset, as we do in other classes
$parser = new Helper\XMLParser();
$GLOBALS['xmlrpc_valid_parents'] = $parser->xmlrpc_valid_parents;
$charset = Charset::instance();
$GLOBALS['xml_iso88591_Entities'] = $charset->getEntities('iso88591');
}
@@ -139,14 +295,23 @@ class PhpXmlRpc
* 2. set the values, e.g. $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
* 3. import them: PhpXmlRpc\PhpXmlRpc::importGlobals();
* 4. run your own code.
*
* @return void
*
* @deprecated
*
* @todo this function does not import back xmlrpc_valid_parents and xml_iso88591_Entities
*/
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];
foreach ($reflection->getStaticProperties() as $name => $value) {
if (!in_array($name, array('xmlrpc_return_datetimes', 'xmlrpc_reject_invalid_values', 'xmlrpc_datetime_format',
'xmlrpc_int_format', 'xmlrpc_double_format', 'xmlrpc_methodname_format', 'xmlrpc_silence_deprecations')))
{
if (isset($GLOBALS[$name])) {
self::$$name = $GLOBALS[$name];
}
}
}
}
+331 -185
View File
@@ -3,72 +3,44 @@
namespace PhpXmlRpc;
use PhpXmlRpc\Exception\HttpException;
use PhpXmlRpc\Helper\Charset;
use PhpXmlRpc\Helper\Http;
use PhpXmlRpc\Helper\Logger;
use PhpXmlRpc\Helper\XMLParser;
use PhpXmlRpc\Traits\CharsetEncoderAware;
use PhpXmlRpc\Traits\DeprecationLogger;
use PhpXmlRpc\Traits\ParserAware;
use PhpXmlRpc\Traits\PayloadBearer;
/**
* 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.
*
* @todo feature creep - add a protected $httpRequest member, in the same way the Response has one
*
* @property string $methodname deprecated - public access left in purely for BC. Access via method()/__construct()
* @property Value[] $params deprecated - public access left in purely for BC. Access via getParam()/__construct()
* @property int $debug deprecated - public access left in purely for BC. Access via .../setDebug()
* @property string $payload deprecated - public access left in purely for BC. Access via getPayload()/setPayload()
* @property string $content_type deprecated - public access left in purely for BC. Access via getContentType()/setPayload()
*/
class Request
{
protected static $logger;
protected static $parser;
protected static $charsetEncoder;
use CharsetEncoderAware;
use DeprecationLogger;
use ParserAware;
use PayloadBearer;
/// @todo: do these need to be public?
public $payload;
/** @internal */
public $methodname;
/** @internal */
public $params = array();
public $debug = 0;
public $content_type = 'text/xml';
/** @var string */
protected $methodname;
/** @var Value[] */
protected $params = array();
/** @var int */
protected $debug = 0;
// holds data while parsing the response. NB: Not a full Response object
/** @deprecated will be removed in a future release */
protected $httpResponse = array();
public function getLogger()
{
if (self::$logger === null) {
self::$logger = Logger::instance();
}
return self::$logger;
}
public static function setLogger($logger)
{
self::$logger = $logger;
}
public function getParser()
{
if (self::$parser === null) {
self::$parser = new XMLParser();
}
return self::$parser;
}
public static function setParser($parser)
{
self::$parser = $parser;
}
public function getCharsetEncoder()
{
if (self::$charsetEncoder === null) {
self::$charsetEncoder = Charset::instance();
}
return self::$charsetEncoder;
}
public function setCharsetEncoder($charsetEncoder)
{
self::$charsetEncoder = $charsetEncoder;
}
/**
* holds data while parsing the response. NB: Not a full Response object
* @deprecated will be removed in a future release; still accessible by subclasses for the moment
*/
private $httpResponse = array();
/**
* @param string $methodName the name of the method to invoke
@@ -83,56 +55,9 @@ class Request
}
/**
* @internal this function will become protected in the future
* @param string $charsetEncoding
* @return string
*/
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";
}
}
/**
* @internal this function will become protected in the future
* @return string
*/
public function xml_footer()
{
return '</methodCall>';
}
/**
* @internal this function will become protected in the future
* @param string $charsetEncoding
*/
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>' . $this->getCharsetEncoder()->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.
* Gets/sets the xml-rpc 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 = '')
@@ -144,37 +69,22 @@ class Request
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)
{
// check: do not add to self params which are not xmlrpc values
// check: do not add to self params which are not xml-rpc values
if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
$this->params[] = $param;
return true;
} else {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': value passed in must be a PhpXmlRpc\Value');
return false;
}
}
@@ -183,7 +93,6 @@ class Request
* 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)
@@ -202,7 +111,79 @@ class Request
}
/**
* Given an open file handle, read all data available and parse it as an xmlrpc response.
* Returns xml representation of the message, XML prologue included. Sets `payload` and `content_type` properties
*
* @param string $charsetEncoding
* @return string the xml representation of the message, xml prologue included
*/
public function serialize($charsetEncoding = '')
{
$this->createPayload($charsetEncoding);
return $this->payload;
}
/**
* @internal this function will become protected in the future (and be folded into serialize)
*
* @param string $charsetEncoding
* @return void
*/
public function createPayload($charsetEncoding = '')
{
$this->logDeprecationUnlessCalledBy('serialize');
if ($charsetEncoding != '') {
$this->content_type = 'text/xml; charset=' . $charsetEncoding;
} else {
$this->content_type = 'text/xml';
}
$result = $this->xml_header($charsetEncoding);
$result .= '<methodName>' . $this->getCharsetEncoder()->encodeEntities(
$this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
$result .= "<params>\n";
foreach ($this->params as $p) {
$result .= "<param>\n" . $p->serialize($charsetEncoding) .
"</param>\n";
}
$result .= "</params>\n";
$result .= $this->xml_footer();
$this->payload = $result;
}
/**
* @internal this function will become protected in the future (and be folded into serialize)
*
* @param string $charsetEncoding
* @return string
*/
public function xml_header($charsetEncoding = '')
{
$this->logDeprecationUnlessCalledBy('createPayload');
if ($charsetEncoding != '') {
return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
} else {
return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
}
}
/**
* @internal this function will become protected in the future (and be folded into serialize)
*
* @return string
*/
public function xml_footer()
{
$this->logDeprecationUnlessCalledBy('createPayload');
return '</methodCall>';
}
/**
* Given an open file handle, read all data available and parse it as an xml-rpc 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
@@ -212,12 +193,15 @@ class Request
* @param resource $fp stream pointer
* @param bool $headersProcessed
* @param string $returnType
*
* @return Response
*
* @todo arsing Responses is not really the responsibility of the Request class. Maybe of the Client...
* @todo feature creep - add a flag to disable trying to parse the http headers
*/
public function parseResponseFile($fp, $headersProcessed = false, $returnType = 'xmlrpcvals')
{
$ipd = '';
// q: is there an optimal buffer size? Is there any value in making the buffer size a tuneable?
while ($data = fread($fp, 32768)) {
$ipd .= $data;
}
@@ -225,30 +209,33 @@ class Request
}
/**
* Parse the xmlrpc response contained in the string $data and return a Response object.
* Parse the xml-rpc 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 string $data the xml-rpc 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
*
* @todo parsing Responses is not really the responsibility of the Request class. Maybe of the Client...
* @todo what about only populating 'raw_data' in httpResponse when debug mode is > 0?
* @todo feature creep - allow parsing data gotten from a stream pointer instead of a string: read it piecewise,
* looking first for separation between headers and body, then for charset indicators, server debug info and
* </methodResponse>. That would require a notable increase in code complexity...
*/
public function parseResponse($data = '', $headersProcessed = false, $returnType = XMLParser::RETURN_XMLRPCVALS)
{
if ($this->debug) {
$this->getLogger()->debugMessage("---GOT---\n$data\n---END---");
if ($this->debug > 0) {
$this->getLogger()->debug("---GOT---\n$data\n---END---");
}
$this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
if ($data == '') {
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': no response received from server.');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': no response received from server.');
return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
}
@@ -256,7 +243,7 @@ class Request
if (substr($data, 0, 4) == 'HTTP') {
$httpParser = new Http();
try {
$this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
$httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug > 0);
} catch (HttpException $e) {
// failed processing of HTTP response headers
// save into response obj the full payload received, for debugging
@@ -264,42 +251,54 @@ class Request
} catch(\Exception $e) {
return new Response(0, $e->getCode(), $e->getMessage(), '', array('raw_data' => $data));
}
} else {
$httpResponse = $this->httpResponse;
}
// be tolerant of extra whitespace in response body
$data = trim($data);
/// @todo return an error msg if $data == '' ?
/// @todo optimization creep - 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 <[email protected]> originally in PEARified version of the lib
// idea from Luca Mariano, 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);
$respEncoding = XMLParser::guessEncoding(
isset($httpResponse['headers']['content-type']) ? $httpResponse['headers']['content-type'] : '',
$data
);
if ($this->debug) {
if ($this->debug >= 0) {
$this->httpResponse = $httpResponse;
} else {
$httpResponse = null;
}
if ($this->debug > 0) {
$start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
if ($start) {
$start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
/// @todo what if there is no end tag?
$end = strpos($data, '-->', $start);
$comments = substr($data, $start, $end - $start);
$this->getLogger()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
$this->getLogger()->debug("---SERVER DEBUG INFO (DECODED)---\n\t" .
str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", array('encoding' => $respEncoding));
}
}
// if user wants back raw xml, give it to her
// if the user wants back raw xml, give it to her
if ($returnType == 'xml') {
return new Response($data, 0, '', 'xml', $this->httpResponse);
return new Response($data, 0, '', 'xml', $httpResponse);
}
/// @todo move this block of code into the XMLParser
if ($respEncoding != '') {
// Since parsing will fail if charset is not specified in the xml prologue,
// Since parsing will fail if charset is not specified in the xml declaration,
// 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')))
@@ -307,75 +306,81 @@ class Request
if (function_exists('mb_convert_encoding')) {
$data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
} else {
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': unsupported charset encoding of received response: ' . $respEncoding);
if ($respEncoding == 'ISO-8859-1') {
$data = utf8_encode($data);
} else {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': unsupported charset encoding of received response: ' . $respEncoding);
}
}
}
}
// PHP internally might use 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'))) {
/// @todo emit a warning
$options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8');
} else {
// What if internal encoding is not in one of the 3 allowed? We use the broadest one, i.e. utf8
if (in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
$options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
} else {
$options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8', 'target_charset' => PhpXmlRpc::$xmlrpc_internalencoding);
}
$xmlRpcParser = $this->getParser();
$xmlRpcParser->parse($data, $returnType, XMLParser::ACCEPT_RESPONSE, $options);
$_xh = $xmlRpcParser->parse($data, $returnType, XMLParser::ACCEPT_RESPONSE, $options);
// BC
if (!is_array($_xh)) {
$_xh = $xmlRpcParser->_xh;
}
// first error check: xml not well formed
if ($xmlRpcParser->_xh['isf'] > 2) {
// first error check: xml not well-formed
if ($_xh['isf'] == 3) {
// BC break: in the past for some cases we used the error message: 'XML error at line 1, check URL'
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason'], '',
$this->httpResponse
);
// Q: should we give back an error with variable error number, as we do server-side? But if we do, will
// we be able to tell apart the two cases? In theory, we never emit invalid xml on our end, but
// there could be proxies meddling with the request, or network data corruption...
if ($this->debug) {
print $xmlRpcParser->_xh['isf_reason'];
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_xml'],
PhpXmlRpc::$xmlrpcstr['invalid_xml'] . ' ' . $_xh['isf_reason'], '', $httpResponse);
if ($this->debug > 0) {
$this->getLogger()->debug($_xh['isf_reason']);
}
}
// second error check: xml well formed but not xml-rpc compliant
elseif ($xmlRpcParser->_xh['isf'] == 2) {
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason'], '',
$this->httpResponse
);
// second error check: xml well-formed but not xml-rpc compliant
elseif ($_xh['isf'] == 2) {
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['xml_not_compliant'],
PhpXmlRpc::$xmlrpcstr['xml_not_compliant'] . ' ' . $_xh['isf_reason'], '', $httpResponse);
if ($this->debug) {
/// @todo echo something for user?
}
/// @todo echo something for the user? check if it was already done by the parser...
//if ($this->debug > 0) {
// $this->getLogger()->debug($_xh['isf_reason']);
//}
}
// third error check: parsing of the response has somehow gone boink.
/// @todo shall we omit this check, since we trust the parsing code?
elseif ($returnType == XMLParser::RETURN_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'],
'', $this->httpResponse
elseif ($_xh['isf'] > 3 || $returnType == XMLParser::RETURN_XMLRPCVALS && !is_object($_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['xml_parsing_error'], PhpXmlRpc::$xmlrpcstr['xml_parsing_error'],
'', $httpResponse
);
/// @todo echo something for the user?
} else {
if ($this->debug > 1) {
$this->getLogger()->debugMessage(
"---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
$this->getLogger()->debug(
"---PARSED---\n".var_export($_xh['value'], true)."\n---END---"
);
}
$v = $xmlRpcParser->_xh['value'];
$v = $_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 ($_xh['isf']) {
/// @todo we should test (here or preferably in the parser) if server sent an int and a string, and/or
/// coerce them into such...
if ($returnType == XMLParser::RETURN_XMLRPCVALS) {
$errNo_v = $v['faultCode'];
$errStr_v = $v['faultString'];
$errNo = $errNo_v->scalarval();
$errStr = $errStr_v->scalarval();
$errNo = $errNo_v->scalarVal();
$errStr = $errStr_v->scalarVal();
} else {
$errNo = $v['faultCode'];
$errStr = $v['faultString'];
@@ -383,12 +388,16 @@ class Request
if ($errNo == 0) {
// FAULT returned, errno needs to reflect that
/// @todo feature creep - add this code to PhpXmlRpc::$xmlrpcerr
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': fault response received with faultCode 0 or null. Converted it to -1');
/// @todo in Encoder::decodeXML, we use PhpXmlRpc::$xmlrpcerr['invalid_return'] for this case (see
/// also the todo 17 lines above)
$errNo = -1;
}
$r = new Response(0, $errNo, $errStr, '', $this->httpResponse);
$r = new Response(0, $errNo, $errStr, '', $httpResponse);
} else {
$r = new Response($v, 0, '', $returnType, $this->httpResponse);
$r = new Response($v, 0, '', $returnType, $httpResponse);
}
}
@@ -396,7 +405,7 @@ class Request
}
/**
* Kept the old name even if Request class was renamed, for compatibility.
* Kept the old name even if Request class was renamed, for BC.
*
* @return string
*/
@@ -406,12 +415,149 @@ class Request
}
/**
* Enables/disables the echoing to screen of the xmlrpc responses received.
* Enables/disables the echoing to screen of the xml-rpc responses received.
*
* @param integer $level values 0, 1, 2 are supported
* @param integer $level values <0, 0, 1, >1 are supported
* @return $this
*/
public function setDebug($level)
{
$this->debug = $level;
return $this;
}
// *** BC layer ***
// we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
public function &__get($name)
{
switch ($name) {
case 'me':
case 'mytype':
case '_php_class':
case 'payload':
case 'content_type':
$this->logDeprecation('Getting property Request::' . $name . ' is deprecated');
return $this->$name;
case 'httpResponse':
// manually implement the 'protected property' behaviour
$canAccess = false;
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
if (isset($trace[1]) && isset($trace[1]['class'])) {
if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
$canAccess = true;
}
}
if ($canAccess) {
$this->logDeprecation('Getting property Request::' . $name . ' is deprecated');
return $this->httpResponse;
} else {
trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
}
break;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
$result = null;
return $result;
}
}
public function __set($name, $value)
{
switch ($name) {
case 'methodname':
case 'params':
case 'debug':
case 'payload':
case 'content_type':
$this->logDeprecation('Setting property Request::' . $name . ' is deprecated');
$this->$name = $value;
break;
case 'httpResponse':
// manually implement the 'protected property' behaviour
$canAccess = false;
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
if (isset($trace[1]) && isset($trace[1]['class'])) {
if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
$canAccess = true;
}
}
if ($canAccess) {
$this->logDeprecation('Setting property Request::' . $name . ' is deprecated');
$this->httpResponse = $value;
} else {
trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
}
break;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
public function __isset($name)
{
switch ($name) {
case 'methodname':
case 'params':
case 'debug':
case 'payload':
case 'content_type':
$this->logDeprecation('Checking property Request::' . $name . ' is deprecated');
return isset($this->$name);
case 'httpResponse':
// manually implement the 'protected property' behaviour
$canAccess = false;
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
if (isset($trace[1]) && isset($trace[1]['class'])) {
if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
$canAccess = true;
}
}
if ($canAccess) {
$this->logDeprecation('Checking property Request::' . $name . ' is deprecated');
return isset($this->httpResponse);
}
// break through voluntarily
default:
return false;
}
}
public function __unset($name)
{
switch ($name) {
case 'methodname':
case 'params':
case 'debug':
case 'payload':
case 'content_type':
$this->logDeprecation('Unsetting property Request::' . $name . ' is deprecated');
unset($this->$name);
break;
case 'httpResponse':
// manually implement the 'protected property' behaviour
$canAccess = false;
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
if (isset($trace[1]) && isset($trace[1]['class'])) {
if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
$canAccess = true;
}
}
if ($canAccess) {
$this->logDeprecation('Unsetting property Request::' . $name . ' is deprecated');
unset($this->httpResponse);
} else {
trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
}
break;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
}
+144 -69
View File
@@ -2,58 +2,58 @@
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
use PhpXmlRpc\Exception\StateErrorException;
use PhpXmlRpc\Traits\CharsetEncoderAware;
use PhpXmlRpc\Traits\DeprecationLogger;
use PhpXmlRpc\Traits\PayloadBearer;
/**
* 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.
*
* @property array $hdrs deprecated, use $httpResponse['headers']
* @property array _cookies deprecated, use $httpResponse['cookies']
* @property string $raw_data deprecated, use $httpResponse['raw_data']
* @property Value|string|mixed $val deprecated - public access left in purely for BC. Access via value()/__construct()
* @property string $valtyp deprecated - public access left in purely for BC. Access via valueType()/__construct()
* @property int $errno deprecated - public access left in purely for BC. Access via faultCode()/__construct()
* @property string $errstr deprecated - public access left in purely for BC. Access faultString()/__construct()
* @property string $payload deprecated - public access left in purely for BC. Access via getPayload()/setPayload()
* @property string $content_type deprecated - public access left in purely for BC. Access via getContentType()/setPayload()
* @property array $hdrs deprecated. Access via httpResponse()['headers'], set via $httpResponse['headers']
* @property array _cookies deprecated. Access via httpResponse()['cookies'], set via $httpResponse['cookies']
* @property string $raw_data deprecated. Access via httpResponse()['raw_data'], set via $httpResponse['raw_data']
*/
class Response
{
protected static $charsetEncoder;
use CharsetEncoderAware;
use DeprecationLogger;
use PayloadBearer;
/** @var Value|string|mixed */
protected $val = 0;
/** @var string */
protected $valtyp;
/** @var int */
protected $errno = 0;
/** @var string */
protected $errstr = '';
/// @todo: do these need to be public?
/** @internal */
public $val = 0;
/** @internal */
public $valtyp;
/** @internal */
public $errno = 0;
/** @internal */
public $errstr = '';
public $payload;
public $content_type = 'text/xml';
protected $httpResponse = array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null);
public function getCharsetEncoder()
{
if (self::$charsetEncoder === null) {
self::$charsetEncoder = Charset::instance();
}
return self::$charsetEncoder;
}
public function setCharsetEncoder($charsetEncoder)
{
self::$charsetEncoder = $charsetEncoder;
}
/**
* @param Value|string|mixed $val either a Value object, a php value or the xml serialization of an xmlrpc value (a string)
* @param Value|string|mixed $val either a Value object, a php value or the xml serialization of an xml-rpc value (a string).
* Note that using anything other than a Value object wll have an impact on serialization.
* @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.
* @param array|null $httpResponse
* the code guess the correct type by looking at $val - in which case strings are assumed
* to be serialized xml
* @param array|null $httpResponse this should be set when the response is being built out of data received from
* http (i.e. not when programmatically building a Response server-side). Array
* keys should include, if known: headers, cookies, raw_data, status_code
*
* @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...
* @todo add check that $val / $fCode / $fString is of correct type? We could at least log a warning for fishy cases...
* NB: as of now we do not do it, since it might be either an xml-rpc value or a plain php val, or a complete
* xml chunk, depending on usage of Client::send() inside which the constructor is called.
*/
public function __construct($val, $fCode = 0, $fString = '', $valType = '', $httpResponse = null)
{
@@ -74,8 +74,12 @@ class Response
$this->valtyp = 'phpvals';
}
} else {
// user declares type of resp value: believe him
$this->valtyp = $valType;
// user declares the type of resp value: we "almost" trust it... but log errors just in case
if (($this->valtyp == 'xmlrpcvals' && (!is_a($this->val, 'PhpXmlRpc\Value'))) ||
($this->valtyp == 'xml' && (!is_string($this->val)))) {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': value passed in does not match type ' . $valType);
}
}
}
@@ -116,13 +120,22 @@ class Response
return $this->val;
}
/**
* @return string
*/
public function valueType()
{
return $this->valtyp;
}
/**
* 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.
* with the next request to the server (using $client->setCookie) or not.
* The values are filled in at constructor time, and might not be set for specific debug values used.
*
* @return array[] array of cookies received from the server
*/
@@ -132,7 +145,10 @@ class Response
}
/**
* @return array array with keys 'headers', 'cookies', 'raw_data' and 'status_code'
* Returns an array with info about the http response received from the server.
* The values are filled in at constructor time, and might not be set for specific debug values used.
*
* @return array array with keys 'headers', 'cookies', 'raw_data' and 'status_code'.
*/
public function httpResponse()
{
@@ -140,13 +156,11 @@ class Response
}
/**
* Returns xml representation of the response. XML prologue not included.
* Returns xml representation of the response, XML prologue _not_ included. Sets `payload` and `content_type` properties
*
* @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
* @throws StateErrorException if the response was built out of a value of an unsupported type
*/
public function serialize($charsetEncoding = '')
{
@@ -155,6 +169,7 @@ class Response
} else {
$this->content_type = 'text/xml';
}
if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
$result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
} else {
@@ -165,78 +180,125 @@ class Response
$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>";
$this->getCharsetEncoder()->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 using the Encoder...
throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values');
}
} else {
if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
$result .= "<params>\n<param>\n" . $this->val->serialize($charsetEncoding) . "</param>\n</params>";
} else if (is_string($this->val) && $this->valtyp == 'xml') {
$result .= "<params>\n<param>\n" .
$this->val->serialize($charsetEncoding) .
$this->val .
"</param>\n</params>";
} else if ($this->valtyp == 'phpvals') {
$encoder = new Encoder();
$val = $encoder->encode($this->val);
$result .= "<params>\n<param>\n" . $val->serialize($charsetEncoding) . "</param>\n</params>";
} else {
throw new StateErrorException('cannot serialize xmlrpc response objects whose content is native php values');
}
}
$result .= "\n</methodResponse>";
$this->payload = $result;
return $result;
}
// BC layer
public function __get($name)
/**
* @param string $charsetEncoding
* @return string
*/
public function xml_header($charsetEncoding = '')
{
//trigger_error('getting property Response::' . $name . ' is deprecated', E_USER_DEPRECATED);
if ($charsetEncoding != '') {
return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
} else {
return "<?xml version=\"1.0\"?" . ">\n";
}
}
switch($name) {
// *** BC layer ***
// we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
public function &__get($name)
{
switch ($name) {
case 'val':
case 'valtyp':
case 'errno':
case 'errstr':
case 'payload':
case 'content_type':
$this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
return $this->$name;
case 'hdrs':
$this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
return $this->httpResponse['headers'];
case '_cookies':
$this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
return $this->httpResponse['cookies'];
case 'raw_data':
$this->logDeprecation('Getting property Response::' . $name . ' is deprecated');
return $this->httpResponse['raw_data'];
default:
$trace = debug_backtrace();
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
return null;
$result = null;
return $result;
}
}
public function __set($name, $value)
{
//trigger_error('setting property Response::' . $name . ' is deprecated', E_USER_DEPRECATED);
switch($name) {
switch ($name) {
case 'val':
case 'valtyp':
case 'errno':
case 'errstr':
case 'payload':
case 'content_type':
$this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
$this->$name = $value;
break;
case 'hdrs':
$this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
$this->httpResponse['headers'] = $value;
break;
case '_cookies':
$this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
$this->httpResponse['cookies'] = $value;
break;
case 'raw_data':
$this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
$this->httpResponse['raw_data'] = $value;
break;
default:
$trace = debug_backtrace();
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
public function __isset($name)
{
switch($name) {
switch ($name) {
case 'val':
case 'valtyp':
case 'errno':
case 'errstr':
case 'payload':
case 'content_type':
$this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
return isset($this->$name);
case 'hdrs':
$this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
return isset($this->httpResponse['headers']);
case '_cookies':
$this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
return isset($this->httpResponse['cookies']);
case 'raw_data':
$this->logDeprecation('Checking property Response::' . $name . ' is deprecated');
return isset($this->httpResponse['raw_data']);
default:
return false;
@@ -245,18 +307,31 @@ class Response
public function __unset($name)
{
switch($name) {
switch ($name) {
case 'val':
case 'valtyp':
case 'errno':
case 'errstr':
case 'payload':
case 'content_type':
$this->logDeprecation('Setting property Response::' . $name . ' is deprecated');
unset($this->$name);
break;
case 'hdrs':
$this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
unset($this->httpResponse['headers']);
break;
case '_cookies':
$this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
unset($this->httpResponse['cookies']);
break;
case 'raw_data':
$this->logDeprecation('Unsetting property Response::' . $name . ' is deprecated');
unset($this->httpResponse['raw_data']);
break;
default:
$trace = debug_backtrace();
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
+696 -280
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
<?php
namespace PhpXmlRpc\Traits;
use PhpXmlRpc\Helper\Charset;
trait CharsetEncoderAware
{
protected static $charsetEncoder;
public function getCharsetEncoder()
{
if (self::$charsetEncoder === null) {
self::$charsetEncoder = Charset::instance();
}
return self::$charsetEncoder;
}
/**
* @param $charsetEncoder
* @return void
*/
public static function setCharsetEncoder($charsetEncoder)
{
self::$charsetEncoder = $charsetEncoder;
}
}
@@ -0,0 +1,40 @@
<?php
namespace PhpXmlRpc\Traits;
use PhpXmlRpc\PhpXmlRpc;
trait DeprecationLogger
{
use LoggerAware;
protected function logDeprecation($message)
{
if (PhpXmlRpc::$xmlrpc_silence_deprecations) {
return;
}
$this->getLogger()->warning('XML-RPC Deprecated: ' . $message);
}
/**
* @param string $callee
* @param string $expectedCaller atm only the method name is supported
* @return void
*/
protected function logDeprecationUnlessCalledBy($expectedCaller)
{
if (PhpXmlRpc::$xmlrpc_silence_deprecations) {
return;
}
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
/// @todo we should check as well $trace[2]['class'], and make sure that it is a descendent of the class passed in in $expectedCaller
if ($trace[2]['function'] === $expectedCaller) {
return;
}
$this->getLogger()->warning('XML-RPC Deprecated: ' . $trace[1]['class'] . '::' . $trace[1]['function'] .
' is only supposed to be called by ' . $expectedCaller);
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace PhpXmlRpc\Traits;
use PhpXmlRpc\Helper\Logger;
trait LoggerAware
{
protected static $logger;
public function getLogger()
{
if (self::$logger === null) {
self::$logger = Logger::instance();
}
return self::$logger;
}
/**
* @param $logger
* @return void
*/
public static function setLogger($logger)
{
self::$logger = $logger;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace PhpXmlRpc\Traits;
use PhpXmlRpc\Helper\XMLParser;
trait ParserAware
{
protected static $parser;
/// @todo feature-creep: allow passing in $options (but then, how to deal with changing options between invocations?)
public function getParser()
{
if (self::$parser === null) {
self::$parser = new XMLParser();
}
return self::$parser;
}
/**
* @param $parser
* @return void
*/
public static function setParser($parser)
{
self::$parser = $parser;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace PhpXmlRpc\Traits;
trait PayloadBearer
{
/** @var string */
protected $payload;
/** @var string */
protected $content_type = 'text/xml';
/**
* @internal
*
* @param string $payload
* @param string $contentType
* @return $this
*/
public function setPayload($payload, $contentType = '')
{
$this->payload = $payload;
if ($contentType != '') {
$this->content_type = $contentType;
}
return $this;
}
/**
* @return string
*/
public function getPayload()
{
return $this->payload;
}
/**
* @return string
*/
public function getContentType()
{
return $this->content_type;
}
}
+372 -301
View File
@@ -2,14 +2,24 @@
namespace PhpXmlRpc;
use PhpXmlRpc\Helper\Charset;
use PhpXmlRpc\Helper\Logger;
use PhpXmlRpc\Exception\StateErrorException;
use PhpXmlRpc\Exception\TypeErrorException;
use PhpXmlRpc\Exception\ValueErrorException;
use PhpXmlRpc\Traits\CharsetEncoderAware;
use PhpXmlRpc\Traits\DeprecationLogger;
/**
* This class enables the creation of values for XML-RPC, by encapsulating plain php values.
*
* @property Value[]|mixed $me deprecated - public access left in purely for BC. Access via scalarVal()/__construct()
* @property int $params $mytype - public access left in purely for BC. Access via kindOf()/__construct()
* @property string|null $_php_class deprecated - public access left in purely for BC.
*/
class Value implements \Countable, \IteratorAggregate, \ArrayAccess
{
use CharsetEncoderAware;
use DeprecationLogger;
public static $xmlrpcI4 = "i4";
public static $xmlrpcI8 = "i8";
public static $xmlrpcInt = "int";
@@ -37,56 +47,25 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
"null" => 1,
);
protected static $logger;
protected static $charsetEncoder;
/// @todo: do these need to be public?
/** @var Value[]|mixed */
public $me = array();
protected $me = array();
/**
* @var int $mytype
* @internal
* @var int 0 for undef, 1 for scalar, 2 for array, 3 for struct
*/
public $mytype = 0;
/** @var string|null $_php_class */
public $_php_class = null;
public function getLogger()
{
if (self::$logger === null) {
self::$logger = Logger::instance();
}
return self::$logger;
}
public static function setLogger($logger)
{
self::$logger = $logger;
}
public function getCharsetEncoder()
{
if (self::$charsetEncoder === null) {
self::$charsetEncoder = Charset::instance();
}
return self::$charsetEncoder;
}
public function setCharsetEncoder($charsetEncoder)
{
self::$charsetEncoder = $charsetEncoder;
}
protected $mytype = 0;
/** @var string|null */
protected $_php_class = null;
/**
* Build an xmlrpc value.
* Build an xml-rpc value.
*
* When no value or type is passed in, the value is left uninitialized, and the value can be added later.
*
* @param Value[]|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,
* @param string $type any valid xml-rpc 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.
* You should refer to http://xmlrpc.com/spec.md for more information on what each of these mean.
*/
public function __construct($val = -1, $type = '')
{
@@ -119,22 +98,27 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
$this->me['struct'] = $val;
break;
default:
$this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
$this->getLogger()->error("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
}
}
}
/**
* Add a single php value to an xmlrpc value.
* Add a single php value to an xml-rpc 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.
* If the xml-rpc value is an array, the php value is added as its last element.
* If the xml-rpc value is empty (uninitialized), this method makes it a scalar value, and sets that value.
* Fails if the xml-rpc value is not an array (i.e. a struct or a scalar) 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
*
* @todo arguably, as we have addArray to add elements to an Array value, and addStruct to add elements to a Struct
* value, we should not allow this method to add values to an Array. The 'scalar' in the method name refers to
* the expected state of the target object, not to the type of $val. Also, this works differently from
* addScalar/addStruct in that, when adding an element to an array, it wraps it into a new Value
* @todo rename?
*/
public function addScalar($val, $type = 'string')
{
@@ -144,13 +128,13 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
if ($typeOf !== 1) {
$this->getLogger()->errorLog("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
$this->getLogger()->error("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...
/// @todo 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;
@@ -161,14 +145,16 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
switch ($this->mytype) {
case 1:
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
return 0;
case 3:
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
$this->getLogger()->error('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);
/// @todo should we try avoiding re-wrapping Value objects?
$class = get_class($this);
$this->me['array'][] = new $class($val, $type);
return 1;
default:
@@ -181,17 +167,17 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
/**
* Add an array of xmlrpc value objects to an xmlrpc value.
* Add an array of xml-rpc value objects to an xml-rpc 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.
* If the xml-rpc value is an array, the elements are appended to the existing ones.
* If the xml-rpc 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?
* @todo add some checking for $values to be an array of xml-rpc values?
* @todo rename to addToArray?
*/
public function addArray($values)
{
@@ -206,23 +192,23 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
return 1;
} else {
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
return 0;
}
}
/**
* Merges an array of named xmlrpc value objects into an xmlrpc value.
* Merges an array of named xml-rpc value objects into an xml-rpc 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.
* If the xml-rpc value is a struct, the elements are merged with the existing ones (overwriting existing ones).
* If the xml-rpc 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?
* @todo add some checking for $values to be an array of xml-rpc values?
* @todo rename to addToStruct?
*/
public function addStruct($values)
{
@@ -237,15 +223,15 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
return 1;
} else {
$this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
$this->getLogger()->error('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.
* Returns a string describing the base type of the value.
*
* @return string
* @return string either "struct", "array", "scalar" or "undef"
*/
public function kindOf()
{
@@ -261,187 +247,13 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
}
/**
* @param string $typ
* @param Value[]|mixed $val
* @param string $charsetEncoding
* @return string
*/
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}>"; // TODO: Remove this modification in MDL-76415.
break;
case static::$xmlrpcBoolean:
$rs .= "<{$typ}>" . ($val ? '1' : '0') . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
break;
case static::$xmlrpcString:
// Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
$rs .= "<{$typ}>" . $this->getCharsetEncoder()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
break;
case static::$xmlrpcInt:
case static::$xmlrpcI4:
case static::$xmlrpcI8:
$rs .= "<{$typ}>" . (int)$val . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
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, PhpXmlRpc::$xmlpc_double_precision, '.', '')) . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
break;
case static::$xmlrpcDateTime:
if (is_string($val)) {
$rs .= "<{$typ}>{$val}</{$typ}>"; // TODO: Remove this modification in MDL-76415.
} elseif (is_a($val, 'DateTime') || is_a($val, 'DateTimeInterface')) {
$rs .= "<{$typ}>" . $val->format('Ymd\TH:i:s') . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
} elseif (is_int($val)) {
$rs .= "<{$typ}>" . date('Ymd\TH:i:s', $val) . "</{$typ}>"; // TODO: Remove this modification in MDL-76415.
} else {
// not really a good idea here: but what should we output anyway? left for backward compat...
$rs .= "<{$typ}>{$val}</{$typ}>"; // TODO: Remove this modification in MDL-76415.
}
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}>"; // TODO: Remove this modification in MDL-76415.
}
break;
case 3:
// struct
if ($this->_php_class) {
$rs .= '<struct php_class="' . $this->_php_class . "\">\n";
} else {
$rs .= "<struct>\n";
}
$charsetEncoder = $this->getCharsetEncoder();
/** @var Value $val2 */
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";
/** @var Value $element */
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 = '')
{
$val = reset($this->me);
$typ = key($this->me);
return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
}
/**
* 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)
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
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)
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
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()
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
reset($this->me['struct']);
}
/**
* Return next member element for xmlrpc values of type struct.
*
* @return Value
* @throws \Error starting with php 8.0, this function should not be used, as it will always throw
*
* @deprecated iterate directly over the object using foreach instead
*/
public function structeach()
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return @each($this->me['struct']);
}
/**
* Returns the value of a scalar xmlrpc value (base 64 decoding is automatically handled here)
* Returns the value of a scalar xml-rpc value (base 64 decoding is automatically handled here)
*
* @return mixed
*/
public function scalarval()
public function scalarVal()
{
$b = reset($this->me);
@@ -449,13 +261,12 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
/**
* Returns the type of the xmlrpc value.
* Returns the type of the xml-rpc value.
*
* For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and returned as such
*
* @return string
* @return string For integers, 'int' is always returned in place of 'i4'. 'i8' is considered a separate type and
* returned as such
*/
public function scalartyp()
public function scalarTyp()
{
reset($this->me);
$a = key($this->me);
@@ -467,51 +278,123 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
/**
* Returns the m-th member of an xmlrpc value of array type.
* Returns the xml representation of the value. XML prologue not included.
*
* @param integer $key the index of the value to be retrieved (zero based)
*
* @return Value
*
* @deprecated use array access, e.g. $val[$key]
* @param string $charsetEncoding the charset to be used for serialization. If null, US-ASCII is assumed
* @return string
*/
public function arraymem($key)
public function serialize($charsetEncoding = '')
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
$val = reset($this->me);
$typ = key($this->me);
return $this->me['array'][$key];
return '<value>' . $this->serializeData($typ, $val, $charsetEncoding) . "</value>\n";
}
/**
* Returns the number of members in an xmlrpc value of array type.
* @param string $typ
* @param Value[]|mixed $val
* @param string $charsetEncoding
* @return string
*
* @return integer
*
* @deprecated use count() instead
* @deprecated this should be folded back into serialize()
*/
public function arraysize()
protected function serializeData($typ, $val, $charsetEncoding = '')
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
$this->logDeprecationUnlessCalledBy('serialize');
return count($this->me['array']);
if (!isset(static::$xmlrpcTypes[$typ])) {
return '';
}
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:
// Do NOT use htmlentities, since it will produce named html entities, which are invalid xml
$rs = "<{$typ}>" . $this->getCharsetEncoder()->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 xml-rpc spec forbids exponential notation.
// sprintf('%F') could be most likely ok, but it fails e.g. 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, PhpXmlRpc::$xmlpc_double_precision, '.', '')) . "</{$typ}>";
break;
case static::$xmlrpcDateTime:
if (is_string($val)) {
$rs = "<{$typ}>{$val}</{$typ}>";
// DateTimeInterface is not present in php 5.4...
} elseif (is_a($val, 'DateTimeInterface') || is_a($val, 'DateTime')) {
$rs = "<{$typ}>" . $val->format('Ymd\TH:i:s') . "</{$typ}>";
} elseif (is_int($val)) {
$rs = "<{$typ}>" . date('Ymd\TH:i:s', $val) . "</{$typ}>";
} else {
// not really a good idea here: but what should 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 xml-rpc 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 = $this->getCharsetEncoder();
/** @var Value $val2 */
foreach ($val as $key2 => $val2) {
$rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
$rs .= $val2->serialize($charsetEncoding);
$rs .= "</member>\n";
}
$rs .= '</struct>';
break;
case 2:
// array
$rs = "<array>\n<data>\n";
/** @var Value $element */
foreach ($val as $element) {
$rs .= $element->serialize($charsetEncoding);
}
$rs .= "</data>\n</array>";
break;
default:
/// @todo log a warning?
$rs = '';
break;
}
return $rs;
}
/**
* Returns the number of members in an xmlrpc value of struct type.
*
* @return integer
*
* @deprecated use count() instead
*/
public function structsize()
{
//trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return count($this->me['struct']);
}
/**
* Returns the number of members in an xmlrpc value:
* Returns the number of members in an xml-rpc value:
* - 0 for uninitialized values
* - 1 for scalar values
* - the number of elements for struct and array values
@@ -535,9 +418,9 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
/**
* Implements the IteratorAggregate interface
* @internal required to be public to implement an Interface
*
* @return \ArrayIterator
* @internal required to be public to implement an Interface
*/
#[\ReturnTypeWillChange]
public function getIterator()
@@ -556,28 +439,31 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @param mixed $value
* @throws \Exception
* @return void
*
* @throws ValueErrorException|TypeErrorException
*/
#[\ReturnTypeWillChange]
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 (!($value instanceof Value)) {
throw new TypeErrorException('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');
throw new ValueErrorException('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 (!($value instanceof Value)) {
throw new TypeErrorException('It is only possible to add Value objects to an XML-RPC Array');
}
if (is_null($offset)) {
$this->me['array'][] = $value;
@@ -587,22 +473,24 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
}
return;
case 1:
// todo: handle i4 vs int
/// @todo: should we handle usage of i4 to retrieve int (in both set/unset/isset)? After all we consider
/// 'int' to be the preferred form, as evidenced in scalarTyp()
reset($this->me);
$type = key($this->me);
if ($type != $offset) {
throw new \Exception('');
if ($type != $offset && ($type != 'i4' || $offset != 'int')) {
throw new ValueErrorException('...');
}
$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");
// it would be nice to allow empty values to be turned into non-empty ones this way, but we miss info to do so
throw new ValueErrorException("XML-RPC Value is of type 'undef' and its value can not be set using array index");
}
}
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @return bool
*/
@@ -615,8 +503,14 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
case 2:
return isset($this->me['array'][$offset]);
case 1:
// todo: handle i4 vs int
return $offset == $this->scalartyp();
// handle i4 vs int
if ($offset == 'i4') {
// to be consistent with set and unset, we disallow usage of i4 to check for int
reset($this->me);
return $offset == key($this->me);
} else {
return $offset == $this->scalarTyp();
}
default:
return false;
}
@@ -624,8 +518,11 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @throws \Exception
* @return void
*
* @throws ValueErrorException|StateErrorException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
@@ -639,17 +536,19 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
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");
/// @todo feature creep - allow this to move back the value to 'undef' state?
throw new StateErrorException("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");
throw new StateErrorException("XML-RPC Value is of type 'undef' and its value can not be unset using array index");
}
}
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @return mixed|Value|null
* @throws \Exception
* @throws StateErrorException
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
@@ -660,13 +559,185 @@ class Value implements \Countable, \IteratorAggregate, \ArrayAccess
case 2:
return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
case 1:
// on bad type: null or exception?
/// @todo what to return on bad type: null or exception?
$value = reset($this->me);
$type = key($this->me);
return $type == $offset ? $value : null;
return $type == $offset ? $value : (($type == 'i4' && $offset == 'int') ? $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");
// return null or exception?
throw new StateErrorException("XML-RPC Value is of type 'undef' and can not be accessed using array index");
}
}
// *** BC layer ***
/**
* Checks whether a struct member with a given name is present.
*
* Works only on xml-rpc 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)
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
return array_key_exists($key, $this->me['struct']);
}
/**
* Returns the value of a given struct member (an xml-rpc 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)
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
return $this->me['struct'][$key];
}
/**
* Reset internal pointer for xml-rpc values of type struct.
* @return void
*
* @deprecated iterate directly over the object using foreach instead
*/
public function structReset()
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
reset($this->me['struct']);
}
/**
* Return next member element for xml-rpc values of type struct.
*
* @return array having the same format as PHP's `each` method
*
* @deprecated iterate directly over the object using foreach instead
*/
public function structEach()
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
$key = key($this->me['struct']);
$value = current($this->me['struct']);
next($this->me['struct']);
return array(1 => $value, 'value' => $value, 0 => $key, 'key' => $key);
}
/**
* Returns the n-th member of an xml-rpc 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)
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
return $this->me['array'][$key];
}
/**
* Returns the number of members in an xml-rpc value of array type.
*
* @return integer
*
* @deprecated use count() instead
*/
public function arraySize()
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
return count($this->me['array']);
}
/**
* Returns the number of members in an xml-rpc value of struct type.
*
* @return integer
*
* @deprecated use count() instead
*/
public function structSize()
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
return count($this->me['struct']);
}
// we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
public function &__get($name)
{
switch ($name) {
case 'me':
case 'mytype':
case '_php_class':
$this->logDeprecation('Getting property Value::' . $name . ' is deprecated');
return $this->$name;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
$result = null;
return $result;
}
}
public function __set($name, $value)
{
switch ($name) {
case 'me':
case 'mytype':
case '_php_class':
$this->logDeprecation('Setting property Value::' . $name . ' is deprecated');
$this->$name = $value;
break;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
public function __isset($name)
{
switch ($name) {
case 'me':
case 'mytype':
case '_php_class':
$this->logDeprecation('Checking property Value::' . $name . ' is deprecated');
return isset($this->$name);
default:
return false;
}
}
public function __unset($name)
{
switch ($name) {
case 'me':
case 'mytype':
case '_php_class':
$this->logDeprecation('Unsetting property Value::' . $name . ' is deprecated');
unset($this->$name);
break;
default:
/// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
}
}
}
+382 -286
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -16,7 +16,7 @@ To update:
- Edit this file and update the release and commit details below.
- Edit lib/thirdpartylibs.xml and update the information details too.
Current version imported: 4.8.1 (c74cc31)
Current version imported: 4.10.1 (ac18e31)
Local changes:
* 2023/01/26 - Server.php and Value.php files have minor changes for PHP 8.2 compatibility. See MDL-76415 for more details.
+1 -1
View File
@@ -633,7 +633,7 @@ All rights reserved.</copyright>
<location>phpxmlrpc</location>
<name>phpxmlrpc</name>
<description>A php library for building xml-rpc clients and servers</description>
<version>4.8.1</version>
<version>4.10.1</version>
<license>BSD</license>
<licenseversion>3-Clause</licenseversion>
<repository>https://github.com/gggeek/phpxmlrpc</repository>
+6 -6
View File
@@ -62,20 +62,20 @@ function mnet_get_public_key($uri, $application=null) {
new \PhpXmlRpc\Value($application->name),
];
$request = new \PhpXmlRpc\Request('system/keyswap', $params);
$request->request_charset_encoding = 'utf-8';
// Let's create a client to handle the request and the response easily.
$client = new \PhpXmlRpc\Client($uri . $application->xmlrpc_server_url);
$client->setUseCurl(\PhpXmlRpc\Client::USE_CURL_ALWAYS);
$client->setUserAgent('Moodle');
$client->setOption('use_curl', \PhpXmlRpc\Client::USE_CURL_ALWAYS);
$client->setOption('user_agent', 'Moodle');
$client->return_type = 'xmlrpcvals'; // This (keyswap) is not encrypted, so we can expect proper xmlrpc in this case.
$client->request_charset_encoding = 'utf-8';
$client->setOption('request_charset_encoding', 'utf-8');
$client->setOption('accepted_charset_encodings', ['utf-8']);
// TODO: Link this to DEBUG DEVELOPER or with MNET debugging...
// $client->setdebug(1); // See a good number of complete requests and responses.
$client->setSSLVerifyHost(0);
$client->setSSLVerifyPeer(false);
$client->setOption('verifyhost', 0);
$client->setOption('verifypeer', false);
// TODO: It's curious that this service (keyswap) that needs
// a custom client, different from mnet_xmlrpc_client, because