first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+388
View File
@@ -0,0 +1,388 @@
<?php
namespace PhpXmlRpc;
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.
*
* @todo implement an interface
* @todo add class constants for the options values
*/
class Encoder
{
use LoggerAware;
use ParserAware;
/**
* 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
* 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
*
* @param Value|Request $xmlrpcVal
* @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 = $xmlrpcVal->scalarVal();
$typ = $xmlrpcVal->scalarTyp();
switch ($typ) {
case 'dateTime.iso8601':
$xmlrpcVal = array(
'xmlrpc_type' => 'datetime',
'scalar' => $val,
'timestamp' => \PhpXmlRpc\Helper\Date::iso8601Decode($val)
);
return (object)$xmlrpcVal;
case 'base64':
$xmlrpcVal = array(
'xmlrpc_type' => 'base64',
'scalar' => $val
);
return (object)$xmlrpcVal;
case 'string':
if (isset($options['extension_api_encoding'])) {
// 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;
}
}
// 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 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') || is_a($out, 'DateTime')) {
return $out;
}
}
return $xmlrpcVal->scalarVal();
case 'array':
$arr = array();
foreach ($xmlrpcVal as $value) {
$arr[] = $this->decode($value, $options);
}
return $arr;
case 'struct':
// If user said so, try to rebuild php objects for specific struct vals.
/// @todo should we raise a warning for class not found?
// shall we check for proper subclass of 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)
) {
$obj = @new $xmlrpcVal->_php_class();
foreach ($xmlrpcVal as $key => $value) {
$obj->$key = $this->decode($value, $options);
}
return $obj;
} else {
$arr = array();
foreach ($xmlrpcVal as $key => $value) {
$arr[$key] = $this->decode($value, $options);
}
return $arr;
}
case 'msg':
$paramCount = $xmlrpcVal->getNumParams();
$arr = array();
for ($i = 0; $i < $paramCount; $i++) {
$arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
}
return $arr;
/// @todo throw on unsupported type
}
}
/**
* 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.
*
* @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':
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);
}
break;
case 'integer':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
break;
case 'double':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
break;
case 'boolean':
$xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
break;
case 'array':
// A shorter one-liner would be
// $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
// but execution time skyrockets!
$j = 0;
$arr = array();
$ko = false;
foreach ($phpVal as $key => $val) {
$arr[$key] = $this->encode($val, $options);
if (!$ko && $key !== $j) {
$ko = true;
}
$j++;
}
if ($ko) {
$xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
} else {
$xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
}
break;
case 'object':
if (is_a($phpVal, 'PhpXmlRpc\Value')) {
$xmlrpcVal = $phpVal;
// 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
if (isset($phpVal->scalar)) {
switch ($phpVal->xmlrpc_type) {
case 'base64':
$xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcBase64);
break;
case 'datetime':
$xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcDateTime);
break;
default:
$xmlrpcVal = new Value();
}
} else {
$xmlrpcVal = new Value();
}
} else {
$arr = array();
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 xml-rpc value: it might be useful later on...
$xmlrpcVal->_php_class = get_class($phpVal);
}
}
break;
case 'NULL':
if (in_array('extension_api', $options)) {
$xmlrpcVal = new Value('', Value::$xmlrpcString);
} elseif (in_array('null_extension', $options)) {
$xmlrpcVal = new Value('', Value::$xmlrpcNull);
} else {
$xmlrpcVal = new Value();
}
break;
case 'resource':
if (in_array('extension_api', $options)) {
$xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
} else {
$xmlrpcVal = new Value();
}
break;
// catch "user function", "unknown type"
default:
// it has to return an empty object in case, not a boolean. (giancarlo pinerolo)
$xmlrpcVal = new Value();
break;
}
return $xmlrpcVal;
}
/**
* Convert the xml representation of a method response, method request or single
* xml-rpc value into the appropriate object (a.k.a. deserialize).
*
* @param string $xmlVal
* @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())
{
// 'guestimate' encoding
$valEncoding = XMLParser::guessEncoding('', $xmlVal);
if ($valEncoding != '') {
// 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($valEncoding, array('UTF-8'))
if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
if (function_exists('mb_convert_encoding')) {
$xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
} else {
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, 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();
$_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 ($_xh['isf'] > 1) {
// test that $_xh['value'] is an obj, too???
$this->getLogger()->error('XML-RPC: ' . $_xh['isf_reason']);
return false;
}
switch ($_xh['rt']) {
case 'methodresponse':
$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());
} else {
$r = new Response($v);
}
return $r;
case 'methodcall':
$req = new Request($_xh['method']);
for ($i = 0; $i < count($_xh['params']); $i++) {
$req->addParam($_xh['params'][$i]);
}
return $req;
case 'value':
return $_xh['value'];
case 'fault':
// EPI api emulation
$v = $_xh['value'];
// use a known error code
/** @var Value $vc */
$vc = isset($v['faultCode']) ? $v['faultCode']->scalarVal() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
/** @var Value $vs */
$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
{
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace PhpXmlRpc\Exception;
/**
* To be used for all errors related to parsing HTTP requests and responses
*/
class HttpException extends TransportException
{
protected $statusCode;
public function __construct($message = "", $code = 0, $previous = null, $statusCode = null)
{
parent::__construct($message, $code, $previous);
$this->statusCode = $statusCode;
}
public function statusCode()
{
return $this->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
{
}
@@ -0,0 +1,4 @@
<?php
// 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
{
}
+396
View File
@@ -0,0 +1,396 @@
<?php
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());
//protected $xml_cp1252_Entities = array('in' => array(), out' => array());
protected $charset_supersets = array(
'US-ASCII' => array('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',),
);
/** @var Charset $instance */
protected static $instance = null;
/**
* This class is singleton for performance reasons.
*
* @return Charset
*
* @todo should we just make $xml_iso88591_Entities a static variable instead ?
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}
/**
* Force usage as singleton.
*/
protected function __construct()
{
}
/**
* @param string $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
* @todo should we add to the latin-1 table the characters from cp_1252 range, i.e. 128 to 159 ?
* Those will NOT be present in true ISO-8859-1, but will save the unwary windows user from sending junk
* (though no luck when receiving them...)
* 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?
*/
protected function buildConversionTable($tableName)
{
switch ($tableName) {
case 'xml_iso88591_Entities':
if (count($this->xml_iso88591_Entities['in'])) {
return;
}
for ($i = 0; $i < 32; $i++) {
$this->xml_iso88591_Entities["in"][] = chr($i);
$this->xml_iso88591_Entities["out"][] = "&#{$i};";
}
/// @todo to be 'print safe', should we encode as well character 127 (DEL) ?
for ($i = 160; $i < 256; $i++) {
$this->xml_iso88591_Entities["in"][] = chr($i);
$this->xml_iso88591_Entities["out"][] = "&#{$i};";
}
break;
/*case 'xml_cp1252_Entities':
if (count($this->xml_cp1252_Entities['in'])) {
return;
}
for ($i = 128; $i < 160; $i++)
{
$this->xml_cp1252_Entities['in'][] = chr($i);
}
$this->xml_cp1252_Entities['out'] = array(
'&#x20AC;', '?', '&#x201A;', '&#x0192;',
'&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
'&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
'&#x0152;', '?', '&#x017D;', '?',
'?', '&#x2018;', '&#x2019;', '&#x201C;',
'&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
'&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
'&#x0153;', '?', '&#x017E;', '&#x0178;'
);
$this->buildConversionTable('xml_iso88591_Entities');
break;*/
default:
throw new ValueErrorException('Unsupported table: ' . $tableName);
}
}
/**
* 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 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
* present in the message into their equivalent 'charset entity'. Charset entities enumerated this way are
* independent of the charset encoding used to transmit them, and all XML parsers are bound to understand them.
*
* Note that 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...)
*
* @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 = '')
{
if ($srcEncoding == '') {
// lame, but we know no better...
$srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding;
}
if ($destEncoding == '') {
$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
switch ($conversion) {
case 'UTF-8_UTF-8':
case 'ISO-8859-1_ISO-8859-1':
case 'US-ASCII_UTF-8':
case 'US-ASCII_US-ASCII':
case 'US-ASCII_ISO-8859-1':
//case 'CP1252_CP1252':
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
break;
case 'UTF-8_US-ASCII':
case 'UTF-8_ISO-8859-1':
// NB: this will choke on invalid UTF-8, going most likely beyond EOF
$escapedData = '';
// be kind to users creating string xml-rpc values out of different php types
$data = (string)$data;
$ns = strlen($data);
for ($nn = 0; $nn < $ns; $nn++) {
$ch = $data[$nn];
$ii = ord($ch);
// 7 bits in 1 byte: 0bbbbbbb (127)
if ($ii < 32) {
if ($conversion == 'UTF-8_US-ASCII') {
$escapedData .= sprintf('&#%d;', $ii);
} else {
$escapedData .= $ch;
}
}
else if ($ii < 128) {
/// @todo shall we replace this with a (supposedly) faster str_replace?
/// @todo to be 'print safe', should we encode as well character 127 (DEL) ?
switch ($ii) {
case 34:
$escapedData .= '&quot;';
break;
case 38:
$escapedData .= '&amp;';
break;
case 39:
$escapedData .= '&apos;';
break;
case 60:
$escapedData .= '&lt;';
break;
case 62:
$escapedData .= '&gt;';
break;
default:
$escapedData .= $ch;
} // switch
} // 11 bits in 2 bytes: 110bbbbb 10bbbbbb (2047)
elseif ($ii >> 5 == 6) {
$b1 = ($ii & 31);
$b2 = (ord($data[$nn + 1]) & 63);
$ii = ($b1 * 64) + $b2;
$escapedData .= sprintf('&#%d;', $ii);
$nn += 1;
} // 16 bits in 3 bytes: 1110bbbb 10bbbbbb 10bbbbbb
elseif ($ii >> 4 == 14) {
$b1 = ($ii & 15);
$b2 = (ord($data[$nn + 1]) & 63);
$b3 = (ord($data[$nn + 2]) & 63);
$ii = ((($b1 * 64) + $b2) * 64) + $b3;
$escapedData .= sprintf('&#%d;', $ii);
$nn += 2;
} // 21 bits in 4 bytes: 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
elseif ($ii >> 3 == 30) {
$b1 = ($ii & 7);
$b2 = (ord($data[$nn + 1]) & 63);
$b3 = (ord($data[$nn + 2]) & 63);
$b4 = (ord($data[$nn + 3]) & 63);
$ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
$escapedData .= sprintf('&#%d;', $ii);
$nn += 3;
}
}
// when converting to latin-1, do not be so eager with using entities for characters 160-255
if ($conversion == 'UTF-8_ISO-8859-1') {
$this->buildConversionTable('xml_iso88591_Entities');
$escapedData = str_replace(array_slice($this->xml_iso88591_Entities['out'], 32), array_slice($this->xml_iso88591_Entities['in'], 32), $escapedData);
}
break;
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');
} else {
$escapedData = utf8_encode($escapedData);
}
break;
case 'ISO-8859-1_US-ASCII':
$this->buildConversionTable('xml_iso88591_Entities');
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
$escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData);
break;
/*
case 'CP1252_US-ASCII':
$this->buildConversionTable('xml_cp1252_Entities');
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
$escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData);
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
break;
case 'CP1252_UTF-8':
$this->buildConversionTable('xml_cp1252_Entities');
$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 = utf8_encode($escapedData);
break;
case 'CP1252_ISO-8859-1':
$this->buildConversionTable('xml_cp1252_Entities');
$escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
// we might as well replace all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...
$escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
break;
*/
default:
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)) {
return true;
} else {
if (array_key_exists($encoding, $this->charset_supersets)) {
foreach ($validList as $allowed) {
if (in_array($allowed, $this->charset_supersets[$encoding])) {
return true;
}
}
}
return false;
}
}
/**
* Used only for backwards compatibility (the .inc shims).
* @deprecated
*
* @param string $charset
* @return array
* @throws ValueErrorException for unknown/unsupported charsets
*/
public function getEntities($charset)
{
$this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
switch ($charset)
{
case 'iso88591':
return $this->xml_iso88591_Entities;
default:
throw new ValueErrorException('Unsupported charset: ' . $charset);
}
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
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
{
/**
* Given a timestamp, return the corresponding ISO8601 encoded string.
*
* Really, timezones ought to be supported but the XML-RPC spec says:
*
* "Don't assume a timezone. It should be specified by the server in its documentation what assumptions it makes
* about timezones."
*
* 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 {
$t = gmdate('Ymd\TH:i:s', $timet);
}
return $t;
}
/**
* Given an ISO8601 date string, return a timestamp in the localtime, or UTC.
*
* @param string $idate
* @param bool|int $utc either 0 (assume date is in local time) or 1 (assume date is in UTC)
*
* @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(PhpXmlRpc::$xmlrpc_datetime_format, $idate, $regs)) {
if ($utc) {
$t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
} else {
$t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
}
}
return $t;
}
}
+283
View File
@@ -0,0 +1,283 @@
<?php
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.
* 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
*/
public static function decodeChunked($buffer)
{
// length := 0
$length = 0;
$new = '';
// read chunk-size, chunk-extension (if any) and crlf
// get the position of the linebreak
$chunkEnd = strpos($buffer, "\r\n") + 2;
$temp = substr($buffer, 0, $chunkEnd);
$chunkSize = hexdec(trim($temp));
$chunkStart = $chunkEnd;
while ($chunkSize > 0) {
$chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
// just in case we got a broken connection
if ($chunkEnd == false) {
$chunk = substr($buffer, $chunkStart);
// append chunk-data to entity-body
$new .= $chunk;
$length += strlen($chunk);
break;
}
// read chunk-data and crlf
$chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
// append chunk-data to entity-body
$new .= $chunk;
// length := length + chunk-size
$length += strlen($chunk);
// read chunk-size and crlf
$chunkStart = $chunkEnd + 2;
$chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
if ($chunkEnd == false) {
break; // just in case we got a broken connection
}
$temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
$chunkSize = hexdec(trim($temp));
$chunkStart = $chunkEnd;
}
return $new;
}
/**
* Parses HTTP an http response'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)
{
$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)
$pos = strpos($data, "\r\n\r\n");
if ($pos || is_int($pos)) {
$bd = $pos + 4;
} else {
$pos = strpos($data, "\n\n");
if ($pos || is_int($pos)) {
$bd = $pos + 2;
} else {
// No separation between response headers and body: fault?
$bd = 0;
}
}
if ($bd) {
// this filters out all http headers from proxy. maybe we could take them into account, too?
$data = substr($data, $bd);
} else {
$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']);
}
}
// Strip HTTP 1.1 100 Continue header if present
while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
$pos = strpos($data, 'HTTP', 12);
// server sent a Continue header without any (valid) content following...
// give the client a chance to know it
if (!$pos && !is_int($pos)) {
/// @todo this construct works fine in php 3, 4 and 5 - 8; would it not be enough to have !== false now ?
break;
}
$data = substr($data, $pos);
}
// 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...
/// @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|30[1278]) .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
}
}
if (preg_match('/^HTTP\/([0-9](?:\.[0-9])?) ([0-9]{3}) /', $data, $matches)) {
$httpResponse['protocol_version'] = $matches[1];
$httpResponse['status_code'] = $matches[2];
}
if ($httpResponse['status_code'] !== '200') {
$errstr = substr($data, 0, strpos($data, "\n") - 1);
$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)
$pos = strpos($data, "\r\n\r\n");
if ($pos || is_int($pos)) {
$bd = $pos + 4;
} else {
$pos = strpos($data, "\n\n");
if ($pos || is_int($pos)) {
$bd = $pos + 2;
} else {
// No separation between response headers and body: fault?
// we could take some action here instead of going on...
$bd = 0;
}
}
// be tolerant to line endings, and extra empty lines
$ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
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]));
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 {
$httpResponse['headers'][$headerName] = trim($cookie);
}
// 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 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);
}
}
$data = substr($data, $bd);
if ($debug && count($httpResponse['headers'])) {
$msg = '';
foreach ($httpResponse['headers'] as $header => $value) {
$msg .= "HEADER: $header: $value\n";
}
foreach ($httpResponse['cookies'] as $header => $value) {
$msg .= "COOKIE: $header={$value['value']}\n";
}
$this->getLogger()->debug($msg);
}
// if CURL was used for the call, http headers have been processed, and dechunking + reinflating have been carried out
if (!$headersProcessed) {
// Decode chunked encoding sent by http 1.1 servers
if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
if (!$data = static::decodeChunked($data)) {
$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']);
}
}
// Decode gzip-compressed stuff
// code shamelessly inspired from nusoap library by Dietrich Ayala
if (isset($httpResponse['headers']['content-encoding'])) {
$httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
// if decoding works, use it. else assume data wasn't gzencoded
if (function_exists('gzinflate')) {
if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
$data = $degzdata;
if ($debug) {
$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) {
$this->getLogger()->debug("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
}
} else {
$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 {
$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']);
}
}
}
} // end of 'if needed, de-chunk, re-inflate response'
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;
}
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace PhpXmlRpc\Helper;
/**
* @todo implement an interface
* @todo make constructor private to force users to go through `instance()` ?
*/
class Logger
{
protected static $instance = null;
/**
* This class can be used as singleton, so that later we can move to DI patterns (ish...)
*
* @return Logger
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self();
}
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 deprecated
* @return void
*
* @internal left in purely for BC
*/
public function debugMessage($message, $encoding = null)
{
// US-ASCII is a warning for PHP and a fatal for HHVM
if ($encoding == 'US-ASCII') {
$encoding = 'UTF-8';
}
if (PHP_SAPI != 'cli') {
$flags = ENT_COMPAT;
// avoid warnings on php < 5.4...
if (defined('ENT_HTML401')) {
$flags = $flags | ENT_HTML401;
}
if (defined('ENT_SUBSTITUTE')) {
$flags = $flags | ENT_SUBSTITUTE;
}
if ($encoding != null) {
print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
} else {
print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
}
} else {
print "\n$message\n";
}
// let the user see this now in case there's a time-out later...
flush();
}
/**
* Writes a message to the error log.
*
* @param string $message
* @return void
*
* @internal left in purely for BC
*/
public function errorLog($message)
{
error_log($message);
}
}
File diff suppressed because it is too large Load Diff
+318
View File
@@ -0,0 +1,318 @@
<?php
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
{
/**
* @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,
'server_cannot_decompress' => 106,
'server_decompress_fail' => 107,
);
/**
* @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",
'http_error' => "Didn't receive 200 OK from remote server",
'no_data' => 'No data received from server',
'no_ssl' => 'No SSL support compiled in',
'curl_fail' => 'CURL error',
'invalid_request' => 'Invalid request payload',
'no_curl' => 'No CURL support compiled in',
'server_error' => 'Internal server error',
'multicall_error' => 'Received from server invalid multicall response',
'multicall_notstruct' => 'system.multicall expected struct',
'multicall_nomethod' => 'Missing methodName',
'multicall_notstring' => 'methodName is not a string',
'multicall_recursion' => 'Recursive system.multicall forbidden',
'multicall_noparams' => 'Missing params',
'multicall_notarray' => 'params is not an array',
'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',
'dechunk_fail' => 'Received from server invalid chunked HTTP',
'server_cannot_decompress' => 'Received from client compressed HTTP request and cannot decompress',
'server_decompress_fail' => 'Received from client invalid compressed HTTP request',
);
/**
* @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";
/**
* @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();
/**
* @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";
/**
* @var string
*/
public static $xmlrpcVersion = "4.10.1";
/**
* @var int
* Let user errors start at 800
*/
public static $xmlrpcerruser = 800;
/**
* @var int
* Let XML parse errors start at 100
*/
public static $xmlrpcerrxml = 100;
/**
* @var bool
* Set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values
*/
public static $xmlrpc_null_extension = false;
/**
* @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";
/**
* @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) {
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,
// as they are NOT reimported back during calls to importGlobals()
$reflection = new \ReflectionClass('PhpXmlRpc\Value');
foreach ($reflection->getStaticProperties() as $name => $value) {
if (!in_array($name, array('logger', 'charsetEncoder'))) {
$GLOBALS[$name] = $value;
}
}
/// @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');
}
/**
* A function to be used for compatibility with legacy code: it gets the values of all global variables which used
* to be declared, such as library version etc... and sets them to php classes.
* It should be used by code which changed the values of those global variables to alter the working of the library.
* Example code:
* 1. include xmlrpc.inc
* 2. set the values, e.g. $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
* 3. import them: PhpXmlRpc\PhpXmlRpc::importGlobals();
* 4. run your own code.
*
* @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');
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];
}
}
}
}
}
+563
View File
@@ -0,0 +1,563 @@
<?php
namespace PhpXmlRpc;
use PhpXmlRpc\Exception\HttpException;
use PhpXmlRpc\Helper\Http;
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
{
use CharsetEncoderAware;
use DeprecationLogger;
use ParserAware;
use PayloadBearer;
/** @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; still accessible by subclasses for the moment
*/
private $httpResponse = array();
/**
* @param string $methodName the name of the method to invoke
* @param Value[] $params array of parameters to be passed to the method (NB: Value objects, not plain php values)
*/
public function __construct($methodName, $params = array())
{
$this->methodname = $methodName;
foreach ($params as $param) {
$this->addParam($param);
}
}
/**
* 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 = '')
{
if ($methodName != '') {
$this->methodname = $methodName;
}
return $this->methodname;
}
/**
* 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 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;
}
}
/**
* Returns the nth parameter in the request. The index zero-based.
*
* @param integer $i the index of the parameter to fetch (zero based)
* @return Value the i-th parameter
*/
public function getParam($i)
{
return $this->params[$i];
}
/**
* Returns the number of parameters in the message.
*
* @return integer the number of parameters currently set
*/
public function getNumParams()
{
return count($this->params);
}
/**
* 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
* feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case,
* because we cannot trust the caller to give us a valid pointer to an open file...
*
* @param resource $fp stream pointer
* @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;
}
return $this->parseResponse($ipd, $headersProcessed, $returnType);
}
/**
* 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 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 > 0) {
$this->getLogger()->debug("---GOT---\n$data\n---END---");
}
$this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
if ($data == '') {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': no response received from server.');
return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
}
// parse the HTTP headers of the response, if present, and separate them from data
if (substr($data, 0, 4) == 'HTTP') {
$httpParser = new Http();
try {
$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
return new Response(0, $e->getCode(), $e->getMessage(), '', array('raw_data' => $data, 'status_code', $e->statusCode()));
} 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 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, 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(
isset($httpResponse['headers']['content-type']) ? $httpResponse['headers']['content-type'] : '',
$data
);
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()->debug("---SERVER DEBUG INFO (DECODED)---\n\t" .
str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", array('encoding' => $respEncoding));
}
}
// if the user wants back raw xml, give it to her
if ($returnType == 'xml') {
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 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')))
if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
if (function_exists('mb_convert_encoding')) {
$data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
} else {
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, 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();
$_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 ($_xh['isf'] == 3) {
// BC break: in the past for some cases we used the error message: 'XML error at line 1, check URL'
// 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...
$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 ($_xh['isf'] == 2) {
$r = new Response(0, PhpXmlRpc::$xmlrpcerr['xml_not_compliant'],
PhpXmlRpc::$xmlrpcstr['xml_not_compliant'] . ' ' . $_xh['isf_reason'], '', $httpResponse);
/// @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 ($_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()->debug(
"---PARSED---\n".var_export($_xh['value'], true)."\n---END---"
);
}
$v = $_xh['value'];
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();
} else {
$errNo = $v['faultCode'];
$errStr = $v['faultString'];
}
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, '', $httpResponse);
} else {
$r = new Response($v, 0, '', $returnType, $httpResponse);
}
}
return $r;
}
/**
* Kept the old name even if Request class was renamed, for BC.
*
* @return string
*/
public function kindOf()
{
return 'msg';
}
/**
* Enables/disables the echoing to screen of the xml-rpc responses received.
*
* @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);
}
}
}
+338
View File
@@ -0,0 +1,338 @@
<?php
namespace PhpXmlRpc;
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 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
{
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 = '';
protected $httpResponse = array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null);
/**
* @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 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? 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)
{
if ($fCode != 0) {
// error response
$this->errno = $fCode;
$this->errstr = $fString;
} else {
// successful response
$this->val = $val;
if ($valType == '') {
// user did not declare type of response value: try to guess it
if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
$this->valtyp = 'xmlrpcvals';
} elseif (is_string($this->val)) {
$this->valtyp = 'xml';
} else {
$this->valtyp = 'phpvals';
}
} else {
$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);
}
}
}
if (is_array($httpResponse)) {
$this->httpResponse = array_merge(array('headers' => array(), 'cookies' => array(), 'raw_data' => '', 'status_code' => null), $httpResponse);
}
}
/**
* Returns the error code of the response.
*
* @return integer the error code of this response (0 for not-error responses)
*/
public function faultCode()
{
return $this->errno;
}
/**
* Returns the error code of the response.
*
* @return string the error string of this response ('' for not-error responses)
*/
public function faultString()
{
return $this->errstr;
}
/**
* Returns the value received by the server. If the Response's faultCode is non-zero then the value returned by this
* method should not be used (it may not even be an object).
*
* @return Value|string|mixed the Value object returned by the server. Might be an xml string or plain php value
* depending on the convention adopted when creating the Response
*/
public function value()
{
return $this->val;
}
/**
* @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.
* 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
*/
public function cookies()
{
return $this->httpResponse['cookies'];
}
/**
* 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()
{
return $this->httpResponse;
}
/**
* 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 StateErrorException if the response was built out of a value of an unsupported type
*/
public function serialize($charsetEncoding = '')
{
if ($charsetEncoding != '') {
$this->content_type = 'text/xml; charset=' . $charsetEncoding;
} else {
$this->content_type = 'text/xml';
}
if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
$result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
} else {
$result = "<methodResponse>\n";
}
if ($this->errno) {
// Let non-ASCII response messages be tolerated by clients by xml-encoding non ascii chars
$result .= "<fault>\n" .
"<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
"</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
$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')) {
$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 .
"</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;
}
/**
* @param string $charsetEncoding
* @return string
*/
public function xml_header($charsetEncoding = '')
{
if ($charsetEncoding != '') {
return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
} else {
return "<?xml version=\"1.0\"?" . ">\n";
}
}
// *** 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:
/// @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 '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:
/// @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 '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;
}
}
public function __unset($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:
/// @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);
}
}
}
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;
}
}
+743
View File
@@ -0,0 +1,743 @@
<?php
namespace PhpXmlRpc;
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";
public static $xmlrpcBoolean = "boolean";
public static $xmlrpcDouble = "double";
public static $xmlrpcString = "string";
public static $xmlrpcDateTime = "dateTime.iso8601";
public static $xmlrpcBase64 = "base64";
public static $xmlrpcArray = "array";
public static $xmlrpcStruct = "struct";
public static $xmlrpcValue = "undefined";
public static $xmlrpcNull = "null";
public static $xmlrpcTypes = array(
"i4" => 1,
"i8" => 1,
"int" => 1,
"boolean" => 1,
"double" => 1,
"string" => 1,
"dateTime.iso8601" => 1,
"base64" => 1,
"array" => 2,
"struct" => 3,
"null" => 1,
);
/** @var Value[]|mixed */
protected $me = array();
/**
* @var int 0 for undef, 1 for scalar, 2 for array, 3 for struct
*/
protected $mytype = 0;
/** @var string|null */
protected $_php_class = null;
/**
* 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 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://xmlrpc.com/spec.md for more information on what each of these mean.
*/
public function __construct($val = -1, $type = '')
{
// optimization creep - do not call addXX, do it all inline.
// downside: booleans will not be coerced anymore
if ($val !== -1 || $type != '') {
switch ($type) {
case '':
$this->mytype = 1;
$this->me['string'] = $val;
break;
case 'i4':
case 'i8':
case 'int':
case 'double':
case 'string':
case 'boolean':
case 'dateTime.iso8601':
case 'base64':
case 'null':
$this->mytype = 1;
$this->me[$type] = $val;
break;
case 'array':
$this->mytype = 2;
$this->me['array'] = $val;
break;
case 'struct':
$this->mytype = 3;
$this->me['struct'] = $val;
break;
default:
$this->getLogger()->error("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
}
}
}
/**
* Add a single php value to an xml-rpc value.
*
* 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')
{
$typeOf = null;
if (isset(static::$xmlrpcTypes[$type])) {
$typeOf = static::$xmlrpcTypes[$type];
}
if ($typeOf !== 1) {
$this->getLogger()->error("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
return 0;
}
// coerce booleans into correct values
/// @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;
} else {
$val = false;
}
}
switch ($this->mytype) {
case 1:
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
return 0;
case 3:
$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
/// @todo should we try avoiding re-wrapping Value objects?
$class = get_class($this);
$this->me['array'][] = new $class($val, $type);
return 1;
default:
// a scalar, so set the value and remember we're scalar
$this->me[$type] = $val;
$this->mytype = $typeOf;
return 1;
}
}
/**
* Add an array of xml-rpc value objects to an xml-rpc 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 xml-rpc values?
* @todo rename to addToArray?
*/
public function addArray($values)
{
if ($this->mytype == 0) {
$this->mytype = static::$xmlrpcTypes['array'];
$this->me['array'] = $values;
return 1;
} elseif ($this->mytype == 2) {
// we're adding to an array here
$this->me['array'] = array_merge($this->me['array'], $values);
return 1;
} else {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
return 0;
}
}
/**
* Merges an array of named xml-rpc value objects into an xml-rpc 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 of xml-rpc values?
* @todo rename to addToStruct?
*/
public function addStruct($values)
{
if ($this->mytype == 0) {
$this->mytype = static::$xmlrpcTypes['struct'];
$this->me['struct'] = $values;
return 1;
} elseif ($this->mytype == 3) {
// we're adding to a struct here
$this->me['struct'] = array_merge($this->me['struct'], $values);
return 1;
} else {
$this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
return 0;
}
}
/**
* Returns a string describing the base type of the value.
*
* @return string either "struct", "array", "scalar" or "undef"
*/
public function kindOf()
{
switch ($this->mytype) {
case 3:
return 'struct';
case 2:
return 'array';
case 1:
return 'scalar';
default:
return 'undef';
}
}
/**
* Returns the value of a scalar xml-rpc value (base 64 decoding is automatically handled here)
*
* @return mixed
*/
public function scalarVal()
{
$b = reset($this->me);
return $b;
}
/**
* Returns the type of the xml-rpc value.
*
* @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()
{
reset($this->me);
$a = key($this->me);
if ($a == static::$xmlrpcI4) {
$a = static::$xmlrpcInt;
}
return $a;
}
/**
* 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";
}
/**
* @param string $typ
* @param Value[]|mixed $val
* @param string $charsetEncoding
* @return string
*
* @deprecated this should be folded back into serialize()
*/
protected function serializeData($typ, $val, $charsetEncoding = '')
{
$this->logDeprecationUnlessCalledBy('serialize');
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 xml-rpc value:
* - 0 for uninitialized values
* - 1 for scalar values
* - the number of elements for struct and array values
*
* @return integer
*/
#[\ReturnTypeWillChange]
public function count()
{
switch ($this->mytype) {
case 3:
return count($this->me['struct']);
case 2:
return count($this->me['array']);
case 1:
return 1;
default:
return 0;
}
}
/**
* Implements the IteratorAggregate interface
* @internal required to be public to implement an Interface
*
* @return \ArrayIterator
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
switch ($this->mytype) {
case 3:
return new \ArrayIterator($this->me['struct']);
case 2:
return new \ArrayIterator($this->me['array']);
case 1:
return new \ArrayIterator($this->me);
default:
return new \ArrayIterator();
}
}
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @param mixed $value
* @return void
*
* @throws ValueErrorException|TypeErrorException
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
switch ($this->mytype) {
case 3:
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 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 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;
} else {
// nb: we are not checking that $offset is above the existing array range...
$this->me['array'][$offset] = $value;
}
return;
case 1:
/// @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 && ($type != 'i4' || $offset != 'int')) {
throw new ValueErrorException('...');
}
$this->me[$type] = $value;
return;
default:
// 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
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
switch ($this->mytype) {
case 3:
return isset($this->me['struct'][$offset]);
case 2:
return isset($this->me['array'][$offset]);
case 1:
// 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;
}
}
/**
* @internal required to be public to implement an Interface
*
* @param mixed $offset
* @return void
*
* @throws ValueErrorException|StateErrorException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
switch ($this->mytype) {
case 3:
unset($this->me['struct'][$offset]);
return;
case 2:
unset($this->me['array'][$offset]);
return;
case 1:
// can not remove value from a scalar
/// @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 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 StateErrorException
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
switch ($this->mytype) {
case 3:
return isset($this->me['struct'][$offset]) ? $this->me['struct'][$offset] : null;
case 2:
return isset($this->me['array'][$offset]) ? $this->me['array'][$offset] : null;
case 1:
/// @todo what to return on bad type: null or exception?
$value = reset($this->me);
$type = key($this->me);
return $type == $offset ? $value : (($type == 'i4' && $offset == 'int') ? $value : null);
default:
// 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);
}
}
}
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
Description of XMLRPC for PHP library import into Moodle.
Source: https://github.com/gggeek/phpxmlrpc
This library provides XMLRPC client and server support
from PHP code. It's a modern replacement for the old
(removed from core since PHP 8.0) xmlrpc extension.
To update:
- Pick a release of the library @ https://github.com/gggeek/phpxmlrpc/releases.
- Download or checkout it.
- Delete the contents on the lib/phpxmlrpc directory (but this file) completely.
- Copy the /src directory contents of the library to lib/phpxmlrpc.
- Remove the following files:
- Autoloader.php
- 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.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.
Since version 4.9.1, the phpxmlrpc already has the fix, so if someone executing the upgrading version and
it has the patch, please ignore this note.
* 2023-01-31 lib/phpxmlrpc/* has minor changes for PHP 8.2 compatibility. See MDL-76412 for more details.
Since version 4.9.5, phpxmlrpc already has the fix, so if someone executing the upgrading version and
it has the patch, please ignore this note.
* 2023-01-31 Applied patch https://github.com/gggeek/phpxmlrpc/pull/110. See MDL-76412 for more details.
* readme_moodle.txt - this file ;-)