first commit

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

806
lib/JSON.php Normal file
View File

@@ -0,0 +1,806 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

453
lib/Text/Diff.php Normal file
View File

@@ -0,0 +1,453 @@
<?php
/**
* General API for generating and formatting diffs - the differences between
* two sequences of strings.
*
* The original PHP version of this code was written by Geoffrey T. Dairiki
* <dairiki@dairiki.org>, and is used/adapted with his permission.
*
* $Horde: framework/Text_Diff/Diff.php,v 1.11.2.11 2008/02/24 10:57:46 jan Exp $
*
* Copyright 2004 Geoffrey T. Dairiki <dairiki@dairiki.org>
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff {
/**
* Array of changes.
*
* @var array
*/
var $_edits;
/**
* Computes diffs between sequences of strings.
*
* @param string $engine Name of the diffing engine to use. 'auto'
* will automatically select the best.
* @param array $params Parameters to pass to the diffing engine.
* Normally an array of two arrays, each
* containing the lines from a file.
*/
function Text_Diff($engine, $params)
{
// Backward compatibility workaround.
if (!is_string($engine)) {
$params = array($engine, $params);
$engine = 'auto';
}
if ($engine == 'auto') {
$engine = extension_loaded('xdiff') ? 'xdiff' : 'native';
} else {
$engine = basename($engine);
}
require_once 'Text/Diff/Engine/' . $engine . '.php';
$class = 'Text_Diff_Engine_' . $engine;
$diff_engine = new $class();
$this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params);
}
/**
* Returns the array of differences.
*/
function getDiff()
{
return $this->_edits;
}
/**
* returns the number of new (added) lines in a given diff.
*
* @since Text_Diff 1.1.0
* @since Horde 3.2
*
* @return integer The number of new lines
*/
function countAddedLines()
{
$count = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_add') ||
is_a($edit, 'Text_Diff_Op_change')) {
$count += $edit->nfinal();
}
}
return $count;
}
/**
* Returns the number of deleted (removed) lines in a given diff.
*
* @since Text_Diff 1.1.0
* @since Horde 3.2
*
* @return integer The number of deleted lines
*/
function countDeletedLines()
{
$count = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_delete') ||
is_a($edit, 'Text_Diff_Op_change')) {
$count += $edit->norig();
}
}
return $count;
}
/**
* Computes a reversed diff.
*
* Example:
* <code>
* $diff = new Text_Diff($lines1, $lines2);
* $rev = $diff->reverse();
* </code>
*
* @return Text_Diff A Diff object representing the inverse of the
* original diff. Note that we purposely don't return a
* reference here, since this essentially is a clone()
* method.
*/
function reverse()
{
if (version_compare(zend_version(), '2', '>')) {
$rev = clone($this);
} else {
$rev = $this;
}
$rev->_edits = array();
foreach ($this->_edits as $edit) {
$rev->_edits[] = $edit->reverse();
}
return $rev;
}
/**
* Checks for an empty diff.
*
* @return boolean True if two sequences were identical.
*/
function isEmpty()
{
foreach ($this->_edits as $edit) {
if (!is_a($edit, 'Text_Diff_Op_copy')) {
return false;
}
}
return true;
}
/**
* Computes the length of the Longest Common Subsequence (LCS).
*
* This is mostly for diagnostic purposes.
*
* @return integer The length of the LCS.
*/
function lcs()
{
$lcs = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_copy')) {
$lcs += count($edit->orig);
}
}
return $lcs;
}
/**
* Gets the original set of lines.
*
* This reconstructs the $from_lines parameter passed to the constructor.
*
* @return array The original sequence of strings.
*/
function getOriginal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->orig) {
array_splice($lines, count($lines), 0, $edit->orig);
}
}
return $lines;
}
/**
* Gets the final set of lines.
*
* This reconstructs the $to_lines parameter passed to the constructor.
*
* @return array The sequence of strings.
*/
function getFinal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->final) {
array_splice($lines, count($lines), 0, $edit->final);
}
}
return $lines;
}
/**
* Removes trailing newlines from a line of text. This is meant to be used
* with array_walk().
*
* @param string $line The line to trim.
* @param integer $key The index of the line in the array. Not used.
*/
function trimNewlines(&$line, $key)
{
$line = str_replace(array("\n", "\r"), '', $line);
}
/**
* Determines the location of the system temporary directory.
*
* @static
*
* @access protected
*
* @return string A directory name which can be used for temp files.
* Returns false if one could not be found.
*/
function _getTempDir()
{
$tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp',
'c:\windows\temp', 'c:\winnt\temp');
/* Try PHP's upload_tmp_dir directive. */
$tmp = ini_get('upload_tmp_dir');
/* Otherwise, try to determine the TMPDIR environment variable. */
if (!strlen($tmp)) {
$tmp = getenv('TMPDIR');
}
/* If we still cannot determine a value, then cycle through a list of
* preset possibilities. */
while (!strlen($tmp) && count($tmp_locations)) {
$tmp_check = array_shift($tmp_locations);
if (@is_dir($tmp_check)) {
$tmp = $tmp_check;
}
}
/* If it is still empty, we have failed, so return false; otherwise
* return the directory determined. */
return strlen($tmp) ? $tmp : false;
}
/**
* Checks a diff for validity.
*
* This is here only for debugging purposes.
*/
function _check($from_lines, $to_lines)
{
if (serialize($from_lines) != serialize($this->getOriginal())) {
trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
}
if (serialize($to_lines) != serialize($this->getFinal())) {
trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
}
$rev = $this->reverse();
if (serialize($to_lines) != serialize($rev->getOriginal())) {
trigger_error("Reversed original doesn't match", E_USER_ERROR);
}
if (serialize($from_lines) != serialize($rev->getFinal())) {
trigger_error("Reversed final doesn't match", E_USER_ERROR);
}
$prevtype = null;
foreach ($this->_edits as $edit) {
if ($prevtype == get_class($edit)) {
trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
}
$prevtype = get_class($edit);
}
return true;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_MappedDiff extends Text_Diff {
/**
* Computes a diff between sequences of strings.
*
* This can be used to compute things like case-insensitve diffs, or diffs
* which ignore changes in white-space.
*
* @param array $from_lines An array of strings.
* @param array $to_lines An array of strings.
* @param array $mapped_from_lines This array should have the same size
* number of elements as $from_lines. The
* elements in $mapped_from_lines and
* $mapped_to_lines are what is actually
* compared when computing the diff.
* @param array $mapped_to_lines This array should have the same number
* of elements as $to_lines.
*/
function Text_MappedDiff($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines)
{
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0;
for ($i = 0; $i < count($this->_edits); $i++) {
$orig = &$this->_edits[$i]->orig;
if (is_array($orig)) {
$orig = array_slice($from_lines, $xi, count($orig));
$xi += count($orig);
}
$final = &$this->_edits[$i]->final;
if (is_array($final)) {
$final = array_slice($to_lines, $yi, count($final));
$yi += count($final);
}
}
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op {
var $orig;
var $final;
function &reverse()
{
trigger_error('Abstract method', E_USER_ERROR);
}
function norig()
{
return $this->orig ? count($this->orig) : 0;
}
function nfinal()
{
return $this->final ? count($this->final) : 0;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_copy extends Text_Diff_Op {
function Text_Diff_Op_copy($orig, $final = false)
{
if (!is_array($final)) {
$final = $orig;
}
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_copy($this->final, $this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_delete extends Text_Diff_Op {
function Text_Diff_Op_delete($lines)
{
$this->orig = $lines;
$this->final = false;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_add($this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_add extends Text_Diff_Op {
function Text_Diff_Op_add($lines)
{
$this->final = $lines;
$this->orig = false;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_delete($this->final);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_Op_change extends Text_Diff_Op {
function Text_Diff_Op_change($orig, $final)
{
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
$reverse = &new Text_Diff_Op_change($this->final, $this->orig);
return $reverse;
}
}

View File

@@ -0,0 +1,438 @@
<?php
/**
* Class used internally by Text_Diff to actually compute the diffs.
*
* This class is implemented using native PHP code.
*
* The algorithm used here is mostly lifted from the perl module
* Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
* http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
*
* More ideas are taken from: http://www.ics.uci.edu/~eppstein/161/960229.html
*
* Some ideas (and a bit of code) are taken from analyze.c, of GNU
* diffutils-2.7, which can be found at:
* ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
*
* Some ideas (subdivision by NCHUNKS > 2, and some optimizations) are from
* Geoffrey T. Dairiki <dairiki@dairiki.org>. The original PHP version of this
* code was written by him, and is used/adapted with his permission.
*
* $Horde: framework/Text_Diff/Diff/Engine/native.php,v 1.7.2.4 2008/01/04 10:38:10 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @package Text_Diff
*/
class Text_Diff_Engine_native {
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
$n_from = count($from_lines);
$n_to = count($to_lines);
$this->xchanged = $this->ychanged = array();
$this->xv = $this->yv = array();
$this->xind = $this->yind = array();
unset($this->seq);
unset($this->in_seq);
unset($this->lcs);
// Skip leading common lines.
for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
if ($from_lines[$skip] !== $to_lines[$skip]) {
break;
}
$this->xchanged[$skip] = $this->ychanged[$skip] = false;
}
// Skip trailing common lines.
$xi = $n_from; $yi = $n_to;
for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
if ($from_lines[$xi] !== $to_lines[$yi]) {
break;
}
$this->xchanged[$xi] = $this->ychanged[$yi] = false;
}
// Ignore lines which do not exist in both files.
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$xhash[$from_lines[$xi]] = 1;
}
for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
$line = $to_lines[$yi];
if (($this->ychanged[$yi] = empty($xhash[$line]))) {
continue;
}
$yhash[$line] = 1;
$this->yv[] = $line;
$this->yind[] = $yi;
}
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$line = $from_lines[$xi];
if (($this->xchanged[$xi] = empty($yhash[$line]))) {
continue;
}
$this->xv[] = $line;
$this->xind[] = $xi;
}
// Find the LCS.
$this->_compareseq(0, count($this->xv), 0, count($this->yv));
// Merge edits when possible.
$this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged);
$this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged);
// Compute the edit operations.
$edits = array();
$xi = $yi = 0;
while ($xi < $n_from || $yi < $n_to) {
assert($yi < $n_to || $this->xchanged[$xi]);
assert($xi < $n_from || $this->ychanged[$yi]);
// Skip matching "snake".
$copy = array();
while ($xi < $n_from && $yi < $n_to
&& !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
$copy[] = $from_lines[$xi++];
++$yi;
}
if ($copy) {
$edits[] = &new Text_Diff_Op_copy($copy);
}
// Find deletes & adds.
$delete = array();
while ($xi < $n_from && $this->xchanged[$xi]) {
$delete[] = $from_lines[$xi++];
}
$add = array();
while ($yi < $n_to && $this->ychanged[$yi]) {
$add[] = $to_lines[$yi++];
}
if ($delete && $add) {
$edits[] = &new Text_Diff_Op_change($delete, $add);
} elseif ($delete) {
$edits[] = &new Text_Diff_Op_delete($delete);
} elseif ($add) {
$edits[] = &new Text_Diff_Op_add($add);
}
}
return $edits;
}
/**
* Divides the Largest Common Subsequence (LCS) of the sequences (XOFF,
* XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized
* segments.
*
* Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of
* NCHUNKS+1 (X, Y) indexes giving the diving points between sub
* sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1),
* the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) ==
* (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
*
* This function assumes that the first lines of the specified portions of
* the two files do not match, and likewise that the last lines do not
* match. The caller must trim matching lines from the beginning and end
* of the portions it is going to specify.
*/
function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks)
{
$flip = false;
if ($xlim - $xoff > $ylim - $yoff) {
/* Things seems faster (I'm not sure I understand why) when the
* shortest sequence is in X. */
$flip = true;
list ($xoff, $xlim, $yoff, $ylim)
= array($yoff, $ylim, $xoff, $xlim);
}
if ($flip) {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->xv[$i]][] = $i;
}
} else {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->yv[$i]][] = $i;
}
}
$this->lcs = 0;
$this->seq[0]= $yoff - 1;
$this->in_seq = array();
$ymids[0] = array();
$numer = $xlim - $xoff + $nchunks - 1;
$x = $xoff;
for ($chunk = 0; $chunk < $nchunks; $chunk++) {
if ($chunk > 0) {
for ($i = 0; $i <= $this->lcs; $i++) {
$ymids[$i][$chunk - 1] = $this->seq[$i];
}
}
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks);
for (; $x < $x1; $x++) {
$line = $flip ? $this->yv[$x] : $this->xv[$x];
if (empty($ymatches[$line])) {
continue;
}
$matches = $ymatches[$line];
reset($matches);
while (list(, $y) = each($matches)) {
if (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
break;
}
}
while (list(, $y) = each($matches)) {
if ($y > $this->seq[$k - 1]) {
assert($y <= $this->seq[$k]);
/* Optimization: this is a common case: next match is
* just replacing previous match. */
$this->in_seq[$this->seq[$k]] = false;
$this->seq[$k] = $y;
$this->in_seq[$y] = 1;
} elseif (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
}
}
}
}
$seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
$ymid = $ymids[$this->lcs];
for ($n = 0; $n < $nchunks - 1; $n++) {
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
$y1 = $ymid[$n] + 1;
$seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
}
$seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
return array($this->lcs, $seps);
}
function _lcsPos($ypos)
{
$end = $this->lcs;
if ($end == 0 || $ypos > $this->seq[$end]) {
$this->seq[++$this->lcs] = $ypos;
$this->in_seq[$ypos] = 1;
return $this->lcs;
}
$beg = 1;
while ($beg < $end) {
$mid = (int)(($beg + $end) / 2);
if ($ypos > $this->seq[$mid]) {
$beg = $mid + 1;
} else {
$end = $mid;
}
}
assert($ypos != $this->seq[$end]);
$this->in_seq[$this->seq[$end]] = false;
$this->seq[$end] = $ypos;
$this->in_seq[$ypos] = 1;
return $end;
}
/**
* Finds LCS of two sequences.
*
* The results are recorded in the vectors $this->{x,y}changed[], by
* storing a 1 in the element for each line that is an insertion or
* deletion (ie. is not in the LCS).
*
* The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1.
*
* Note that XLIM, YLIM are exclusive bounds. All line numbers are
* origin-0 and discarded lines are not counted.
*/
function _compareseq ($xoff, $xlim, $yoff, $ylim)
{
/* Slide down the bottom initial diagonal. */
while ($xoff < $xlim && $yoff < $ylim
&& $this->xv[$xoff] == $this->yv[$yoff]) {
++$xoff;
++$yoff;
}
/* Slide up the top initial diagonal. */
while ($xlim > $xoff && $ylim > $yoff
&& $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
--$xlim;
--$ylim;
}
if ($xoff == $xlim || $yoff == $ylim) {
$lcs = 0;
} else {
/* This is ad hoc but seems to work well. $nchunks =
* sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks =
* max(2,min(8,(int)$nchunks)); */
$nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
list($lcs, $seps)
= $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
}
if ($lcs == 0) {
/* X and Y sequences have no common subsequence: mark all
* changed. */
while ($yoff < $ylim) {
$this->ychanged[$this->yind[$yoff++]] = 1;
}
while ($xoff < $xlim) {
$this->xchanged[$this->xind[$xoff++]] = 1;
}
} else {
/* Use the partitions to split this problem into subproblems. */
reset($seps);
$pt1 = $seps[0];
while ($pt2 = next($seps)) {
$this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
$pt1 = $pt2;
}
}
}
/**
* Adjusts inserts/deletes of identical lines to join changes as much as
* possible.
*
* We do something when a run of changed lines include a line at one end
* and has an excluded, identical line at the other. We are free to
* choose which identical line is included. `compareseq' usually chooses
* the one at the beginning, but usually it is cleaner to consider the
* following identical line to be the "change".
*
* This is extracted verbatim from analyze.c (GNU diffutils-2.7).
*/
function _shiftBoundaries($lines, &$changed, $other_changed)
{
$i = 0;
$j = 0;
assert('count($lines) == count($changed)');
$len = count($lines);
$other_len = count($other_changed);
while (1) {
/* Scan forward to find the beginning of another run of
* changes. Also keep track of the corresponding point in the
* other file.
*
* Throughout this code, $i and $j are adjusted together so that
* the first $i elements of $changed and the first $j elements of
* $other_changed both contain the same number of zeros (unchanged
* lines).
*
* Furthermore, $j is always kept so that $j == $other_len or
* $other_changed[$j] == false. */
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
while ($i < $len && ! $changed[$i]) {
assert('$j < $other_len && ! $other_changed[$j]');
$i++; $j++;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
if ($i == $len) {
break;
}
$start = $i;
/* Find the end of this run of changes. */
while (++$i < $len && $changed[$i]) {
continue;
}
do {
/* Record the length of this run of changes, so that we can
* later determine whether the run has grown. */
$runlength = $i - $start;
/* Move the changed region back, so long as the previous
* unchanged line matches the last changed one. This merges
* with previous changed regions. */
while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
$changed[--$start] = 1;
$changed[--$i] = false;
while ($start > 0 && $changed[$start - 1]) {
$start--;
}
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
/* Set CORRESPONDING to the end of the changed run, at the
* last point where it corresponds to a changed run in the
* other file. CORRESPONDING == LEN means no such point has
* been found. */
$corresponding = $j < $other_len ? $i : $len;
/* Move the changed region forward, so long as the first
* changed line matches the following unchanged one. This
* merges with following changed regions. Do this second, so
* that if there are no merges, the changed region is moved
* forward as far as possible. */
while ($i < $len && $lines[$start] == $lines[$i]) {
$changed[$start++] = false;
$changed[$i++] = 1;
while ($i < $len && $changed[$i]) {
$i++;
}
assert('$j < $other_len && ! $other_changed[$j]');
$j++;
if ($j < $other_len && $other_changed[$j]) {
$corresponding = $i;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
}
} while ($runlength != $i - $start);
/* If possible, move the fully-merged run of changes back to a
* corresponding run in the other file. */
while ($corresponding < $i) {
$changed[--$start] = 1;
$changed[--$i] = 0;
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
}
}
}

View File

@@ -0,0 +1,164 @@
<?php
/**
* Class used internally by Diff to actually compute the diffs.
*
* This class uses the Unix `diff` program via shell_exec to compute the
* differences between the two input arrays.
*
* $Horde: framework/Text_Diff/Diff/Engine/shell.php,v 1.6.2.3 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2007-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Milian Wolff <mail@milianw.de>
* @package Text_Diff
* @since 0.3.0
*/
class Text_Diff_Engine_shell {
/**
* Path to the diff executable
*
* @var string
*/
var $_diffCommand = 'diff';
/**
* Returns the array of differences.
*
* @param array $from_lines lines of text from old file
* @param array $to_lines lines of text from new file
*
* @return array all changes made (array with Text_Diff_Op_* objects)
*/
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
$temp_dir = Text_Diff::_getTempDir();
// Execute gnu diff or similar to get a standard diff file.
$from_file = tempnam($temp_dir, 'Text_Diff');
$to_file = tempnam($temp_dir, 'Text_Diff');
$fp = fopen($from_file, 'w');
fwrite($fp, implode("\n", $from_lines));
fclose($fp);
$fp = fopen($to_file, 'w');
fwrite($fp, implode("\n", $to_lines));
fclose($fp);
$diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file);
unlink($from_file);
unlink($to_file);
if (is_null($diff)) {
// No changes were made
return array(new Text_Diff_Op_copy($from_lines));
}
$from_line_no = 1;
$to_line_no = 1;
$edits = array();
// Get changed lines by parsing something like:
// 0a1,2
// 1,2c4,6
// 1,5d6
preg_match_all('#^(\d+)(?:,(\d+))?([adc])(\d+)(?:,(\d+))?$#m', $diff,
$matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (!isset($match[5])) {
// This paren is not set every time (see regex).
$match[5] = false;
}
if ($match[3] == 'a') {
$from_line_no--;
}
if ($match[3] == 'd') {
$to_line_no--;
}
if ($from_line_no < $match[1] || $to_line_no < $match[4]) {
// copied lines
assert('$match[1] - $from_line_no == $match[4] - $to_line_no');
array_push($edits,
new Text_Diff_Op_copy(
$this->_getLines($from_lines, $from_line_no, $match[1] - 1),
$this->_getLines($to_lines, $to_line_no, $match[4] - 1)));
}
switch ($match[3]) {
case 'd':
// deleted lines
array_push($edits,
new Text_Diff_Op_delete(
$this->_getLines($from_lines, $from_line_no, $match[2])));
$to_line_no++;
break;
case 'c':
// changed lines
array_push($edits,
new Text_Diff_Op_change(
$this->_getLines($from_lines, $from_line_no, $match[2]),
$this->_getLines($to_lines, $to_line_no, $match[5])));
break;
case 'a':
// added lines
array_push($edits,
new Text_Diff_Op_add(
$this->_getLines($to_lines, $to_line_no, $match[5])));
$from_line_no++;
break;
}
}
if (!empty($from_lines)) {
// Some lines might still be pending. Add them as copied
array_push($edits,
new Text_Diff_Op_copy(
$this->_getLines($from_lines, $from_line_no,
$from_line_no + count($from_lines) - 1),
$this->_getLines($to_lines, $to_line_no,
$to_line_no + count($to_lines) - 1)));
}
return $edits;
}
/**
* Get lines from either the old or new text
*
* @access private
*
* @param array &$text_lines Either $from_lines or $to_lines
* @param int &$line_no Current line number
* @param int $end Optional end line, when we want to chop more
* than one line.
*
* @return array The chopped lines
*/
function _getLines(&$text_lines, &$line_no, $end = false)
{
if (!empty($end)) {
$lines = array();
// We can shift even more
while ($line_no <= $end) {
array_push($lines, array_shift($text_lines));
$line_no++;
}
} else {
$lines = array(array_shift($text_lines));
$line_no++;
}
return $lines;
}
}

View File

@@ -0,0 +1,237 @@
<?php
/**
* Parses unified or context diffs output from eg. the diff utility.
*
* Example:
* <code>
* $patch = file_get_contents('example.patch');
* $diff = new Text_Diff('string', array($patch));
* $renderer = new Text_Diff_Renderer_inline();
* echo $renderer->render($diff);
* </code>
*
* $Horde: framework/Text_Diff/Diff/Engine/string.php,v 1.5.2.5 2008/09/10 08:31:58 jan Exp $
*
* Copyright 2005 Örjan Persson <o@42mm.org>
* Copyright 2005-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Örjan Persson <o@42mm.org>
* @package Text_Diff
* @since 0.2.0
*/
class Text_Diff_Engine_string {
/**
* Parses a unified or context diff.
*
* First param contains the whole diff and the second can be used to force
* a specific diff type. If the second parameter is 'autodetect', the
* diff will be examined to find out which type of diff this is.
*
* @param string $diff The diff content.
* @param string $mode The diff mode of the content in $diff. One of
* 'context', 'unified', or 'autodetect'.
*
* @return array List of all diff operations.
*/
function diff($diff, $mode = 'autodetect')
{
if ($mode != 'autodetect' && $mode != 'context' && $mode != 'unified') {
return PEAR::raiseError('Type of diff is unsupported');
}
if ($mode == 'autodetect') {
$context = strpos($diff, '***');
$unified = strpos($diff, '---');
if ($context === $unified) {
return PEAR::raiseError('Type of diff could not be detected');
} elseif ($context === false || $unified === false) {
$mode = $context !== false ? 'context' : 'unified';
} else {
$mode = $context < $unified ? 'context' : 'unified';
}
}
// Split by new line and remove the diff header, if there is one.
$diff = explode("\n", $diff);
if (($mode == 'context' && strpos($diff[0], '***') === 0) ||
($mode == 'unified' && strpos($diff[0], '---') === 0)) {
array_shift($diff);
array_shift($diff);
}
if ($mode == 'context') {
return $this->parseContextDiff($diff);
} else {
return $this->parseUnifiedDiff($diff);
}
}
/**
* Parses an array containing the unified diff.
*
* @param array $diff Array of lines.
*
* @return array List of all diff operations.
*/
function parseUnifiedDiff($diff)
{
$edits = array();
$end = count($diff) - 1;
for ($i = 0; $i < $end;) {
$diff1 = array();
switch (substr($diff[$i], 0, 1)) {
case ' ':
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == ' ');
$edits[] = new Text_Diff_Op_copy($diff1);
break;
case '+':
// get all new lines
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == '+');
$edits[] = new Text_Diff_Op_add($diff1);
break;
case '-':
// get changed or removed lines
$diff2 = array();
do {
$diff1[] = substr($diff[$i], 1);
} while (++$i < $end && substr($diff[$i], 0, 1) == '-');
while ($i < $end && substr($diff[$i], 0, 1) == '+') {
$diff2[] = substr($diff[$i++], 1);
}
if (count($diff2) == 0) {
$edits[] = new Text_Diff_Op_delete($diff1);
} else {
$edits[] = new Text_Diff_Op_change($diff1, $diff2);
}
break;
default:
$i++;
break;
}
}
return $edits;
}
/**
* Parses an array containing the context diff.
*
* @param array $diff Array of lines.
*
* @return array List of all diff operations.
*/
function parseContextDiff(&$diff)
{
$edits = array();
$i = $max_i = $j = $max_j = 0;
$end = count($diff) - 1;
while ($i < $end && $j < $end) {
while ($i >= $max_i && $j >= $max_j) {
// Find the boundaries of the diff output of the two files
for ($i = $j;
$i < $end && substr($diff[$i], 0, 3) == '***';
$i++);
for ($max_i = $i;
$max_i < $end && substr($diff[$max_i], 0, 3) != '---';
$max_i++);
for ($j = $max_i;
$j < $end && substr($diff[$j], 0, 3) == '---';
$j++);
for ($max_j = $j;
$max_j < $end && substr($diff[$max_j], 0, 3) != '***';
$max_j++);
}
// find what hasn't been changed
$array = array();
while ($i < $max_i &&
$j < $max_j &&
strcmp($diff[$i], $diff[$j]) == 0) {
$array[] = substr($diff[$i], 2);
$i++;
$j++;
}
while ($i < $max_i && ($max_j-$j) <= 1) {
if ($diff[$i] != '' && substr($diff[$i], 0, 1) != ' ') {
break;
}
$array[] = substr($diff[$i++], 2);
}
while ($j < $max_j && ($max_i-$i) <= 1) {
if ($diff[$j] != '' && substr($diff[$j], 0, 1) != ' ') {
break;
}
$array[] = substr($diff[$j++], 2);
}
if (count($array) > 0) {
$edits[] = new Text_Diff_Op_copy($array);
}
if ($i < $max_i) {
$diff1 = array();
switch (substr($diff[$i], 0, 1)) {
case '!':
$diff2 = array();
do {
$diff1[] = substr($diff[$i], 2);
if ($j < $max_j && substr($diff[$j], 0, 1) == '!') {
$diff2[] = substr($diff[$j++], 2);
}
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '!');
$edits[] = new Text_Diff_Op_change($diff1, $diff2);
break;
case '+':
do {
$diff1[] = substr($diff[$i], 2);
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '+');
$edits[] = new Text_Diff_Op_add($diff1);
break;
case '-':
do {
$diff1[] = substr($diff[$i], 2);
} while (++$i < $max_i && substr($diff[$i], 0, 1) == '-');
$edits[] = new Text_Diff_Op_delete($diff1);
break;
}
}
if ($j < $max_j) {
$diff2 = array();
switch (substr($diff[$j], 0, 1)) {
case '+':
do {
$diff2[] = substr($diff[$j++], 2);
} while ($j < $max_j && substr($diff[$j], 0, 1) == '+');
$edits[] = new Text_Diff_Op_add($diff2);
break;
case '-':
do {
$diff2[] = substr($diff[$j++], 2);
} while ($j < $max_j && substr($diff[$j], 0, 1) == '-');
$edits[] = new Text_Diff_Op_delete($diff2);
break;
}
}
}
return $edits;
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Class used internally by Diff to actually compute the diffs.
*
* This class uses the xdiff PECL package (http://pecl.php.net/package/xdiff)
* to compute the differences between the two input arrays.
*
* $Horde: framework/Text_Diff/Diff/Engine/xdiff.php,v 1.4.2.3 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Jon Parise <jon@horde.org>
* @package Text_Diff
*/
class Text_Diff_Engine_xdiff {
/**
*/
function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Text_Diff', 'trimNewlines'));
/* Convert the two input arrays into strings for xdiff processing. */
$from_string = implode("\n", $from_lines);
$to_string = implode("\n", $to_lines);
/* Diff the two strings and convert the result to an array. */
$diff = xdiff_string_diff($from_string, $to_string, count($to_lines));
$diff = explode("\n", $diff);
/* Walk through the diff one line at a time. We build the $edits
* array of diff operations by reading the first character of the
* xdiff output (which is in the "unified diff" format).
*
* Note that we don't have enough information to detect "changed"
* lines using this approach, so we can't add Text_Diff_Op_changed
* instances to the $edits array. The result is still perfectly
* valid, albeit a little less descriptive and efficient. */
$edits = array();
foreach ($diff as $line) {
switch ($line[0]) {
case ' ':
$edits[] = &new Text_Diff_Op_copy(array(substr($line, 1)));
break;
case '+':
$edits[] = &new Text_Diff_Op_add(array(substr($line, 1)));
break;
case '-':
$edits[] = &new Text_Diff_Op_delete(array(substr($line, 1)));
break;
}
}
return $edits;
}
}

55
lib/Text/Diff/Mapped.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
/**
* $Horde: framework/Text_Diff/Diff/Mapped.php,v 1.3.2.3 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2007-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff_Mapped extends Text_Diff {
/**
* Computes a diff between sequences of strings.
*
* This can be used to compute things like case-insensitve diffs, or diffs
* which ignore changes in white-space.
*
* @param array $from_lines An array of strings.
* @param array $to_lines An array of strings.
* @param array $mapped_from_lines This array should have the same size
* number of elements as $from_lines. The
* elements in $mapped_from_lines and
* $mapped_to_lines are what is actually
* compared when computing the diff.
* @param array $mapped_to_lines This array should have the same number
* of elements as $to_lines.
*/
function Text_Diff_Mapped($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines)
{
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0;
for ($i = 0; $i < count($this->_edits); $i++) {
$orig = &$this->_edits[$i]->orig;
if (is_array($orig)) {
$orig = array_slice($from_lines, $xi, count($orig));
$xi += count($orig);
}
$final = &$this->_edits[$i]->final;
if (is_array($final)) {
$final = array_slice($to_lines, $yi, count($final));
$yi += count($final);
}
}
}
}

237
lib/Text/Diff/Renderer.php Normal file
View File

@@ -0,0 +1,237 @@
<?php
/**
* A class to render Diffs in different formats.
*
* This class renders the diff in classic diff format. It is intended that
* this class be customized via inheritance, to obtain fancier outputs.
*
* $Horde: framework/Text_Diff/Diff/Renderer.php,v 1.5.10.10 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
*/
class Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*
* This should be left at zero for this class, but subclasses may want to
* set this to other values.
*/
var $_leading_context_lines = 0;
/**
* Number of trailing context "lines" to preserve.
*
* This should be left at zero for this class, but subclasses may want to
* set this to other values.
*/
var $_trailing_context_lines = 0;
/**
* Constructor.
*/
function Text_Diff_Renderer($params = array())
{
foreach ($params as $param => $value) {
$v = '_' . $param;
if (isset($this->$v)) {
$this->$v = $value;
}
}
}
/**
* Get any renderer parameters.
*
* @return array All parameters of this renderer object.
*/
function getParams()
{
$params = array();
foreach (get_object_vars($this) as $k => $v) {
if ($k[0] == '_') {
$params[substr($k, 1)] = $v;
}
}
return $params;
}
/**
* Renders a diff.
*
* @param Text_Diff $diff A Text_Diff object.
*
* @return string The formatted output.
*/
function render($diff)
{
$xi = $yi = 1;
$block = false;
$context = array();
$nlead = $this->_leading_context_lines;
$ntrail = $this->_trailing_context_lines;
$output = $this->_startDiff();
$diffs = $diff->getDiff();
foreach ($diffs as $i => $edit) {
/* If these are unchanged (copied) lines, and we want to keep
* leading or trailing context lines, extract them from the copy
* block. */
if (is_a($edit, 'Text_Diff_Op_copy')) {
/* Do we have any diff blocks yet? */
if (is_array($block)) {
/* How many lines to keep as context from the copy
* block. */
$keep = $i == count($diffs) - 1 ? $ntrail : $nlead + $ntrail;
if (count($edit->orig) <= $keep) {
/* We have less lines in the block than we want for
* context => keep the whole block. */
$block[] = $edit;
} else {
if ($ntrail) {
/* Create a new block with as many lines as we need
* for the trailing context. */
$context = array_slice($edit->orig, 0, $ntrail);
$block[] = &new Text_Diff_Op_copy($context);
}
/* @todo */
$output .= $this->_block($x0, $ntrail + $xi - $x0,
$y0, $ntrail + $yi - $y0,
$block);
$block = false;
}
}
/* Keep the copy block as the context for the next block. */
$context = $edit->orig;
} else {
/* Don't we have any diff blocks yet? */
if (!is_array($block)) {
/* Extract context lines from the preceding copy block. */
$context = array_slice($context, count($context) - $nlead);
$x0 = $xi - count($context);
$y0 = $yi - count($context);
$block = array();
if ($context) {
$block[] = &new Text_Diff_Op_copy($context);
}
}
$block[] = $edit;
}
if ($edit->orig) {
$xi += count($edit->orig);
}
if ($edit->final) {
$yi += count($edit->final);
}
}
if (is_array($block)) {
$output .= $this->_block($x0, $xi - $x0,
$y0, $yi - $y0,
$block);
}
return $output . $this->_endDiff();
}
function _block($xbeg, $xlen, $ybeg, $ylen, &$edits)
{
$output = $this->_startBlock($this->_blockHeader($xbeg, $xlen, $ybeg, $ylen));
foreach ($edits as $edit) {
switch (strtolower(get_class($edit))) {
case 'text_diff_op_copy':
$output .= $this->_context($edit->orig);
break;
case 'text_diff_op_add':
$output .= $this->_added($edit->final);
break;
case 'text_diff_op_delete':
$output .= $this->_deleted($edit->orig);
break;
case 'text_diff_op_change':
$output .= $this->_changed($edit->orig, $edit->final);
break;
}
}
return $output . $this->_endBlock();
}
function _startDiff()
{
return '';
}
function _endDiff()
{
return '';
}
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
if ($xlen > 1) {
$xbeg .= ',' . ($xbeg + $xlen - 1);
}
if ($ylen > 1) {
$ybeg .= ',' . ($ybeg + $ylen - 1);
}
// this matches the GNU Diff behaviour
if ($xlen && !$ylen) {
$ybeg--;
} elseif (!$xlen) {
$xbeg--;
}
return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
}
function _startBlock($header)
{
return $header . "\n";
}
function _endBlock()
{
return '';
}
function _lines($lines, $prefix = ' ')
{
return $prefix . implode("\n$prefix", $lines) . "\n";
}
function _context($lines)
{
return $this->_lines($lines, ' ');
}
function _added($lines)
{
return $this->_lines($lines, '> ');
}
function _deleted($lines)
{
return $this->_lines($lines, '< ');
}
function _changed($orig, $final)
{
return $this->_deleted($orig) . "---\n" . $this->_added($final);
}
}

View File

@@ -0,0 +1,77 @@
<?php
/**
* "Context" diff renderer.
*
* This class renders the diff in classic "context diff" format.
*
* $Horde: framework/Text_Diff/Diff/Renderer/context.php,v 1.3.2.3 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
*/
/** Text_Diff_Renderer */
require_once 'Text/Diff/Renderer.php';
/**
* @package Text_Diff
*/
class Text_Diff_Renderer_context extends Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*/
var $_leading_context_lines = 4;
/**
* Number of trailing context "lines" to preserve.
*/
var $_trailing_context_lines = 4;
var $_second_block = '';
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
if ($xlen != 1) {
$xbeg .= ',' . $xlen;
}
if ($ylen != 1) {
$ybeg .= ',' . $ylen;
}
$this->_second_block = "--- $ybeg ----\n";
return "***************\n*** $xbeg ****";
}
function _endBlock()
{
return $this->_second_block;
}
function _context($lines)
{
$this->_second_block .= $this->_lines($lines, ' ');
return $this->_lines($lines, ' ');
}
function _added($lines)
{
$this->_second_block .= $this->_lines($lines, '+ ');
return '';
}
function _deleted($lines)
{
return $this->_lines($lines, '- ');
}
function _changed($orig, $final)
{
$this->_second_block .= $this->_lines($final, '! ');
return $this->_lines($orig, '! ');
}
}

View File

@@ -0,0 +1,170 @@
<?php
/**
* "Inline" diff renderer.
*
* $Horde: framework/Text_Diff/Diff/Renderer/inline.php,v 1.4.10.14 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Ciprian Popovici
* @package Text_Diff
*/
/** Text_Diff_Renderer */
require_once 'Text/Diff/Renderer.php';
/**
* "Inline" diff renderer.
*
* This class renders diffs in the Wiki-style "inline" format.
*
* @author Ciprian Popovici
* @package Text_Diff
*/
class Text_Diff_Renderer_inline extends Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*/
var $_leading_context_lines = 10000;
/**
* Number of trailing context "lines" to preserve.
*/
var $_trailing_context_lines = 10000;
/**
* Prefix for inserted text.
*/
var $_ins_prefix = '<ins>';
/**
* Suffix for inserted text.
*/
var $_ins_suffix = '</ins>';
/**
* Prefix for deleted text.
*/
var $_del_prefix = '<del>';
/**
* Suffix for deleted text.
*/
var $_del_suffix = '</del>';
/**
* Header for each change block.
*/
var $_block_header = '';
/**
* What are we currently splitting on? Used to recurse to show word-level
* changes.
*/
var $_split_level = 'lines';
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
return $this->_block_header;
}
function _startBlock($header)
{
return $header;
}
function _lines($lines, $prefix = ' ', $encode = true)
{
if ($encode) {
array_walk($lines, array(&$this, '_encode'));
}
if ($this->_split_level == 'words') {
return implode('', $lines);
} else {
return implode("\n", $lines) . "\n";
}
}
function _added($lines)
{
array_walk($lines, array(&$this, '_encode'));
$lines[0] = $this->_ins_prefix . $lines[0];
$lines[count($lines) - 1] .= $this->_ins_suffix;
return $this->_lines($lines, ' ', false);
}
function _deleted($lines, $words = false)
{
array_walk($lines, array(&$this, '_encode'));
$lines[0] = $this->_del_prefix . $lines[0];
$lines[count($lines) - 1] .= $this->_del_suffix;
return $this->_lines($lines, ' ', false);
}
function _changed($orig, $final)
{
/* If we've already split on words, don't try to do so again - just
* display. */
if ($this->_split_level == 'words') {
$prefix = '';
while ($orig[0] !== false && $final[0] !== false &&
substr($orig[0], 0, 1) == ' ' &&
substr($final[0], 0, 1) == ' ') {
$prefix .= substr($orig[0], 0, 1);
$orig[0] = substr($orig[0], 1);
$final[0] = substr($final[0], 1);
}
return $prefix . $this->_deleted($orig) . $this->_added($final);
}
$text1 = implode("\n", $orig);
$text2 = implode("\n", $final);
/* Non-printing newline marker. */
$nl = "\0";
/* We want to split on word boundaries, but we need to
* preserve whitespace as well. Therefore we split on words,
* but include all blocks of whitespace in the wordlist. */
$diff = new Text_Diff($this->_splitOnWords($text1, $nl),
$this->_splitOnWords($text2, $nl));
/* Get the diff in inline format. */
$renderer = new Text_Diff_Renderer_inline(array_merge($this->getParams(),
array('split_level' => 'words')));
/* Run the diff and get the output. */
return str_replace($nl, "\n", $renderer->render($diff)) . "\n";
}
function _splitOnWords($string, $newlineEscape = "\n")
{
// Ignore \0; otherwise the while loop will never finish.
$string = str_replace("\0", '', $string);
$words = array();
$length = strlen($string);
$pos = 0;
while ($pos < $length) {
// Eat a word with any preceding whitespace.
$spaces = strspn(substr($string, $pos), " \n");
$nextpos = strcspn(substr($string, $pos + $spaces), " \n");
$words[] = str_replace("\n", $newlineEscape, substr($string, $pos, $spaces + $nextpos));
$pos += $spaces + $nextpos;
}
return $words;
}
function _encode(&$string)
{
$string = htmlspecialchars($string);
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* "Unified" diff renderer.
*
* This class renders the diff in classic "unified diff" format.
*
* $Horde: framework/Text_Diff/Diff/Renderer/unified.php,v 1.3.10.6 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2004-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @author Ciprian Popovici
* @package Text_Diff
*/
/** Text_Diff_Renderer */
require_once 'Text/Diff/Renderer.php';
/**
* @package Text_Diff
*/
class Text_Diff_Renderer_unified extends Text_Diff_Renderer {
/**
* Number of leading context "lines" to preserve.
*/
var $_leading_context_lines = 4;
/**
* Number of trailing context "lines" to preserve.
*/
var $_trailing_context_lines = 4;
function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
if ($xlen != 1) {
$xbeg .= ',' . $xlen;
}
if ($ylen != 1) {
$ybeg .= ',' . $ylen;
}
return "@@ -$xbeg +$ybeg @@";
}
function _context($lines)
{
return $this->_lines($lines, ' ');
}
function _added($lines)
{
return $this->_lines($lines, '+');
}
function _deleted($lines)
{
return $this->_lines($lines, '-');
}
function _changed($orig, $final)
{
return $this->_deleted($orig) . $this->_added($final);
}
}

276
lib/Text/Diff/ThreeWay.php Normal file
View File

@@ -0,0 +1,276 @@
<?php
/**
* A class for computing three way diffs.
*
* $Horde: framework/Text_Diff/Diff/ThreeWay.php,v 1.3.2.3 2008/01/04 10:37:27 jan Exp $
*
* Copyright 2007-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @since 0.3.0
*/
/** Text_Diff */
require_once 'Text/Diff.php';
/**
* A class for computing three way diffs.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff_ThreeWay extends Text_Diff {
/**
* Conflict counter.
*
* @var integer
*/
var $_conflictingBlocks = 0;
/**
* Computes diff between 3 sequences of strings.
*
* @param array $orig The original lines to use.
* @param array $final1 The first version to compare to.
* @param array $final2 The second version to compare to.
*/
function Text_Diff_ThreeWay($orig, $final1, $final2)
{
if (extension_loaded('xdiff')) {
$engine = new Text_Diff_Engine_xdiff();
} else {
$engine = new Text_Diff_Engine_native();
}
$this->_edits = $this->_diff3($engine->diff($orig, $final1),
$engine->diff($orig, $final2));
}
/**
*/
function mergedOutput($label1 = false, $label2 = false)
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->isConflict()) {
/* FIXME: this should probably be moved somewhere else. */
$lines = array_merge($lines,
array('<<<<<<<' . ($label1 ? ' ' . $label1 : '')),
$edit->final1,
array("======="),
$edit->final2,
array('>>>>>>>' . ($label2 ? ' ' . $label2 : '')));
$this->_conflictingBlocks++;
} else {
$lines = array_merge($lines, $edit->merged());
}
}
return $lines;
}
/**
* @access private
*/
function _diff3($edits1, $edits2)
{
$edits = array();
$bb = new Text_Diff_ThreeWay_BlockBuilder();
$e1 = current($edits1);
$e2 = current($edits2);
while ($e1 || $e2) {
if ($e1 && $e2 && is_a($e1, 'Text_Diff_Op_copy') && is_a($e2, 'Text_Diff_Op_copy')) {
/* We have copy blocks from both diffs. This is the (only)
* time we want to emit a diff3 copy block. Flush current
* diff3 diff block, if any. */
if ($edit = $bb->finish()) {
$edits[] = $edit;
}
$ncopy = min($e1->norig(), $e2->norig());
assert($ncopy > 0);
$edits[] = new Text_Diff_ThreeWay_Op_copy(array_slice($e1->orig, 0, $ncopy));
if ($e1->norig() > $ncopy) {
array_splice($e1->orig, 0, $ncopy);
array_splice($e1->final, 0, $ncopy);
} else {
$e1 = next($edits1);
}
if ($e2->norig() > $ncopy) {
array_splice($e2->orig, 0, $ncopy);
array_splice($e2->final, 0, $ncopy);
} else {
$e2 = next($edits2);
}
} else {
if ($e1 && $e2) {
if ($e1->orig && $e2->orig) {
$norig = min($e1->norig(), $e2->norig());
$orig = array_splice($e1->orig, 0, $norig);
array_splice($e2->orig, 0, $norig);
$bb->input($orig);
}
if (is_a($e1, 'Text_Diff_Op_copy')) {
$bb->out1(array_splice($e1->final, 0, $norig));
}
if (is_a($e2, 'Text_Diff_Op_copy')) {
$bb->out2(array_splice($e2->final, 0, $norig));
}
}
if ($e1 && ! $e1->orig) {
$bb->out1($e1->final);
$e1 = next($edits1);
}
if ($e2 && ! $e2->orig) {
$bb->out2($e2->final);
$e2 = next($edits2);
}
}
}
if ($edit = $bb->finish()) {
$edits[] = $edit;
}
return $edits;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_ThreeWay_Op {
function Text_Diff_ThreeWay_Op($orig = false, $final1 = false, $final2 = false)
{
$this->orig = $orig ? $orig : array();
$this->final1 = $final1 ? $final1 : array();
$this->final2 = $final2 ? $final2 : array();
}
function merged()
{
if (!isset($this->_merged)) {
if ($this->final1 === $this->final2) {
$this->_merged = &$this->final1;
} elseif ($this->final1 === $this->orig) {
$this->_merged = &$this->final2;
} elseif ($this->final2 === $this->orig) {
$this->_merged = &$this->final1;
} else {
$this->_merged = false;
}
}
return $this->_merged;
}
function isConflict()
{
return $this->merged() === false;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_ThreeWay_Op_copy extends Text_Diff_ThreeWay_Op {
function Text_Diff_ThreeWay_Op_Copy($lines = false)
{
$this->orig = $lines ? $lines : array();
$this->final1 = &$this->orig;
$this->final2 = &$this->orig;
}
function merged()
{
return $this->orig;
}
function isConflict()
{
return false;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff_ThreeWay_BlockBuilder {
function Text_Diff_ThreeWay_BlockBuilder()
{
$this->_init();
}
function input($lines)
{
if ($lines) {
$this->_append($this->orig, $lines);
}
}
function out1($lines)
{
if ($lines) {
$this->_append($this->final1, $lines);
}
}
function out2($lines)
{
if ($lines) {
$this->_append($this->final2, $lines);
}
}
function isEmpty()
{
return !$this->orig && !$this->final1 && !$this->final2;
}
function finish()
{
if ($this->isEmpty()) {
return false;
} else {
$edit = new Text_Diff_ThreeWay_Op($this->orig, $this->final1, $this->final2);
$this->_init();
return $edit;
}
}
function _init()
{
$this->orig = $this->final1 = $this->final2 = array();
}
function _append(&$array, $lines)
{
array_splice($array, sizeof($array), 0, $lines);
}
}

276
lib/Text/Diff3.php Normal file
View File

@@ -0,0 +1,276 @@
<?php
/**
* A class for computing three way diffs.
*
* $Horde: framework/Text_Diff/Diff3.php,v 1.2.10.6 2008/01/04 10:37:26 jan Exp $
*
* Copyright 2007-2008 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @since 0.3.0
*/
/** Text_Diff */
require_once 'Text/Diff.php';
/**
* A class for computing three way diffs.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff3 extends Text_Diff {
/**
* Conflict counter.
*
* @var integer
*/
var $_conflictingBlocks = 0;
/**
* Computes diff between 3 sequences of strings.
*
* @param array $orig The original lines to use.
* @param array $final1 The first version to compare to.
* @param array $final2 The second version to compare to.
*/
function Text_Diff3($orig, $final1, $final2)
{
if (extension_loaded('xdiff')) {
$engine = new Text_Diff_Engine_xdiff();
} else {
$engine = new Text_Diff_Engine_native();
}
$this->_edits = $this->_diff3($engine->diff($orig, $final1),
$engine->diff($orig, $final2));
}
/**
*/
function mergedOutput($label1 = false, $label2 = false)
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->isConflict()) {
/* FIXME: this should probably be moved somewhere else. */
$lines = array_merge($lines,
array('<<<<<<<' . ($label1 ? ' ' . $label1 : '')),
$edit->final1,
array("======="),
$edit->final2,
array('>>>>>>>' . ($label2 ? ' ' . $label2 : '')));
$this->_conflictingBlocks++;
} else {
$lines = array_merge($lines, $edit->merged());
}
}
return $lines;
}
/**
* @access private
*/
function _diff3($edits1, $edits2)
{
$edits = array();
$bb = new Text_Diff3_BlockBuilder();
$e1 = current($edits1);
$e2 = current($edits2);
while ($e1 || $e2) {
if ($e1 && $e2 && is_a($e1, 'Text_Diff_Op_copy') && is_a($e2, 'Text_Diff_Op_copy')) {
/* We have copy blocks from both diffs. This is the (only)
* time we want to emit a diff3 copy block. Flush current
* diff3 diff block, if any. */
if ($edit = $bb->finish()) {
$edits[] = $edit;
}
$ncopy = min($e1->norig(), $e2->norig());
assert($ncopy > 0);
$edits[] = new Text_Diff3_Op_copy(array_slice($e1->orig, 0, $ncopy));
if ($e1->norig() > $ncopy) {
array_splice($e1->orig, 0, $ncopy);
array_splice($e1->final, 0, $ncopy);
} else {
$e1 = next($edits1);
}
if ($e2->norig() > $ncopy) {
array_splice($e2->orig, 0, $ncopy);
array_splice($e2->final, 0, $ncopy);
} else {
$e2 = next($edits2);
}
} else {
if ($e1 && $e2) {
if ($e1->orig && $e2->orig) {
$norig = min($e1->norig(), $e2->norig());
$orig = array_splice($e1->orig, 0, $norig);
array_splice($e2->orig, 0, $norig);
$bb->input($orig);
}
if (is_a($e1, 'Text_Diff_Op_copy')) {
$bb->out1(array_splice($e1->final, 0, $norig));
}
if (is_a($e2, 'Text_Diff_Op_copy')) {
$bb->out2(array_splice($e2->final, 0, $norig));
}
}
if ($e1 && ! $e1->orig) {
$bb->out1($e1->final);
$e1 = next($edits1);
}
if ($e2 && ! $e2->orig) {
$bb->out2($e2->final);
$e2 = next($edits2);
}
}
}
if ($edit = $bb->finish()) {
$edits[] = $edit;
}
return $edits;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff3_Op {
function Text_Diff3_Op($orig = false, $final1 = false, $final2 = false)
{
$this->orig = $orig ? $orig : array();
$this->final1 = $final1 ? $final1 : array();
$this->final2 = $final2 ? $final2 : array();
}
function merged()
{
if (!isset($this->_merged)) {
if ($this->final1 === $this->final2) {
$this->_merged = &$this->final1;
} elseif ($this->final1 === $this->orig) {
$this->_merged = &$this->final2;
} elseif ($this->final2 === $this->orig) {
$this->_merged = &$this->final1;
} else {
$this->_merged = false;
}
}
return $this->_merged;
}
function isConflict()
{
return $this->merged() === false;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff3_Op_copy extends Text_Diff3_Op {
function Text_Diff3_Op_Copy($lines = false)
{
$this->orig = $lines ? $lines : array();
$this->final1 = &$this->orig;
$this->final2 = &$this->orig;
}
function merged()
{
return $this->orig;
}
function isConflict()
{
return false;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*
* @access private
*/
class Text_Diff3_BlockBuilder {
function Text_Diff3_BlockBuilder()
{
$this->_init();
}
function input($lines)
{
if ($lines) {
$this->_append($this->orig, $lines);
}
}
function out1($lines)
{
if ($lines) {
$this->_append($this->final1, $lines);
}
}
function out2($lines)
{
if ($lines) {
$this->_append($this->final2, $lines);
}
}
function isEmpty()
{
return !$this->orig && !$this->final1 && !$this->final2;
}
function finish()
{
if ($this->isEmpty()) {
return false;
} else {
$edit = new Text_Diff3_Op($this->orig, $this->final1, $this->final2);
$this->_init();
return $edit;
}
}
function _init()
{
$this->orig = $this->final1 = $this->final2 = array();
}
function _append(&$array, $lines)
{
array_splice($array, sizeof($array), 0, $lines);
}
}

View File

@@ -0,0 +1,55 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: array_key_exists.php,v 1.1 2005/07/11 16:34:35 ggiunta Exp $
/**
* Replace array_key_exists()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.array_key_exists
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.1 $
* @since PHP 4.1.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('array_key_exists')) {
function array_key_exists($key, $search)
{
if (!is_scalar($key)) {
user_error('array_key_exists() The first argument should be either a string or an integer',
E_USER_WARNING);
return false;
}
if (is_object($search)) {
$search = get_object_vars($search);
}
if (!is_array($search)) {
user_error('array_key_exists() The second argument should be either an array or an object',
E_USER_WARNING);
return false;
}
return in_array($key, array_keys($search));
}
}
?>

47
lib/compat/is_a.php Normal file
View File

@@ -0,0 +1,47 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: is_a.php,v 1.2 2005/11/21 10:57:23 ggiunta Exp $
/**
* Replace function is_a()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_a
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.2 $
* @since PHP 4.2.0
* @require PHP 4.0.0 (user_error) (is_subclass_of)
*/
if (!function_exists('is_a')) {
function is_a($object, $class)
{
if (!is_object($object)) {
return false;
}
if (get_class($object) == strtolower($class)) {
return true;
} else {
return is_subclass_of($object, $class);
}
}
}
?>

View File

@@ -0,0 +1,53 @@
<?php
/**
* Replace function is_callable()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_callable
* @author Gaetano Giunta <giunta.gaetano@sea-aeroportimilano.it>
* @version $Id: is_callable.php,v 1.3 2006/08/21 14:03:15 ggiunta Exp $
* @since PHP 4.0.6
* @require PHP 4.0.0 (true, false, etc...)
* @todo add the 3rd parameter syntax...
*/
if (!function_exists('is_callable')) {
function is_callable($var, $syntax_only=false)
{
if ($syntax_only)
{
/* from The Manual:
* If the syntax_only argument is TRUE the function only verifies
* that var might be a function or method. It will only reject simple
* variables that are not strings, or an array that does not have a
* valid structure to be used as a callback. The valid ones are
* supposed to have only 2 entries, the first of which is an object
* or a string, and the second a string
*/
return (is_string($var) || (is_array($var) && count($var) == 2 && is_string(end($var)) && (is_string(reset($var)) || is_object(reset($var)))));
}
else
{
if (is_string($var))
{
return function_exists($var);
}
else if (is_array($var) && count($var) == 2 && is_string($method = end($var)))
{
$obj = reset($var);
if (is_string($obj))
{
$methods = get_class_methods($obj);
return (bool)(is_array($methods) && in_array(strtolower($method), $methods));
}
else if (is_object($obj))
{
return method_exists($obj, $method);
}
}
return false;
}
}
}
?>

38
lib/compat/is_scalar.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
//
// $Id: is_scalar.php,v 1.2 2005/11/21 10:57:23 ggiunta Exp $
/**
* Replace is_scalar()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_scalar
* @author Gaetano Giunta
* @version $Revision: 1.2 $
* @since PHP 4.0.5
* @require PHP 4 (is_bool)
*/
if (!function_exists('is_scalar')) {
function is_scalar($val)
{
// Check input
return (is_bool($val) || is_int($val) || is_float($val) || is_string($val));
}
}
?>

105
lib/compat/var_export.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: var_export.php,v 1.2 2005/11/21 10:57:23 ggiunta Exp $
/**
* Replace var_export()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.var_export
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.2 $
* @since PHP 4.2.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('var_export')) {
function var_export($array, $return = false, $lvl=0)
{
// Common output variables
$indent = ' ';
$doublearrow = ' => ';
$lineend = ",\n";
$stringdelim = '\'';
// Check the export isn't a simple string / int
if (is_string($array)) {
$out = $stringdelim . str_replace('\'', '\\\'', str_replace('\\', '\\\\', $array)) . $stringdelim;
} elseif (is_int($array) || is_float($array)) {
$out = (string)$array;
} elseif (is_bool($array)) {
$out = $array ? 'true' : 'false';
} elseif (is_null($array)) {
$out = 'NULL';
} elseif (is_resource($array)) {
$out = 'resource';
} else {
// Begin the array export
// Start the string
$out = "array (\n";
// Loop through each value in array
foreach ($array as $key => $value) {
// If the key is a string, delimit it
if (is_string($key)) {
$key = str_replace('\'', '\\\'', str_replace('\\', '\\\\', $key));
$key = $stringdelim . $key . $stringdelim;
}
$val = var_export($value, true, $lvl+1);
// Delimit value
/*if (is_array($value)) {
// We have an array, so do some recursion
// Do some basic recursion while increasing the indent
$recur_array = explode($newline, var_export($value, true));
$temp_array = array();
foreach ($recur_array as $recur_line) {
$temp_array[] = $indent . $recur_line;
}
$recur_array = implode($newline, $temp_array);
$value = $newline . $recur_array;
} elseif (is_null($value)) {
$value = 'NULL';
} else {
$value = str_replace($find, $replace, $value);
$value = $stringdelim . $value . $stringdelim;
}*/
// Piece together the line
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= $key . $doublearrow . $val . $lineend;
}
// End our string
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= ")";
}
// Decide method of output
if ($return === true) {
return $out;
} else {
echo $out;
return;
}
}
}
?>

View File

@@ -0,0 +1,179 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Philippe Jausions <Philippe.Jausions@11abacus.com> |
// | Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: version_compare.php,v 1.1 2005/07/11 16:34:36 ggiunta Exp $
/**
* Replace version_compare()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.version_compare
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.1 $
* @since PHP 4.1.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('version_compare')) {
function version_compare($version1, $version2, $operator = '<')
{
// Check input
if (!is_scalar($version1)) {
user_error('version_compare() expects parameter 1 to be string, ' .
gettype($version1) . ' given', E_USER_WARNING);
return;
}
if (!is_scalar($version2)) {
user_error('version_compare() expects parameter 2 to be string, ' .
gettype($version2) . ' given', E_USER_WARNING);
return;
}
if (!is_scalar($operator)) {
user_error('version_compare() expects parameter 3 to be string, ' .
gettype($operator) . ' given', E_USER_WARNING);
return;
}
// Standardise versions
$v1 = explode('.',
str_replace('..', '.',
preg_replace('/([^0-9\.]+)/', '.$1.',
str_replace(array('-', '_', '+'), '.',
trim($version1)))));
$v2 = explode('.',
str_replace('..', '.',
preg_replace('/([^0-9\.]+)/', '.$1.',
str_replace(array('-', '_', '+'), '.',
trim($version2)))));
// Replace empty entries at the start of the array
while (empty($v1[0]) && array_shift($v1)) {}
while (empty($v2[0]) && array_shift($v2)) {}
// Release state order
// '#' stands for any number
$versions = array(
'dev' => 0,
'alpha' => 1,
'a' => 1,
'beta' => 2,
'b' => 2,
'RC' => 3,
'#' => 4,
'p' => 5,
'pl' => 5);
// Loop through each segment in the version string
$compare = 0;
for ($i = 0, $x = min(count($v1), count($v2)); $i < $x; $i++) {
if ($v1[$i] == $v2[$i]) {
continue;
}
$i1 = $v1[$i];
$i2 = $v2[$i];
if (is_numeric($i1) && is_numeric($i2)) {
$compare = ($i1 < $i2) ? -1 : 1;
break;
}
// We use the position of '#' in the versions list
// for numbers... (so take care of # in original string)
if ($i1 == '#') {
$i1 = '';
} elseif (is_numeric($i1)) {
$i1 = '#';
}
if ($i2 == '#') {
$i2 = '';
} elseif (is_numeric($i2)) {
$i2 = '#';
}
if (isset($versions[$i1]) && isset($versions[$i2])) {
$compare = ($versions[$i1] < $versions[$i2]) ? -1 : 1;
} elseif (isset($versions[$i1])) {
$compare = 1;
} elseif (isset($versions[$i2])) {
$compare = -1;
} else {
$compare = 0;
}
break;
}
// If previous loop didn't find anything, compare the "extra" segments
if ($compare == 0) {
if (count($v2) > count($v1)) {
if (isset($versions[$v2[$i]])) {
$compare = ($versions[$v2[$i]] < 4) ? 1 : -1;
} else {
$compare = -1;
}
} elseif (count($v2) < count($v1)) {
if (isset($versions[$v1[$i]])) {
$compare = ($versions[$v1[$i]] < 4) ? -1 : 1;
} else {
$compare = 1;
}
}
}
// Compare the versions
if (func_num_args() > 2) {
switch ($operator) {
case '>':
case 'gt':
return (bool) ($compare > 0);
break;
case '>=':
case 'ge':
return (bool) ($compare >= 0);
break;
case '<=':
case 'le':
return (bool) ($compare <= 0);
break;
case '==':
case '=':
case 'eq':
return (bool) ($compare == 0);
break;
case '<>':
case '!=':
case 'ne':
return (bool) ($compare != 0);
break;
case '':
case '<':
case 'lt':
return (bool) ($compare < 0);
break;
default:
return;
}
}
return $compare;
}
}
?>

6
lib/phpxmlrpc/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/.idea
composer.phar
composer.lock
/vendor/*
/tests/coverage/*
/build/*

53
lib/phpxmlrpc/.travis.yml Normal file
View File

@@ -0,0 +1,53 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
matrix:
# current versions of hhvm do fail one test... see https://github.com/facebook/hhvm/issues/4837
allow_failures:
- php: hhvm
before_install:
# This is mandatory or the 'apt-get install' calls following will fail
- sudo apt-get update -qq
- sudo apt-get install -y apache2 libapache2-mod-fastcgi
- sudo apt-get install -y privoxy
install:
- composer self-update && composer install
before_script:
# Disable xdebug for speed.
# NB: this should NOT be done for hhvm and php 7.0.
# Also we use the php 5.6 run to generate code coverage reports, and we need xdebug for that
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" -a "$TRAVIS_PHP_VERSION" != "7.0" -a "$TRAVIS_PHP_VERSION" != "5.6" ]; then phpenv config-rm xdebug.ini; fi
# Set up Apache and Privoxy instances inside the Travis VM and use them for testing against
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ]; then ./tests/ci/travis/setup_php_fpm.sh; ./tests/ci/travis/setup_apache.sh; fi
- if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then ./tests/ci/travis/setup_hhvm.sh; ./tests/ci/travis/setup_apache_hhvm.sh; fi
- ./tests/ci/travis/setup_privoxy.sh
script:
# Travis currently compiles PHP with an oldish cURL/GnuTLS combination;
# to make the tests pass when Apache has a bogus SSL cert whe need the full set of options below
vendor/bin/phpunit --coverage-clover=coverage.clover tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 DEBUG=1
after_failure:
# Save as much info as we can to help developers
- cat apache_error.log
- cat apache_access.log
#- cat /var/log/hhvm/error.log
#- if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then php -i; fi
after_script:
# Upload code-coverage to Scrutinizer
- if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi
- if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi
# Upload code-coverage CodeClimate
- if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then CODECLIMATE_REPO_TOKEN=7fa6ee01e345090e059e5e42f3bfbcc8692feb8340396382dd76390a3019ac13 ./vendor/bin/test-reporter --coverage-report=coverage.clover; fi

1623
lib/phpxmlrpc/ChangeLog Normal file

File diff suppressed because it is too large Load Diff

88
lib/phpxmlrpc/INSTALL.md Normal file
View File

@@ -0,0 +1,88 @@
XMLRPC for PHP
==============
Requirements
------------
The following requirements should be met prior to using 'XMLRPC for PHP':
* PHP 5.3.0 or later
* the php "curl" extension is needed if you wish to use SSL or HTTP 1.1 to
communicate with remote servers
The php "xmlrpc" native extension is not required, but if it is installed,
there will be no interference with the operation of this library.
Installation instructions
-------------------------
Installation of the library is quite easy:
1. Via Composer (highly recommended):
1. Install composer if you don't have it already present on your system.
Depending on how you install, you may end up with a composer.phar file in your directory.
In that case, no worries! Just substitute 'php composer.phar' for 'composer' in the commands below.
2. If you're creating a new project, create a new empty directory for it.
3. Open a terminal and use Composer to grab the library.
$ composer require phpxmlrpc/phpxmlrpc:4.0
4. Write your code.
Once Composer has downloaded the component(s), all you need to do is include the vendor/autoload.php file that
was generated by Composer. This file takes care of autoloading all of the libraries so that you can use them
immediately, including phpxmlrpc:
// File example: src/script.php
// update this to the path to the "vendor/" directory, relative to this file
require_once __DIR__.'/../vendor/autoload.php';
use PhpXmlRpc\Value;
use PhpXmlRpc\Request;
use PhpXmlRpc\Client;
$client = new Client('http://some/server');
$response = $client->send(new Request('method', array(new Value('parameter'))));
5. IMPORTANT! Make sure that the vendor/phpxmlrpc directory is not directly accessible from the internet,
as leaving it open to access means that any visitor can trigger execution of php code such as
the built-in debugger.
2. Via manual download and autoload configuration
1. copy the contents of the src/ folder to any location required by your
application (it can be inside the web server root or not).
2. configure your app autoloading mechanism so that all classes in the PhpXmlRpc namespace are loaded
from that location: any PSR-4 compliant autoloader can do that, if you don't have any there is one
available in src/Autoloader.php
3. Write your code.
// File example: script.php
require_once __DIR__.'my_autoloader.php';
use PhpXmlRpc\Value;
use PhpXmlRpc\Request;
use PhpXmlRpc\Client;
$client = new Client('http://some/server');
$response = $client->send(new Request('method', array(new Value('parameter'))));
5. IMPORTANT! Make sure that the vendor/phpxmlrpc directory is not directly accessible from the internet,
as leaving it open to access means that any visitor can trigger execution of php code such as
the built-in debugger.
Tips
----
Please note that usage of the 'pake' command is not required for installation of the library.
At this moment it is only useful to build the html and pdf versions of the documentation, and the tarballs
for distribution of the library.

629
lib/phpxmlrpc/NEWS Normal file
View File

@@ -0,0 +1,629 @@
XML-RPC for PHP version 4.1.0 - 2016/6/26
* improved: Added support for receiving <I8> and <EX:I8> integers, sending <I8>
If php is compiled in 32 bit mode, and an i8 int is received from a 3rd party, and error will be emitted.
Integers sent from the library to 3rd parties can be encoded using the i8 tag, but default to using 'int' by default;
the developer will have to create values as i8 explicitly if needed.
The library does *not* check if an outgoing integer is too big to fit in 4 bytes and convert it to an i8 automatically.
XML-RPC for PHP version 4.0.1 - 2016/3/27
* improved: all of the API documentation has been moved out of the manual and into the source code phpdoc comments
* fixed: when the internal character set is set to UTF-8 and the client sends requests (or the server responses), too
many characters were encoded as numeric entities, whereas some, like åäö, needed not not be
* fixed: the 'valtyp' property of Response was not present in all cases; the ValType property had been added by error
and has been removed
XML-RPC for PHP version 4.0.0 - 2016/1/20
This release does away with the past and starts a transition to modern-world php.
Code has been heavily refactored, taking care to preserve backwards compatibility as much as possible,
but some breackage is to be expected.
The minimum required php version has been increased to 5.3, even though we strongly urge you to use
more recent versions.
PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade.
* new: introduction of namespaces and full OOP.
All php classes have been renamed and moved to separate files.
Class autoloading can now be done in accord with the PSR-4 standard.
All global variables and global functions have been removed.
Iterating over xmlrpc value objects is now easier thank to support for ArrayAccess and Traversable interfaces.
Backward compatibility is maintained via lib/xmlrpc.inc, lib/xmlrpcs.inc and lib/xmlrpc_wrappers.inc.
For more details, head on to doc/api_changes_v4.md
* changed: the default character encoding delivered from the library to your code is now utf8.
It can be changed at any time setting a value to PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding
* improved: the library now accepts requests/responses sent using other character sets than UTF-8/ISO-8859-1/ASCII.
This only works when the mbstring php extension is enabled.
* improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https
with recent curl builds
* improved: the xmlrpcval class now supports the interfaces Countable and IteratorAggregate
* improved: a specific option allows users to decide the version of SSL to use for https calls.
This is useful f.e. for the testing suite, when the server target of calls has no proper ssl certificate,
and the cURL extension has been compiled with GnuTLS (such as on Travis VMs)
* improved: the function wrap_php_function() now can be used to wrap closures (it is now a method btw)
* improved: all wrap_something() functions now return a closure by default instead of a function name
* improved: debug messages are not html-escaped any more when executing from the command line
* improved: the library is now tested using Travis ( https://travis-ci.org/ ).
Tests are executed using all php versions from 5.3 to 7.0 nightly, plus HHVM; code-coverage information
is generated using php 5.6 and uploaded to both Code Coverage and Scrutinizer online services
* improved: phpunit is now installed via composer, not bundled anymore
* improved: when phpunit is used to generate code-coverage data, the code executed server-side is accounted for
* improved: the test suite has basic checks for the debugger and demo files
* improved: more tests in the test suite
* fixed: the server would not reset the user-set debug messages between subsequent service() calls
* fixed: the server would not reset previous php error handlers when an exception was thrown by user code and
exception_handling set to 2
* fixed: the server would fail to decode a request with ISO-8859-1 payload and character set declaration in the xml
prolog only
* fixed: the client would fail to decode a response with ISO-8859-1 payload and character set declaration in the xml
prolog only
* fixed: the function decode_xml() would not decode an xml with character set declaration in the xml prolog
* fixed: the client can now successfully call methods using ISO-8859-1 or UTF-8 characters in their name
* fixed: the debugger would fail sending a request with ISO-8859-1 payload (it missed the character set declaration).
It would have a hard time coping with ISO-8859-1 in other fields, such as e.g. the remote method name
* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for signatures containing NULL
or undefined parameters
* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for methods with multiple
signatures
* improved: the debugger is displayed using UTF-8, making it more useful to debug any kind of service
* improved: echo all debug messages even when there are characters in them which php deems to be in a wrong encoding;
previously those messages would just disappear (this is visible e.g. in the debugger)
* changed: debug info handling
- at debug level 1, the rebuilt php objects are not dumped to screen (server-side already did that)
- at debug level 1, curl communication info are not dumped to screen
- at debug level 1, the tests echo payloads of failures; at debug level 2 all payloads
* improved: makefiles have been replaced with a php_based pakefile
* improved: the source for the manual is stored in asciidoc format, which can be displayed natively by GitHub
with nice html formatting. Also the HTML version generated by hand and bundled in tarballs is much nicer
to look at than previous versions
* improved: all php code is now formatted according to the PSR-2 standard
XML-RPC for PHP version 3.0.0 - 2014/6/15
This release corrects all bugs that have been reported and successfully reproduced since
version 3.0.0 beta.
The requirements have increased to php 5.1.0 - which is still way older than what you should be running for any serious
purpose, really.
It also is the first release to be installable via composer.
See the Changelog file or the pdf docs for a complete list of changes.
XML-RPC for PHP version 3.0.0 beta - 2009/09/05
This is the first release of the library to only support PHP 5.
Some legacy code has been removed, and support for features such as exceptions
and dateTime objects introduced.
The "beta" tag is meant to indicate the fact that the refactoring has been more widespread
than in precedent releases and that more changes are likely to be introduced with time -
the library is still considered to be production quality.
* improved: removed all usage of php functions deprecated in php 5.3, usage of assign-by-ref when creating new objects
etc...
* improved: add support for the <ex:nil/> tag used by the apache library, both in input and output
* improved: add support for dateTime objects in both in php_xmlrpc_encode and as parameter for constructor of xmlrpcval
* improved: add support for timestamps as parameter for constructor of xmlrpcval
* improved: add option 'dates_as_objects' to php_xmlrpc_decode to return dateTime objects for xmlrpc datetimes
* improved: add new method SetCurlOptions to xmrlpc_client to allow extra flexibility in tweaking http config, such as
explicitly binding to an ip address
* improved: add new method SetUserAgent to xmrlpc_client to to allow having different user-agent http headers
* improved: add a new member variable in server class to allow fine-tuning of the encoding of returned values when the
server is in 'phpvals' mode
* improved: allow servers in 'xmlrpcvals' mode to also register plain php functions by defining them in the dispatch map
with an added option
* improved: catch exceptions thrown during execution of php functions exposed as methods by the server
* fixed: bad encoding if same object is encoded twice using php_xmlrpc_encode
XML-RPC for PHP version 2.2.2 - 2009/03/16
This release corrects all bugs that have been reported and sucesfully reproduced since
version 2.2.1.
Regardless of the intimidating message about dropping PHP 4 support, it still does
support that ancient, broken and insecure platform.
* fixed: php warning when receiving 'false' in a bool value
* fixed: improve robustness of the debugger when parsing weird results from non-compliant servers
* fixed: format floating point values using the correct decimal separator even when php locale is set to one that uses
comma
* fixed: use feof() to test if socket connections are to be closed instead of the number of bytes read (rare bug when
communicating with some servers)
* fixed: be more tolerant in detection of charset in http headers
* fixed: fix encoding of UTF8 chars outside of the BMP plane
* fixed: fix detection of zlib.output_compression
* improved: allow the add_to_map server method to add docs for single params too
* improved: added the possibility to wrap for exposure as xmlrpc methods plain php class methods, object methods and
even whole classes
XML-RPC for PHP version 2.2.1 - 2008/03/06
This release corrects all bugs that have been reported and sucesfully reproduced.
It is the last release of the library that will support PHP 4.
* fixed: work around bug in php 5.2.2 which broke support of HTTP_RAW_POST_DATA
* fixed: is_dir parameter of setCaCertificate() method is reversed
* fixed: a php warning in xmlrpc_client creator method
* fixed: parsing of '1e+1' as valid float
* fixed: allow errorlevel 3 to work when prev. error handler was a static method
* fixed: usage of client::setcookie() for multiple cookies in non-ssl mode
* improved: support for CP1252 charset is not part or the library but almost possible
* improved: more info when curl is enabled and debug mode is on
XML-RPC for PHP version 2.2 - 2007/02/25
This release corrects a couple of bugs and adds a few minor features.
* fixed: debugger errors on php installs with magic_quotes_gpc on
* fixed: support for https connections via proxy
* fixed: wrap_xmlrpc_method() generated code failed to properly encode php objects
* improved: slightly faster encoding of data which is internally UTF-8
* improved: debugger always generates a 'null' id for jsonrpc if user omits it
* new: debugger can take advantage of a graphical value builder
(it has to be downloaded separately, as part of jsxmlrpc package)
* new: support for the <NIL/> xmlrpc extension
* new: server support for the system.getCapabilities xmlrpc extension
* new: wrap_xmlrpc_method() accepts two new options: debug and return_on_fault
XML-RPC for PHP version 2.1 - 2006/08/28
This release corrects quite a few bugs and adds some interesting new features.
There is a minor security enhancement and overall speedup too.
It has been tested with PHP 4.0.5 up to 4.4.4 and 5.1.5.
Please note that 404pl1 is NOT supported, and has not been since 2.0.
*** PLEASE READ CAREFULLY BELOW ***
CHANGES THAT MIGHT AFFECT DEPLOYED APPLICATIONS:
The wrap_php_function and wrap_xmlrpc_method functions have been moved out of
the base library file xmlrpc.inc into a file of their own: xmlrpc_wrappers.inc.
You will have to include() / require() it in your scripts if you have been using
those functions.
For increased security, the automatic rebuilding of php object instances out of
received xmlrpc structs in wrap_xmlrpc_method() has been disabled (but it can be
optionally reenabled).
The constructor of xmlrpcval() values has seen major changes, and it will not
throw a php warning anymore when invoked using an unknown xmlrpc type: the
error will only be written to php error log. Also new xmlrpcval('true', 'boolean')
is not supported anymore.
MAJOR IMPROVEMENTS:
The new function php_xmlrpc_decode_xml() will take the xml representation of
either an xmlrpc request, response or single value and return the corresponding
php-xmlrpc object instance.
Both wrap_php_function() and wrap_xmlrpc_method() functions accept many more
options to fine tune their behaviour, including one to return the php code to
be saved and later used as standalone php script.
A new function wrap_xmlrpc_server() has been added, to wrap all (or some) of the
methods exposed by a remote xmlrpc server into a php class.
Lib internals have been modified to provide better support for grafting extra
functionality on top of it. Stay tuned for future releases of the EXTRAS package.
Last but not least a new file has been added: verify_compat.php, to help users
diagnose the level of compliance of the current php install with the library.
CHANGELOG IN DETAIL:
* fixed bug 1311927: client not playing nice with some proxy/firewall on ports != 80
* fixed bug 1334340: all ereg_ functions have been replaced with corresponding preg_
* fixed bug: wrong handling of 'deflate' http encoding, both server and client side
* fixed bug: sending compressed responses when php output compression is enabled was not working
* fixed bug: addarray() and addstruct() where not returning 1 when adding data to already initialized values
* fixed bug: non-ascii chars used in struct element names where not being encoded correctly
* restored compatibility with php 4.0.5 (for those poor souls still stuck on it)
* server->service() now returns either the payload or xmlrpcresp instance
* server->add_to_map() now accepts methods with no param definitions
* added new function: php_xmlrpc_decode_xml()
* added new function: wrap_xmlrpc_server()
* major improvements and security enhancements to wrap_php_function() and wrap_xmlrpc_method()
* documentation for single parameters of exposed methods can be added to the dispatch map
(and turned into html docs in conjunction with a future release of the extras package)
* full response payload is saved into xmlrpcresp object for further debugging
* stricter parsing of incoming xmlrpc messages: two more invalid cases are now detected
(double data element inside array and struct/array after scalar inside value element)
* debugger can now generate code that wraps a remote method into php function (works for jsonrpc, too)
* debugger has better support for being activated via a single GET call (for integration into other tools?)
* more logging of errors in a lot of situations
* javadoc documentation of lib files almost complete
* the usual amount of new testcases in the testsuite
* many performance tweaks and code cleanups
* added foundation for emulating the API of the xmlrpc extension (extras package needed)
XML-RPC for PHP version 2.0 - 2006/04/24
I'm pleased to announce XML-RPC for PHP version 2.0, final.
With respect to the last release candidate, this release corrects a few small
bugs and adds a couple of new features: more authentication options (digest and
ntlm for servers, ntlm for proxies, and some https custom certificates stuff);
all the examples have been reviewed and some demo files added,
including a ready-made xmlrpc proxy (useful e.g. for ajax calls, when the xmlrpc
client is a browser); the server logs more warning messages for incorrect situations;
both client and server are more tolerant of commonly-found mistakes.
The debugger has been upgraded to reflect the new client capabilities.
In greater detail:
* fixed bug: method xmlrpcval::structmemexists($value) would not work
* fixed bug: wrap_xmlrpc_method would fail if invoked with a client object that
has return_type=phpvals
* fixed bug: in case of call to client::multicall without fallback and server error
* fixed bug: recursive serialization of xmlrpcvals loosing specified UTF8 charset
* fixed bug: serializing to ISO-8859-1 with php 5 would raise an error if non-ascii
chars where found when decoding
* new: client can use NTLM and Digest authentication methods for https and http 1.1
connections; authentication to proxy can be set to NTLM, too
* new: server tolerates user functions returning a single xmlrpcval object instead
of an xmlrpcresp
* new: server does more checks for presence and correct return type of user
coded method handling functions, and logs inconsistencies to php error log
* new: client method SetCaCertificate($cert, $is_dir) to validate server against
* new: both server and client tolerate receiving 'true' and 'false' for bool values
(which btw are not valid according to the xmlrpc spec)
XML-RPC for PHP version 2.0RC3 - 2006/01/22
This release corrects a few bugs and adds some interesting new features.
It has been tested with PHP up to 4.4.2 and 5.1.2.
* fixed bug: server not recognizing clients that declare support for http compression
* fixed bug: serialization of new xmlrpcval (8, 'string') when internal encoding
set to UTF-8
* fixed bug: serialization of new xmlrpcval ('hello', 'int') would produce
invalid xml-rpc
* new: let the server accept 'class::method' syntax in the dispatch map
* new: php_xmlrpc_decode() can decode xmlrpcmessage objects
* new: both client and server can specify a charset to be used for serializing
values instead of the default 'US-ASCII+xml-entities-for-other-characters'.
Values allowed: ISO-8859-1 and UTF-8
* new: the server object can register 'plain' php functions instead of functions
that accept a single parameter of type xmlrpcmsg. Faster, uses less memory
(but comes with minor drawbacks as well, read the manual for more details)
* new: client::setDebug(2) can be used to have the request payload printed to
screen before being sent
* new: server::service($data) lets user parse data other than POST body, for
easier testing / subclassing
* changed: framework-generated debug messages are sent back by the server base64
encoded, to avoid any charset/xml compatibility problem
* other minor fixes
The usual refactoring of a lot of (private) methods has taken place, with new
parameters added to some functions.
Javadoc documentation has been improved a lot.
The HTML documentation has been shuffled around a bit, hoping to give it a more
logical organization.
The experimental support for the JSON protocol has been removed, and will be
packaged as a separate download with some extra very interesting stuff (human
readable auto-generated documentation, anyone?).
XML-RPC for PHP version 2.0RC2 - 2005/11/22
This release corrects a few bugs and adds basically one new method for better
HTTPS support:
* fixed two bugs that prevented xmlrpc calls to take place over https
* fixed two bugs that prevented proper recognition of xml character set
when it was declared inside the xml prologue
* added xmlrpc_client::setKey($key, $keypass) method, to allow using client
side certificates for https connections
* fixed bug that prevented proper serialization of string xmlrpcvals when
$xmlrpc_internalencoding was set to UTF-8
* fixed bug in xmlrpc_server::echoInput() (and marked method as deprecated)
* correctly set cookies/http headers into xmlrpcresp objects even when the
send() method call fails for some reason
* added a benchmark file in the testsuite directory
A couple of (private/protected) methods have been refactored, as well as a
couple of extra parameters added to some (private) functions - this has no
impact on the public API and should be of interest primarily to people extending
/ subclassing the lib.
There is also new, PARTIAL support for the JSON-RPC protocol, implemented in
two files in the extras dir (more info about json-rpc at http://json-rpc.org)
XML-RPC for PHP version 2.0RC1 - 2005/10/03
I'm pleased to announce XML-RPC for PHP version 2.0, release candidate 1.
This release introduces so many new features it is almost impossible to list them
here, making the library finally on pair with, if not more advanced than, any other
similar offer (e.g. the PEAR XMLRPC package or the Incutio IXR library).
No, really, trust me.
The minimum supported PHP version is now 4.2 - natively - or 4.0.4pl1 - by usage of
a couple of compatibility classes (code taken from PEAR php_compat package).
The placement of files and directories in the distribution has been deeply modified,
in the hope of making it more clear, now that the file count has increased.
I hope you find it easy.
Support for "advanced" HTTP features such as cookies, proxies and keep-alives has
been added at last.
It is now much easier to convert between xmlrpcval objects and php values, and
in fact php_xmlrpc_encode and php_xmlrpc_decode are now the recommended methods
for all cases, except when encoding base64 data.
Two new (experimental) functions have been added, allowing automagic conversion
of a php function into an xmlrpc method to be exposed and vice-versa.
PHP objects can be now automatically serialized as xmlrpc struct values and
correctly deserialized on the other end of the transmission, provided that the
same class definition is present on both sides and no object members are of
type resource.
A lot of the existing class methods have been overloaded with extra parameters
or new functionality, and a few added ex-novo, making usage easier than ever.
A complete debugger solution is included in the distribution. It needs a web server
to run (a freely available version of the same debugger is accessible online, it
can be found at http://phpxmlrpc.sourceforge.net).
For a more detailed list of changes, please read carefully chapter 2 of the
included documentation, or, even better, take a look at the source code, which
is commented in javadoc style quite a bit.
XML-RPC for PHP version 1.2 - 2005/08/14
This removes all use of eval(), which is a potential security problem.
All users are encouraged to upgrade as soon as possible.
As of this release we are no longer php3-compatible.
XML-RPC for PHP version 1.1.1 - 2005/06/30
This is a security vulnerability fix release.
All users are invited to upgrade as soon as possible.
XML-RPC for PHP version 1.1 - 2005/05/03
I'm pleased to announce XML-RPC for PHP version 1.1
It's taken two years to get to the this point, but here we are, finally.
This is a bugfix and maintenance release. No major new features have been added.
All known bugs have been ironed out, unless fixing would have meant breaking
the API.
The code has been tested with PHP 3, 4 and 5, even tough PHP 4 is the main
development platform (and some warnings will be emitted when running PHP5).
Noteworthy changes include:
* do not clash any more with the EPI xmlrpc extension bundled with PHP 4 and 5
* fixed the unicode/charset problems that have been plaguing the lib for years
* proper parsing of int and float values prepended with zeroes or the '+' char
* accept float values in exponential notation
* configurable http user-agent string
* use the same timeout on client socket reads as used for connecting
* more explicative error messages in xmlrpcresponse in many cases
* much more tolerant parsing of malformed http responses from xmlrpc servers
* fixed memleak that prevented the client to be used in never-ending scripts
* parse bigger xmlrpc messages without crashing (1MB in size or more)
* be tolerant to xmlrpc responses generated on public servers that add
javascript advertising at the end of hosted content
* the lib generates quite a few less PHP warnings during standard operation
This is the last release that will support PHP 3.
The next release will include better support for PHP 5 and (possibly) a slew of
new features.
The changelog is available at:
http://cvs.sourceforge.net/viewcvs.py/phpxmlrpc/xmlrpc/ChangeLog?view=markup
Please report bugs to the XML-RPC PHP mailing list or to the sourceforge project
pages at http://sourceforge.net/projects/phpxmlrpc/
XML-RPC for PHP version 1.0
I'm pleased to announce XML-RPC for PHP version 1.0 (final). It's taken
two years to get to the 1.0 point, but here we are, finally. The major change
is re-licensing with the BSD open source license, a move from the custom
license previously used.
After this release I expect to move the project to SourceForge and find
another primary maintainer for the code. More details will follow to the
mailing list.
It can be downloaded from http://xmlrpc.usefulinc.com/php.html
Comprehensive documentation is available in the distribution, but you
can also browse it at http://xmlrpc.usefulinc.com/doc/
Bugfixes in this release include:
* Small fixes and tidying up.
New features include:
* experimental support for SSL via the curl extensions to PHP. Needs
PHP 4.0.2 or greater, but not PHP 4.0.6 which has broken SSL support.
The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
Please report bugs to the XML-RPC PHP mailing list, of which more details are
available at http://xmlrpc.usefulinc.com/list.html, or to
<xmlrpc@usefulinc.com>.
XML-RPC for PHP version 1.0 beta 9
I'm pleased to announce XML-RPC for PHP version 1.0 beta 9. This is
is largely a bugfix release.
It can be downloaded from http://xmlrpc.usefulinc.com/php.html
Comprehensive documentation is available in the distribution, but you
can also browse it at http://xmlrpc.usefulinc.com/doc/
Bugfixes in this release include:
* Fixed string handling bug where characters between a </string>
and </value> tag were not ignored.
* Added in support for PHP's native boolean type.
New features include:
* new getval() method (experimental only) which has support for
recreating nested arrays.
* fledgling unit test suite
* server.php has support for basic interop test suite
The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
Please test this as hard as possible and report bugs to the XML-RPC PHP
mailing list, of which more details are available at
http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
XML-RPC for PHP version 1.0 beta 8
I'm pleased to announce XML-RPC for PHP version 1.0 beta 8.
This release fixes several bugs and adds a couple of new helper
functions. The most critical change in this release is that you can no
longer print debug info in comments inside a server method -- you must
now use the new xmlrpc_debugmsg() function.
It can be downloaded from http://xmlrpc.usefulinc.com/php.html
Comprehensive documentation is available in the distribution, but you
can also browse it at http://xmlrpc.usefulinc.com/doc/
Bugfixes in this release include:
* fixed whitespace handling in values
* correct sending of Content-length from the server
New features include:
* xmlrpc_debugmsg() method allows sending of debug info in comments in
the return payload from a server
* xmlrpc_encode() and xmlrpc_decode() translate between xmlrpcval
objects and PHP language arrays. They aren't suitable for all
datatypes, but can speed up coding in simple scenarios. Thanks to Dan
Libby for these.
The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
Please test this as hard as possible and report bugs to the XML-RPC PHP
mailing list, of which more details are available at
http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
XML-RPC for PHP version 1.0 beta 7
I'm pleased to announce XML-RPC for PHP version 1.0 beta 7. This is
fixes some critical bugs that crept in. If it shows itself to be stable
then it'll become the 1.0 release.
It can be downloaded from http://xmlrpc.usefulinc.com/php.html
Comprehensive documentation is available in the distribution, but you
can also browse it at http://xmlrpc.usefulinc.com/doc/
Bugfixes in this release include:
* Passing of booleans should now work as expected
* Dollar signs and backslashes in strings should pass OK
* addScalar() now works properly to append to array vals
New features include:
* Added support for HTTP Basic authorization through the
xmlrpc_client::setCredentials method.
* Added test script and method for verifying correct passing of
booleans
The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
Please test this as hard as possible and report bugs to the XML-RPC PHP
mailing list, of which more details are available at
http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
XML-RPC for PHP version 1.0 beta 6
I'm pleased to announce XML-RPC for PHP version 1.0 beta 6. This is the
final beta before the 1.0 release.
It can be downloaded from http://xmlrpc.usefulinc.com/php.html
Comprehensive documentation is available in the distribution, but you
can also browse it at http://xmlrpc.usefulinc.com/doc/
New features in this release include:
* Perl and Python test programs for the demo server
* Proper fault generation on a non-"200 OK" response from a remote host
* Bugfixed base64 decoding
* ISO8601 helper routines for translation to and from UNIX timestamps
* reorganization of code to allow eventual integration of alternative
transports
The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
Please test this as hard as possible and report bugs to the XML-RPC PHP
mailing list, of which more details are available at
http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.

48
lib/phpxmlrpc/README.md Normal file
View File

@@ -0,0 +1,48 @@
XMLRPC for PHP
==============
A php library for building xml-rpc clients and servers.
Installation
------------
The recommended way to install this library is using Composer.
Detailed installation instructions are in the [INSTALL.md](INSTALL.md) file, along with system requirements listing.
Documentation
-------------
*NB: the user manual has not been updated yet with all the changes made in version 4. Please consider it unreliable!*
*You are encouraged to look instead the code examples found in the demo/ directory*
The user manual can be found in the doc/manual directory, in Asciidoc format: [phpxmlrpc_manual.adoc](doc/manual/phpxmlrpc_manual.adoc)
Release tarballs also contain the HTML and PDF versions, as well as an automatically generated API documentation.
Upgrading
---------
If you are upgrading from version 3 or earlier you have two options:
1. adapt your code to the new API (all changes needed are described in [doc/api_changes_v4.md](doc/api_changes_v4.md))
2. use instead the *compatibility layer* which is provided. Instructions and pitfalls described in [doc/api_changes_v4.md](doc/api_changes_v4.md##enabling-compatibility-with-legacy-code)
In any case, read carefully the docs in [doc/api_changes_v4.md](doc/api_changes_v4.md) and report back any undocumented
issue using GitHub.
License
-------
Use of this software is subject to the terms in the [license.txt](license.txt) file
SSL-certificate
---------------
The passphrase for the rsakey.pem certificate is 'test'.
[![License](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/license)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
[![Latest Stable Version](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/v/stable)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
[![Total Downloads](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/downloads)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
[![Build Status](https://travis-ci.org/gggeek/phpxmlrpc.svg?branch=php53)](https://travis-ci.org/gggeek/phpxmlrpc)
[![Test Coverage](https://codeclimate.com/github/gggeek/phpxmlrpc/badges/coverage.svg)](https://codeclimate.com/github/gggeek/phpxmlrpc)
[![Code Coverage](https://scrutinizer-ci.com/g/gggeek/phpxmlrpc/badges/coverage.png?b=php53)](https://scrutinizer-ci.com/g/gggeek/phpxmlrpc/?branch=php53)

View File

@@ -0,0 +1,45 @@
{
"name": "phpxmlrpc/phpxmlrpc",
"description": "A php library for building xmlrpc clients and servers",
"license": "BSD-3-Clause",
"homepage": "http://gggeek.github.io/phpxmlrpc/",
"keywords": [ "xmlrpc", "webservices" ],
"require": {
"php": ">=5.3.0",
"ext-xml": "*"
},
"require-dev": {
"phpunit/phpunit": ">=4.0.0",
"phpunit/phpunit-selenium": "*",
"codeclimate/php-test-reporter": "dev-master",
"ext-curl": "*",
"ext-mbstring": "*",
"indeyets/pake": "~1.99",
"sami/sami": "~3.1",
"docbook/docbook-xsl": "~1.78"
},
"suggest": {
"ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...",
"ext-zlib": "Needed for sending compressed requests and receiving compressed responses, if cURL is not available",
"ext-mbstring": "Needed to allow reception of requests/responses in character sets other than ASCII,LATIN-1,UTF-8"
},
"autoload": {
"psr-4": {"PhpXmlRpc\\": "src/"}
},
"config": {
"secure-http": false
},
"repositories": [
{
"type": "package",
"package": {
"name": "docbook/docbook-xsl",
"version": "1.78.1",
"dist": {
"url": "https://sourceforge.net/projects/docbook/files/docbook-xsl/1.78.1/docbook-xsl-1.78.1.zip/download",
"type": "zip"
}
}
}
]
}

View File

@@ -0,0 +1,565 @@
<?php
/**
* @author Gaetano Giunta
* @copyright (C) 2005-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*
* @todo switch params for http compression from 0,1,2 to values to be used directly
* @todo use ob_start to catch debug info and echo it AFTER method call results?
* @todo be smarter in creating client stub for proxy/auth cases: only set appropriate property of client obj
**/
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XMLRPC Debugger</title>
<meta name="robots" content="index,nofollow"/>
<style type="text/css">
<!--
body {
border-top: 1px solid gray;
padding: 1em;
font-family: Verdana, Arial, Helvetica;
font-size: 8pt;
}
h3 {
font-size: 9.5pt;
}
h2 {
font-size: 12pt;
}
.dbginfo {
padding: 1em;
background-color: #EEEEEE;
border: 1px dashed silver;
font-family: monospace;
}
#response {
padding: 1em;
margin-top: 1em;
background-color: #DDDDDD;
border: 1px solid gray;
white-space: pre;
font-family: monospace;
}
table {
padding: 2px;
margin-top: 1em;
}
th {
background-color: navy;
color: white;
padding: 0.5em;
}
td {
padding: 0.5em;
font-family: monospace;
}
td form {
margin: 0;
}
.oddrow {
background-color: #EEEEEE;
}
.evidence {
color: blue;
}
#phpcode {
background-color: #EEEEEE;
padding: 1em;
margin-top: 1em;
}
-->
</style>
</head>
<body>
<?php
include __DIR__ . '/common.php';
if ($action) {
include_once __DIR__ . "/../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
// make sure the script waits long enough for the call to complete...
if ($timeout) {
set_time_limit($timeout + 10);
}
if ($wstype == 1) {
@include 'jsonrpc.inc';
if (!class_exists('jsonrpc_client')) {
die('Error: to debug the jsonrpc protocol the jsonrpc.inc file is needed');
}
$clientClass = 'PhpJsRpc\Client';
$requestClass = 'PhpJsRpc\Request';
$protoName = 'JSONRPC';
} else {
$clientClass = 'PhpXmlRpc\Client';
$requestClass = 'PhpXmlRpc\Request';
$protoName = 'XMLRPC';
}
if ($port != "") {
$client = new $clientClass($path, $host, $port);
$server = "$host:$port$path";
} else {
$client = new $clientClass($path, $host);
$server = "$host$path";
}
if ($protocol == 2) {
$server = 'https://' . $server;
} else {
$server = 'http://' . $server;
}
if ($proxy != '') {
$pproxy = explode(':', $proxy);
if (count($pproxy) > 1) {
$pport = $pproxy[1];
} else {
$pport = 8080;
}
$client->setProxy($pproxy[0], $pport, $proxyuser, $proxypwd);
}
if ($protocol == 2) {
$client->setSSLVerifyPeer($verifypeer);
$client->setSSLVerifyHost($verifyhost);
if ($cainfo) {
$client->setCaCertificate($cainfo);
}
$httpprotocol = 'https';
} elseif ($protocol == 1) {
$httpprotocol = 'http11';
} else {
$httpprotocol = 'http';
}
if ($username) {
$client->setCredentials($username, $password, $authtype);
}
$client->setDebug($debug);
switch ($requestcompression) {
case 0:
$client->request_compression = '';
break;
case 1:
$client->request_compression = 'gzip';
break;
case 2:
$client->request_compression = 'deflate';
break;
}
switch ($responsecompression) {
case 0:
$client->accepted_compression = '';
break;
case 1:
$client->accepted_compression = array('gzip');
break;
case 2:
$client->accepted_compression = array('deflate');
break;
case 3:
$client->accepted_compression = array('gzip', 'deflate');
break;
}
$cookies = explode(',', $clientcookies);
foreach ($cookies as $cookie) {
if (strpos($cookie, '=')) {
$cookie = explode('=', $cookie);
$client->setCookie(trim($cookie[0]), trim(@$cookie[1]));
}
}
$msg = array();
switch ($action) {
// fall thru intentionally
case 'describe':
case 'wrap':
$msg[0] = new $requestClass('system.methodHelp', array(), $id);
$msg[0]->addparam(new PhpXmlRpc\Value($method));
$msg[1] = new $requestClass('system.methodSignature', array(), $id + 1);
$msg[1]->addparam(new PhpXmlRpc\Value($method));
$actionname = 'Description of method "' . $method . '"';
break;
case 'list':
$msg[0] = new $requestClass('system.listMethods', array(), $id);
$actionname = 'List of available methods';
break;
case 'execute':
if (!payload_is_safe($payload)) {
die("Tsk tsk tsk, please stop it or I will have to call in the cops!");
}
$msg[0] = new $requestClass($method, array(), $id);
// hack! build xml payload by hand
if ($wstype == 1) {
$msg[0]->payload = "{\n" .
'"method": "' . $method . "\",\n\"params\": [" .
$payload .
"\n],\n\"id\": ";
// fix: if user gave an empty string, use NULL, or we'll break json syntax
if ($id == "") {
$msg[0]->payload .= "null\n}";
} else {
if (is_numeric($id) || $id == 'false' || $id == 'true' || $id == 'null') {
$msg[0]->payload .= "$id\n}";
} else {
$msg[0]->payload .= "\"$id\"\n}";
}
}
} else {
$msg[0]->payload = $msg[0]->xml_header($inputcharset) .
'<methodName>' . $method . "</methodName>\n<params>" .
$payload .
"</params>\n" . $msg[0]->xml_footer();
}
$actionname = 'Execution of method ' . $method;
break;
default: // give a warning
$actionname = '[ERROR: unknown action] "' . $action . '"';
}
// Before calling execute, echo out brief description of action taken + date and time ???
// this gives good user feedback for long-running methods...
echo '<h2>' . htmlspecialchars($actionname, ENT_COMPAT, $inputcharset) . ' on server ' . htmlspecialchars($server, ENT_COMPAT, $inputcharset) . " ...</h2>\n";
flush();
$response = null;
// execute method(s)
if ($debug) {
echo '<div class="dbginfo"><h2>Debug info:</h2>';
} /// @todo use ob_start instead
$resp = array();
$time = microtime(true);
foreach ($msg as $message) {
// catch errors: for older xmlrpc libs, send does not return by ref
@$response = $client->send($message, $timeout, $httpprotocol);
$resp[] = $response;
if (!$response || $response->faultCode()) {
break;
}
}
$time = microtime(true) - $time;
if ($debug) {
echo "</div>\n";
}
if ($response) {
if ($response->faultCode()) {
// call failed! echo out error msg!
//echo '<h2>'.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'</h2>';
echo "<h3>$protoName call FAILED!</h3>\n";
echo "<p>Fault code: [" . htmlspecialchars($response->faultCode(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
"] Reason: '" . htmlspecialchars($response->faultString(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "'</p>\n";
echo(strftime("%d/%b/%Y:%H:%M:%S\n"));
} else {
// call succeeded: parse results
//echo '<h2>'.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'</h2>';
printf("<h3>%s call(s) OK (%.2f secs.)</h3>\n", $protoName, $time);
echo(strftime("%d/%b/%Y:%H:%M:%S\n"));
switch ($action) {
case 'list':
$v = $response->value();
if ($v->kindOf() == "array") {
$max = $v->count();
echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
echo "<thead>\n<tr><th>Method ($max)</th><th>Description</th></tr>\n</thead>\n<tbody>\n";
foreach($v as $i => $rec) {
if ($i % 2) {
$class = ' class="oddrow"';
} else {
$class = ' class="evenrow"';
}
echo("<tr><td$class>" . htmlspecialchars($rec->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "</td><td$class><form action=\"controller.php\" method=\"get\" target=\"frmcontroller\">" .
"<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
"<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
"<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
"<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
"<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
"<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
"<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
"<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($rec->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "\" />" .
"<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
"<input type=\"hidden\" name=\"action\" value=\"describe\" />" .
"<input type=\"hidden\" name=\"run\" value=\"now\" />" .
"<input type=\"submit\" value=\"Describe\" /></form></td>");
//echo("</tr>\n");
// generate the skeleton for method payload per possible tests
//$methodpayload="<methodCall>\n<methodName>".$rec->scalarval()."</methodName>\n<params>\n<param><value></value></param>\n</params>\n</methodCall>";
/*echo ("<form action=\"{$_SERVER['PHP_SELF']}\" method=\"get\"><td>".
"<input type=\"hidden\" name=\"host\" value=\"$host\" />".
"<input type=\"hidden\" name=\"port\" value=\"$port\" />".
"<input type=\"hidden\" name=\"path\" value=\"$path\" />".
"<input type=\"hidden\" name=\"method\" value=\"".$rec->scalarval()."\" />".
"<input type=\"hidden\" name=\"methodpayload\" value=\"$payload\" />".
"<input type=\"hidden\" name=\"action\" value=\"execute\" />".
"<input type=\"submit\" value=\"Test\" /></td></form>");*/
echo("</tr>\n");
}
echo "</tbody>\n</table>";
}
break;
case 'describe':
$r1 = $resp[0]->value();
$r2 = $resp[1]->value();
echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
echo "<thead>\n<tr><th>Method</th><th>" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "</th><th>&nbsp;</th><th>&nbsp;</th></tr>\n</thead>\n<tbody>\n";
$desc = htmlspecialchars($r1->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding);
if ($desc == "") {
$desc = "-";
}
echo "<tr><td class=\"evenrow\">Description</td><td colspan=\"3\" class=\"evenrow\">$desc</td></tr>\n";
if ($r2->kindOf() != "array") {
echo "<tr><td class=\"oddrow\">Signature</td><td class=\"oddrow\">Unknown</td><td class=\"oddrow\">&nbsp;</td></tr>\n";
} else {
foreach($r2 as $i => $x) {
$payload = "";
$alt_payload = "";
if ($i + 1 % 2) {
$class = ' class="oddrow"';
} else {
$class = ' class="evenrow"';
}
echo "<tr><td$class>Signature&nbsp;" . ($i + 1) . "</td><td$class>";
if ($x->kindOf() == "array") {
$ret = $x[0];
echo "<code>OUT:&nbsp;" . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "<br />IN: (";
if ($x->count() > 1) {
foreach($x as $k => $y) {
if ($k == 0) continue;
echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding);
if ($wstype != 1) {
$type = $y->scalarval();
$payload .= '<param><value>';
switch($type) {
case 'undefined':
break;
case 'null';
$type = 'nil';
// fall thru intentionally
default:
$payload .= '<' .
htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
'></' . htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
'>';
}
$payload .= "</value></param>\n";
}
$alt_payload .= $y->scalarval();
if ($k < $x->count() - 1) {
$alt_payload .= ';';
echo ", ";
}
}
}
echo ")</code>";
} else {
echo 'Unknown';
}
echo '</td>';
// button to test this method
//$payload="<methodCall>\n<methodName>$method</methodName>\n<params>\n$payload</params>\n</methodCall>";
echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">" .
"<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
"<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
"<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
"<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
"<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
"<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
"<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
"<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"methodpayload\" value=\"" . htmlspecialchars($payload, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"altmethodpayload\" value=\"" . htmlspecialchars($alt_payload, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
"<input type=\"hidden\" name=\"action\" value=\"execute\" />";
if ($wstype != 1) {
echo "<input type=\"submit\" value=\"Load method synopsis\" />";
}
echo "</form></td>\n";
echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">" .
"<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
"<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
"<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
"<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
"<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
"<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
"<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
"<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"methodsig\" value=\"" . $i . "\" />" .
"<input type=\"hidden\" name=\"methodpayload\" value=\"" . htmlspecialchars($payload, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"altmethodpayload\" value=\"" . htmlspecialchars($alt_payload, ENT_COMPAT, $inputcharset) . "\" />" .
"<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
"<input type=\"hidden\" name=\"run\" value=\"now\" />" .
"<input type=\"hidden\" name=\"action\" value=\"wrap\" />" .
"<input type=\"submit\" value=\"Generate method call stub code\" />";
echo "</form></td></tr>\n";
}
}
echo "</tbody>\n</table>";
break;
case 'wrap':
$r1 = $resp[0]->value();
$r2 = $resp[1]->value();
if ($r2->kindOf() != "array" || $r2->count() <= $methodsig) {
echo "Error: signature unknown\n";
} else {
$mdesc = $r1->scalarval();
$encoder = new PhpXmlRpc\Encoder();
$msig = $encoder->decode($r2);
$msig = $msig[$methodsig];
$proto = $protocol == 2 ? 'https' : $protocol == 1 ? 'http11' : '';
if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression &&
$clientcookies == ''
) {
$opts = 1; // simple client copy in stub code
} else {
$opts = 0; // complete client copy in stub code
}
if ($wstype == 1) {
$prefix = 'jsonrpc';
} else {
$prefix = 'xmlrpc';
}
$wrapper = new PhpXmlRpc\Wrapper();
$code = $wrapper->buildWrapMethodSource($client, $method, array('timeout' => $timeout, 'protocol' => $proto, 'simple_client_copy' => $opts, 'prefix' => $prefix), str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc);
//if ($code)
//{
echo "<div id=\"phpcode\">\n";
highlight_string("<?php\n" . $code['docstring'] . $code['source'] . '?>');
echo "\n</div>";
//}
//else
//{
// echo 'Error while building php code stub...';
}
break;
case 'execute':
echo '<div id="response"><h2>Response:</h2>' . htmlspecialchars($response->serialize()) . '</div>';
break;
default: // give a warning
}
} // if !$response->faultCode()
} // if $response
} else {
// no action taken yet: give some instructions on debugger usage
?>
<h3>Instructions on usage of the debugger</h3>
<ol>
<li>Run a 'list available methods' action against desired server</li>
<li>If list of methods appears, click on 'describe method' for desired method</li>
<li>To run method: click on 'load method synopsis' for desired method. This will load a skeleton for method call
parameters in the form above. Complete all xmlrpc values with appropriate data and click 'Execute'
</li>
</ol>
<?php
if (!extension_loaded('curl')) {
echo "<p class=\"evidence\">You will need to enable the CURL extension to use the HTTPS and HTTP 1.1 transports</p>\n";
}
?>
<h3>Example</h3>
<p>
Server Address: phpxmlrpc.sourceforge.net<br/>
Path: /server.php
</p>
<h3>Notice</h3>
<p>all usernames and passwords entered on the above form will be written to the web server logs of this server. Use
with care.</p>
<h3>Changelog</h3>
<ul>
<li>2015-05-30: fix problems with generating method payloads for NIL and Undefined parameters</li>
<li>2015-04-19: fix problems with LATIN-1 characters in payload</li>
<li>2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id</li>
<li>2006-06-26: support building php code stub for calling remote methods</li>
<li>2006-05-25: better support for long running queries; check for no-curl installs</li>
<li>2006-05-02: added support for JSON-RPC. Note that many interesting json-rpc features are not implemented
yet, such as notifications or multicall.
</li>
<li>2006-04-22: added option for setting custom CA certs to verify peer with in SSLmode</li>
<li>2006-03-05: added option for setting Basic/Digest/NTLM auth type</li>
<li>2006-01-18: added option echoing to screen xmlrpc request before sending it ('More' debug)</li>
<li>2005-10-01: added option for setting cookies to be sent to server</li>
<li>2005-08-07: added switches for compression of requests and responses and http 1.1</li>
<li>2005-06-27: fixed possible security breach in parsing malformed xml</li>
<li>2005-06-24: fixed error with calling methods having parameters...</li>
</ul>
<?php
}
?>
</body>
</html>

View File

@@ -0,0 +1,143 @@
<?php
/**
* @author Gaetano Giunta
* @copyright (C) 2005-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*
* Parses GET/POST variables
*
* @todo switch params for http compression from 0,1,2 to values to be used directly
* @todo do some more sanitization of received parameters
*/
// work around magic quotes
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_GET = array_map('stripslashes_deep', $_GET);
}
$preferredEncodings = 'UTF-8, ASCII, ISO-8859-1, UTF-7, EUC-JP, SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP';
$inputcharset = mb_detect_encoding(urldecode($_SERVER['REQUEST_URI']), $preferredEncodings);
if (isset($_GET['usepost']) && $_GET['usepost'] === 'true') {
$_GET = $_POST;
$inputcharset = mb_detect_encoding(implode('', $_GET), $preferredEncodings);
}
/// @todo if $inputcharset is not UTF8, we should probably re-encode $_GET to make it UTF-8
// recover input parameters
$debug = false;
$protocol = 0;
$run = false;
$wstype = 0;
$id = '';
if (isset($_GET['action'])) {
if (isset($_GET['wstype']) && $_GET['wstype'] == '1') {
$wstype = 1;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
}
$host = isset($_GET['host']) ? $_GET['host'] : 'localhost'; // using '' will trigger an xmlrpc error...
if (isset($_GET['protocol']) && ($_GET['protocol'] == '1' || $_GET['protocol'] == '2')) {
$protocol = $_GET['protocol'];
}
if (strpos($host, 'http://') === 0) {
$host = substr($host, 7);
} elseif (strpos($host, 'https://') === 0) {
$host = substr($host, 8);
$protocol = 2;
}
$port = isset($_GET['port']) ? $_GET['port'] : '';
$path = isset($_GET['path']) ? $_GET['path'] : '';
// in case user forgot initial '/' in xmlrpc server path, add it back
if ($path && ($path[0]) != '/') {
$path = '/' . $path;
}
if (isset($_GET['debug']) && ($_GET['debug'] == '1' || $_GET['debug'] == '2')) {
$debug = $_GET['debug'];
}
$verifyhost = (isset($_GET['verifyhost']) && ($_GET['verifyhost'] == '1' || $_GET['verifyhost'] == '2')) ? $_GET['verifyhost'] : 0;
if (isset($_GET['verifypeer']) && $_GET['verifypeer'] == '1') {
$verifypeer = true;
} else {
$verifypeer = false;
}
$cainfo = isset($_GET['cainfo']) ? $_GET['cainfo'] : '';
$proxy = isset($_GET['proxy']) ? $_GET['proxy'] : 0;
if (strpos($proxy, 'http://') === 0) {
$proxy = substr($proxy, 7);
}
$proxyuser = isset($_GET['proxyuser']) ? $_GET['proxyuser'] : '';
$proxypwd = isset($_GET['proxypwd']) ? $_GET['proxypwd'] : '';
$timeout = isset($_GET['timeout']) ? $_GET['timeout'] : 0;
if (!is_numeric($timeout)) {
$timeout = 0;
}
$action = $_GET['action'];
$method = isset($_GET['method']) ? $_GET['method'] : '';
$methodsig = isset($_GET['methodsig']) ? $_GET['methodsig'] : 0;
$payload = isset($_GET['methodpayload']) ? $_GET['methodpayload'] : '';
$alt_payload = isset($_GET['altmethodpayload']) ? $_GET['altmethodpayload'] : '';
if (isset($_GET['run']) && $_GET['run'] == 'now') {
$run = true;
}
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$authtype = (isset($_GET['authtype']) && ($_GET['authtype'] == '2' || $_GET['authtype'] == '8')) ? $_GET['authtype'] : 1;
if (isset($_GET['requestcompression']) && ($_GET['requestcompression'] == '1' || $_GET['requestcompression'] == '2')) {
$requestcompression = $_GET['requestcompression'];
} else {
$requestcompression = 0;
}
if (isset($_GET['responsecompression']) && ($_GET['responsecompression'] == '1' || $_GET['responsecompression'] == '2' || $_GET['responsecompression'] == '3')) {
$responsecompression = $_GET['responsecompression'];
} else {
$responsecompression = 0;
}
$clientcookies = isset($_GET['clientcookies']) ? $_GET['clientcookies'] : '';
} else {
$host = '';
$port = '';
$path = '';
$action = '';
$method = '';
$methodsig = 0;
$payload = '';
$alt_payload = '';
$username = '';
$password = '';
$authtype = 1;
$verifyhost = 0;
$verifypeer = false;
$cainfo = '';
$proxy = '';
$proxyuser = '';
$proxypwd = '';
$timeout = 0;
$requestcompression = 0;
$responsecompression = 0;
$clientcookies = '';
}
// check input for known XMLRPC attacks against this or other libs
function payload_is_safe($input)
{
return true;
}

View File

@@ -0,0 +1,357 @@
<?php
/**
* @author Gaetano Giunta
* @copyright (C) 2005-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*
* @todo add links to documentation from every option caption
* @todo switch params for http compression from 0,1,2 to values to be used directly
* @todo add a little bit more CSS formatting: we broke IE box model getting a width > 100%...
* @todo add support for more options, such as ntlm auth to proxy, or request charset encoding
* @todo parse content of payload textarea to be fed to visual editor
* @todo add http no-cache headers
**/
// make sure we set the correct charset type for output, so that we can display all characters
header('Content-Type: text/html; charset=utf-8');
include __DIR__ . '/common.php';
if ($action == '') {
$action = 'list';
}
// relative path to the visual xmlrpc editing dialog
$editorpath = '../../phpjsrpc/debugger/';
$editorlibs = '../../phpjsrpc/lib/';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XMLRPC Debugger</title>
<meta name="robots" content="index,nofollow"/>
<script type="text/javascript" language="Javascript">
if (window.name != 'frmcontroller')
top.location.replace('index.php?run=' + escape(self.location));
</script>
<!-- xmlrpc/jsonrpc base library -->
<script type="text/javascript" src="<?php echo $editorlibs; ?>xmlrpc_lib.js"></script>
<script type="text/javascript" src="<?php echo $editorlibs; ?>jsonrpc_lib.js"></script>
<style type="text/css">
<!--
html {
overflow: -moz-scrollbars-vertical;
}
body {
padding: 0.5em;
background-color: #EEEEEE;
font-family: Verdana, Arial, Helvetica;
font-size: 8pt;
}
h1 {
font-size: 12pt;
margin: 0.5em;
}
h2 {
font-size: 10pt;
display: inline;
vertical-align: top;
}
table {
border: 1px solid gray;
margin-bottom: 0.5em;
padding: 0.25em;
width: 100%;
}
#methodpayload {
display: inline;
}
td {
vertical-align: top;
font-family: Verdana, Arial, Helvetica;
font-size: 8pt;
}
.labelcell {
text-align: right;
}
-->
</style>
<script language="JavaScript" type="text/javascript">
<!--
function verifyserver() {
if (document.frmaction.host.value == '') {
alert('Please insert a server name or address');
return false;
}
if (document.frmaction.path.value == '')
document.frmaction.path.value = '/';
var action = '';
for (counter = 0; counter < document.frmaction.action.length; counter++)
if (document.frmaction.action[counter].checked) {
action = document.frmaction.action[counter].value;
}
if (document.frmaction.method.value == '' && (action == 'execute' || action == 'wrap' || action == 'describe')) {
alert('Please insert a method name');
return false;
}
if (document.frmaction.authtype.value != '1' && document.frmaction.username.value == '') {
alert('No username for authenticating to server: authentication disabled');
}
return true;
}
function switchaction() {
// reset html layout depending on action to be taken
var action = '';
for (counter = 0; counter < document.frmaction.action.length; counter++)
if (document.frmaction.action[counter].checked) {
action = document.frmaction.action[counter].value;
}
if (action == 'execute') {
document.frmaction.methodpayload.disabled = false;
displaydialogeditorbtn(true);//if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
document.frmaction.method.disabled = false;
document.frmaction.methodpayload.rows = 10;
}
else {
document.frmaction.methodpayload.rows = 1;
if (action == 'describe' || action == 'wrap') {
document.frmaction.methodpayload.disabled = true;
displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = true;
document.frmaction.method.disabled = false;
}
else // list
{
document.frmaction.methodpayload.disabled = true;
displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
document.frmaction.method.disabled = true;
}
}
}
function switchssl() {
if (document.frmaction.protocol.value != '2') {
document.frmaction.verifypeer.disabled = true;
document.frmaction.verifyhost.disabled = true;
document.frmaction.cainfo.disabled = true;
}
else {
document.frmaction.verifypeer.disabled = false;
document.frmaction.verifyhost.disabled = false;
document.frmaction.cainfo.disabled = false;
}
}
function switchauth() {
if (document.frmaction.protocol.value != '0') {
document.frmaction.authtype.disabled = false;
}
else {
document.frmaction.authtype.disabled = true;
document.frmaction.authtype.value = 1;
}
}
function swicthcainfo() {
if (document.frmaction.verifypeer.checked == true) {
document.frmaction.cainfo.disabled = false;
}
else {
document.frmaction.cainfo.disabled = true;
}
}
function switchtransport(is_json) {
if (is_json == 0) {
document.getElementById("idcell").style.visibility = 'hidden';
document.frmjsonrpc.yes.checked = false;
document.frmxmlrpc.yes.checked = true;
document.frmaction.wstype.value = "0";
}
else {
document.getElementById("idcell").style.visibility = 'visible';
document.frmjsonrpc.yes.checked = true;
document.frmxmlrpc.yes.checked = false;
document.frmaction.wstype.value = "1";
}
}
function displaydialogeditorbtn(show) {
if (show && ((typeof base64_decode) == 'function')) {
document.getElementById('methodpayloadbtn').innerHTML = '[<a href="#" onclick="activateeditor(); return false;">Edit</a>]';
}
else {
document.getElementById('methodpayloadbtn').innerHTML = '';
}
}
function activateeditor() {
var url = '<?php echo $editorpath; ?>visualeditor.php?params=<?php echo $alt_payload; ?>';
if (document.frmaction.wstype.value == "1")
url += '&type=jsonrpc';
var wnd = window.open(url, '_blank', 'width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=1');
}
// if javascript version of the lib is found, allow it to send us params
function buildparams(base64data) {
if (typeof base64_decode == 'function') {
if (base64data == '0') // workaround for bug in base64_encode...
document.getElementById('methodpayload').value = '';
else
document.getElementById('methodpayload').value = base64_decode(base64data);
}
}
// use GET for ease of refresh, switch to POST when payload is too big to fit in url (in IE: 2048 bytes! see http://support.microsoft.com/kb/q208427/)
function switchFormMethod() {
/// @todo use a more precise calculation, adding the rest of the fields to the actual generated url lenght
if (document.frmaction.methodpayload.value.length > 1536) {
document.frmaction.action = 'action.php?usepost=true';
document.frmaction.method = 'post';
}
}
//-->
</script>
</head>
<body
onload="switchtransport(<?php echo $wstype; ?>); switchaction(); switchssl(); switchauth(); swicthcainfo();<?php if ($run) {
echo ' document.forms[2].submit();';
} ?>">
<h1>XMLRPC
<form name="frmxmlrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(0);"/></form>
/
<form name="frmjsonrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(1);"/></form>
JSONRPC Debugger (based on the <a href="http://gggeek.github.io/phpxmlrpc/">PHP-XMLRPC</a> library)
</h1>
<form name="frmaction" method="get" action="action.php" target="frmaction" onSubmit="switchFormMethod();">
<table id="serverblock">
<tr>
<td><h2>Target server</h2></td>
<td class="labelcell">Address:</td>
<td><input type="text" name="host" value="<?php echo htmlspecialchars($host, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Port:</td>
<td><input type="text" name="port" value="<?php echo htmlspecialchars($port, ENT_COMPAT, $inputcharset); ?>" size="5" maxlength="5"/>
</td>
<td class="labelcell">Path:</td>
<td><input type="text" name="path" value="<?php echo htmlspecialchars($path, ENT_COMPAT, $inputcharset); ?>"/></td>
</tr>
</table>
<table id="actionblock">
<tr>
<td><h2>Action</h2></td>
<td>List available methods<input type="radio" name="action" value="list"<?php if ($action == 'list') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
<td>Describe method<input type="radio" name="action" value="describe"<?php if ($action == 'describe') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
<td>Execute method<input type="radio" name="action" value="execute"<?php if ($action == 'execute') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
<td>Generate stub for method call<input type="radio" name="action" value="wrap"<?php if ($action == 'wrap') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
</tr>
</table>
<input type="hidden" name="methodsig" value="<?php echo htmlspecialchars($methodsig, ENT_COMPAT, $inputcharset); ?>"/>
<table id="methodblock">
<tr>
<td><h2>Method</h2></td>
<td class="labelcell">Name:</td>
<td><input type="text" name="method" value="<?php echo htmlspecialchars($method, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Payload:<br/>
<div id="methodpayloadbtn"></div>
</td>
<td><textarea id="methodpayload" name="methodpayload" rows="1" cols="40"><?php echo htmlspecialchars($payload, ENT_COMPAT, $inputcharset); ?></textarea></td>
<td class="labelcell" id="idcell">Msg id: <input type="text" name="id" size="3" value="<?php echo htmlspecialchars($id, ENT_COMPAT, $inputcharset); ?>"/></td>
<td><input type="hidden" name="wstype" value="<?php echo $wstype; ?>"/>
<input type="submit" value="Execute" onclick="return verifyserver();"/></td>
</tr>
</table>
<table id="optionsblock">
<tr>
<td><h2>Client options</h2></td>
<td class="labelcell">Show debug info:</td>
<td><select name="debug">
<option value="0"<?php if ($debug == 0) { echo ' selected="selected"'; } ?>>No</option>
<option value="1"<?php if ($debug == 1) { echo ' selected="selected"'; } ?>>Yes</option>
<option value="2"<?php if ($debug == 2) { echo ' selected="selected"'; } ?>>More</option>
</select>
</td>
<td class="labelcell">Timeout:</td>
<td><input type="text" name="timeout" size="3" value="<?php if ($timeout > 0) { echo $timeout; } ?>"/></td>
<td class="labelcell">Protocol:</td>
<td><select name="protocol" onchange="switchssl(); switchauth(); swicthcainfo();">
<option value="0"<?php if ($protocol == 0) { echo ' selected="selected"'; } ?>>HTTP 1.0</option>
<option value="1"<?php if ($protocol == 1) { echo ' selected="selected"'; } ?>>HTTP 1.1</option>
<option value="2"<?php if ($protocol == 2) { echo ' selected="selected"'; } ?>>HTTPS</option>
</select></td>
</tr>
<tr>
<td class="labelcell">AUTH:</td>
<td class="labelcell">Username:</td>
<td><input type="text" name="username" value="<?php echo htmlspecialchars($username, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Pwd:</td>
<td><input type="password" name="password" value="<?php echo htmlspecialchars($password, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Type</td>
<td><select name="authtype">
<option value="1"<?php if ($authtype == 1) { echo ' selected="selected"'; } ?>>Basic</option>
<option value="2"<?php if ($authtype == 2) { echo ' selected="selected"'; } ?>>Digest</option>
<option value="8"<?php if ($authtype == 8) { echo ' selected="selected"'; } ?>>NTLM</option>
</select></td>
<td></td>
</tr>
<tr>
<td class="labelcell">SSL:</td>
<td class="labelcell">Verify Host's CN:</td>
<td><select name="verifyhost">
<option value="0"<?php if ($verifyhost == 0) { echo ' selected="selected"'; } ?>>No</option>
<option value="1"<?php if ($verifyhost == 1) { echo ' selected="selected"'; } ?>>Check CN existence</option>
<option value="2"<?php if ($verifyhost == 2) { echo ' selected="selected"'; } ?>>Check CN match</option>
</select></td>
<td class="labelcell">Verify Cert:</td>
<td><input type="checkbox" value="1" name="verifypeer" onclick="swicthcainfo();"<?php if ($verifypeer) { echo ' checked="checked"'; } ?> /></td>
<td class="labelcell">CA Cert file:</td>
<td><input type="text" name="cainfo" value="<?php echo htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset); ?>"/></td>
</tr>
<tr>
<td class="labelcell">PROXY:</td>
<td class="labelcell">Server:</td>
<td><input type="text" name="proxy" value="<?php echo htmlspecialchars($proxy, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Proxy user:</td>
<td><input type="text" name="proxyuser" value="<?php echo htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset); ?>"/></td>
<td class="labelcell">Proxy pwd:</td>
<td><input type="password" name="proxypwd" value="<?php echo htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset); ?>"/></td>
</tr>
<tr>
<td class="labelcell">COMPRESSION:</td>
<td class="labelcell">Request:</td>
<td><select name="requestcompression">
<option value="0"<?php if ($requestcompression == 0) { echo ' selected="selected"'; } ?>>None </option>
<option value="1"<?php if ($requestcompression == 1) { echo ' selected="selected"'; } ?>>Gzip</option>
<option value="2"<?php if ($requestcompression == 2) { echo ' selected="selected"'; } ?>>Deflate</option>
</select></td>
<td class="labelcell">Response:</td>
<td><select name="responsecompression">
<option value="0"<?php if ($responsecompression == 0) { echo ' selected="selected"'; } ?>>None</option>
<option value="1"<?php if ($responsecompression == 1) { echo ' selected="selected"'; } ?>>Gzip</option>
<option value="2"<?php if ($responsecompression == 2) { echo ' selected="selected"'; } ?>>Deflate</option>
<option value="3"<?php if ($responsecompression == 3) { echo ' selected="selected"'; } ?>>Any</option>
</select></td>
<td></td>
</tr>
<tr>
<td class="labelcell">COOKIES:</td>
<td colspan="4" class="labelcell"><input type="text" name="clientcookies" size="80" value="<?php echo htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset); ?>"/></td>
<td colspan="2">Format: 'cookie1=value1, cookie2=value2'</td>
</tr>
</table>
</form>
</body>
</html>

View File

@@ -0,0 +1,21 @@
<?php
$query = '';
if (isset($_GET['run'])) {
$path = parse_url($_GET['run']);
if (isset($path['query'])) {
$query = '?' . $path['query'];
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>XMLRPC Debugger</title>
</head>
<frameset rows="360,*">
<frame name="frmcontroller" src="controller.php<?php echo htmlspecialchars($query); ?>" marginwidth="0"
marginheight="0" frameborder="0"/>
<frame name="frmaction" src="action.php" marginwidth="0" marginheight="0" frameborder="0"/>
</frameset>
</html>

View File

@@ -0,0 +1,68 @@
<html>
<head><title>xmlrpc - Agesort demo</title></head>
<body>
<h1>Agesort demo</h1>
<h2>Send an array of 'name' => 'age' pairs to the server that will send it back sorted.</h2>
<h3>The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs</h3>
<p></p>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
$inAr = array("Dave" => 24, "Edd" => 45, "Joe" => 37, "Fred" => 27);
print "This is the input data:<br/><pre>";
foreach($inAr as $key => $val) {
print $key . ", " . $val . "\n";
}
print "</pre>";
// create parameters from the input array: an xmlrpc array of xmlrpc structs
$p = array();
foreach ($inAr as $key => $val) {
$p[] = new PhpXmlRpc\Value(
array(
"name" => new PhpXmlRpc\Value($key),
"age" => new PhpXmlRpc\Value($val, "int")
),
"struct"
);
}
$v = new PhpXmlRpc\Value($p, "array");
print "Encoded into xmlrpc format it looks like this: <pre>\n" . htmlentities($v->serialize()) . "</pre>\n";
// create client and message objects
$req = new PhpXmlRpc\Request('examples.sortByAge', array($v));
$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
// set maximum debug level, to have the complete communication printed to screen
$client->setDebug(2);
// send request
print "Now sending request (detailed debug info follows)";
$resp = $client->send($req);
// check response for errors, and take appropriate action
if (!$resp->faultCode()) {
print "The server gave me these results:<pre>";
$value = $resp->value();
foreach ($value as $struct) {
$name = $struct["name"];
$age = $struct["age"];
print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
}
print "<hr/>For nerds: I got this value back<br/><pre>" .
htmlentities($resp->serialize()) . "</pre><hr/>\n";
} else {
print "An error occurred:<pre>";
print "Code: " . htmlspecialchars($resp->faultCode()) .
"\nReason: '" . htmlspecialchars($resp->faultString()) . '\'</pre><hr/>';
}
?>
</body>
</html>

View File

@@ -0,0 +1,43 @@
<html>
<head><title>xmlrpc - Getstatename demo</title></head>
<body>
<h1>Getstatename demo</h1>
<h2>Send a U.S. state number to the server and get back the state name</h2>
<h3>The code demonstrates usage of automatic encoding/decoding of php variables into xmlrpc values</h3>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
if (isset($_POST["stateno"]) && $_POST["stateno"] != "") {
$stateNo = (integer)$_POST["stateno"];
$encoder = new PhpXmlRpc\Encoder();
$req = new PhpXmlRpc\Request('examples.getStateName',
array($encoder->encode($stateNo))
);
print "Sending the following request:<pre>\n\n" . htmlentities($req->serialize()) . "\n\n</pre>Debug info of server data follows...\n\n";
$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
$client->setDebug(1);
$r = $client->send($req);
if (!$r->faultCode()) {
$v = $r->value();
print "<br/>State number <b>" . $stateNo . "</b> is <b>"
. htmlspecialchars($encoder->decode($v)) . "</b><br/>";
} else {
print "An error occurred: ";
print "Code: " . htmlspecialchars($r->faultCode())
. " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
}
} else {
$stateNo = "";
}
print "<form action=\"getstatename.php\" method=\"POST\">
<input name=\"stateno\" value=\"" . $stateNo . "\"><input type=\"submit\" value=\"go\" name=\"submit\"></form>
<p>Enter a state number to query its name</p>";
?>
</body>
</html>

View File

@@ -0,0 +1,86 @@
<html>
<head><title>xmlrpc - Introspect demo</title></head>
<body>
<h1>Introspect demo</h1>
<h2>Query server for available methods and their description</h2>
<h3>The code demonstrates usage of multicall and introspection methods</h3>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
function display_error($r)
{
print "An error occurred: ";
print "Code: " . $r->faultCode()
. " Reason: '" . $r->faultString() . "'<br/>";
}
$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
// First off, let's retrieve the list of methods available on the remote server
print "<h3>methods available at http://" . $client->server . $client->path . "</h3>\n";
$req = new PhpXmlRpc\Request('system.listMethods');
$resp = $client->send($req);
if ($resp->faultCode()) {
display_error($resp);
} else {
$v = $resp->value();
// Then, retrieve the signature and help text of each available method
foreach ($v as $methodName) {
print "<h4>" . $methodName->scalarval() . "</h4>\n";
// build messages first, add params later
$m1 = new PhpXmlRpc\Request('system.methodHelp');
$m2 = new PhpXmlRpc\Request('system.methodSignature');
$val = new PhpXmlRpc\Value($methodName->scalarval(), "string");
$m1->addParam($val);
$m2->addParam($val);
// Send multiple requests in one http call.
// If server does not support multicall, client will automatically fall back to 2 separate calls
$ms = array($m1, $m2);
$rs = $client->send($ms);
if ($rs[0]->faultCode()) {
display_error($rs[0]);
} else {
$val = $rs[0]->value();
$txt = $val->scalarval();
if ($txt != "") {
print "<h4>Documentation</h4><p>${txt}</p>\n";
} else {
print "<p>No documentation available.</p>\n";
}
}
if ($rs[1]->faultCode()) {
display_error($rs[1]);
} else {
print "<h4>Signature</h4><p>\n";
// note: using PhpXmlRpc\Encoder::decode() here would lead to cleaner code
$val = $rs[1]->value();
if ($val->kindOf() == "array") {
foreach ($val as $x) {
$ret = $x[0];
print "<code>" . $ret->scalarval() . " "
. $methodName->scalarval() . "(";
if ($x->count() > 1) {
for ($k = 1; $k < $x->count(); $k++) {
$y = $x[$k];
print $y->scalarval();
if ($k < $x->count() - 1) {
print ", ";
}
}
}
print ")</code><br/>\n";
}
} else {
print "Signature unknown\n";
}
print "</p>\n";
}
}
}
?>
</body>
</html>

View File

@@ -0,0 +1,66 @@
<?php
// Allow users to see the source of this file even if PHP is not configured for it
if (isset($_GET['showSource']) && $_GET['showSource']) {
highlight_file(__FILE__);
die();
}
?>
<html>
<head><title>xmlrpc - Mail demo</title></head>
<body>
<h1>Mail demo</h1>
<p>This form enables you to send mail via an XML-RPC server.
When you press <kbd>Send</kbd> this page will reload, showing you the XML-RPC request sent to the host server, the
XML-RPC response received and the internal evaluation done by the PHP implementation.</p>
<p>You can find the source to this page here: <a href="mail.php?showSource=1">mail.php</a><br/>
And the source to a functionally identical mail-by-XML-RPC server in the file <a
href="../server/server.php?showSource=1">server.php</a> included with the library (look for the 'mail_send'
method)</p>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
if (isset($_POST["mailto"]) && $_POST["mailto"]) {
$server = "http://phpxmlrpc.sourceforge.net/server.php";
$req = new PhpXmlRpc\Request('mail.send', array(
new PhpXmlRpc\Value($_POST["mailto"]),
new PhpXmlRpc\Value($_POST["mailsub"]),
new PhpXmlRpc\Value($_POST["mailmsg"]),
new PhpXmlRpc\Value($_POST["mailfrom"]),
new PhpXmlRpc\Value($_POST["mailcc"]),
new PhpXmlRpc\Value($_POST["mailbcc"]),
new PhpXmlRpc\Value("text/plain")
));
$client = new PhpXmlRpc\Client($server);
$client->setDebug(2);
$resp = $client->send($req);
if (!$resp->faultCode()) {
print "Mail sent OK<br/>\n";
} else {
print "<fonr color=\"red\">";
print "Mail send failed<br/>\n";
print "Fault: ";
print "Code: " . htmlspecialchars($resp->faultCode()) .
" Reason: '" . htmlspecialchars($resp->faultString()) . "'<br/>";
print "</font><br/>";
}
}
?>
<form method="POST">
From <input size="60" name="mailfrom" value=""/><br/>
<hr/>
To <input size="60" name="mailto" value=""/><br/>
Cc <input size="60" name="mailcc" value=""/><br/>
Bcc <input size="60" name="mailbcc" value=""/><br/>
<hr/>
Subject <input size="60" name="mailsub" value="A message from xmlrpc"/>
<hr/>
Body <textarea rows="7" cols="60" name="mailmsg">Your message here</textarea><br/>
<input type="Submit" value="Send"/>
</form>
</body>
</html>

View File

@@ -0,0 +1,60 @@
<html>
<head><title>xmlrpc - Proxy demo</title></head>
<body>
<h1>proxy demo</h1>
<h2>Query server using a 'proxy' object</h2>
<h3>The code demonstrates usage for the terminally lazy. For a more complete proxy, look at at the Wrapper class</h3>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
class PhpXmlRpcProxy
{
protected $client;
protected $prefix = 'examples.';
public function __construct(PhpXmlRpc\Client $client)
{
$this->client = $client;
}
/**
* Translates any method call to an xmlrpc call.
*
* @author Toth Istvan
*
* @param string $name remote function name. Will be prefixed
* @param array $arguments
*
* @return mixed
*
* @throws Exception
*/
function __call($name, $arguments)
{
$encoder = new PhpXmlRpc\Encoder();
$valueArray = array();
foreach ($arguments as $parameter) {
$valueArray[] = $encoder->encode($parameter);
}
// just in case this was set to something else
$this->client->return_type = 'phpvals';
$resp = $this->client->send(new PhpXmlRpc\Request($this->prefix.$name, $valueArray));
if ($resp->faultCode()) {
throw new Exception($resp->faultString(), $resp->faultCode());
} else {
return $resp->value();
}
}
}
$stateNo = rand(1, 51);
$proxy = new PhpXmlRpcProxy(new \PhpXmlRpc\Client('http://phpxmlrpc.sourceforge.net/server.php'));
$stateName = $proxy->getStateName($stateNo);
echo "State $stateNo is ".htmlspecialchars($stateName);

View File

@@ -0,0 +1,30 @@
<html>
<head><title>xmlrpc - Which toolkit demo</title></head>
<body>
<h1>Which toolkit demo</h1>
<h2>Query server for toolkit information</h2>
<h3>The code demonstrates usage of the PhpXmlRpc\Encoder class</h3>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
$req = new PhpXmlRpc\Request('interopEchoTests.whichToolkit', array());
$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
$resp = $client->send($req);
if (!$resp->faultCode()) {
$encoder = new PhpXmlRpc\Encoder();
$value = $encoder->decode($resp->value());
print "<pre>";
print "name: " . htmlspecialchars($value["toolkitName"]) . "\n";
print "version: " . htmlspecialchars($value["toolkitVersion"]) . "\n";
print "docs: " . htmlspecialchars($value["toolkitDocsUrl"]) . "\n";
print "os: " . htmlspecialchars($value["toolkitOperatingSystem"]) . "\n";
print "</pre>";
} else {
print "An error occurred: ";
print "Code: " . htmlspecialchars($resp->faultCode()) . " Reason: '" . htmlspecialchars($resp->faultString()) . "'\n";
}
?>
</body>
</html>

View File

@@ -0,0 +1,53 @@
<html>
<head><title>xmlrpc - Webservice wrappper demo</title></head>
<body>
<h1>Webservice wrappper demo</h1>
<h2>Wrap methods exposed by server into php functions</h2>
<h3>The code demonstrates usage of some the most automagic client usage possible:<br/>
1) client that returns php values instead of xmlrpc value objects<br/>
2) wrapping of remote methods into php functions<br/>
See also proxy.php for an alternative take
</h3>
<?php
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
$client->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals
$resp = $client->send(new PhpXmlRpc\Request('system.listMethods'));
if ($resp->faultCode()) {
echo "<p>Server methods list could not be retrieved: error {$resp->faultCode()} '" . htmlspecialchars($resp->faultString()) . "'</p>\n";
} else {
echo "<p>Server methods list retrieved, now wrapping it up...</p>\n<ul>\n";
flush();
$callable = false;
$wrapper = new PhpXmlRpc\Wrapper();
foreach ($resp->value() as $methodName) {
// $resp->value is an array of strings
if ($methodName == 'examples.getStateName') {
$callable = $wrapper->wrapXmlrpcMethod($client, $methodName);
if ($callable) {
echo "<li>Remote server method " . htmlspecialchars($methodName) . " wrapped into php function</li>\n";
} else {
echo "<li>Remote server method " . htmlspecialchars($methodName) . " could not be wrapped!</li>\n";
}
break;
}
}
echo "</ul>\n";
flush();
if ($callable) {
echo "Now testing function for remote method to convert U.S. state number into state name";
$stateNum = rand(1, 51);
// the 2nd parameter gets added to the closure - it is teh debug level to be used for the client
$stateName = $callable($stateNum, 2);
}
}
?>
</body>
</html>

View File

@@ -0,0 +1,60 @@
<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>thearray</name>
<value>
<array>
<data>
<value>
<string>ABCDEFHIJ</string>
</value>
<value>
<int>1234</int>
</value>
<value>
<boolean>1</boolean>
</value>
</data>
</array>
</value>
</member>
<member>
<name>theint</name>
<value>
<int>23</int>
</value>
</member>
<member>
<name>thestring</name>
<value>
<string>foobarwhizz</string>
</value>
</member>
<member>
<name>thestruct</name>
<value>
<struct>
<member>
<name>one</name>
<value>
<int>1</int>
</value>
</member>
<member>
<name>two</name>
<value>
<int>2</int>
</value>
</member>
</struct>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value>
<string>South Dakota's own</string>
</value>
</param>
</params>
</methodResponse>

View File

@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value>
<int>4</int>
</value>
</member>
<member>
<name>faultString</name>
<value>
<string>Too many parameters.</string>
</value>
</member>
</struct>
</value>
</fault>
</methodResponse>

View File

@@ -0,0 +1,99 @@
<?php
include_once __DIR__ . "/../../vendor/autoload.php";
use PhpXmlRpc\Value;
$addComment_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString));
$addComment_doc = 'Adds a comment to an item. The first parameter
is the item ID, the second the name of the commenter, and the third
is the comment itself. Returns the number of comments against that
ID.';
function addComment($req)
{
$err = "";
// since validation has already been carried out for us,
// we know we got exactly 3 string values
$encoder = new PhpXmlRpc\Encoder();
$n = $encoder->decode($req);
$msgID = $n[0];
$name = $n[1];
$comment = $n[2];
$dbh = dba_open("/tmp/comments.db", "c", "db2");
if ($dbh) {
$countID = "${msgID}_count";
if (dba_exists($countID, $dbh)) {
$count = dba_fetch($countID, $dbh);
} else {
$count = 0;
}
// add the new comment in
dba_insert($msgID . "_comment_${count}", $comment, $dbh);
dba_insert($msgID . "_name_${count}", $name, $dbh);
$count++;
dba_replace($countID, $count, $dbh);
dba_close($dbh);
} else {
$err = "Unable to open comments database.";
}
// if we generated an error, create an error return response
if ($err) {
return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
} else {
// otherwise, we create the right response
return new PhpXmlRpc\Response(new PhpXmlRpc\Value($count, "int"));
}
}
$getComments_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcString));
$getComments_doc = 'Returns an array of comments for a given ID, which
is the sole argument. Each array item is a struct containing name
and comment text.';
function getComments($req)
{
$err = "";
$ra = array();
$encoder = new PhpXmlRpc\Encoder();
$msgID = $encoder->decode($req->getParam(0));
$dbh = dba_open("/tmp/comments.db", "r", "db2");
if ($dbh) {
$countID = "${msgID}_count";
if (dba_exists($countID, $dbh)) {
$count = dba_fetch($countID, $dbh);
for ($i = 0; $i < $count; $i++) {
$name = dba_fetch("${msgID}_name_${i}", $dbh);
$comment = dba_fetch("${msgID}_comment_${i}", $dbh);
// push a new struct onto the return array
$ra[] = array(
"name" => $name,
"comment" => $comment,
);
}
}
}
// if we generated an error, create an error return response
if ($err) {
return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
} else {
// otherwise, we create the right response
return new PhpXmlRpc\Response($encoder->encode($ra));
}
}
$srv = new PhpXmlRpc\Server(array(
"discuss.addComment" => array(
"function" => "addComment",
"signature" => $addComment_sig,
"docstring" => $addComment_doc,
),
"discuss.getComments" => array(
"function" => "getComments",
"signature" => $getComments_sig,
"docstring" => $getComments_doc,
),
));

View File

@@ -0,0 +1,88 @@
<?php
/**
* XMLRPC server acting as proxy for requests to other servers
* (useful e.g. for ajax-originated calls that can only connect back to
* the originating server).
*
* @author Gaetano Giunta
* @copyright (C) 2006-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*/
include_once __DIR__ . "/../../src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
/**
* Forward an xmlrpc request to another server, and return to client the response received.
*
* DO NOT RUN AS IS IN PRODUCTION - this is an open relay !!!
*
* @param PhpXmlRpc\Request $req (see method docs below for a description of the expected parameters)
*
* @return PhpXmlRpc\Response
*/
function forward_request($req)
{
$encoder = new \PhpXmlRpc\Encoder();
// create client
$timeout = 0;
$url = $encoder->decode($req->getParam(0));
$client = new PhpXmlRpc\Client($url);
if ($req->getNumParams() > 3) {
// we have to set some options onto the client.
// Note that if we do not untaint the received values, warnings might be generated...
$options = $encoder->decode($req->getParam(3));
foreach ($options as $key => $val) {
switch ($key) {
case 'Cookie':
break;
case 'Credentials':
break;
case 'RequestCompression':
$client->setRequestCompression($val);
break;
case 'SSLVerifyHost':
$client->setSSLVerifyHost($val);
break;
case 'SSLVerifyPeer':
$client->setSSLVerifyPeer($val);
break;
case 'Timeout':
$timeout = (integer)$val;
break;
} // switch
}
}
// build call for remote server
/// @todo find a way to forward client info (such as IP) to server, either
/// - as xml comments in the payload, or
/// - using std http header conventions, such as X-forwarded-for...
$reqMethod = $encoder->decode($req->getParam(1));
$pars = $req->getParam(2);
$req = new PhpXmlRpc\Request($reqMethod);
foreach ($pars as $par) {
$req->addParam($par);
}
// add debug info into response we give back to caller
PhpXmlRpc\Server::xmlrpc_debugmsg("Sending to server $url the payload: " . $req->serialize());
return $client->send($req, $timeout);
}
// run the server
$server = new PhpXmlRpc\Server(
array(
'xmlrpcproxy.call' => array(
'function' => 'forward_request',
'signature' => array(
array('mixed', 'string', 'string', 'array'),
array('mixed', 'string', 'string', 'array', 'struct'),
),
'docstring' => 'forwards xmlrpc calls to remote servers. Returns remote method\'s response. Accepts params: remote server url (might include basic auth credentials), method name, array of params, and (optionally) a struct containing call options',
),
)
);

View File

@@ -0,0 +1,981 @@
<?php
/**
* Demo server for xmlrpc library.
*
* Implements a lot of webservices, including a suite of services used for
* interoperability testing (validator1 methods), and some whose only purpose
* is to be used for unit-testing the library.
*
* Please do not copy this file verbatim into your production server.
**/
// give user a chance to see the source for this server instead of running the services
if ($_SERVER['REQUEST_METHOD'] != 'POST' && isset($_GET['showSource'])) {
highlight_file(__FILE__);
die();
}
include_once __DIR__ . "/../../vendor/autoload.php";
// out-of-band information: let the client manipulate the server operations.
// we do this to help the testsuite script: do not reproduce in production!
if (isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) {
$GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = '/tmp/phpxmlrpc_coverage';
if (!is_dir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'])) {
mkdir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY']);
}
include_once __DIR__ . "/../../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/prepend.php";
}
use PhpXmlRpc\Value;
/**
* Used to test usage of object methods in dispatch maps and in wrapper code.
*/
class xmlrpcServerMethodsContainer
{
/**
* Method used to test logging of php warnings generated by user functions.
* @param PhpXmlRpc\Request $req
* @return PhpXmlRpc\Response
*/
public function phpWarningGenerator($req)
{
$a = $undefinedVariable; // this triggers a warning in E_ALL mode, since $undefinedVariable is undefined
return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcBoolean));
}
/**
* Method used to test catching of exceptions in the server.
* @param PhpXmlRpc\Request $req
* @throws Exception
*/
public function exceptionGenerator($req)
{
throw new Exception("it's just a test", 1);
}
/**
* @param string $msg
*/
public function debugMessageGenerator($msg)
{
PhpXmlRpc\Server::xmlrpc_debugmsg($msg);
}
/**
* A PHP version of the state-number server. Send me an integer and i'll sell you a state.
* Used to test wrapping of PHP methods into xmlrpc methods.
*
* @param integer $num
* @return string
* @throws Exception
*/
public static function findState($num)
{
return inner_findstate($num);
}
/**
* Returns an instance of stdClass.
* Used to test wrapping of PHP objects with class preservation
*/
public function returnObject()
{
$obj = new stdClass();
$obj->hello = 'world';
return $obj;
}
}
// a PHP version of the state-number server
// send me an integer and i'll sell you a state
$stateNames = array(
"Alabama", "Alaska", "Arizona", "Arkansas", "California",
"Colorado", "Columbia", "Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada",
"New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina",
"North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont",
"Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming",
);
$findstate_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcInt));
$findstate_doc = 'When passed an integer between 1 and 51 returns the
name of a US state, where the integer is the index of that state name
in an alphabetic order.';
function findState($req)
{
global $stateNames;
$err = "";
// get the first param
$sno = $req->getParam(0);
// param must be there and of the correct type: server object does the validation for us
// extract the value of the state number
$snv = $sno->scalarval();
// look it up in our array (zero-based)
if (isset($stateNames[$snv - 1])) {
$stateName = $stateNames[$snv - 1];
} else {
// not there, so complain
$err = "I don't have a state for the index '" . $snv . "'";
}
// if we generated an error, create an error return response
if ($err) {
return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
} else {
// otherwise, we create the right response with the state name
return new PhpXmlRpc\Response(new Value($stateName));
}
}
/**
* Inner code of the state-number server.
* Used to test wrapping of PHP functions into xmlrpc methods.
*
* @param integer $stateNo the state number
*
* @return string the name of the state (or error description)
*
* @throws Exception if state is not found
*/
function inner_findstate($stateNo)
{
global $stateNames;
if (isset($stateNames[$stateNo - 1])) {
return $stateNames[$stateNo - 1];
} else {
// not, there so complain
throw new Exception("I don't have a state for the index '" . $stateNo . "'", PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser);
}
}
$wrapper = new PhpXmlRpc\Wrapper();
$findstate2_sig = $wrapper->wrapPhpFunction('inner_findstate');
$findstate3_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'));
$obj = new xmlrpcServerMethodsContainer();
$findstate4_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'));
$findstate5_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true));
eval($findstate5_sig['source']);
$findstate6_sig = $wrapper->wrapPhpFunction('inner_findstate', '', array('return_source' => true));
eval($findstate6_sig['source']);
$findstate7_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true));
eval($findstate7_sig['source']);
$obj = new xmlrpcServerMethodsContainer();
$findstate8_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'), '', array('return_source' => true));
eval($findstate8_sig['source']);
$findstate9_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true));
eval($findstate9_sig['source']);
$findstate10_sig = array(
"function" => function ($req) { return findState($req); },
"signature" => $findstate_sig,
"docstring" => $findstate_doc,
);
$findstate11_sig = $wrapper->wrapPhpFunction(function ($stateNo) { return inner_findstate($stateNo); });
$c = new xmlrpcServerMethodsContainer;
$moreSignatures = $wrapper->wrapPhpClass($c, array('prefix' => 'tests.', 'method_type' => 'all'));
$returnObj_sig = $wrapper->wrapPhpFunction(array($c, 'returnObject'), '', array('encode_php_objs' => true));
// used to test signatures with NULL params
$findstate12_sig = array(
array(Value::$xmlrpcString, Value::$xmlrpcInt, Value::$xmlrpcNull),
array(Value::$xmlrpcString, Value::$xmlrpcNull, Value::$xmlrpcInt),
);
function findStateWithNulls($req)
{
$a = $req->getParam(0);
$b = $req->getParam(1);
if ($a->scalartyp() == Value::$xmlrpcNull)
return new PhpXmlRpc\Response(new Value(inner_findstate($b->scalarval())));
else
return new PhpXmlRpc\Response(new Value(inner_findstate($a->scalarval())));
}
$addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt));
$addtwo_doc = 'Add two integers together and return the result';
function addTwo($req)
{
$s = $req->getParam(0);
$t = $req->getParam(1);
return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcInt));
}
$addtwodouble_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble, Value::$xmlrpcDouble));
$addtwodouble_doc = 'Add two doubles together and return the result';
function addTwoDouble($req)
{
$s = $req->getParam(0);
$t = $req->getParam(1);
return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcDouble));
}
$stringecho_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
$stringecho_doc = 'Accepts a string parameter, returns the string.';
function stringEcho($req)
{
// just sends back a string
return new PhpXmlRpc\Response(new Value($req->getParam(0)->scalarval()));
}
$echoback_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
$echoback_doc = 'Accepts a string parameter, returns the entire incoming payload';
function echoBack($req)
{
// just sends back a string with what i got sent to me, just escaped, that's all
$s = "I got the following message:\n" . $req->serialize();
return new PhpXmlRpc\Response(new Value($s));
}
$echosixtyfour_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcBase64));
$echosixtyfour_doc = 'Accepts a base64 parameter and returns it decoded as a string';
function echoSixtyFour($req)
{
// Accepts an encoded value, but sends it back as a normal string.
// This is to test that base64 encoding is working as expected
$incoming = $req->getParam(0);
return new PhpXmlRpc\Response(new Value($incoming->scalarval(), Value::$xmlrpcString));
}
$bitflipper_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$bitflipper_doc = 'Accepts an array of booleans, and returns them inverted';
function bitFlipper($req)
{
$v = $req->getParam(0);
$rv = new Value(array(), Value::$xmlrpcArray);
foreach ($v as $b) {
if ($b->scalarval()) {
$rv[] = new Value(false, Value::$xmlrpcBoolean);
} else {
$rv[] = new Value(true, Value::$xmlrpcBoolean);
}
}
return new PhpXmlRpc\Response($rv);
}
// Sorting demo
//
// send me an array of structs thus:
//
// Dave 35
// Edd 45
// Fred 23
// Barney 37
//
// and I'll return it to you in sorted order
function agesorter_compare($a, $b)
{
global $agesorter_arr;
// don't even ask me _why_ these come padded with hyphens, I couldn't tell you :p
$a = str_replace("-", "", $a);
$b = str_replace("-", "", $b);
if ($agesorter_arr[$a] == $agesorter_arr[$b]) {
return 0;
}
return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1;
}
$agesorter_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$agesorter_doc = 'Send this method an array of [string, int] structs, eg:
<pre>
Dave 35
Edd 45
Fred 23
Barney 37
</pre>
And the array will be returned with the entries sorted by their numbers.
';
function ageSorter($req)
{
global $agesorter_arr, $s;
PhpXmlRpc\Server::xmlrpc_debugmsg("Entering 'agesorter'");
// get the parameter
$sno = $req->getParam(0);
// error string for [if|when] things go wrong
$err = "";
$agar = array();
$max = $sno->count();
PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements");
foreach ($sno as $i => $rec) {
if ($rec->kindOf() != "struct") {
$err = "Found non-struct in array at element $i";
break;
}
// extract name and age from struct
$n = $rec["name"];
$a = $rec["age"];
// $n and $a are xmlrpcvals,
// so get the scalarval from them
$agar[$n->scalarval()] = $a->scalarval();
}
// create the output value
$v = new Value(array(), Value::$xmlrpcArray);
$agesorter_arr = $agar;
// hack, must make global as uksort() won't
// allow us to pass any other auxiliary information
uksort($agesorter_arr, 'agesorter_compare');
while (list($key, $val) = each($agesorter_arr)) {
// recreate each struct element
$v[] = new Value(
array(
"name" => new Value($key),
"age" => new Value($val, "int")
),
Value::$xmlrpcStruct
);
}
if ($err) {
return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
} else {
return new PhpXmlRpc\Response($v);
}
}
// signature and instructions, place these in the dispatch map
$mailsend_sig = array(array(
Value::$xmlrpcBoolean, Value::$xmlrpcString, Value::$xmlrpcString,
Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString,
Value::$xmlrpcString, Value::$xmlrpcString,
));
$mailsend_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)<br/>
recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.<br/>
subject is a string, the subject of the message.<br/>
sender is a string, it\'s the email address of the person sending the message. This string can not be
a comma-separated list, it must contain a single email address only.<br/>
text is a string, it contains the body of the message.<br/>
mimetype, a string, is a standard MIME type, for example, text/plain.
';
// WARNING; this functionality depends on the sendmail -t option
// it may not work with Windows machines properly; particularly
// the Bcc option. Sneak on your friends at your own risk!
function mailSend($req)
{
$err = "";
$mTo = $req->getParam(0);
$mSub = $req->getParam(1);
$mBody = $req->getParam(2);
$mFrom = $req->getParam(3);
$mCc = $req->getParam(4);
$mBcc = $req->getParam(5);
$mMime = $req->getParam(6);
if ($mTo->scalarval() == "") {
$err = "Error, no 'To' field specified";
}
if ($mFrom->scalarval() == "") {
$err = "Error, no 'From' field specified";
}
$msgHdr = "From: " . $mFrom->scalarval() . "\n";
$msgHdr .= "To: " . $mTo->scalarval() . "\n";
if ($mCc->scalarval() != "") {
$msgHdr .= "Cc: " . $mCc->scalarval() . "\n";
}
if ($mBcc->scalarval() != "") {
$msgHdr .= "Bcc: " . $mBcc->scalarval() . "\n";
}
if ($mMime->scalarval() != "") {
$msgHdr .= "Content-type: " . $mMime->scalarval() . "\n";
}
$msgHdr .= "X-Mailer: XML-RPC for PHP mailer 1.0";
if ($err == "") {
if (!mail("",
$mSub->scalarval(),
$mBody->scalarval(),
$msgHdr)
) {
$err = "Error, could not send the mail.";
}
}
if ($err) {
return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
} else {
return new PhpXmlRpc\Response(new Value(true, Value::$xmlrpcBoolean));
}
}
$getallheaders_sig = array(array(Value::$xmlrpcStruct));
$getallheaders_doc = 'Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS';
function getAllHeaders_xmlrpc($req)
{
$encoder = new PhpXmlRpc\Encoder();
if (function_exists('getallheaders')) {
return new PhpXmlRpc\Response($encoder->encode(getallheaders()));
} else {
$headers = array();
// IIS: poor man's version of getallheaders
foreach ($_SERVER as $key => $val) {
if (strpos($key, 'HTTP_') === 0) {
$key = ucfirst(str_replace('_', '-', strtolower(substr($key, 5))));
$headers[$key] = $val;
}
}
return new PhpXmlRpc\Response($encoder->encode($headers));
}
}
$setcookies_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
$setcookies_doc = 'Sends to client a response containing a single \'1\' digit, and sets to it http cookies as received in the request (array of structs describing a cookie)';
function setCookies($req)
{
$encoder = new PhpXmlRpc\Encoder();
$cookies = $req->getParam(0);
foreach ($cookies as $name => $value) {
$cookieDesc = $encoder->decode($value);
setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']);
}
return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcInt));
}
$getcookies_sig = array(array(Value::$xmlrpcStruct));
$getcookies_doc = 'Sends to client a response containing all http cookies as received in the request (as struct)';
function getCookies($req)
{
$encoder = new PhpXmlRpc\Encoder();
return new PhpXmlRpc\Response($encoder->encode($_COOKIE));
}
$v1_arrayOfStructs_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcArray));
$v1_arrayOfStructs_doc = 'This handler takes a single parameter, an array of structs, each of which contains at least three elements named moe, larry and curly, all <i4>s. Your handler must add all the struct elements named curly and return the result.';
function v1_arrayOfStructs($req)
{
$sno = $req->getParam(0);
$numCurly = 0;
foreach ($sno as $str) {
foreach ($str as $key => $val) {
if ($key == "curly") {
$numCurly += $val->scalarval();
}
}
}
return new PhpXmlRpc\Response(new Value($numCurly, Value::$xmlrpcInt));
}
$v1_easyStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
$v1_easyStruct_doc = 'This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all &lt;i4&gt;s. Your handler must add the three numbers and return the result.';
function v1_easyStruct($req)
{
$sno = $req->getParam(0);
$moe = $sno["moe"];
$larry = $sno["larry"];
$curly = $sno["curly"];
$num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval();
return new PhpXmlRpc\Response(new Value($num, Value::$xmlrpcInt));
}
$v1_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct));
$v1_echoStruct_doc = 'This handler takes a single parameter, a struct. Your handler must return the struct.';
function v1_echoStruct($req)
{
$sno = $req->getParam(0);
return new PhpXmlRpc\Response($sno);
}
$v1_manyTypes_sig = array(array(
Value::$xmlrpcArray, Value::$xmlrpcInt, Value::$xmlrpcBoolean,
Value::$xmlrpcString, Value::$xmlrpcDouble, Value::$xmlrpcDateTime,
Value::$xmlrpcBase64,
));
$v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.';
function v1_manyTypes($req)
{
return new PhpXmlRpc\Response(new Value(
array(
$req->getParam(0),
$req->getParam(1),
$req->getParam(2),
$req->getParam(3),
$req->getParam(4),
$req->getParam(5)
),
Value::$xmlrpcArray
));
}
$v1_moderateSizeArrayCheck_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcArray));
$v1_moderateSizeArrayCheck_doc = 'This handler takes a single parameter, which is an array containing between 100 and 200 elements. Each of the items is a string, your handler must return a string containing the concatenated text of the first and last elements.';
function v1_moderateSizeArrayCheck($req)
{
$ar = $req->getParam(0);
$sz = $ar->count();
$first = $ar[0];
$last = $ar[$sz - 1];
return new PhpXmlRpc\Response(new Value($first->scalarval() .
$last->scalarval(), Value::$xmlrpcString));
}
$v1_simpleStructReturn_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcInt));
$v1_simpleStructReturn_doc = 'This handler takes one parameter, and returns a struct containing three elements, times10, times100 and times1000, the result of multiplying the number by 10, 100 and 1000.';
function v1_simpleStructReturn($req)
{
$sno = $req->getParam(0);
$v = $sno->scalarval();
return new PhpXmlRpc\Response(new Value(
array(
"times10" => new Value($v * 10, Value::$xmlrpcInt),
"times100" => new Value($v * 100, Value::$xmlrpcInt),
"times1000" => new Value($v * 1000, Value::$xmlrpcInt)
),
Value::$xmlrpcStruct
));
}
$v1_nestedStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
$v1_nestedStruct_doc = 'This handler takes a single parameter, a struct, that models a daily calendar. At the top level, there is one struct for each year. Each year is broken down into months, and months into days. Most of the days are empty in the struct you receive, but the entry for April 1, 2000 contains a least three elements named moe, larry and curly, all &lt;i4&gt;s. Your handler must add the three numbers and return the result.';
function v1_nestedStruct($req)
{
$sno = $req->getParam(0);
$twoK = $sno["2000"];
$april = $twoK["04"];
$fools = $april["01"];
$curly = $fools["curly"];
$larry = $fools["larry"];
$moe = $fools["moe"];
return new PhpXmlRpc\Response(new Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), Value::$xmlrpcInt));
}
$v1_countTheEntities_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcString));
$v1_countTheEntities_doc = 'This handler takes a single parameter, a string, that contains any number of predefined entities, namely &lt;, &gt;, &amp; \' and ".<BR>Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.';
function v1_countTheEntities($req)
{
$sno = $req->getParam(0);
$str = $sno->scalarval();
$gt = 0;
$lt = 0;
$ap = 0;
$qu = 0;
$amp = 0;
for ($i = 0; $i < strlen($str); $i++) {
$c = substr($str, $i, 1);
switch ($c) {
case ">":
$gt++;
break;
case "<":
$lt++;
break;
case "\"":
$qu++;
break;
case "'":
$ap++;
break;
case "&":
$amp++;
break;
default:
break;
}
}
return new PhpXmlRpc\Response(new Value(
array(
"ctLeftAngleBrackets" => new Value($lt, Value::$xmlrpcInt),
"ctRightAngleBrackets" => new Value($gt, Value::$xmlrpcInt),
"ctAmpersands" => new Value($amp, Value::$xmlrpcInt),
"ctApostrophes" => new Value($ap, Value::$xmlrpcInt),
"ctQuotes" => new Value($qu, Value::$xmlrpcInt)
),
Value::$xmlrpcStruct
));
}
// trivial interop tests
// http://www.xmlrpc.com/stories/storyReader$1636
$i_echoString_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
$i_echoString_doc = "Echoes string.";
$i_echoStringArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$i_echoStringArray_doc = "Echoes string array.";
$i_echoInteger_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt));
$i_echoInteger_doc = "Echoes integer.";
$i_echoIntegerArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$i_echoIntegerArray_doc = "Echoes integer array.";
$i_echoFloat_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble));
$i_echoFloat_doc = "Echoes float.";
$i_echoFloatArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$i_echoFloatArray_doc = "Echoes float array.";
$i_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct));
$i_echoStruct_doc = "Echoes struct.";
$i_echoStructArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
$i_echoStructArray_doc = "Echoes struct array.";
$i_echoValue_doc = "Echoes any value back.";
$i_echoValue_sig = array(array(Value::$xmlrpcValue, Value::$xmlrpcValue));
$i_echoBase64_sig = array(array(Value::$xmlrpcBase64, Value::$xmlrpcBase64));
$i_echoBase64_doc = "Echoes base64.";
$i_echoDate_sig = array(array(Value::$xmlrpcDateTime, Value::$xmlrpcDateTime));
$i_echoDate_doc = "Echoes dateTime.";
function i_echoParam($req)
{
$s = $req->getParam(0);
return new PhpXmlRpc\Response($s);
}
function i_echoString($req)
{
return i_echoParam($req);
}
function i_echoInteger($req)
{
return i_echoParam($req);
}
function i_echoFloat($req)
{
return i_echoParam($req);
}
function i_echoStruct($req)
{
return i_echoParam($req);
}
function i_echoStringArray($req)
{
return i_echoParam($req);
}
function i_echoIntegerArray($req)
{
return i_echoParam($req);
}
function i_echoFloatArray($req)
{
return i_echoParam($req);
}
function i_echoStructArray($req)
{
return i_echoParam($req);
}
function i_echoValue($req)
{
return i_echoParam($req);
}
function i_echoBase64($req)
{
return i_echoParam($req);
}
function i_echoDate($req)
{
return i_echoParam($req);
}
$i_whichToolkit_sig = array(array(Value::$xmlrpcStruct));
$i_whichToolkit_doc = "Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem.";
function i_whichToolkit($req)
{
global $SERVER_SOFTWARE;
$ret = array(
"toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/",
"toolkitName" => PhpXmlRpc\PhpXmlRpc::$xmlrpcName,
"toolkitVersion" => PhpXmlRpc\PhpXmlRpc::$xmlrpcVersion,
"toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'],
);
$encoder = new PhpXmlRpc\Encoder();
return new PhpXmlRpc\Response($encoder->encode($ret));
}
$object = new xmlrpcServerMethodsContainer();
$signatures = array(
"examples.getStateName" => array(
"function" => "findState",
"signature" => $findstate_sig,
"docstring" => $findstate_doc,
),
"examples.sortByAge" => array(
"function" => "ageSorter",
"signature" => $agesorter_sig,
"docstring" => $agesorter_doc,
),
"examples.addtwo" => array(
"function" => "addTwo",
"signature" => $addtwo_sig,
"docstring" => $addtwo_doc,
),
"examples.addtwodouble" => array(
"function" => "addTwoDouble",
"signature" => $addtwodouble_sig,
"docstring" => $addtwodouble_doc,
),
"examples.stringecho" => array(
"function" => "stringEcho",
"signature" => $stringecho_sig,
"docstring" => $stringecho_doc,
),
"examples.echo" => array(
"function" => "echoBack",
"signature" => $echoback_sig,
"docstring" => $echoback_doc,
),
"examples.decode64" => array(
"function" => "echoSixtyFour",
"signature" => $echosixtyfour_sig,
"docstring" => $echosixtyfour_doc,
),
"examples.invertBooleans" => array(
"function" => "bitFlipper",
"signature" => $bitflipper_sig,
"docstring" => $bitflipper_doc,
),
// signature omitted on purpose
"tests.generatePHPWarning" => array(
"function" => array($object, "phpWarningGenerator"),
),
// signature omitted on purpose
"tests.raiseException" => array(
"function" => array($object, "exceptionGenerator"),
),
// Greek word 'kosme'. NB: NOT a valid ISO8859 string!
// NB: we can only register this when setting internal encoding to UTF-8, or it will break system.listMethods
"tests.utf8methodname." . 'κόσμε' => array(
"function" => "stringEcho",
"signature" => $stringecho_sig,
"docstring" => $stringecho_doc,
),
/*"tests.iso88591methodname." . chr(224) . chr(252) . chr(232) => array(
"function" => "stringEcho",
"signature" => $stringecho_sig,
"docstring" => $stringecho_doc,
),*/
"examples.getallheaders" => array(
"function" => 'getAllHeaders_xmlrpc',
"signature" => $getallheaders_sig,
"docstring" => $getallheaders_doc,
),
"examples.setcookies" => array(
"function" => 'setCookies',
"signature" => $setcookies_sig,
"docstring" => $setcookies_doc,
),
"examples.getcookies" => array(
"function" => 'getCookies',
"signature" => $getcookies_sig,
"docstring" => $getcookies_doc,
),
"mail.send" => array(
"function" => "mailSend",
"signature" => $mailsend_sig,
"docstring" => $mailsend_doc,
),
"validator1.arrayOfStructsTest" => array(
"function" => "v1_arrayOfStructs",
"signature" => $v1_arrayOfStructs_sig,
"docstring" => $v1_arrayOfStructs_doc,
),
"validator1.easyStructTest" => array(
"function" => "v1_easyStruct",
"signature" => $v1_easyStruct_sig,
"docstring" => $v1_easyStruct_doc,
),
"validator1.echoStructTest" => array(
"function" => "v1_echoStruct",
"signature" => $v1_echoStruct_sig,
"docstring" => $v1_echoStruct_doc,
),
"validator1.manyTypesTest" => array(
"function" => "v1_manyTypes",
"signature" => $v1_manyTypes_sig,
"docstring" => $v1_manyTypes_doc,
),
"validator1.moderateSizeArrayCheck" => array(
"function" => "v1_moderateSizeArrayCheck",
"signature" => $v1_moderateSizeArrayCheck_sig,
"docstring" => $v1_moderateSizeArrayCheck_doc,
),
"validator1.simpleStructReturnTest" => array(
"function" => "v1_simpleStructReturn",
"signature" => $v1_simpleStructReturn_sig,
"docstring" => $v1_simpleStructReturn_doc,
),
"validator1.nestedStructTest" => array(
"function" => "v1_nestedStruct",
"signature" => $v1_nestedStruct_sig,
"docstring" => $v1_nestedStruct_doc,
),
"validator1.countTheEntities" => array(
"function" => "v1_countTheEntities",
"signature" => $v1_countTheEntities_sig,
"docstring" => $v1_countTheEntities_doc,
),
"interopEchoTests.echoString" => array(
"function" => "i_echoString",
"signature" => $i_echoString_sig,
"docstring" => $i_echoString_doc,
),
"interopEchoTests.echoStringArray" => array(
"function" => "i_echoStringArray",
"signature" => $i_echoStringArray_sig,
"docstring" => $i_echoStringArray_doc,
),
"interopEchoTests.echoInteger" => array(
"function" => "i_echoInteger",
"signature" => $i_echoInteger_sig,
"docstring" => $i_echoInteger_doc,
),
"interopEchoTests.echoIntegerArray" => array(
"function" => "i_echoIntegerArray",
"signature" => $i_echoIntegerArray_sig,
"docstring" => $i_echoIntegerArray_doc,
),
"interopEchoTests.echoFloat" => array(
"function" => "i_echoFloat",
"signature" => $i_echoFloat_sig,
"docstring" => $i_echoFloat_doc,
),
"interopEchoTests.echoFloatArray" => array(
"function" => "i_echoFloatArray",
"signature" => $i_echoFloatArray_sig,
"docstring" => $i_echoFloatArray_doc,
),
"interopEchoTests.echoStruct" => array(
"function" => "i_echoStruct",
"signature" => $i_echoStruct_sig,
"docstring" => $i_echoStruct_doc,
),
"interopEchoTests.echoStructArray" => array(
"function" => "i_echoStructArray",
"signature" => $i_echoStructArray_sig,
"docstring" => $i_echoStructArray_doc,
),
"interopEchoTests.echoValue" => array(
"function" => "i_echoValue",
"signature" => $i_echoValue_sig,
"docstring" => $i_echoValue_doc,
),
"interopEchoTests.echoBase64" => array(
"function" => "i_echoBase64",
"signature" => $i_echoBase64_sig,
"docstring" => $i_echoBase64_doc,
),
"interopEchoTests.echoDate" => array(
"function" => "i_echoDate",
"signature" => $i_echoDate_sig,
"docstring" => $i_echoDate_doc,
),
"interopEchoTests.whichToolkit" => array(
"function" => "i_whichToolkit",
"signature" => $i_whichToolkit_sig,
"docstring" => $i_whichToolkit_doc,
),
'tests.getStateName.2' => $findstate2_sig,
'tests.getStateName.3' => $findstate3_sig,
'tests.getStateName.4' => $findstate4_sig,
'tests.getStateName.5' => $findstate5_sig,
'tests.getStateName.6' => $findstate6_sig,
'tests.getStateName.7' => $findstate7_sig,
'tests.getStateName.8' => $findstate8_sig,
'tests.getStateName.9' => $findstate9_sig,
'tests.getStateName.10' => $findstate10_sig,
'tests.getStateName.11' => $findstate11_sig,
'tests.getStateName.12' => array(
"function" => "findStateWithNulls",
"signature" => $findstate12_sig,
"docstring" => $findstate_doc,
),
'tests.returnPhpObject' => $returnObj_sig,
);
$signatures = array_merge($signatures, $moreSignatures);
// enable support for the NULL extension
PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_extension = true;
$s = new PhpXmlRpc\Server($signatures, false);
$s->setdebug(3);
$s->compress_response = true;
// out-of-band information: let the client manipulate the server operations.
// we do this to help the testsuite script: do not reproduce in production!
if (isset($_GET['RESPONSE_ENCODING'])) {
$s->response_charset_encoding = $_GET['RESPONSE_ENCODING'];
}
if (isset($_GET['DETECT_ENCODINGS'])) {
PhpXmlRpc\PhpXmlRpc::$xmlrpc_detectencodings = $_GET['DETECT_ENCODINGS'];
}
if (isset($_GET['EXCEPTION_HANDLING'])) {
$s->exception_handling = $_GET['EXCEPTION_HANDLING'];
}
$s->service();
// that should do all we need!
// out-of-band information: let the client manipulate the server operations.
// we do this to help the testsuite script: do not reproduce in production!
if (isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) {
include_once __DIR__ . "/../../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/append.php";
}

View File

@@ -0,0 +1,95 @@
<html>
<head><title>xmlrpc</title></head>
<body>
<?php
include_once __DIR__ . "/../vendor/autoload.php";
$req = new PhpXmlRpc\Request('examples.getStateName');
print "<h3>Testing value serialization</h3>\n";
$v = new PhpXmlRpc\Value(23, "int");
print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
$v = new PhpXmlRpc\Value("What are you saying? >> << &&");
print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
$v = new PhpXmlRpc\Value(
array(
new PhpXmlRpc\Value("ABCDEFHIJ"),
new PhpXmlRpc\Value(1234, 'int'),
new PhpXmlRpc\Value(1, 'boolean'),
),
"array"
);
print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
$v = new PhpXmlRpc\Value(
array(
"thearray" => new PhpXmlRpc\Value(
array(
new PhpXmlRpc\Value("ABCDEFHIJ"),
new PhpXmlRpc\Value(1234, 'int'),
new PhpXmlRpc\Value(1, 'boolean'),
new PhpXmlRpc\Value(0, 'boolean'),
new PhpXmlRpc\Value(true, 'boolean'),
new PhpXmlRpc\Value(false, 'boolean'),
),
"array"
),
"theint" => new PhpXmlRpc\Value(23, 'int'),
"thestring" => new PhpXmlRpc\Value("foobarwhizz"),
"thestruct" => new PhpXmlRpc\Value(
array(
"one" => new PhpXmlRpc\Value(1, 'int'),
"two" => new PhpXmlRpc\Value(2, 'int'),
),
"struct"
),
),
"struct"
);
print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
$w = new PhpXmlRpc\Value(array($v, new PhpXmlRpc\Value("That was the struct!")), "array");
print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
$w = new PhpXmlRpc\Value("Mary had a little lamb,
Whose fleece was white as snow,
And everywhere that Mary went
the lamb was sure to go.
Mary had a little lamb
She tied it to a pylon
Ten thousand volts went down its back
And turned it into nylon", "base64"
);
print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
print "<PRE>Value of base64 string is: '" . $w->scalarval() . "'</PRE>";
$req->method('');
$req->addParam(new PhpXmlRpc\Value("41", "int"));
print "<h3>Testing request serialization</h3>\n";
$op = $req->serialize();
print "<PRE>" . htmlentities($op) . "</PRE>";
print "<h3>Testing ISO date format</h3><pre>\n";
$t = time();
$date = PhpXmlRpc\Helper\Date::iso8601Encode($t);
print "Now is $t --> $date\n";
print "Or in UTC, that is " . PhpXmlRpc\Helper\Date::iso8601Encode($t, 1) . "\n";
$tb = PhpXmlRpc\Helper\Date::iso8601Decode($date);
print "That is to say $date --> $tb\n";
print "Which comes out at " . PhpXmlRpc\Helper\Date::iso8601Encode($tb) . "\n";
print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601Encode($date, 1) . "\n";
print "</pre>\n";
?>
</body>
</html>

View File

@@ -0,0 +1,237 @@
API Changes between library versions 3 and 4
============================================
Class loading
-------------
It is not necessary any more to include the files xmlrpc.inc, xmlrpcs.inc and xmlrpc_wrappers.inc to have the
library classes available.
Instead, it is recommended to rely on class autoloading.
* If you are using Composer, just install the library by declaring it as dependency for your project in composer.json
"require": {
...,
"phpxmlrpc/phpxmlrpc": "~4.0"
},
* If you do not use Composer, an autoloader for the library can be found in src/Atuloader.php.
The php example files in the demo/client folder do make use of it.
Example code to set up the autoloader:
include_once <path to library> . "/src/Autoloader.php";
PhpXmlRpc\Autoloader::register();
* If you still include manually xmlrpc.inc, xmlrpcs.inc or xmlrpc_wrappers.inc, you will not need to set up
class autoloading, as those files do include all the source files for the library classes
New class naming
----------------
All classes have ben renamed, are now properly namespaced and follow the CamelCase naming convention.
Existing class methods and members have been preserved; all new method names follow camelCase.
Conversion table:
| Old class | New class | Notes |
| ------------- | ------------------ | ------------------------------------- |
| xmlrpc_client | PhpXmlRpc\Client | |
| xmlrpc_server | PhpXmlRpc\Server | Removed method: echoInput |
| xmlrpcmsg | PhpXmlRpc\Request | |
| xmlrpcresp | PhpXmlRpc\Response | |
| xmlrpcval | PhpXmlRpc\Value | Removed methods: serializeval, getval |
New class methods
-----------------
In case you had extended the classes of the library and added methods to the subclasses, you might find that your
implementation clashes with the new one if you implemented:
| Class | Method | Notes |
| --------- | ------------ | --------------------------------------- |
| xmlrpcval | count | implements interface: Countable |
| xmlrpcval | getIterator | implements interface: IteratorAggregate |
| xmlrpcval | offsetExists | implements interface: ArrayAccess |
| xmlrpcval | offsetGet | implements interface: ArrayAccess |
| xmlrpcval | offsetSet | implements interface: ArrayAccess |
| xmlrpcval | offsetUnset | implements interface: ArrayAccess |
Global variables cleanup
------------------------
All variables in the global scope have been moved into classes.
Conversion table:
| Old variable | New variable | Notes |
| ------------------------ | ------------------------------------------- | --------- |
| _xmlrpc_debuginfo | PhpXmlRpc\Server::$_xmlrpc_debuginfo | protected |
| _xmlrpcs_capabilities | NOT AVAILABLE YET | |
| _xmlrpcs_dmap | NOT AVAILABLE YET | |
| _xmlrpcs_occurred_errors | PhpXmlRpc\Server::$_xmlrpcs_occurred_errors | protected |
| _xmlrpcs_prev_ehandler | PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler | protected |
| xmlrpcWPFObjHolder | PhpXmlRpc\Wrapper::$objHolder | |
| ... | | |
Global functions cleanup
------------------------
Most functions in the global scope have been moved into classes.
Some have been slightly changed.
| Old function | New function | Notes |
| -------------------------------- | ------------------------------------------- | ------------------------------------------------------ |
| build_client_wrapper_code | none | |
| build_remote_method_wrapper_code | PhpXmlRpc\Wrapper->buildWrapMethodSource | signature changed |
| decode_chunked | PhpXmlRpc\Helper\Http::decodeChunked | |
| guess_encoding | PhpXmlRpc\Helper\XMLParser::guessEncoding | |
| has_encoding | PhpXmlRpc\Helper\XMLParser::hasEncoding | |
| is_valid_charset | PhpXmlRpc\Helper\Charset->isValidCharset | this method is not static, you need a Charset obj |
| iso8601_decode | PhpXmlRpc\Helper\Date::iso8601Decode | |
| iso8601_encode | PhpXmlRpc\Helper\Date::iso8601Encode | |
| php_2_xmlrpc_type | PhpXmlRpc\Wrapper->php2XmlrpcType | this method is not static, you need a Wrapper obj |
| php_xmlrpc_decode | PhpXmlRpc\Encoder->decode | this method is not static, you need an Encoder obj |
| php_xmlrpc_decode_xml | PhpXmlRpc\Encoder->decodeXml | this method is not static, you need an Encoder obj |
| php_xmlrpc_encode | PhpXmlRpc\Encoder->encode | this method is not static, you need an Encoder obj |
| wrap_php_class | PhpXmlRpc\Wrapper->wrapPhpClass | returns closures instead of function names by default |
| wrap_php_function | PhpXmlRpc\Wrapper->wrapPhpFunction | returns closures instead of function names by default |
| wrap_xmlrpc_method | PhpXmlRpc\Wrapper->wrapXmrlpcMethod | returns closures instead of function names by default |
| wrap_xmlrpc_server | PhpXmlRpc\Wrapper->wrapXmrlpcServer | returns closures instead of function names by default; |
| | | returns an array ready for usage in dispatch map |
| xmlrpc_2_php_type | PhpXmlRpc\Wrapper->Xmlrpc2phpType | this method is not static, you need a Wrapper obj |
| xmlrpc_debugmsg | PhpXmlRpc\Server->xmlrpc_debugmsg | |
| xmlrpc_encode_entitites | PhpXmlRpc\Helper\Charset->encodeEntitities | this method is not static, you need a Charset obj |
Character sets and encoding
---------------------------
The default character set used by the library to deliver data to your app is now UTF8.
It is also the character set that the library expects data from your app to be in (including method names).
The value can be changed (to either US-ASCII or ISO-8859-1) by setting the desired value to
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding
Usage of closures for wrapping
------------------------------
...
Differences in server behaviour
-------------------------------
The results for calls to system.listMethods and system.getCapabilities can not be set anymore via changes to
global variables.
Other
-----
* when serialize() is invoked on a response and its payload can not be serialized, an exception is thrown instead of
ending all execution
* all error messages now mention the class and method which generated them
* all library source code has been moved to the src/ directory
* all source code has been reformatted according to modern PSR standards
Enabling compatibility with legacy code
---------------------------------------
If you have code which relies on version 3 of the phpxmlrpc API, you *should* be able to use version 4 as a drop-in
replacement, regardless of all of the changes mentioned above.
The magic happens via the xmlrpc.inc, xmlrpcs.inc and xmlrpc_wrappers.inc files, which have been kept solely for
the purpose of backwards compatibility (you might notice that they are still in the 'lib' directory, whereas all of
the refactored code now sits in the 'src' directory).
Of course, some minor changes where inevitable, and backwards compatibility can not be guaranteed at 100%.
Below is the list of all known changes and possible pitfalls when enabling 'compatibility mode'.
### Default character set used for application data
* when including the xmlrpc.inc file, the defalt character set used by the lib to give data to your app gets switched
back to ISO-8859-1, as it was in previous versions
* if yor app used to change that value, you will need to add one line to your code, to make sure it is properly used
// code as was before
include('xmlrpc.inc');
$GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
// new line needed now
PhpXmlRpc\PhpXmlRpc::importGlobals();
### Usage of global variables
* ALL global variables which existed after including xmlrpc.inc in version 3 still do exist after including it in v. 4
* Code which relies on using (as in 'reading') their value will keep working unchanged
* Changing the value of some of those variables does not have any effect anymore on library operation.
This is true for:
$GLOBALS['xmlrpcI4']
$GLOBALS['xmlrpcInt']
$GLOBALS['xmlrpcBoolean']
$GLOBALS['xmlrpcDouble']
$GLOBALS['xmlrpcString']
$GLOBALS['xmlrpcDatetTme']
$GLOBALS['xmlrpcBase64']
$GLOBALS['xmlrpcArray']
$GLOBALS['xmlrpcStruct']
$GLOBALS['xmlrpcValue']
$GLOBALS['xmlrpcNull']
$GLOBALS['xmlrpcTypes']
$GLOBALS['xmlrpc_valid_parents']
$GLOBALS['xml_iso88591_Entities']
* Changing the value of the other global variables will still have an effect on operation of the library, but only after
a call to PhpXmlRpc::importGlobals()
Example:
// code as was before
include('xmlrpc.inc');
$GLOBALS['xmlrpc_null_apache_encoding'] = true;
// new line needed now
PhpXmlRpc\PhpXmlRpc::importGlobals();
Alternative solution:
include('xmlrpc.inc');
PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_apache_encoding = true;
* Not all variables which existed after including xmlrpcs.inc in version 3 are available
- $GLOBALS['_xmlrpcs_prev_ehandler'] has been replaced with protected static var PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler
and is thus not available any more
- same for $GLOBALS['_xmlrpcs_occurred_errors']
- same for $GLOBALS['_xmlrpc_debuginfo']
- $GLOBALS['_xmlrpcs_capabilities'] and $GLOBALS['_xmlrpcs_dmap'] have been removed
### Using typeof/class-name checks in your code
* if you are checking the types of returned objects, your checks will most likely fail.
This is due to the fact that 'old' classes extend the 'new' versions, but library code that creates object
instances will return the new classes.
Example:
is_a(php_xmlrpc_encode('hello world'), 'xmlrpcval') => false
is_a(php_xmlrpc_encode('hello world'), 'PhpXmlRpc\Value') => true
### server behaviour can not be changed by setting global variables (the ones starting with _xmlrpcs_ )
might be fixed later?

103
lib/phpxmlrpc/doc/build/custom.fo.xsl vendored Normal file
View File

@@ -0,0 +1,103 @@
<?xml version='1.0'?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<!--
Customization xsl stylesheet for docbook to pdf transform
@author Gaetano Giunta
@copyright (c) 2007-2015 G. Giunta
@license code licensed under the BSD License
@todo make the xsl more dynamic: the path to import docbook.xsl could be f.e. rewritten/injected by the php user
-->
<!-- import base stylesheet -->
<xsl:import href="../../../../vendor/docbook/docbook-xsl/fo/docbook.xsl"/>
<!-- customization vars -->
<xsl:param name="fop1.extensions">1</xsl:param>
<xsl:param name="draft.mode">no</xsl:param>
<xsl:param name="funcsynopsis.style">ansi</xsl:param>
<xsl:param name="id.warnings">0</xsl:param>
<xsl:param name="highlight.source">1</xsl:param>
<xsl:param name="highlight.default.language">php</xsl:param>
<xsl:param name="paper.type">A4</xsl:param>
<xsl:param name="shade.verbatim">1</xsl:param>
<xsl:attribute-set name="verbatim.properties">
<xsl:attribute name="font-size">80%</xsl:attribute>
</xsl:attribute-set>
<!-- elements added / modified -->
<xsl:template match="funcdef/function">
<xsl:choose>
<xsl:when test="$funcsynopsis.decoration != 0">
<fo:inline font-weight="bold">
<xsl:apply-templates/>
</fo:inline>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
<xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="funcdef/type">
<xsl:apply-templates/>
<xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="void">
<xsl:choose>
<xsl:when test="$funcsynopsis.style='ansi'">
<xsl:text>( void )</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>( )</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="varargs">
<xsl:text>( ... )</xsl:text>
</xsl:template>
<xsl:template match="paramdef">
<xsl:variable name="paramnum">
<xsl:number count="paramdef" format="1"/>
</xsl:variable>
<xsl:if test="$paramnum=1">( </xsl:if>
<xsl:choose>
<xsl:when test="$funcsynopsis.style='ansi'">
<xsl:apply-templates/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="./parameter"/>
</xsl:otherwise>
</xsl:choose>
<xsl:choose>
<xsl:when test="following-sibling::paramdef">
<xsl:text>, </xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text> )</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="paramdef/type">
<xsl:apply-templates/>
<xsl:text> </xsl:text>
</xsl:template>
<!-- default values for function parameters -->
<xsl:template match="paramdef/initializer">
<xsl:text> = </xsl:text>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>

91
lib/phpxmlrpc/doc/build/custom.xsl vendored Normal file
View File

@@ -0,0 +1,91 @@
<?xml version='1.0'?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--
Customization xsl stylesheet for docbook to chunked html transform
@author Gaetano Giunta
@copyright (c) 2007-2015 G. Giunta
@license code licensed under the BSD License
@todo make the xsl more dynamic: the path to import chunk.xsl could be f.e. rewritten/injected by the php user.
This would be needed f.e. if the lib is installed as a dependency and is not the top-level composer project.
Note: according to http://stackoverflow.com/questions/9861355/using-dynamic-href-in-xslt-import-include this is
not easy to do - it would have to be done f.e. by the invoking php script...
-->
<!-- import base stylesheet -->
<xsl:import href="../../../../vendor/docbook/docbook-xsl/xhtml/chunk.xsl"/>
<!-- customization vars -->
<xsl:param name="draft.mode">no</xsl:param>
<xsl:param name="funcsynopsis.style">ansi</xsl:param>
<xsl:param name="html.stylesheet">xmlrpc.css</xsl:param>
<xsl:param name="id.warnings">0</xsl:param>
<!-- elements added / modified -->
<!-- space between function name and opening parenthesis -->
<xsl:template match="funcdef" mode="ansi-nontabular">
<code>
<xsl:apply-templates select="." mode="class.attribute"/>
<xsl:apply-templates mode="ansi-nontabular"/>
<xsl:text> ( </xsl:text>
</code>
</xsl:template>
<!-- space between return type and function name -->
<xsl:template match="funcdef/type" mode="ansi-nontabular">
<xsl:apply-templates mode="ansi-nontabular"/>
<xsl:text> </xsl:text>
</xsl:template>
<!-- space between last param and closing parenthesis, remove tailing semicolon -->
<xsl:template match="void" mode="ansi-nontabular">
<code>void )</code>
</xsl:template>
<xsl:template match="varargs" mode="ansi-nontabular">
<xsl:text>...</xsl:text>
<code> )</code>
</xsl:template>
<xsl:template match="paramdef" mode="ansi-nontabular">
<xsl:apply-templates mode="ansi-nontabular"/>
<xsl:choose>
<xsl:when test="following-sibling::*">
<xsl:text>, </xsl:text>
</xsl:when>
<xsl:otherwise>
<code> )</code>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- param types get code formatted (leave a space after type, as it is supposed to be before param name) -->
<xsl:template match="paramdef/type" mode="ansi-nontabular">
<xsl:choose>
<xsl:when test="$funcsynopsis.decoration != 0">
<code>
<xsl:apply-templates mode="ansi-nontabular"/>
</code>
</xsl:when>
<xsl:otherwise>
<code>
<xsl:apply-templates mode="ansi-nontabular"/>
</code>
</xsl:otherwise>
</xsl:choose>
<xsl:text> </xsl:text>
</xsl:template>
<!-- default values for function parameters -->
<xsl:template match="paramdef/initializer" mode="ansi-nontabular">
<xsl:text> = </xsl:text>
<xsl:apply-templates mode="ansi-nontabular"/>
</xsl:template>
</xsl:stylesheet>

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,9 @@
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAM12w6/J20HMj0V9VC24xPFQG9RKSDt8vmviM+tnc1BgCrzPyF1v
3/rWGoWDjkJrE9WFOeqIjJHeEWWT4uKq2ZkCAwEAAQJAZZYJ7Nld+et9DvuHak/H
uBRGnjDYA+mKcObXitWMUzk2ZodL8UoCP1J9kKqV8Zp/l2cBZkLo0aWTN94sWkHy
rQIhAOhxWxRXSZ4kArIQqZnDG9JgtOAeaaFso/zpxIHpN6OrAiEA4klzl+rUc32/
7SDcJYa9j5vehp1jCTnkN+n0rujTM8sCIAGwMRUovSQk5tAcRt8TB7SzdxzZm7LM
czR3DjJTW1AZAiEAlYN+svPgJ+cAdwdtLgZXHZoZb8xx8Vik6CTXHPKNCf0CIBQL
zF4Qp8/C+gjsXtEZJvhxY7i1luHn6iNwNnE932r3
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,52 @@
#!/usr/local/bin/perl
use Frontier::Client;
my $serverURL='http://phpxmlrpc.sourceforge.net/server.php';
# try the simplest example
my $client = Frontier::Client->new( 'url' => $serverURL,
'debug' => 0, 'encoding' => 'iso-8859-1' );
my $resp = $client->call("examples.getStateName", 32);
print "Got '${resp}'\n";
# now send a mail to nobody in particular
$resp = $client->call("mail.send", ("edd", "Test",
"Bonjour. Je m'appelle Gérard. Mañana. ", "freddy", "", "",
'text/plain; charset="iso-8859-1"'));
if ($resp->value()) {
print "Mail sent OK.\n";
} else {
print "Error sending mail.\n";
}
# test echoing of characters works fine
$resp = $client->call("examples.echo", 'Three "blind" mice - ' .
"See 'how' they run");
print $resp . "\n";
# test name and age example. this exercises structs and arrays
$resp = $client->call("examples.sortByAge",
[ { 'name' => 'Dave', 'age' => 35},
{ 'name' => 'Edd', 'age' => 45 },
{ 'name' => 'Fred', 'age' => 23 },
{ 'name' => 'Barney', 'age' => 36 } ] );
my $e;
foreach $e (@$resp) {
print $$e{'name'} . ", " . $$e{'age'} . "\n";
}
# test base64
$resp = $client->call("examples.decode64",
$client->base64("TWFyeSBoYWQgYSBsaXR0bGUgbGFtYiBTaGUgd" .
"GllZCBpdCB0byBhIHB5bG9u"));
print $resp . "\n";

View File

@@ -0,0 +1,37 @@
#!/usr/local/bin/python
from xmlrpclib import *
import sys
server = Server("http://phpxmlrpc.sourceforge.net/server.php")
try:
print "Got '" + server.examples.getStateName(32) + "'"
r = server.mail.send("edd", "Test",
"Bonjour. Je m'appelle Gérard. Mañana. ", "freddy", "", "",
'text/plain; charset="iso-8859-1"')
if r:
print "Mail sent OK"
else:
print "Error sending mail"
r = server.examples.echo('Three "blind" mice - ' + "See 'how' they run")
print r
# name/age example. this exercises structs and arrays
a = [ {'name': 'Dave', 'age': 35}, {'name': 'Edd', 'age': 45 },
{'name': 'Fred', 'age': 23}, {'name': 'Barney', 'age': 36 }]
r = server.examples.sortByAge(a)
print r
# test base 64
b = Binary("Mary had a little lamb She tied it to a pylon")
b.encode(sys.stdout)
r = server.examples.decode64(b)
print r
except Error, v:
print "XML-RPC Error:",v

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,217 @@
<?php
// by Edd Dumbill (C) 1999-2002
// <edd@usefulinc.com>
// Copyright (c) 1999,2000,2002 Edd Dumbill.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of the "XML-RPC for PHP" nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
/******************************************************************************
*
* *** DEPRECATED ***
*
* This file is only used to insure backwards compatibility
* with the API of the library <= rev. 3
*
* If it is included, the library will work without any further autoloading
*****************************************************************************/
include_once(__DIR__.'/../src/PhpXmlRpc.php');
include_once(__DIR__.'/../src/Value.php');
include_once(__DIR__.'/../src/Request.php');
include_once(__DIR__.'/../src/Response.php');
include_once(__DIR__.'/../src/Client.php');
include_once(__DIR__.'/../src/Encoder.php');
include_once(__DIR__.'/../src/Helper/Charset.php');
include_once(__DIR__.'/../src/Helper/Date.php');
include_once(__DIR__.'/../src/Helper/Http.php');
include_once(__DIR__.'/../src/Helper/Logger.php');
include_once(__DIR__.'/../src/Helper/XMLParser.php');
/* Expose the global variables which used to be defined */
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; // old default
PhpXmlRpc\PhpXmlRpc::exportGlobals();
/* some stuff deprecated enough that we do not want to put it in the new lib version */
/// @deprecated
$GLOBALS['xmlEntities'] = array(
'amp' => '&',
'quot' => '"',
'lt' => '<',
'gt' => '>',
'apos' => "'"
);
// formulate backslashes for escaping regexp
// Not in use anymore since 2.0. Shall we remove it?
/// @deprecated
$GLOBALS['xmlrpc_backslash'] = chr(92).chr(92);
/* Expose with the old names the classes which have been namespaced */
class xmlrpcval extends PhpXmlRpc\Value
{
/**
* @deprecated
* @param xmlrpcval $o
* @return string
*/
public function serializeval($o)
{
// add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
//if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
//{
$ar = $o->me;
reset($ar);
list($typ, $val) = each($ar);
return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
//}
}
/**
* @deprecated this code looks like it is very fragile and has not been fixed
* for a long long time. Shall we remove it for 2.0?
*/
public function getval()
{
// UNSTABLE
reset($this->me);
list($a, $b) = each($this->me);
// contributed by I Sofer, 2001-03-24
// add support for nested arrays to scalarval
// i've created a new method here, so as to
// preserve back compatibility
if (is_array($b)) {
@reset($b);
while (list($id, $cont) = @each($b)) {
$b[$id] = $cont->scalarval();
}
}
// add support for structures directly encoding php objects
if (is_object($b)) {
$t = get_object_vars($b);
@reset($t);
while (list($id, $cont) = @each($t)) {
$t[$id] = $cont->scalarval();
}
@reset($t);
while (list($id, $cont) = @each($t)) {
@$b->$id = $cont;
}
}
// end contrib
return $b;
}
/// reset functionality added by parent class: same as it would happen if no interface was declared
public function count()
{
return 1;
}
/// reset functionality added by parent class: same as it would happen if no interface was declared
public function getIterator() {
return new ArrayIterator($this);
}
}
class xmlrpcmsg extends PhpXmlRpc\Request
{
}
class xmlrpcresp extends PhpXmlRpc\Response
{
}
class xmlrpc_client extends PhpXmlRpc\Client
{
}
/* Expose as global functions the ones which are now class methods */
/// Wrong speling, but we are adamant on backwards compatibility!
function xmlrpc_encode_entitites($data, $srcEncoding='', $destEncoding='')
{
return PhpXmlRpc\Helper\Charset::instance()->encodeEntitites($data, $srcEncoding, $destEncoding);
}
function iso8601_encode($timeT, $utc=0)
{
return PhpXmlRpc\Helper\Date::iso8601Encode($timeT, $utc);
}
function iso8601_decode($iDate, $utc=0)
{
return PhpXmlRpc\Helper\Date::iso8601Decode($iDate, $utc);
}
function decode_chunked($buffer)
{
return PhpXmlRpc\Helper\Http::decodeChunked($buffer);
}
function php_xmlrpc_decode($xmlrpcVal, $options=array())
{
$encoder = new PhpXmlRpc\Encoder();
return $encoder->decode($xmlrpcVal, $options);
}
function php_xmlrpc_encode($phpVal, $options=array())
{
$encoder = new PhpXmlRpc\Encoder();
return $encoder->encode($phpVal, $options);
}
function php_xmlrpc_decode_xml($xmlVal, $options=array())
{
$encoder = new PhpXmlRpc\Encoder();
return $encoder->decodeXml($xmlVal, $options);
}
function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null)
{
return PhpXmlRpc\Helper\XMLParser::guessEncoding($httpHeader, $xmlChunk, $encodingPrefs);
}
function has_encoding($xmlChunk)
{
return PhpXmlRpc\Helper\XMLParser::hasEncoding($xmlChunk);
}
function is_valid_charset($encoding, $validList)
{
return PhpXmlRpc\Helper\Charset::instance()->isValidCharset($encoding, $validList);
}

View File

@@ -0,0 +1,243 @@
<?php
/******************************************************************************
*
* *** DEPRECATED ***
*
* This file is only used to insure backwards compatibility
* with the API of the library <= rev. 3
*****************************************************************************/
include_once(__DIR__.'/../src/Wrapper.php');
/* Expose as global functions the ones which are now class methods */
/**
* @see PhpXmlRpc\Wrapper::php_2_xmlrpc_type
* @param string $phpType
* @return string
*/
function php_2_xmlrpc_type($phpType)
{
$wrapper = new PhpXmlRpc\Wrapper();
return $wrapper->php2XmlrpcType($phpType);
}
/**
* @see PhpXmlRpc\Wrapper::xmlrpc_2_php_type
* @param string $xmlrpcType
* @return string
*/
function xmlrpc_2_php_type($xmlrpcType)
{
$wrapper = new PhpXmlRpc\Wrapper();
return $wrapper->xmlrpc2PhpType($xmlrpcType);
}
/**
* @see PhpXmlRpc\Wrapper::wrap_php_function
* @param callable $funcName
* @param string $newFuncName
* @param array $extraOptions
* @return array|false
*/
function wrap_php_function($funcName, $newFuncName='', $extraOptions=array())
{
$wrapper = new PhpXmlRpc\Wrapper();
if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) {
// backwards compat: return string instead of callable
$extraOptions['return_source'] = true;
$wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions);
eval($wrapped['source']);
} else {
$wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions);
}
return $wrapped;
}
/**
* NB: this function returns an array in a format which is unsuitable for direct use in the server dispatch map, unlike
* PhpXmlRpc\Wrapper::wrapPhpClass. This behaviour might seem like a bug, but has been kept for backwards compatibility.
*
* @see PhpXmlRpc\Wrapper::wrap_php_class
* @param string|object $className
* @param array $extraOptions
* @return array|false
*/
function wrap_php_class($className, $extraOptions=array())
{
$wrapper = new PhpXmlRpc\Wrapper();
$fix = false;
if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) {
// backwards compat: return string instead of callable
$extraOptions['return_source'] = true;
$fix = true;
}
$wrapped = $wrapper->wrapPhpClass($className, $extraOptions);
foreach($wrapped as $name => $value) {
if ($fix) {
eval($value['source']);
}
$wrapped[$name] = $value['function'];
}
return $wrapped;
}
/**
* @see PhpXmlRpc\Wrapper::wrapXmlrpcMethod
* @param xmlrpc_client $client
* @param string $methodName
* @param int|array $extraOptions the usage of an int as signature number is deprecated, use an option in $extraOptions
* @param int $timeout deprecated, use an option in $extraOptions
* @param string $protocol deprecated, use an option in $extraOptions
* @param string $newFuncName deprecated, use an option in $extraOptions
* @return array|callable|false
*/
function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $protocol='', $newFuncName='')
{
if (!is_array($extraOptions))
{
$sigNum = $extraOptions;
$extraOptions = array(
'signum' => $sigNum,
'timeout' => $timeout,
'protocol' => $protocol,
'new_function_name' => $newFuncName
);
}
$wrapper = new PhpXmlRpc\Wrapper();
if (!isset($extraOptions['return_source']) || $extraOptions['return_source'] == false) {
// backwards compat: return string instead of callable
$extraOptions['return_source'] = true;
$wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions);
eval($wrapped['source']);
$wrapped = $wrapped['function'];
} else {
$wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions);
}
return $wrapped;
}
/**
* @see PhpXmlRpc\Wrapper::wrap_xmlrpc_server
* @param xmlrpc_client $client
* @param array $extraOptions
* @return mixed
*/
function wrap_xmlrpc_server($client, $extraOptions=array())
{
$wrapper = new PhpXmlRpc\Wrapper();
return $wrapper->wrapXmlrpcServer($client, $extraOptions);
}
/**
* Given the necessary info, build php code that creates a new function to invoke a remote xmlrpc method.
* Take care that no full checking of input parameters is done to ensure that valid php code is emitted.
* Only kept for backwards compatibility
* Note: real spaghetti code follows...
*
* @deprecated
*/
function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName,
$mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc',
$decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false,
$faultResponse = '', $namespace = '\\PhpXmlRpc\\')
{
$code = "function $xmlrpcFuncName (";
if ($clientCopyMode < 2) {
// client copy mode 0 or 1 == partial / full client copy in emitted code
$innerCode = build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace);
$innerCode .= "\$client->setDebug(\$debug);\n";
$this_ = '';
} else {
// client copy mode 2 == no client copy in emitted code
$innerCode = '';
$this_ = 'this->';
}
$innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
if ($mDesc != '') {
// take care that PHP comment is not terminated unwillingly by method description
$mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
} else {
$mDesc = "/**\nFunction $xmlrpcFuncName\n";
}
// param parsing
$innerCode .= "\$encoder = new {$namespace}Encoder();\n";
$plist = array();
$pCount = count($mSig);
for ($i = 1; $i < $pCount; $i++) {
$plist[] = "\$p$i";
$pType = $mSig[$i];
if ($pType == 'i4' || $pType == 'i8' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
$pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
) {
// only build directly xmlrpc values when type is known and scalar
$innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
} else {
if ($encodePhpObjects) {
$innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
} else {
$innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
}
}
$innerCode .= "\$req->addparam(\$p$i);\n";
$mDesc .= '* @param ' . xmlrpc_2_php_type($pType) . " \$p$i\n";
}
if ($clientCopyMode < 2) {
$plist[] = '$debug=0';
$mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
}
$plist = implode(', ', $plist);
$mDesc .= '* @return ' . xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
$innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
if ($decodeFault) {
if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
$respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
} else {
$respCode = var_export($faultResponse, true);
}
} else {
$respCode = '$res';
}
if ($decodePhpObjects) {
$innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
} else {
$innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
}
$code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
return array('source' => $code, 'docstring' => $mDesc);
}
/**
* @deprecated
*/
function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
{
$code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).
"', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
// copy all client fields to the client that will be generated runtime
// (this provides for future expansion or subclassing of client obj)
if ($verbatim_client_copy)
{
foreach($client as $fld => $val)
{
if($fld != 'debug' && $fld != 'return_type')
{
$val = var_export($val, true);
$code .= "\$client->$fld = $val;\n";
}
}
}
// only make sure that client always returns the correct data type
$code .= "\$client->return_type = '{$prefix}vals';\n";
//$code .= "\$client->setDebug(\$debug);\n";
return $code;
}

View File

@@ -0,0 +1,121 @@
<?php
// by Edd Dumbill (C) 1999-2002
// <edd@usefulinc.com>
// Copyright (c) 1999,2000,2002 Edd Dumbill.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of the "XML-RPC for PHP" nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
/******************************************************************************
*
* *** DEPRECATED ***
*
* This file is only used to insure backwards compatibility
* with the API of the library <= rev. 3
*****************************************************************************/
include_once(__DIR__.'/../src/Server.php');
class xmlrpc_server extends PhpXmlRpc\Server
{
/**
* A debugging routine: just echoes back the input packet as a string value
* @deprecated
*/
public function echoInput()
{
$r = new Response(new PhpXmlRpc\Value("'Aha said I: '" . file_get_contents('php://input'), 'string'));
print $r->serialize();
}
}
/* Expose as global functions the ones which are now class methods */
/**
* @see PhpXmlRpc\Server::xmlrpc_debugmsg
* @param string $m
*/
function xmlrpc_debugmsg($m)
{
PhpXmlRpc\Server::xmlrpc_debugmsg($m);
}
function _xmlrpcs_getCapabilities($server, $m=null)
{
return PhpXmlRpc\Server::_xmlrpcs_getCapabilities($server, $m);
}
$_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray']));
$_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch';
$_xmlrpcs_listMethods_sdoc=array(array('list of method names'));
function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
{
return PhpXmlRpc\Server::_xmlrpcs_listMethods($server, $m);
}
$_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString']));
$_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)';
$_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described'));
function _xmlrpcs_methodSignature($server, $m)
{
return PhpXmlRpc\Server::_xmlrpcs_methodSignature($server, $m);
}
$_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString']));
$_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string';
$_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described'));
function _xmlrpcs_methodHelp($server, $m)
{
return PhpXmlRpc\Server::_xmlrpcs_methodHelp($server, $m);
}
function _xmlrpcs_multicall_error($err)
{
return PhpXmlRpc\Server::_xmlrpcs_multicall_error($err);
}
function _xmlrpcs_multicall_do_call($server, $call)
{
return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call($server, $call);
}
function _xmlrpcs_multicall_do_call_phpvals($server, $call)
{
return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call_phpvals($server, $call);
}
$_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray']));
$_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';
$_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"'));
function _xmlrpcs_multicall($server, $m)
{
return PhpXmlRpc\Server::_xmlrpcs_multicall($server, $m);
}

29
lib/phpxmlrpc/license.txt Normal file
View File

@@ -0,0 +1,29 @@
Software License Agreement (BSD License)
Copyright (c) 1999,2000,2001 Edd Dumbill, Useful Information Company
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the "XML-RPC for PHP" nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

400
lib/phpxmlrpc/pakefile.php Normal file
View File

@@ -0,0 +1,400 @@
<?php
/**
* Makefile for phpxmlrpc library.
* To be used with the Pake tool: https://github.com/indeyets/pake/wiki
*
* @copyright (c) 2015 G. Giunta
*
* @todo !important allow user to specify location of docbook xslt instead of the one installed via composer
*/
namespace PhpXmlRpc {
class Builder
{
protected static $buildDir = 'build';
protected static $libVersion;
protected static $tools = array(
'asciidoctor' => 'asciidoctor',
'fop' => 'fop',
'php' => 'php',
'zip' => 'zip',
);
protected static $options = array(
'repo' => 'https://github.com/gggeek/phpxmlrpc',
'branch' => 'master'
);
public static function libVersion()
{
if (self::$libVersion == null)
throw new \Exception('Missing library version argument');
return self::$libVersion;
}
public static function buildDir()
{
return self::$buildDir;
}
public static function workspaceDir()
{
return self::buildDir().'/workspace';
}
/// most likely things will break if this one is moved outside of BuildDir
public static function distDir()
{
return self::buildDir().'/xmlrpc-'.self::libVersion();
}
/// these will be generated in BuildDir
public static function distFiles()
{
return array(
'xmlrpc-'.self::libVersion().'.tar.gz',
'xmlrpc-'.self::libVersion().'.zip',
);
}
public static function getOpts($args=array(), $cliOpts=array())
{
if (count($args) > 0)
// throw new \Exception('Missing library version argument');
self::$libVersion = $args[0];
foreach (self::$tools as $name => $binary) {
if (isset($cliOpts[$name])) {
self::$tools[$name] = $cliOpts[$name];
}
}
foreach (self::$options as $name => $value) {
if (isset($cliOpts[$name])) {
self::$options[$name] = $cliOpts[$name];
}
}
//pake_echo('---'.self::$libVersion.'---');
}
/**
* @param string $name
* @return string
*/
public static function tool($name)
{
return self::$tools[$name];
}
/**
* @param string $name
* @return string
*/
public static function option($name)
{
return self::$options[$name];
}
/**
* @param string $inFile
* @param string $xssFile
* @param string $outFileOrDir
* @throws \Exception
*/
public static function applyXslt($inFile, $xssFile, $outFileOrDir)
{
if (!file_exists($inFile)) {
throw new \Exception("File $inFile cannot be found");
}
if (!file_exists($xssFile)) {
throw new \Exception("File $xssFile cannot be found");
}
// Load the XML source
$xml = new \DOMDocument();
$xml->load($inFile);
$xsl = new \DOMDocument();
$xsl->load($xssFile);
// Configure the transformer
$processor = new \XSLTProcessor();
if (version_compare(PHP_VERSION, '5.4', "<")) {
if (defined('XSL_SECPREF_WRITE_FILE')) {
ini_set("xsl.security_prefs", XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
}
} else {
// the php online docs only mention setSecurityPrefs, but somehow some installs have setSecurityPreferences...
if (method_exists('XSLTProcessor', 'setSecurityPrefs')) {
$processor->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
} else {
$processor->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
}
}
$processor->importStyleSheet($xsl); // attach the xsl rules
if (is_dir($outFileOrDir)) {
if (!$processor->setParameter('', 'base.dir', realpath($outFileOrDir))) {
echo "setting param base.dir KO\n";
}
}
$out = $processor->transformToXML($xml);
if (!is_dir($outFileOrDir)) {
file_put_contents($outFileOrDir, $out);
}
}
public static function highlightPhpInHtml($content)
{
$startTag = '<pre class="programlisting">';
$endTag = '</pre>';
//$content = file_get_contents($inFile);
$last = 0;
$out = '';
while (($start = strpos($content, $startTag, $last)) !== false) {
$end = strpos($content, $endTag, $start);
$code = substr($content, $start + strlen($startTag), $end - $start - strlen($startTag));
if ($code[strlen($code) - 1] == "\n") {
$code = substr($code, 0, -1);
}
$code = str_replace(array('&gt;', '&lt;'), array('>', '<'), $code);
$code = highlight_string('<?php ' . $code, true);
$code = str_replace('<span style="color: #0000BB">&lt;?php&nbsp;<br />', '<span style="color: #0000BB">', $code);
$out = $out . substr($content, $last, $start + strlen($startTag) - $last) . $code . $endTag;
$last = $end + strlen($endTag);
}
$out .= substr($content, $last, strlen($content));
return $out;
}
}
}
namespace {
use PhpXmlRpc\Builder;
function run_default($task=null, $args=array(), $cliOpts=array())
{
echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag] {\$task-options}\n";
echo "\n";
echo " Run 'pake help' to list all pake options\n";
echo " Run 'pake -T' to list available tasks\n";
echo " Run 'pake -P' to list all available tasks (including hidden ones) and their dependencies\n";
echo "\n";
echo " Task options:\n";
echo " --repo=REPO URL of the source repository to clone. Defaults to the github repo.\n";
echo " --branch=BRANCH The git branch to build from.\n";
echo " --asciidoctor=ASCIIDOCTOR Location of the asciidoctor command-line tool\n";
echo " --fop=FOP Location of the apache fop command-line tool\n";
echo " --php=PHP Location of the php command-line interpreter\n";
echo " --zip=ZIP Location of the zip tool\n";
}
function run_getopts($task=null, $args=array(), $cliOpts=array())
{
Builder::getOpts($args, $cliOpts);
}
/**
* Downloads source code in the build workspace directory, optionally checking out the given branch/tag
*/
function run_init($task=null, $args=array(), $cliOpts=array())
{
// download the current version into the workspace
$targetDir = Builder::workspaceDir();
// check if workspace exists and is not already set to the correct repo
if (is_dir($targetDir) && pakeGit::isRepository($targetDir)) {
$repo = new pakeGit($targetDir);
$remotes = $repo->remotes();
if (trim($remotes['origin']['fetch']) != Builder::option('repo')) {
throw new Exception("Directory '$targetDir' exists and is not linked to correct git repo");
}
/// @todo should we not just fetch instead?
$repo->pull();
} else {
pake_mkdirs(dirname($targetDir));
$repo = pakeGit::clone_repository(Builder::option('repo'), Builder::workspaceDir());
}
$repo->checkout(Builder::option('branch'));
}
/**
* Runs all the build steps.
*
* (does nothing by itself, as all the steps are managed via task dependencies)
*/
function run_build($task=null, $args=array(), $cliOpts=array())
{
}
function run_clean_doc()
{
pake_remove_dir(Builder::workspaceDir().'/doc/api');
$finder = pakeFinder::type('file')->name('*.html');
pake_remove($finder, Builder::workspaceDir().'/doc/manual');
$finder = pakeFinder::type('file')->name('*.xml');
pake_remove($finder, Builder::workspaceDir().'/doc/manual');
}
/**
* Generates documentation in all formats
*/
function run_doc($task=null, $args=array(), $cliOpts=array())
{
$docDir = Builder::workspaceDir().'/doc';
// API docs
// from phpdoc comments using phpdocumentor
//$cmd = Builder::tool('php');
//pake_sh("$cmd vendor/phpdocumentor/phpdocumentor/bin/phpdoc run -d ".Builder::workspaceDir().'/src'." -t ".Builder::workspaceDir().'/doc/api --title PHP-XMLRPC');
// from phpdoc comments using Sami
$samiConfig = <<<EOT
<?php
\$iterator = Symfony\Component\Finder\Finder::create()
->files()
->exclude('debugger')
->exclude('demo')
->exclude('doc')
->exclude('tests')
->in('./build/workspace');
return new Sami\Sami(\$iterator, array(
'title' => 'PHP-XMLRPC',
'build_dir' => 'build/workspace/doc/api',
'cache_dir' => 'build/cache',
));
EOT;
file_put_contents('build/sami_config.php', $samiConfig);
$cmd = Builder::tool('php');
pake_sh("$cmd vendor/sami/sami/sami.php update -vvv build/sami_config.php");
// User Manual
// html (single file) from asciidoc
$cmd = Builder::tool('asciidoctor');
pake_sh("$cmd -d book $docDir/manual/phpxmlrpc_manual.adoc");
// then docbook from asciidoc
/// @todo create phpxmlrpc_manual.xml with the good version number
/// @todo create phpxmlrpc_manual.xml with the date set to the one of last commit (or today?)
pake_sh("$cmd -d book -b docbook $docDir/manual/phpxmlrpc_manual.adoc");
# Other tools for docbook...
#
# jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g.
# jade -t xml -d custom.dsl xmlrpc_php.xml
#
# convertdoc command for xmlmind xxe editor
# convertdoc docb.toHTML xmlrpc_php.xml -u out
#
# saxon + xerces xml parser + saxon extensions + xslthl: adds a little syntax highligting
# (bold and italics only, no color) for php source examples...
# java \
# -classpath c:\programmi\saxon\saxon.jar\;c:\programmi\saxon\xslthl.jar\;c:\programmi\xerces\xercesImpl.jar\;C:\htdocs\xmlrpc_cvs\docbook-xsl\extensions\saxon65.jar \
# -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \
# -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \
# -Dxslthl.config=file:///c:/htdocs/xmlrpc_cvs/docbook-xsl/highlighting/xslthl-config.xml \
# com.icl.saxon.StyleSheet -o xmlrpc_php.fo.xml xmlrpc_php.xml custom.fo.xsl use.extensions=1
// HTML (multiple files) from docbook - discontinued, as we use the nicer-looking html gotten from asciidoc
/*Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.xsl', $docDir.'/manual');
// post process html files to highlight php code samples
foreach(pakeFinder::type('file')->name('*.html')->in($docDir.'/manual') as $file)
{
file_put_contents($file, Builder::highlightPhpInHtml(file_get_contents($file)));
}*/
// PDF file from docbook
// convert to fo and then to pdf using apache fop
Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.fo.xsl', $docDir.'/manual/phpxmlrpc_manual.fo.xml');
$cmd = Builder::tool('fop');
pake_sh("$cmd $docDir/manual/phpxmlrpc_manual.fo.xml $docDir/manual/phpxmlrpc_manual.pdf");
// cleanup
unlink($docDir.'/manual/phpxmlrpc_manual.xml');
unlink($docDir.'/manual/phpxmlrpc_manual.fo.xml');
}
function run_clean_dist()
{
pake_remove_dir(Builder::distDir());
$finder = pakeFinder::type('file')->name(Builder::distFiles());
pake_remove($finder, Builder::buildDir());
}
/**
* Creates the tarballs for a release
*/
function run_dist($task=null, $args=array(), $cliOpts=array())
{
// copy workspace dir into dist dir, without git
pake_mkdirs(Builder::distDir());
$finder = pakeFinder::type('any')->ignore_version_control();
pake_mirror($finder, realpath(Builder::workspaceDir()), realpath(Builder::distDir()));
// remove unwanted files from dist dir
// also: do we still need to run dos2unix?
// create tarballs
$cwd = getcwd();
chdir(dirname(Builder::distDir()));
foreach(Builder::distFiles() as $distFile) {
// php can not really create good zip files via phar: they are not compressed!
if (substr($distFile, -4) == '.zip') {
$cmd = Builder::tool('zip');
$extra = '-9 -r';
pake_sh("$cmd $distFile $extra ".basename(Builder::distDir()));
}
else {
$finder = pakeFinder::type('any')->pattern(basename(Builder::distDir()).'/**');
// see https://bugs.php.net/bug.php?id=58852
$pharFile = str_replace(Builder::libVersion(), '_LIBVERSION_', $distFile);
pakeArchive::createArchive($finder, '.', $pharFile);
rename($pharFile, $distFile);
}
}
chdir($cwd);
}
function run_clean_workspace($task=null, $args=array(), $cliOpts=array())
{
pake_remove_dir(Builder::workspaceDir());
}
/**
* Cleans up the whole build directory
* @todo 'make clean' usually just removes the results of the build, distclean removes all but sources
*/
function run_clean($task=null, $args=array(), $cliOpts=array())
{
pake_remove_dir(Builder::buildDir());
}
// helper task: display help text
pake_task( 'default' );
// internal task: parse cli options
pake_task('getopts');
pake_task('init', 'getopts');
pake_task('doc', 'getopts', 'init', 'clean-doc');
pake_task('build', 'getopts', 'init', 'doc');
pake_task('dist', 'getopts', 'init', 'build', 'clean-dist');
pake_task('clean-doc', 'getopts');
pake_task('clean-dist', 'getopts');
pake_task('clean-workspace', 'getopts');
pake_task('clean', 'getopts');
}

View File

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

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

File diff suppressed because it is too large Load Diff

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

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,92 @@
<?php
/**
* @author JoakimLofgren
*/
use PhpXmlRpc\Helper\Charset;
/**
* Test conversion between encodings
*
* For Windows if you want to test the output use Consolas font
* and run the following in cmd:
* chcp 28591 (latin1)
* chcp 65001 (utf8)
*/
class CharsetTest extends PHPUnit_Framework_TestCase
{
// Consolas font should render these properly
protected $runes = "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ";
protected $greek = "Τὴ γλῶσσα μοῦ ἔδωσαν ἑλληνικὴ";
protected $russian = "Река неслася; бедный чёлн";
protected $chinese = "我能吞下玻璃而不伤身体。";
protected $latinString;
protected function setUp()
{
// construct a latin string with all chars (except control ones)
$this->latinString = "\n\r\t";
for($i = 32; $i < 127; $i++) {
$this->latinString .= chr($i);
}
for($i = 160; $i < 256; $i++) {
$this->latinString .= chr($i);
}
}
protected function utfToLatin($data)
{
return Charset::instance()->encodeEntities(
$data,
'UTF-8',
'ISO-8859-1'
);
}
public function testUtf8ToLatin1All()
{
/*$this->assertEquals(
'ISO-8859-1',
mb_detect_encoding($this->latinString, 'ISO-8859-1, UTF-8, WINDOWS-1251, ASCII', true),
'Setup latinString is not ISO-8859-1 encoded...'
);*/
$string = utf8_encode($this->latinString);
$encoded = $this->utfToLatin($string);
$this->assertEquals(str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $this->latinString), $encoded);
}
public function testUtf8ToLatin1EuroSymbol()
{
$string = 'a.b.c.å.ä.ö.€.';
$encoded = $this->utfToLatin($string);
$this->assertEquals(utf8_decode('a.b.c.å.ä.ö.&#8364;.'), $encoded);
}
public function testUtf8ToLatin1Runes()
{
$string = $this->runes;
$encoded = $this->utfToLatin($string);
$this->assertEquals('&#5792;&#5831;&#5819;&#5867;&#5842;&#5862;&#5798;&#5867;&#5792;&#5809;&#5801;&#5792;&#5794;&#5809;&#5867;&#5792;&#5825;&#5809;&#5802;&#5867;&#5815;&#5846;&#5819;&#5817;&#5862;&#5850;&#5811;&#5794;&#5847;', $encoded);
}
public function testUtf8ToLatin1Greek()
{
$string = $this->greek;
$encoded = $this->utfToLatin($string);
$this->assertEquals('&#932;&#8052; &#947;&#955;&#8182;&#963;&#963;&#945; &#956;&#959;&#8166; &#7956;&#948;&#969;&#963;&#945;&#957; &#7953;&#955;&#955;&#951;&#957;&#953;&#954;&#8052;', $encoded);
}
public function testUtf8ToLatin1Russian()
{
$string = $this->russian;
$encoded = $this->utfToLatin($string);
$this->assertEquals('&#1056;&#1077;&#1082;&#1072; &#1085;&#1077;&#1089;&#1083;&#1072;&#1089;&#1103;; &#1073;&#1077;&#1076;&#1085;&#1099;&#1081; &#1095;&#1105;&#1083;&#1085;', $encoded);
}
public function testUtf8ToLatin1Chinese()
{
$string = $this->chinese;
$encoded = $this->utfToLatin($string);
$this->assertEquals('&#25105;&#33021;&#21534;&#19979;&#29627;&#29827;&#32780;&#19981;&#20260;&#36523;&#20307;&#12290;', $encoded);
}
}

View File

@@ -0,0 +1,639 @@
<?php
/**
* NB: do not let your IDE fool you. The correct encoding for this file is NOT UTF8.
*/
include_once __DIR__ . '/../lib/xmlrpc.inc';
include_once __DIR__ . '/../lib/xmlrpcs.inc';
include_once __DIR__ . '/parse_args.php';
/**
* Tests involving parsing of xml and handling of xmlrpc values
*/
class ParsingBugsTests extends PHPUnit_Framework_TestCase
{
public $args = array();
protected function setUp()
{
$this->args = argParser::getArgs();
if ($this->args['DEBUG'] == 1)
ob_start();
}
protected function tearDown()
{
if ($this->args['DEBUG'] != 1)
return;
$out = ob_get_clean();
$status = $this->getStatus();
if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
|| $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
echo $out;
}
}
protected function newMsg($methodName, $params = array())
{
$msg = new xmlrpcmsg($methodName, $params);
$msg->setDebug($this->args['DEBUG']);
return $msg;
}
public function testMinusOneString()
{
$v = new xmlrpcval('-1');
$u = new xmlrpcval('-1', 'string');
$t = new xmlrpcval(-1, 'string');
$this->assertEquals($v->scalarval(), $u->scalarval());
$this->assertEquals($v->scalarval(), $t->scalarval());
}
/**
* This looks funny, and we might call it a bug. But we strive for 100 backwards compat...
*/
public function testMinusOneInt()
{
$u = new xmlrpcval();
$v = new xmlrpcval(-1);
$this->assertEquals($u->scalarval(), $v->scalarval());
}
public function testUnicodeInMemberName()
{
$str = "G" . chr(252) . "nter, El" . chr(232) . "ne";
$v = array($str => new xmlrpcval(1));
$r = new xmlrpcresp(new xmlrpcval($v, 'struct'));
$r = $r->serialize();
$m = $this->newMsg('dummy');
$r = $m->parseResponse($r);
$v = $r->value();
$this->assertEquals(true, $v->structmemexists($str));
}
public function testUnicodeInErrorString()
{
$response = utf8_encode(
'<?xml version="1.0"?>
<!-- $Id -->
<!-- found by G. giunta, covers what happens when lib receives
UTF8 chars in response text and comments -->
<!-- ' . chr(224) . chr(252) . chr(232) . '&#224;&#252;&#232; -->
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>888</int></value>
</member>
<member>
<name>faultString</name>
<value><string>' . chr(224) . chr(252) . chr(232) . '&#224;&#252;&#232;</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>');
$m = $this->newMsg('dummy');
$r = $m->parseResponse($response);
$v = $r->faultString();
$this->assertEquals(chr(224) . chr(252) . chr(232) . chr(224) . chr(252) . chr(232), $v);
}
public function testValidNumbers()
{
$m = $this->newMsg('dummy');
$fp =
'<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>integer1</name>
<value><int>01</int></value>
</member>
<member>
<name>integer2</name>
<value><int>+1</int></value>
</member>
<member>
<name>integer3</name>
<value><i4>1</i4></value>
</member>
<member>
<name>float1</name>
<value><double>01.10</double></value>
</member>
<member>
<name>float2</name>
<value><double>+1.10</double></value>
</member>
<member>
<name>float3</name>
<value><double>-1.10e2</double></value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse>';
$r = $m->parseResponse($fp);
$v = $r->value();
$s = $v->structmem('integer1');
$t = $v->structmem('integer2');
$u = $v->structmem('integer3');
$x = $v->structmem('float1');
$y = $v->structmem('float2');
$z = $v->structmem('float3');
$this->assertEquals(1, $s->scalarval());
$this->assertEquals(1, $t->scalarval());
$this->assertEquals(1, $u->scalarval());
$this->assertEquals(1.1, $x->scalarval());
$this->assertEquals(1.1, $y->scalarval());
$this->assertEquals(-110.0, $z->scalarval());
}
public function testI8()
{
if (PHP_INT_SIZE == 4 ) {
$this->markTestSkipped('did not find a locale which sets decimal separator to comma');
return;
}
$m = $this->newMsg('dummy');
$fp =
'<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>integer1</name>
<value><i8>1</i8></value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse>';
$r = $m->parseResponse($fp);
$v = $r->value();
$s = $v->structmem('integer1');
$this->assertEquals(1, $s->scalarval());
}
public function testAddScalarToStruct()
{
$v = new xmlrpcval(array('a' => 'b'), 'struct');
// use @ operator in case error_log gets on screen
$r = @$v->addscalar('c');
$this->assertEquals(0, $r);
}
public function testAddStructToStruct()
{
$v = new xmlrpcval(array('a' => new xmlrpcval('b')), 'struct');
$r = $v->addstruct(array('b' => new xmlrpcval('c')));
$this->assertEquals(2, $v->structsize());
$this->assertEquals(1, $r);
$r = $v->addstruct(array('b' => new xmlrpcval('b')));
$this->assertEquals(2, $v->structsize());
}
public function testAddArrayToArray()
{
$v = new xmlrpcval(array(new xmlrpcval('a'), new xmlrpcval('b')), 'array');
$r = $v->addarray(array(new xmlrpcval('b'), new xmlrpcval('c')));
$this->assertEquals(4, $v->arraysize());
$this->assertEquals(1, $r);
}
public function testEncodeArray()
{
$r = range(1, 100);
$v = php_xmlrpc_encode($r);
$this->assertEquals('array', $v->kindof());
}
public function testEncodeRecursive()
{
$v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string'));
$this->assertEquals('scalar', $v->kindof());
}
public function testBrokenRequests()
{
$s = new xmlrpc_server();
// omitting the 'params' tag: not tolerated by the lib anymore
$f = '<?xml version="1.0"?>
<methodCall>
<methodName>system.methodHelp</methodName>
<param>
<value><string>system.methodHelp</string></value>
</param>
</methodCall>';
$r = $s->parserequest($f);
$this->assertEquals(15, $r->faultCode());
// omitting a 'param' tag
$f = '<?xml version="1.0"?>
<methodCall>
<methodName>system.methodHelp</methodName>
<params>
<value><string>system.methodHelp</string></value>
</params>
</methodCall>';
$r = $s->parserequest($f);
$this->assertEquals(15, $r->faultCode());
// omitting a 'value' tag
$f = '<?xml version="1.0"?>
<methodCall>
<methodName>system.methodHelp</methodName>
<params>
<param><string>system.methodHelp</string></param>
</params>
</methodCall>';
$r = $s->parserequest($f);
$this->assertEquals(15, $r->faultCode());
}
public function testBrokenResponses()
{
$m = $this->newMsg('dummy');
// omitting the 'params' tag: no more tolerated by the lib...
$f = '<?xml version="1.0"?>
<methodResponse>
<param>
<value><string>system.methodHelp</string></value>
</param>
</methodResponse>';
$r = $m->parseResponse($f);
$this->assertEquals(2, $r->faultCode());
// omitting the 'param' tag: no more tolerated by the lib...
$f = '<?xml version="1.0"?>
<methodResponse>
<params>
<value><string>system.methodHelp</string></value>
</params>
</methodResponse>';
$r = $m->parseResponse($f);
$this->assertEquals(2, $r->faultCode());
// omitting a 'value' tag: KO
$f = '<?xml version="1.0"?>
<methodResponse>
<params>
<param><string>system.methodHelp</string></param>
</params>
</methodResponse>';
$r = $m->parseResponse($f);
$this->assertEquals(2, $r->faultCode());
}
public function testBuggyHttp()
{
$s = $this->newMsg('dummy');
$f = 'HTTP/1.1 100 Welcome to the jungle
HTTP/1.0 200 OK
X-Content-Marx-Brothers: Harpo
Chico and Groucho
Content-Length: who knows?
<?xml version="1.0"?>
<!-- First of all, let\'s check out if the lib properly handles a commented </methodResponse> tag... -->
<methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
<script type="text\javascript">document.write(\'Hello, my name is added nag, I\\\'m happy to serve your content for free\');</script>
';
$r = $s->parseResponse($f);
$v = $r->value();
$s = $v->structmem('content');
$this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
}
public function testStringBug()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?>
<!-- $Id -->
<!-- found by 2z69xks7bpy001@sneakemail.com, amongst others
covers what happens when there\'s character data after </string>
and before </value> -->
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>success</name>
<value>
<boolean>1</boolean>
</value>
</member>
<member>
<name>sessionID</name>
<value>
<string>S300510007I</string>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse> ';
$r = $s->parseResponse($f);
$v = $r->value();
$s = $v->structmem('sessionID');
$this->assertEquals('S300510007I', $s->scalarval());
}
public function testWhiteSpace()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->value();
$s = $v->structmem('content');
$this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
}
public function testDoubleDataInArrayTag()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
<data></data>
<data></data>
</array></value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->faultCode();
$this->assertEquals(2, $v);
$f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
<data><value>Hello world</value></data>
<data></data>
</array></value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->faultCode();
$this->assertEquals(2, $v);
}
public function testDoubleStuffInValueTag()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?><methodResponse><params><param><value>
<string>hello world</string>
<array><data></data></array>
</value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->faultCode();
$this->assertEquals(2, $v);
$f = '<?xml version="1.0"?><methodResponse><params><param><value>
<string>hello</string>
<string>world</string>
</value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->faultCode();
$this->assertEquals(2, $v);
$f = '<?xml version="1.0"?><methodResponse><params><param><value>
<string>hello</string>
<struct><member><name>hello><value>world</value></member></struct>
</value></param></params></methodResponse>
';
$r = $s->parseResponse($f);
$v = $r->faultCode();
$this->assertEquals(2, $v);
}
public function testAutodecodeResponse()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f, true, 'phpvals');
$v = $r->value();
$s = $v['content'];
$this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s);
}
public function testNoDecodeResponse()
{
$s = $this->newMsg('dummy');
$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>';
$r = $s->parseResponse($f, true, 'xml');
$v = $r->value();
$this->assertEquals($f, $v);
}
public function testAutoCoDec()
{
$data1 = array(1, 1.0, 'hello world', true, '20051021T23:43:00', -1, 11.0, '~!@#$%^&*()_+|', false, '20051021T23:43:00');
$data2 = array('zero' => $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1);
$data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2);
//$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
$v1 = php_xmlrpc_encode($data, array('auto_dates'));
$v2 = php_xmlrpc_decode_xml($v1->serialize());
$this->assertEquals($v1, $v2);
$r1 = new PhpXmlRpc\Response($v1);
$r2 = php_xmlrpc_decode_xml($r1->serialize());
$r2->serialize(); // needed to set internal member payload
$this->assertEquals($r1, $r2);
$m1 = new PhpXmlRpc\Request('hello dolly', array($v1));
$m2 = php_xmlrpc_decode_xml($m1->serialize());
$m2->serialize(); // needed to set internal member payload
$this->assertEquals($m1, $m2);
}
public function testUTF8Request()
{
$sendstring = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string!
$GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
\PhpXmlRpc\PhpXmlRpc::importGlobals();
$f = new xmlrpcval($sendstring, 'string');
$v = $f->serialize();
$this->assertEquals("<value><string>&#954;&#8057;&#963;&#956;&#949;</string></value>\n", $v);
$GLOBALS['xmlrpc_internalencoding'] = 'ISO-8859-1';
\PhpXmlRpc\PhpXmlRpc::importGlobals();
}
public function testUTF8Response()
{
$string = chr(224) . chr(252) . chr(232);
$s = $this->newMsg('dummy');
$f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . utf8_encode($string) . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f, false, 'phpvals');
$v = $r->value();
$v = $v['content'];
$this->assertEquals($string, $v);
$f = '<?xml version="1.0" encoding="UTF-8"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . utf8_encode($string) . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f, false, 'phpvals');
$v = $r->value();
$v = $v['content'];
$this->assertEquals($string, $v);
$r = php_xmlrpc_decode_xml($f);
$v = $r->value();
$v = $v->structmem('content')->scalarval();
$this->assertEquals($string, $v);
}
public function testLatin1Response()
{
$string = chr(224) . chr(252) . chr(232);
$s = $this->newMsg('dummy');
$f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=ISO-8859-1\r\n\r\n" . '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . $string . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f, false, 'phpvals');
$v = $r->value();
$v = $v['content'];
$this->assertEquals($string, $v);
$f = '<?xml version="1.0" encoding="ISO-8859-1"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . $string . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
';
$r = $s->parseResponse($f, false, 'phpvals');
$v = $r->value();
$v = $v['content'];
$this->assertEquals($string, $v);
$r = php_xmlrpc_decode_xml($f);
$v = $r->value();
$v = $v->structmem('content')->scalarval();
$this->assertEquals($string, $v);
}
public function testUTF8IntString()
{
$v = new xmlrpcval(100, 'int');
$s = $v->serialize('UTF-8');
$this->assertequals("<value><int>100</int></value>\n", $s);
}
public function testStringInt()
{
$v = new xmlrpcval('hello world', 'int');
$s = $v->serialize();
$this->assertequals("<value><int>0</int></value>\n", $s);
}
public function testStructMemExists()
{
$v = php_xmlrpc_encode(array('hello' => 'world'));
$b = $v->structmemexists('hello');
$this->assertequals(true, $b);
$b = $v->structmemexists('world');
$this->assertequals(false, $b);
}
public function testNilvalue()
{
// default case: we do not accept nil values received
$v = new xmlrpcval('hello', 'null');
$r = new xmlrpcresp($v);
$s = $r->serialize();
$m = $this->newMsg('dummy');
$r = $m->parseresponse($s);
$this->assertequals(2, $r->faultCode());
// enable reception of nil values
$GLOBALS['xmlrpc_null_extension'] = true;
\PhpXmlRpc\PhpXmlRpc::importGlobals();
$r = $m->parseresponse($s);
$v = $r->value();
$this->assertequals('null', $v->scalartyp());
// test with the apache version: EX:NIL
$GLOBALS['xmlrpc_null_apache_encoding'] = true;
\PhpXmlRpc\PhpXmlRpc::importGlobals();
// serialization
$v = new xmlrpcval('hello', 'null');
$s = $v->serialize();
$this->assertequals(1, preg_match('#<value><ex:nil/></value>#', $s));
// deserialization
$r = new xmlrpcresp($v);
$s = $r->serialize();
$r = $m->parseresponse($s);
$v = $r->value();
$this->assertequals('null', $v->scalartyp());
$GLOBALS['xmlrpc_null_extension'] = false;
\PhpXmlRpc\PhpXmlRpc::importGlobals();
$r = $m->parseresponse($s);
$this->assertequals(2, $r->faultCode());
}
public function testLocale()
{
$locale = setlocale(LC_NUMERIC, 0);
/// @todo on php 5.3/win setting locale to german does not seem to set decimal separator to comma...
if (setlocale(LC_NUMERIC, 'deu', 'de_DE@euro', 'de_DE', 'de', 'ge') !== false) {
$v = new xmlrpcval(1.1, 'double');
if (strpos($v->scalarval(), ',') == 1) {
$r = $v->serialize();
$this->assertequals(false, strpos($r, ','));
setlocale(LC_NUMERIC, $locale);
} else {
setlocale(LC_NUMERIC, $locale);
$this->markTestSkipped('did not find a locale which sets decimal separator to comma');
}
} else {
$this->markTestSkipped('did not find a locale which sets decimal separator to comma');
}
}
public function testArrayAccess()
{
$v1 = new xmlrpcval(array(new xmlrpcval('one'), new xmlrpcval('two')), 'array');
$this->assertequals(1, count($v1));
$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
foreach($v1 as $key => $val)
{
$expected = each($out);
$this->assertequals($expected['key'], $key);
if (gettype($expected['value']) == 'array') {
$this->assertequals('array', gettype($val));
} else {
$this->assertequals($expected['value'], $val);
}
}
$v2 = new \PhpXmlRpc\Value(array(new \PhpXmlRpc\Value('one'), new \PhpXmlRpc\Value('two')), 'array');
$this->assertequals(2, count($v2));
$out = array(0 => 'object', 1 => 'object');
foreach($v2 as $key => $val)
{
$expected = each($out);
$this->assertequals($expected['key'], $key);
$this->assertequals($expected['value'], gettype($val));
}
}
}

View File

@@ -0,0 +1,94 @@
<?php
include_once __DIR__ . '/../lib/xmlrpc.inc';
include_once __DIR__ . '/parse_args.php';
/**
* Tests involving requests sent to non-existing servers
*/
class InvalidHostTest extends PHPUnit_Framework_TestCase
{
/** @var xmlrpc_client $client */
public $client = null;
public $args = array();
public function setUp()
{
$this->args = argParser::getArgs();
$this->client = new xmlrpc_client('/NOTEXIST.php', $this->args['LOCALSERVER'], 80);
$this->client->setDebug($this->args['DEBUG']);
if ($this->args['DEBUG'] == 1)
ob_start();
}
protected function tearDown()
{
if ($this->args['DEBUG'] != 1)
return;
$out = ob_get_clean();
$status = $this->getStatus();
if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
|| $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
echo $out;
}
}
public function test404()
{
$m = new xmlrpcmsg('examples.echo', array(
new xmlrpcval('hello', 'string'),
));
$r = $this->client->send($m, 5);
$this->assertEquals(5, $r->faultCode());
}
public function testSrvNotFound()
{
$m = new xmlrpcmsg('examples.echo', array(
new xmlrpcval('hello', 'string'),
));
$this->client->server .= 'XXX';
$r = $this->client->send($m, 5);
// make sure there's no freaking catchall DNS in effect
$dnsinfo = dns_get_record($this->client->server);
if ($dnsinfo) {
$this->markTestSkipped('Seems like there is a catchall DNS in effect: host ' . $this->client->server . ' found');
} else {
$this->assertEquals(5, $r->faultCode());
}
}
public function testCurlKAErr()
{
if (!function_exists('curl_init')) {
$this->markTestSkipped('CURL missing: cannot test curl keepalive errors');
return;
}
$m = new xmlrpcmsg('examples.stringecho', array(
new xmlrpcval('hello', 'string'),
));
// test 2 calls w. keepalive: 1st time connection ko, second time ok
$this->client->server .= 'XXX';
$this->client->keepalive = true;
$r = $this->client->send($m, 5, 'http11');
// in case we have a "universal dns resolver" getting in the way, we might get a 302 instead of a 404
$this->assertTrue($r->faultCode() === 8 || $r->faultCode() == 5);
// now test a successful connection
$server = explode(':', $this->args['LOCALSERVER']);
if (count($server) > 1) {
$this->client->port = $server[1];
}
$this->client->server = $server[0];
$this->client->path = $this->args['URI'];
$r = $this->client->send($m, 5, 'http11');
$this->assertEquals(0, $r->faultCode());
$ro = $r->value();
is_object($ro) && $this->assertEquals('hello', $ro->scalarVal());
}
}

View File

@@ -0,0 +1,955 @@
<?php
include_once __DIR__ . '/../lib/xmlrpc.inc';
include_once __DIR__ . '/../lib/xmlrpc_wrappers.inc';
include_once __DIR__ . '/parse_args.php';
/**
* Tests which involve interaction between the client and the server.
* They are run against the server found in demo/server.php
*/
class LocalhostTest extends PHPUnit_Framework_TestCase
{
/** @var xmlrpc_client $client */
protected $client = null;
protected $method = 'http';
protected $timeout = 10;
protected $request_compression = null;
protected $accepted_compression = '';
protected $args = array();
protected static $failed_tests = array();
protected $testId;
/** @var boolean $collectCodeCoverageInformation */
protected $collectCodeCoverageInformation;
protected $coverageScriptUrl;
public static function fail($message = '')
{
// save in a static var that this particular test has failed
// (but only if not called from subclass objects / multitests)
if (function_exists('debug_backtrace') && strtolower(get_called_class()) == 'localhosttests') {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
for ($i = 0; $i < count($trace); $i++) {
if (strpos($trace[$i]['function'], 'test') === 0) {
self::$failed_tests[$trace[$i]['function']] = true;
break;
}
}
}
parent::fail($message);
}
/**
* Reimplemented to allow us to collect code coverage info from the target server.
* Code taken from PHPUnit_Extensions_Selenium2TestCase
*
* @param PHPUnit_Framework_TestResult $result
* @return PHPUnit_Framework_TestResult
* @throws Exception
*/
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->testId = get_class($this) . '__' . $this->getName();
if ($result === NULL) {
$result = $this->createResult();
}
$this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation();
parent::run($result);
if ($this->collectCodeCoverageInformation) {
$coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage(
$this->coverageScriptUrl,
$this->testId
);
$result->getCodeCoverage()->append(
$coverage->get(), $this
);
}
// do not call this before to give the time to the Listeners to run
//$this->getStrategy()->endOfTest($this->session);
return $result;
}
public function setUp()
{
$this->args = argParser::getArgs();
$server = explode(':', $this->args['LOCALSERVER']);
if (count($server) > 1) {
$this->client = new xmlrpc_client($this->args['URI'], $server[0], $server[1]);
} else {
$this->client = new xmlrpc_client($this->args['URI'], $this->args['LOCALSERVER']);
}
$this->client->setDebug($this->args['DEBUG']);
$this->client->request_compression = $this->request_compression;
$this->client->accepted_compression = $this->accepted_compression;
$this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
if ($this->args['DEBUG'] == 1)
ob_start();
}
protected function tearDown()
{
if ($this->args['DEBUG'] != 1)
return;
$out = ob_get_clean();
$status = $this->getStatus();
if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
|| $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
echo $out;
}
}
/**
* @param PhpXmlRpc\Request|array $msg
* @param int|array $errorCode
* @param bool $returnResponse
* @return mixed|\PhpXmlRpc\Response|\PhpXmlRpc\Response[]|\PhpXmlRpc\Value|string|void
*/
protected function send($msg, $errorCode = 0, $returnResponse = false)
{
if ($this->collectCodeCoverageInformation) {
$this->client->setCookie('PHPUNIT_SELENIUM_TEST_ID', $this->testId);
}
$r = $this->client->send($msg, $this->timeout, $this->method);
// for multicall, return directly array of responses
if (is_array($r)) {
return $r;
}
if (is_array($errorCode)) {
$this->assertContains($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
} else {
$this->assertEquals($errorCode, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
}
if (!$r->faultCode()) {
if ($returnResponse) {
return $r;
} else {
return $r->value();
}
} else {
return;
}
}
public function testString()
{
$sendString = "here are 3 \"entities\": < > & " .
"and here's a dollar sign: \$pretendvarname and a backslash too: " . chr(92) .
" - isn't that great? \\\"hackery\\\" at it's best " .
" also don't want to miss out on \$item[0]. " .
"The real weird stuff follows: CRLF here" . chr(13) . chr(10) .
"a simple CR here" . chr(13) .
"a simple LF here" . chr(10) .
"and then LFCR" . chr(10) . chr(13) .
"last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->";
$m = new xmlrpcmsg('examples.stringecho', array(
new xmlrpcval($sendString, 'string'),
));
$v = $this->send($m);
if ($v) {
// when sending/receiving non-US-ASCII encoded strings, XML says cr-lf can be normalized.
// so we relax our tests...
$l1 = strlen($sendString);
$l2 = strlen($v->scalarval());
if ($l1 == $l2) {
$this->assertEquals($sendString, $v->scalarval());
} else {
$this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval());
}
}
}
public function testLatin1String()
{
$sendString =
"last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne";
$x = '<?xml version="1.0" encoding="ISO-8859-1"?><methodCall><methodName>examples.stringecho</methodName><params><param><value>'.
$sendString.
'</value></param></params></methodCall>';
$v = $this->send($x);
if ($v) {
$this->assertEquals($sendString, $v->scalarval());
}
}
public function testExoticCharsetsRequests()
{
// note that we should disable this call also when mbstring is missing server-side
if (!function_exists('mb_convert_encoding')) {
$this->markTestSkipped('Miss mbstring extension to test exotic charsets');
return;
}
$sendString = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string!
$str = '<?xml version="1.0" encoding="_ENC_"?>
<methodCall>
<methodName>examples.stringecho</methodName>
<params>
<param>
<value><string>'.$sendString.'</string></value>
</param>
</params>
</methodCall>';
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
// we have to set the encoding declaration either in the http header or xml prolog, as mb_detect_encoding
// (used on the server side) will fail recognizing these 2 charsets
$v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UCS-4', $str), 'UCS-4', 'UTF-8'));
$this->assertEquals($sendString, $v->scalarval());
$v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UTF-16', $str), 'UTF-16', 'UTF-8'));
$this->assertEquals($sendString, $v->scalarval());
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
}
public function testExoticCharsetsRequests2()
{
// note that we should disable this call also when mbstring is missing server-side
if (!function_exists('mb_convert_encoding')) {
$this->markTestSkipped('Miss mbstring extension to test exotic charsets');
return;
}
$sendString = '安室奈美恵'; // No idea what this means :-) NB: NOT a valid ISO8859 string!
$str = '<?xml version="1.0"?>
<methodCall>
<methodName>examples.stringecho</methodName>
<params>
<param>
<value><string>'.$sendString.'</string></value>
</param>
</params>
</methodCall>';
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
// no encoding declaration either in the http header or xml prolog, let mb_detect_encoding
// (used on the server side) sort it out
$this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=EUC-JP&DETECT_ENCODINGS[]=UTF-8';
$v = $this->send(mb_convert_encoding($str, 'EUC-JP', 'UTF-8'));
$this->assertEquals($sendString, $v->scalarval());
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
}
public function testExoticCharsetsRequests3()
{
// note that we should disable this call also when mbstring is missing server-side
if (!function_exists('mb_convert_encoding')) {
$this->markTestSkipped('Miss mbstring extension to test exotic charsets');
return;
}
$sendString = utf8_decode('élève');
$str = '<?xml version="1.0"?>
<methodCall>
<methodName>examples.stringecho</methodName>
<params>
<param>
<value><string>'.$sendString.'</string></value>
</param>
</params>
</methodCall>';
// no encoding declaration either in the http header or xml prolog, let mb_detect_encoding
// (used on the server side) sort it out
$this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=ISO-8859-1&DETECT_ENCODINGS[]=UTF-8';
$v = $this->send($str);
$this->assertEquals($sendString, $v->scalarval());
}
/*public function testLatin1Method()
{
$f = new xmlrpcmsg("tests.iso88591methodname." . chr(224) . chr(252) . chr(232), array(
new xmlrpcval('hello')
));
$v = $this->send($f);
if ($v) {
$this->assertEquals('hello', $v->scalarval());
}
}*/
public function testUtf8Method()
{
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
$m = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array(
new xmlrpcval('hello')
));
$v = $this->send($m);
if ($v) {
$this->assertEquals('hello', $v->scalarval());
}
PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
}
public function testAddingDoubles()
{
// note that rounding errors mean we
// keep precision to sensible levels here ;-)
$a = 12.13;
$b = -23.98;
$m = new xmlrpcmsg('examples.addtwodouble', array(
new xmlrpcval($a, 'double'),
new xmlrpcval($b, 'double'),
));
$v = $this->send($m);
if ($v) {
$this->assertEquals($a + $b, $v->scalarval());
}
}
public function testAdding()
{
$m = new xmlrpcmsg('examples.addtwo', array(
new xmlrpcval(12, 'int'),
new xmlrpcval(-23, 'int'),
));
$v = $this->send($m);
if ($v) {
$this->assertEquals(12 - 23, $v->scalarval());
}
}
public function testInvalidNumber()
{
$m = new xmlrpcmsg('examples.addtwo', array(
new xmlrpcval('fred', 'int'),
new xmlrpcval("\"; exec('ls')", 'int'),
));
$v = $this->send($m);
/// @todo a fault condition should be generated here
/// by the server, which we pick up on
if ($v) {
$this->assertEquals(0, $v->scalarval());
}
}
public function testBoolean()
{
$m = new xmlrpcmsg('examples.invertBooleans', array(
new xmlrpcval(array(
new xmlrpcval(true, 'boolean'),
new xmlrpcval(false, 'boolean'),
new xmlrpcval(1, 'boolean'),
new xmlrpcval(0, 'boolean')
),
'array'
),));
$answer = '0101';
$v = $this->send($m);
if ($v) {
$sz = $v->arraysize();
$got = '';
for ($i = 0; $i < $sz; $i++) {
$b = $v->arraymem($i);
if ($b->scalarval()) {
$got .= '1';
} else {
$got .= '0';
}
}
$this->assertEquals($answer, $got);
}
}
public function testBase64()
{
$sendString = 'Mary had a little lamb,
Whose fleece was white as snow,
And everywhere that Mary went
the lamb was sure to go.
Mary had a little lamb
She tied it to a pylon
Ten thousand volts went down its back
And turned it into nylon';
$m = new xmlrpcmsg('examples.decode64', array(
new xmlrpcval($sendString, 'base64'),
));
$v = $this->send($m);
if ($v) {
if (strlen($sendString) == strlen($v->scalarval())) {
$this->assertEquals($sendString, $v->scalarval());
} else {
$this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval());
}
}
}
public function testDateTime()
{
$time = time();
$t1 = new xmlrpcval($time, 'dateTime.iso8601');
$t2 = new xmlrpcval(iso8601_encode($time), 'dateTime.iso8601');
$this->assertEquals($t1->serialize(), $t2->serialize());
if (class_exists('DateTime')) {
$datetime = new DateTime();
// skip this test for php 5.2. It is a bit harder there to build a DateTime from unix timestamp with proper TZ info
if (is_callable(array($datetime, 'setTimestamp'))) {
$t3 = new xmlrpcval($datetime->setTimestamp($time), 'dateTime.iso8601');
$this->assertEquals($t1->serialize(), $t3->serialize());
}
}
}
public function testCountEntities()
{
$sendString = "h'fd>onc>>l>>rw&bpu>q>e<v&gxs<ytjzkami<";
$m = new xmlrpcmsg('validator1.countTheEntities', array(
new xmlrpcval($sendString, 'string'),
));
$v = $this->send($m);
if ($v) {
$got = '';
$expected = '37210';
$expect_array = array('ctLeftAngleBrackets', 'ctRightAngleBrackets', 'ctAmpersands', 'ctApostrophes', 'ctQuotes');
while (list(, $val) = each($expect_array)) {
$b = $v->structmem($val);
$got .= $b->me['int'];
}
$this->assertEquals($expected, $got);
}
}
public function _multicall_msg($method, $params)
{
$struct['methodName'] = new xmlrpcval($method, 'string');
$struct['params'] = new xmlrpcval($params, 'array');
return new xmlrpcval($struct, 'struct');
}
public function testServerMulticall()
{
// We manually construct a system.multicall() call to ensure
// that the server supports it.
// NB: This test will NOT pass if server does not support system.multicall.
// Based on http://xmlrpc-c.sourceforge.net/hacks/test_multicall.py
$good1 = $this->_multicall_msg(
'system.methodHelp',
array(php_xmlrpc_encode('system.listMethods')));
$bad = $this->_multicall_msg(
'test.nosuch',
array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
$recursive = $this->_multicall_msg(
'system.multicall',
array(new xmlrpcval(array(), 'array')));
$good2 = $this->_multicall_msg(
'system.methodSignature',
array(php_xmlrpc_encode('system.listMethods')));
$arg = new xmlrpcval(
array($good1, $bad, $recursive, $good2),
'array'
);
$m = new xmlrpcmsg('system.multicall', array($arg));
$v = $this->send($m);
if ($v) {
//$this->assertTrue($r->faultCode() == 0, "fault from system.multicall");
$this->assertTrue($v->arraysize() == 4, "bad number of return values");
$r1 = $v->arraymem(0);
$this->assertTrue(
$r1->kindOf() == 'array' && $r1->arraysize() == 1,
"did not get array of size 1 from good1"
);
$r2 = $v->arraymem(1);
$this->assertTrue(
$r2->kindOf() == 'struct',
"no fault from bad"
);
$r3 = $v->arraymem(2);
$this->assertTrue(
$r3->kindOf() == 'struct',
"recursive system.multicall did not fail"
);
$r4 = $v->arraymem(3);
$this->assertTrue(
$r4->kindOf() == 'array' && $r4->arraysize() == 1,
"did not get array of size 1 from good2"
);
}
}
public function testClientMulticall1()
{
// NB: This test will NOT pass if server does not support system.multicall.
$this->client->no_multicall = false;
$good1 = new xmlrpcmsg('system.methodHelp',
array(php_xmlrpc_encode('system.listMethods')));
$bad = new xmlrpcmsg('test.nosuch',
array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
$recursive = new xmlrpcmsg('system.multicall',
array(new xmlrpcval(array(), 'array')));
$good2 = new xmlrpcmsg('system.methodSignature',
array(php_xmlrpc_encode('system.listMethods'))
);
$r = $this->send(array($good1, $bad, $recursive, $good2));
if ($r) {
$this->assertTrue(count($r) == 4, "wrong number of return values");
}
$this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
if (!$r[0]->faultCode()) {
$val = $r[0]->value();
$this->assertTrue(
$val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
"good1 did not return string"
);
}
$this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
$this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
$this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
if (!$r[3]->faultCode()) {
$val = $r[3]->value();
$this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
}
// This is the only assert in this test which should fail
// if the test server does not support system.multicall.
$this->assertTrue($this->client->no_multicall == false,
"server does not support system.multicall"
);
}
public function testClientMulticall2()
{
// NB: This test will NOT pass if server does not support system.multicall.
$this->client->no_multicall = true;
$good1 = new xmlrpcmsg('system.methodHelp',
array(php_xmlrpc_encode('system.listMethods')));
$bad = new xmlrpcmsg('test.nosuch',
array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
$recursive = new xmlrpcmsg('system.multicall',
array(new xmlrpcval(array(), 'array')));
$good2 = new xmlrpcmsg('system.methodSignature',
array(php_xmlrpc_encode('system.listMethods'))
);
$r = $this->send(array($good1, $bad, $recursive, $good2));
if ($r) {
$this->assertTrue(count($r) == 4, "wrong number of return values");
}
$this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
if (!$r[0]->faultCode()) {
$val = $r[0]->value();
$this->assertTrue(
$val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
"good1 did not return string");
}
$this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
$this->assertTrue($r[2]->faultCode() == 0, "fault from (non recursive) system.multicall");
$this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
if (!$r[3]->faultCode()) {
$val = $r[3]->value();
$this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
}
}
public function testClientMulticall3()
{
// NB: This test will NOT pass if server does not support system.multicall.
$this->client->return_type = 'phpvals';
$this->client->no_multicall = false;
$good1 = new xmlrpcmsg('system.methodHelp',
array(php_xmlrpc_encode('system.listMethods')));
$bad = new xmlrpcmsg('test.nosuch',
array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
$recursive = new xmlrpcmsg('system.multicall',
array(new xmlrpcval(array(), 'array')));
$good2 = new xmlrpcmsg('system.methodSignature',
array(php_xmlrpc_encode('system.listMethods'))
);
$r = $this->send(array($good1, $bad, $recursive, $good2));
if ($r) {
$this->assertTrue(count($r) == 4, "wrong number of return values");
}
$this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
if (!$r[0]->faultCode()) {
$val = $r[0]->value();
$this->assertTrue(
is_string($val), "good1 did not return string");
}
$this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
$this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
$this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
if (!$r[3]->faultCode()) {
$val = $r[3]->value();
$this->assertTrue(is_array($val), "good2 did not return array");
}
$this->client->return_type = 'xmlrpcvals';
}
public function testCatchWarnings()
{
$m = new xmlrpcmsg('tests.generatePHPWarning', array(
new xmlrpcval('whatever', 'string'),
));
$v = $this->send($m);
if ($v) {
$this->assertEquals(true, $v->scalarval());
}
}
public function testCatchExceptions()
{
$m = new xmlrpcmsg('tests.raiseException', array(
new xmlrpcval('whatever', 'string'),
));
$v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
$this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1';
$v = $this->send($m, 1); // the error code of the expected exception
$this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2';
// depending on whether display_errors is ON or OFF on the server, we will get back a different error here,
// as php will generate an http status code of either 200 or 500...
$v = $this->send($m, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error']));
}
public function testZeroParams()
{
$m = new xmlrpcmsg('system.listMethods');
$v = $this->send($m);
}
public function testNullParams()
{
$m = new xmlrpcmsg('tests.getStateName.12', array(
new xmlrpcval('whatever', 'null'),
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
if ($v) {
$this->assertEquals('Michigan', $v->scalarval());
}
$m = new xmlrpcmsg('tests.getStateName.12', array(
new xmlrpcval(23, 'int'),
new xmlrpcval('whatever', 'null'),
));
$v = $this->send($m);
if ($v) {
$this->assertEquals('Michigan', $v->scalarval());
}
$m = new xmlrpcmsg('tests.getStateName.12', array(
new xmlrpcval(23, 'int')
));
$v = $this->send($m, array($GLOBALS['xmlrpcerr']['incorrect_params']));
}
public function testCodeInjectionServerSide()
{
$m = new xmlrpcmsg('system.MethodHelp');
$m->payload = "<?xml version=\"1.0\"?><methodCall><methodName>validator1.echoStructTest</methodName><params><param><value><struct><member><name>','')); echo('gotcha!'); die(); //</name></member></struct></value></param></params></methodCall>";
$v = $this->send($m);
if ($v) {
$this->assertEquals(0, $v->structsize());
}
}
public function testServerWrappedFunction()
{
$m = new xmlrpcmsg('tests.getStateName.2', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
// this generates an exception in the function which was wrapped, which is by default wrapped in a known error response
$m = new xmlrpcmsg('tests.getStateName.2', array(
new xmlrpcval(0, 'int'),
));
$v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
// check if the generated function dispatch map is fine, by checking if the server registered it
$m = new xmlrpcmsg('system.methodSignature', array(
new xmlrpcval('tests.getStateName.2'),
));
$v = $this->send($m);
$encoder = new \PhpXmlRpc\Encoder();
$this->assertEquals(array(array('string', 'int')), $encoder->decode($v));
}
public function testServerWrappedFunctionAsSource()
{
$m = new xmlrpcmsg('tests.getStateName.6', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
// this generates an exception in the function which was wrapped, which is by default wrapped in a known error response
$m = new xmlrpcmsg('tests.getStateName.6', array(
new xmlrpcval(0, 'int'),
));
$v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
}
public function testServerWrappedObjectMethods()
{
$m = new xmlrpcmsg('tests.getStateName.3', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.4', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.5', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.7', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.8', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.9', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
}
public function testServerWrappedObjectMethodsAsSource()
{
$m = new xmlrpcmsg('tests.getStateName.7', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.8', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
$m = new xmlrpcmsg('tests.getStateName.9', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
}
public function testServerClosure()
{
$m = new xmlrpcmsg('tests.getStateName.10', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
}
public function testServerWrappedClosure()
{
$m = new xmlrpcmsg('tests.getStateName.11', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
}
public function testServerWrappedClass()
{
$m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array(
new xmlrpcval(23, 'int'),
));
$v = $this->send($m);
$this->assertEquals('Michigan', $v->scalarval());
}
public function testWrappedMethod()
{
// make a 'deep client copy' as the original one might have many properties set
$func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0));
if ($func == false) {
$this->fail('Registration of examples.getStateName failed');
} else {
$v = $func(23);
// work around bug in current (or old?) version of phpunit when reporting the error
/*if (is_object($v)) {
$v = var_export($v, true);
}*/
$this->assertEquals('Michigan', $v);
}
}
public function testWrappedMethodAsSource()
{
// make a 'deep client copy' as the original one might have many properties set
$func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0, 'return_source' => true));
if ($func == false) {
$this->fail('Registration of examples.getStateName failed');
} else {
eval($func['source']);
$func = $func['function'];
$v = $func(23);
// work around bug in current (or old?) version of phpunit when reporting the error
/*if (is_object($v)) {
$v = var_export($v, true);
}*/
$this->assertEquals('Michigan', $v);
}
}
public function testWrappedClass()
{
// make a 'deep client copy' as the original one might have many properties set
// also for speed only wrap one method of the whole server
$class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 0, 'method_filter' => '/examples\.getStateName/' ));
if ($class == '') {
$this->fail('Registration of remote server failed');
} else {
$obj = new $class();
$v = $obj->examples_getStateName(23);
// work around bug in current (or old?) version of phpunit when reporting the error
/*if (is_object($v)) {
$v = var_export($v, true);
}*/
$this->assertEquals('Michigan', $v);
}
}
public function testTransferOfObjectViaWrapping()
{
// make a 'deep client copy' as the original one might have many properties set
$func = wrap_xmlrpc_method($this->client, 'tests.returnPhpObject', array('simple_client_copy' => true,
'decode_php_objs' => true));
if ($func == false) {
$this->fail('Registration of tests.returnPhpObject failed');
} else {
$v = $func();
$obj = new stdClass();
$obj->hello = 'world';
$this->assertEquals($obj, $v);
}
}
public function testGetCookies()
{
// let server set to us some cookies we tell it
$cookies = array(
//'c1' => array(),
'c2' => array('value' => 'c2'),
'c3' => array('value' => 'c3', 'expires' => time() + 60 * 60 * 24 * 30),
'c4' => array('value' => 'c4', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/'),
'c5' => array('value' => 'c5', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'localhost'),
);
$cookiesval = php_xmlrpc_encode($cookies);
$m = new xmlrpcmsg('examples.setcookies', array($cookiesval));
$r = $this->send($m, 0, true);
if ($r) {
$v = $r->value();
$this->assertEquals(1, $v->scalarval());
// now check if we decoded the cookies as we had set them
$rcookies = $r->cookies();
// remove extra cookies which might have been set by proxies
foreach ($rcookies as $c => $v) {
if (!in_array($c, array('c2', 'c3', 'c4', 'c5'))) {
unset($rcookies[$c]);
}
// Seems like we get this when using php-fpm and php 5.5+ ...
if (isset($rcookies[$c]['Max-Age'])) {
unset($rcookies[$c]['Max-Age']);
}
}
foreach ($cookies as $c => $v) {
// format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT'
// but PHP versions differ on that, some use 'Mon, 31-Oct-2005 13:50:56 GMT'...
if (isset($v['expires'])) {
if (isset($rcookies[$c]['expires']) && strpos($rcookies[$c]['expires'], '-')) {
$cookies[$c]['expires'] = gmdate('D, d\-M\-Y H:i:s \G\M\T', $cookies[$c]['expires']);
} else {
$cookies[$c]['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $cookies[$c]['expires']);
}
}
}
$this->assertEquals($cookies, $rcookies);
}
}
public function testSetCookies()
{
// let server set to us some cookies we tell it
$cookies = array(
'c0' => null,
'c1' => 1,
'c2' => '2 3',
'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-',
);
$m = new xmlrpcmsg('examples.getcookies', array());
foreach ($cookies as $cookie => $val) {
$this->client->setCookie($cookie, $val);
$cookies[$cookie] = (string)$cookies[$cookie];
}
$r = $this->client->send($m, $this->timeout, $this->method);
$this->assertEquals(0, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
if (!$r->faultCode()) {
$v = $r->value();
$v = php_xmlrpc_decode($v);
// take care for the extra cookie used for coverage collection
if (isset($v['PHPUNIT_SELENIUM_TEST_ID'])) {
unset($v['PHPUNIT_SELENIUM_TEST_ID']);
}
// on IIS and Apache getallheaders returns something slightly different...
$this->assertEquals($cookies, $v);
}
}
public function testServerComments()
{
$m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array(
new xmlrpcval('hello world', 'string'),
));
$r = $this->send($m, 0, true);
$this->assertContains('hello world', $r->raw_data);
}
public function testSendTwiceSameMsg()
{
$m = new xmlrpcmsg('examples.stringecho', array(
new xmlrpcval('hello world', 'string'),
));
$v1 = $this->send($m);
$v2 = $this->send($m);
if ($v1 && $v2) {
$this->assertEquals($v1, $v2);
}
}
}

View File

@@ -0,0 +1,215 @@
<?php
include_once __DIR__ . '/../lib/xmlrpc.inc';
include_once __DIR__ . '/../lib/xmlrpc_wrappers.inc';
include_once __DIR__ . '/parse_args.php';
include_once __DIR__ . '/3LocalhostTest.php';
/**
* Tests which stress http features of the library.
* Each of these tests iterates over (almost) all of the 'localhost' tests
*/
class LocalhostMultiTest extends LocalhostTest
{
/**
* @todo reintroduce skipping of tests which failed when executed individually if test runs happen as separate processes
* @todo reintroduce skipping of tests within the loop
*/
function _runtests()
{
$unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments', 'testExoticCharsetsRequests', 'testExoticCharsetsRequests2', 'testExoticCharsetsRequests3');
foreach(get_class_methods('LocalhostTest') as $method)
{
if(strpos($method, 'test') === 0 && !in_array($method, $unsafeMethods))
{
if (!isset(self::$failed_tests[$method]))
$this->$method();
}
/*if ($this->_failed)
{
break;
}*/
}
}
function testDeflate()
{
if(!function_exists('gzdeflate'))
{
$this->markTestSkipped('Zlib missing: cannot test deflate functionality');
return;
}
$this->client->accepted_compression = array('deflate');
$this->client->request_compression = 'deflate';
$this->_runtests();
}
function testGzip()
{
if(!function_exists('gzdeflate'))
{
$this->markTestSkipped('Zlib missing: cannot test gzip functionality');
return;
}
$this->client->accepted_compression = array('gzip');
$this->client->request_compression = 'gzip';
$this->_runtests();
}
function testKeepAlives()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test http 1.1');
return;
}
$this->method = 'http11';
$this->client->keepalive = true;
$this->_runtests();
}
function testProxy()
{
if ($this->args['PROXYSERVER'])
{
$this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
$this->_runtests();
}
else
$this->markTestSkipped('PROXY definition missing: cannot test proxy');
}
function testHttp11()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test http 1.1');
return;
}
$this->method = 'http11'; // not an error the double assignment!
$this->client->method = 'http11';
//$this->client->verifyhost = 0;
//$this->client->verifypeer = 0;
$this->client->keepalive = false;
$this->_runtests();
}
function testHttp11Gzip()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test http 1.1');
return;
}
$this->method = 'http11'; // not an error the double assignment!
$this->client->method = 'http11';
$this->client->keepalive = false;
$this->client->accepted_compression = array('gzip');
$this->client->request_compression = 'gzip';
$this->_runtests();
}
function testHttp11Deflate()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test http 1.1');
return;
}
$this->method = 'http11'; // not an error the double assignment!
$this->client->method = 'http11';
$this->client->keepalive = false;
$this->client->accepted_compression = array('deflate');
$this->client->request_compression = 'deflate';
$this->_runtests();
}
function testHttp11Proxy()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test http 1.1 w. proxy');
return;
}
else if ($this->args['PROXYSERVER'] == '')
{
$this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1');
return;
}
$this->method = 'http11'; // not an error the double assignment!
$this->client->method = 'http11';
$this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
//$this->client->verifyhost = 0;
//$this->client->verifypeer = 0;
$this->client->keepalive = false;
$this->_runtests();
}
function testHttps()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test https functionality');
return;
}
$this->client->server = $this->args['HTTPSSERVER'];
$this->method = 'https';
$this->client->method = 'https';
$this->client->path = $this->args['HTTPSURI'];
$this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']);
$this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']);
$this->client->setSSLVersion($this->args['SSLVERSION']);
$this->_runtests();
}
function testHttpsProxy()
{
if(!function_exists('curl_init'))
{
$this->markTestSkipped('CURL missing: cannot test https functionality');
return;
}
else if ($this->args['PROXYSERVER'] == '')
{
$this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1');
return;
}
$this->client->server = $this->args['HTTPSSERVER'];
$this->method = 'https';
$this->client->method = 'https';
$this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
$this->client->path = $this->args['HTTPSURI'];
$this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']);
$this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']);
$this->client->setSSLVersion($this->args['SSLVERSION']);
$this->_runtests();
}
function testUTF8Responses()
{
//$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8';
$this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=UTF-8';
$this->_runtests();
}
function testUTF8Requests()
{
$this->client->request_charset_encoding = 'UTF-8';
$this->_runtests();
}
function testISOResponses()
{
//$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8';
$this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=ISO-8859-1';
$this->_runtests();
}
function testISORequests()
{
$this->client->request_charset_encoding = 'ISO-8859-1';
$this->_runtests();
}
}

View File

@@ -0,0 +1,76 @@
<?php
include_once __DIR__ . '/LocalFileTestCase.php';
/**
* Tests for php files in the 'demo' directory
*/
class DemoFilesTest extends PhpXmlRpc_LocalFileTestCase
{
public function setUp()
{
$this->args = argParser::getArgs();
$this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/demo/', $this->args['URI'] );
$this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
}
public function testAgeSort()
{
$page = $this->request('client/agesort.php');
}
public function testGetStateName()
{
$page = $this->request('client/getstatename.php');
$page = $this->request('client/getstatename.php', 'POST', array('stateno' => '1'));
}
public function testIntrospect()
{
$page = $this->request('client/introspect.php');
}
public function testMail()
{
$page = $this->request('client/mail.php');
$page = $this->request('client/mail.php', 'POST', array(
"mailto" => '',
"mailsub" => '',
"mailmsg" => '',
"mailfrom" => '',
"mailcc" => '',
"mailbcc" => '',
));
}
public function testProxy()
{
$page = $this->request('client/proxy.php', 'GET', null, true);
}
public function testWhich()
{
$page = $this->request('client/which.php');
}
public function testWrap()
{
$page = $this->request('client/wrap.php');
}
public function testDiscussServer()
{
$page = $this->request('server/discuss.php');
$this->assertContains('<name>faultCode</name>', $page);
$this->assertRegexp('#<int>10(5|3)</int>#', $page);
}
public function testProxyServer()
{
$page = $this->request('server/proxy.php');
$this->assertContains('<name>faultCode</name>', $page);
$this->assertRegexp('#<int>10(5|3)</int>#', $page);
}
}

View File

@@ -0,0 +1,37 @@
<?php
include_once __DIR__ . '/LocalFileTestCase.php';
class DebuggerTest extends PhpXmlRpc_LocalFileTestCase
{
public function setUp()
{
$this->args = argParser::getArgs();
$this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/debugger/', $this->args['URI'] );
$this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
}
public function testIndex()
{
$page = $this->request('index.php');
}
public function testController()
{
$page = $this->request('controller.php');
}
/**
* @todo test:
* - list methods
* - describe a method
* - execute a method
* - wrap a method
*/
public function testAction()
{
$page = $this->request('action.php');
}
}

View File

@@ -0,0 +1,23 @@
<?php
include_once __DIR__ . '/LocalFileTestCase.php';
/**
* Tests for php files in the 'extras' directory
*/
class ExtraTest extends PhpXmlRpc_LocalFileTestCase
{
public function setUp()
{
$this->args = argParser::getArgs();
$this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/tests/', $this->args['URI'] );
$this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
}
public function testVerifyCompat()
{
$page = $this->request('verify_compat.php');
}
}

View File

@@ -0,0 +1,80 @@
<?php
include_once __DIR__ . '/parse_args.php';
abstract class PhpXmlRpc_LocalFileTestCase extends PHPUnit_Framework_TestCase
{
public $args = array();
protected $baseUrl;
protected $testId;
/** @var boolean $collectCodeCoverageInformation */
protected $collectCodeCoverageInformation;
protected $coverageScriptUrl;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->testId = get_class($this) . '__' . $this->getName();
if ($result === NULL) {
$result = $this->createResult();
}
$this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation();
parent::run($result);
if ($this->collectCodeCoverageInformation) {
$coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage(
$this->coverageScriptUrl,
$this->testId
);
$result->getCodeCoverage()->append(
$coverage->get(), $this
);
}
// do not call this before to give the time to the Listeners to run
//$this->getStrategy()->endOfTest($this->session);
return $result;
}
protected function request($file, $method = 'GET', $payload = '', $emptyPageOk = false)
{
$url = $this->baseUrl . $file;
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true
));
if ($method == 'POST')
{
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload
));
}
if ($this->collectCodeCoverageInformation)
{
curl_setopt($ch, CURLOPT_COOKIE, 'PHPUNIT_SELENIUM_TEST_ID=true');
}
if ($this->args['DEBUG'] > 0) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
$page = curl_exec($ch);
curl_close($ch);
$this->assertNotFalse($page);
if (!$emptyPageOk) {
$this->assertNotEquals('', $page);
}
$this->assertNotContains('Fatal error', $page);
$this->assertNotContains('Notice:', $page);
return $page;
}
}

View File

@@ -0,0 +1,311 @@
<?php
/**
* Benchmarking suite for the PHP-XMLRPC lib.
*
* @author Gaetano Giunta
* @copyright (c) 2005-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*
* @todo add a test for response ok in call testing
* @todo add support for --help option to give users the list of supported parameters
**/
use PhpXmlRpc\PhpXmlRpc;
use PhpXmlRpc\Value;
use PhpXmlRpc\Request;
use PhpXmlRpc\Client;
use PhpXmlRpc\Response;
use PhpXmlRpc\Encoder;
include_once __DIR__ . '/../vendor/autoload.php';
include __DIR__ . '/parse_args.php';
$args = argParser::getArgs();
function begin_test($test_name, $test_case)
{
global $test_results;
if (!isset($test_results[$test_name])) {
$test_results[$test_name] = array();
}
$test_results[$test_name][$test_case] = array();
$test_results[$test_name][$test_case]['time'] = microtime(true);
}
function end_test($test_name, $test_case, $test_result)
{
global $test_results;
$end = microtime(true);
if (!isset($test_results[$test_name][$test_case])) {
trigger_error('ending test that was not started');
}
$test_results[$test_name][$test_case]['time'] = $end - $test_results[$test_name][$test_case]['time'];
$test_results[$test_name][$test_case]['result'] = $test_result;
echo '.';
flush();
@ob_flush();
}
// Set up PHP structures to be used in many tests
$data1 = array(1, 1.0, 'hello world', true, '20051021T23:43:00', -1, 11.0, '~!@#$%^&*()_+|', false, '20051021T23:43:00');
$data2 = array('zero' => $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1);
$data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2);
$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
// Begin execution
$test_results = array();
$is_web = isset($_SERVER['REQUEST_METHOD']);
$xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable');
if ($xd) {
$num_tests = 1;
} else {
$num_tests = 10;
}
$title = 'XML-RPC Benchmark Tests';
if ($is_web) {
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<title>$title</title>\n</head>\n<body>\n<h1>$title</h1>\n<pre>\n";
} else {
echo "$title\n\n";
}
if ($is_web) {
echo "<h3>Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "</h3>\n";
if ($xd) {
echo "<h4>XDEBUG profiling enabled: skipping remote tests. Trace file is: " . htmlspecialchars(xdebug_get_profiler_filename()) . "</h4>\n";
}
flush();
ob_flush();
} else {
echo "Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "\n";
if ($xd) {
echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: " . xdebug_get_profiler_filename() . "\n";
}
}
// test 'manual style' data encoding vs. 'automatic style' encoding
begin_test('Data encoding (large array)', 'manual encoding');
for ($i = 0; $i < $num_tests; $i++) {
$vals = array();
for ($j = 0; $j < 10; $j++) {
$valarray = array();
foreach ($data[$j] as $key => $val) {
$values = array();
$values[] = new Value($val[0], 'int');
$values[] = new Value($val[1], 'double');
$values[] = new Value($val[2], 'string');
$values[] = new Value($val[3], 'boolean');
$values[] = new Value($val[4], 'dateTime.iso8601');
$values[] = new Value($val[5], 'int');
$values[] = new Value($val[6], 'double');
$values[] = new Value($val[7], 'string');
$values[] = new Value($val[8], 'boolean');
$values[] = new Value($val[9], 'dateTime.iso8601');
$valarray[$key] = new Value($values, 'array');
}
$vals[] = new Value($valarray, 'struct');
}
$value = new Value($vals, 'array');
$out = $value->serialize();
}
end_test('Data encoding (large array)', 'manual encoding', $out);
begin_test('Data encoding (large array)', 'automatic encoding');
$encoder = new Encoder();
for ($i = 0; $i < $num_tests; $i++) {
$value = $encoder->encode($data, array('auto_dates'));
$out = $value->serialize();
}
end_test('Data encoding (large array)', 'automatic encoding', $out);
if (function_exists('xmlrpc_set_type')) {
begin_test('Data encoding (large array)', 'xmlrpc-epi encoding');
for ($i = 0; $i < $num_tests; $i++) {
for ($j = 0; $j < 10; $j++) {
foreach ($keys as $k) {
xmlrpc_set_type($data[$j][$k][4], 'datetime');
xmlrpc_set_type($data[$j][$k][8], 'datetime');
}
}
$out = xmlrpc_encode($data);
}
end_test('Data encoding (large array)', 'xmlrpc-epi encoding', $out);
}
// test 'old style' data decoding vs. 'automatic style' decoding
$dummy = new Request('');
$out = new Response($value);
$in = '<?xml version="1.0" ?>' . "\n" . $out->serialize();
begin_test('Data decoding (large array)', 'manual decoding');
for ($i = 0; $i < $num_tests; $i++) {
$response = $dummy->ParseResponse($in, true);
$value = $response->value();
$result = array();
foreach($value as $val1) {
$out = array();
foreach($val1 as $name => $val) {
$out[$name] = array();
foreach($val as $data) {
$out[$name][] = $data->scalarval();
}
}
$result[] = $out;
}
}
end_test('Data decoding (large array)', 'manual decoding', $result);
begin_test('Data decoding (large array)', 'manual decoding deprecated');
for ($i = 0; $i < $num_tests; $i++) {
$response = $dummy->ParseResponse($in, true);
$value = $response->value();
$result = array();
$l = $value->arraysize();
for ($k = 0; $k < $l; $k++) {
$val1 = $value->arraymem($k);
$out = array();
while (list($name, $val) = $val1->structeach()) {
$out[$name] = array();
$m = $val->arraysize();
for ($j = 0; $j < $m; $j++) {
$data = $val->arraymem($j);
$out[$name][] = $data->scalarval();
}
} // while
$result[] = $out;
}
}
end_test('Data decoding (large array)', 'manual decoding deprecated', $result);
begin_test('Data decoding (large array)', 'automatic decoding');
for ($i = 0; $i < $num_tests; $i++) {
$response = $dummy->ParseResponse($in, true, 'phpvals');
$value = $response->value();
}
end_test('Data decoding (large array)', 'automatic decoding', $value);
if (function_exists('xmlrpc_decode')) {
begin_test('Data decoding (large array)', 'xmlrpc-epi decoding');
for ($i = 0; $i < $num_tests; $i++) {
$response = $dummy->ParseResponse($in, true, 'xml');
$value = xmlrpc_decode($response->value());
}
end_test('Data decoding (large array)', 'xmlrpc-epi decoding', $value);
}
if (!$xd) {
/// test multicall vs. many calls vs. keep-alives
$encoder = new Encoder();
$value = $encoder->encode($data1, array('auto_dates'));
$req = new Request('interopEchoTests.echoValue', array($value));
$reqs = array();
for ($i = 0; $i < 25; $i++) {
$reqs[] = $req;
}
$server = explode(':', $args['LOCALSERVER']);
if (count($server) > 1) {
$srv = $server[1] . '://' . $server[0] . $args['URI'];
$c = new Client($args['URI'], $server[0], $server[1]);
} else {
$srv = $args['LOCALSERVER'] . $args['URI'];
$c = new Client($args['URI'], $args['LOCALSERVER']);
}
// do not interfere with http compression
$c->accepted_compression = array();
//$c->debug=true;
$testName = "Repeated send (small array) to $srv";
if (function_exists('gzinflate')) {
$c->accepted_compression = null;
}
begin_test($testName, 'http 10');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req);
$response[] = $resp->value();
}
end_test($testName, 'http 10', $response);
if (function_exists('curl_init')) {
begin_test($testName, 'http 11 w. keep-alive');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req, 10, 'http11');
$response[] = $resp->value();
}
end_test($testName, 'http 11 w. keep-alive', $response);
$c->keepalive = false;
begin_test($testName, 'http 11');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req, 10, 'http11');
$response[] = $resp->value();
}
end_test($testName, 'http 11', $response);
}
begin_test($testName, 'multicall');
$response = $c->send($reqs);
foreach ($response as $key => & $val) {
$val = $val->value();
}
end_test($testName, 'multicall', $response);
if (function_exists('gzinflate')) {
$c->accepted_compression = array('gzip');
$c->request_compression = 'gzip';
begin_test($testName, 'http 10 w. compression');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req);
$response[] = $resp->value();
}
end_test($testName, 'http 10 w. compression', $response);
if (function_exists('curl_init')) {
begin_test($testName, 'http 11 w. keep-alive and compression');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req, 10, 'http11');
$response[] = $resp->value();
}
end_test($testName, 'http 11 w. keep-alive and compression', $response);
$c->keepalive = false;
begin_test($testName, 'http 11 w. compression');
$response = array();
for ($i = 0; $i < 25; $i++) {
$resp = $c->send($req, 10, 'http11');
$response[] = $resp->value();
}
end_test($testName, 'http 11 w. compression', $response);
}
begin_test($testName, 'multicall w. compression');
$response = $c->send($reqs);
foreach ($response as $key => & $val) {
$val = $val->value();
}
end_test($testName, 'multicall w. compression', $response);
}
} // end of 'if no xdebug profiling'
echo "\n";
foreach ($test_results as $test => $results) {
echo "\nTEST: $test\n";
foreach ($results as $case => $data) {
echo " $case: {$data['time']} secs - Output data CRC: " . crc32(serialize($data['result'])) . "\n";
}
}
if ($is_web) {
echo "\n</pre>\n</body>\n</html>\n";
}

View File

@@ -0,0 +1,68 @@
# Configuration file for Apache running on Travis.
# PHP setup in FCGI mode
<VirtualHost *:80>
DocumentRoot %TRAVIS_BUILD_DIR%
ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
<Directory "%TRAVIS_BUILD_DIR%">
Options FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
# Wire up Apache to use Travis CI's php-fpm.
<IfModule mod_fastcgi.c>
AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
</IfModule>
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
DocumentRoot %TRAVIS_BUILD_DIR%
ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
<Directory "%TRAVIS_BUILD_DIR%">
Options FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
# Wire up Apache to use Travis CI's php-fpm.
<IfModule mod_fastcgi.c>
AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
#FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
</IfModule>
SSLEngine on
# This cert is bundled by default in Ubuntu
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
</IfModule>

View File

@@ -0,0 +1,74 @@
# Configuration file for Apache running on Travis.
# HHVM setup in FCGI mode
<VirtualHost *:80>
DocumentRoot %TRAVIS_BUILD_DIR%
ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
<Directory "%TRAVIS_BUILD_DIR%">
Options FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
# Configure Apache for HHVM FastCGI.
# See https://github.com/facebook/hhvm/wiki/fastcgi
<IfModule mod_fastcgi.c>
<FilesMatch \.php$>
SetHandler hhvm-php-extension
</FilesMatch>
Alias /hhvm /hhvm
Action hhvm-php-extension /hhvm virtual
FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300
</IfModule>
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
DocumentRoot %TRAVIS_BUILD_DIR%
ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
<Directory "%TRAVIS_BUILD_DIR%">
Options FollowSymLinks MultiViews ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
# Configure Apache for HHVM FastCGI.
# See https://github.com/facebook/hhvm/wiki/fastcgi
<IfModule mod_fastcgi.c>
<FilesMatch \.php$>
SetHandler hhvm-php-extension
</FilesMatch>
Alias /hhvm /hhvm
Action hhvm-php-extension /hhvm virtual
#FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300
</IfModule>
SSLEngine on
# This cert is bundled by default in Ubuntu
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
</IfModule>

View File

@@ -0,0 +1 @@
listen-address 127.0.0.1:8080

View File

@@ -0,0 +1,11 @@
#!/bin/sh
# set up Apache for php-fpm
# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php
sudo a2enmod rewrite actions fastcgi alias ssl
# configure apache virtual hosts
sudo cp -f tests/ci/travis/apache_vhost /etc/apache2/sites-available/default
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default
sudo service apache2 restart

View File

@@ -0,0 +1,11 @@
#!/bin/sh
# set up Apache for hhvm-fcgi
# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php
sudo a2enmod rewrite actions fastcgi alias ssl
# configure apache virtual hosts
sudo cp -f tests/ci/travis/apache_vhost_hhvm /etc/apache2/sites-available/default
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default
sudo service apache2 restart

View File

@@ -0,0 +1,4 @@
#!/bin/sh
# start HHVM
hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true

View File

@@ -0,0 +1,11 @@
#!/bin/sh
# enable php-fpm
sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf
# work around travis issue #3385
if [ "$TRAVIS_PHP_VERSION" = "7.0" -a -n "$(ls -A ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d)" ]; then
sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf
fi
echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
echo "always_populate_raw_post_data = -1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm

View File

@@ -0,0 +1,6 @@
#!/bin/sh
# configure privoxy
sudo cp -f tests/ci/travis/privoxy /etc/privoxy/config
sudo service privoxy restart

View File

@@ -0,0 +1,124 @@
<?php
/**
* Common parameter parsing for benchmark and tests scripts.
*
* @param integer DEBUG
* @param string LOCALSERVER
* @param string URI
* @param string HTTPSSERVER
* @param string HTTPSSURI
* @param string PROXY
* @param string NOPROXY
* @param bool HTTPSIGNOREPEER
* @param int HTTPSVERIFYHOST
* @param int SSLVERSION
*
* @copyright (C) 2007-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
**/
class argParser
{
public static function getArgs()
{
global $argv;
$args = array(
'DEBUG' => 0,
'LOCALSERVER' => 'localhost',
'HTTPSSERVER' => 'gggeek.ssl.altervista.org',
'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php',
'HTTPSIGNOREPEER' => false,
'HTTPSVERIFYHOST' => 2,
'SSLVERSION' => 0,
'PROXYSERVER' => null,
'NOPROXY' => false,
'LOCALPATH' => __DIR__,
);
// check for command line vs web page input params
if (!isset($_SERVER['REQUEST_METHOD'])) {
if (isset($argv)) {
foreach ($argv as $param) {
$param = explode('=', $param);
if (count($param) > 1) {
$pname = strtoupper(ltrim($param[0], '-'));
$$pname = $param[1];
}
}
}
} else {
// NB: we might as well consider using $_GET stuff later on...
extract($_GET);
extract($_POST);
}
if (isset($DEBUG)) {
$args['DEBUG'] = intval($DEBUG);
}
if (isset($LOCALSERVER)) {
$args['LOCALSERVER'] = $LOCALSERVER;
} else {
if (isset($HTTP_HOST)) {
$args['LOCALSERVER'] = $HTTP_HOST;
} elseif (isset($_SERVER['HTTP_HOST'])) {
$args['LOCALSERVER'] = $_SERVER['HTTP_HOST'];
}
}
if (isset($HTTPSSERVER)) {
$args['HTTPSSERVER'] = $HTTPSSERVER;
}
if (isset($HTTPSURI)) {
$args['HTTPSURI'] = $HTTPSURI;
}
if (isset($HTTPSIGNOREPEER)) {
$args['HTTPSIGNOREPEER'] = (bool)$HTTPSIGNOREPEER;
}
if (isset($HTTPSVERIFYHOST)) {
$args['HTTPSVERIFYHOST'] = (int)$HTTPSVERIFYHOST;
}
if (isset($SSLVERSION)) {
$args['SSLVERSION'] = (int)$SSLVERSION;
}
if (isset($PROXY)) {
$arr = explode(':', $PROXY);
$args['PROXYSERVER'] = $arr[0];
if (count($arr) > 1) {
$args['PROXYPORT'] = $arr[1];
} else {
$args['PROXYPORT'] = 8080;
}
}
// used to silence testsuite warnings about proxy code not being tested
if (isset($NOPROXY)) {
$args['NOPROXY'] = true;
}
if (!isset($URI)) {
// GUESTIMATE the url of local demo server
// play nice to php 3 and 4-5 in retrieving URL of server.php
/// @todo filter out query string from REQUEST_URI
if (isset($REQUEST_URI)) {
$URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $REQUEST_URI);
$URI = str_replace('/testsuite.php', '/server.php', $URI);
$URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI);
$URI = str_replace('/benchmark.php', '/server.php', $URI);
} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['REQUEST_METHOD'])) {
$URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']);
$URI = str_replace('/testsuite.php', '/server.php', $URI);
$URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI);
$URI = str_replace('/benchmark.php', '/server.php', $URI);
} else {
$URI = '/demo/server/server.php';
}
}
if ($URI[0] != '/') {
$URI = '/' . $URI;
}
$args['URI'] = $URI;
if (isset($LOCALPATH)) {
$args['LOCALPATH'] = $LOCALPATH;
}
return $args;
}
}

View File

@@ -0,0 +1,16 @@
<?php
/**
* Used to serve back the server-side code coverage results to phpunit-selenium
*
* @copyright (C) 2007-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
**/
$coverageFile = realpath(__DIR__ . "/../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/phpunit_coverage.php");
// has to be the same value as used in server.php
$GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = '/tmp/phpxmlrpc_coverage';
chdir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY']);
include_once $coverageFile;

View File

@@ -0,0 +1,193 @@
<?php
/**
* Verify compatibility level of current php install with php-xmlrpc lib.
*
* @author Gaetano Giunta
* @copyright (C) 2006-2015 G. Giunta
* @license code licensed under the BSD License: see file license.txt
*
* @todo add a test for php output buffering?
*/
function phpxmlrpc_verify_compat($mode = 'client')
{
$tests = array();
if ($mode == 'server') {
// test for php version
$ver = phpversion();
$tests['php_version'] = array();
$tests['php_version']['description'] = 'PHP version found: ' . $ver . ".\n\n";
if (version_compare($ver, '5.3.0') < 0) {
$tests['php_version']['status'] = 0;
$tests['php_version']['description'] .= 'This version of PHP is not compatible with this release of the PHP XMLRPC library. Please upgrade to php 5.1.0 or later';
} else {
$tests['php_version']['status'] = 2;
$tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
}
// test for zlib
$tests['zlib'] = array();
if (!function_exists('gzinflate')) {
$tests['zlib']['status'] = 0;
$tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to receive compressed requests or send compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
} else {
$tests['zlib']['status'] = 2;
$tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to receive compressed requests and send compressed responses for the 'HTTP' protocol";
}
// test for dispaly of php errors in xml reponse
if (ini_get('display_errors')) {
if (intval(ini_get('error_reporting')) && E_NOTICE) {
$tests['display_errors']['status'] = 1;
$tests['display_errors']['description'] = "Error reporting level includes E_NOTICE errors, and display_errors is set to ON.\n\nAny error, warning or notice raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
} else {
$tests['display_errors']['status'] = 1;
$tests['display_errors']['description'] = "display_errors is set to ON.\n\nAny error raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
}
}
} else {
// test for php version
$ver = phpversion();
$tests['php_version'] = array();
$tests['php_version']['description'] = 'PHP version found: ' . $ver . ".\n\n";
if (version_compare($ver, '5.3.0') < 0) {
$tests['php_version']['status'] = 0;
$tests['php_version']['description'] .= 'This version of PHP is not compatible with the PHP XMLRPC library. Please upgrade to 5.1.0 or later';
} else {
$tests['php_version']['status'] = 2;
$tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
}
// test for zlib
$tests['zlib'] = array();
if (!function_exists('gzinflate')) {
$tests['zlib']['status'] = 0;
$tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to send compressed requests or receive compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
} else {
$tests['zlib']['status'] = 2;
$tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to send compressed requests and receive compressed responses for the 'HTTP' protocol";
}
// test for CURL
$tests['curl'] = array();
if (!extension_loaded('curl')) {
$tests['curl']['status'] = 0;
$tests['curl']['description'] = "The cURL extension is not enabled.\n\nYou will not be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
} else {
$info = curl_version();
$tests['curl']['status'] = 2;
$tests['curl']['description'] = "The cURL extension is enabled.\n\nYou will be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
if (version_compare($ver, '4.3.8') < 0) {
$tests['curl']['status'] = 1;
$tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support keep-alives";
}
if (!((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) {
$tests['curl']['status'] = 1;
$tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support compressed messages";
}
if (!((is_string($info) && strpos($info, 'OpenSSL') !== null) || isset($info['ssl_version']))) {
$tests['curl']['status'] = 1;
$tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support HTTPS connections";
}
}
}
return $tests;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>PHP XMLRPC compatibility assessment</title>
<style type="text/css">
body, html {
background-color: white;
font-family: Arial, Verdana, Geneva, sans-serif;
font-size: small;
}
table {
border: 1px solid gray;
padding: 0;
}
thead {
background-color: silver;
color: black;
}
td {
margin: 0;
padding: 0.5em;
}
tbody td {
border-top: 1px solid gray;
}
.res0 {
background-color: red;
color: black;
border-right: 1px solid gray;
}
.res1 {
background-color: yellow;
color: black;
border-right: 1px solid gray;
}
.res2 {
background-color: green;
color: black;
border-right: 1px solid gray;
}
.result {
white-space: pre;
}
</style>
</head>
<body>
<h1>PHPXMLRPC compatibility assessment with the current PHP install</h1>
<h4>For phpxmlrpc version 4.0 or later</h4>
<h3>Server usage</h3>
<table cellspacing="0">
<thead>
<tr>
<td>Test</td>
<td>Result</td>
</tr>
</thead>
<tbody>
<?php
$res = phpxmlrpc_verify_compat('server');
foreach ($res as $test => $result) {
echo '<tr><td class="res' . $result['status'] . '">' . htmlspecialchars($test) . '</td><td class="result">' . htmlspecialchars($result['description']) . "</td></tr>\n";
}
?>
</tbody>
</table>
<h3>Client usage</h3>
<table cellspacing="0">
<thead>
<tr>
<td>Test</td>
<td>Result</td>
</tr>
</thead>
<tbody>
<?php
$res = phpxmlrpc_verify_compat('client');
foreach ($res as $test => $result) {
echo '<tr><td class="res' . $result['status'] . '">' . htmlspecialchars($test) . '</td><td class="result">' . htmlspecialchars($result['description']) . "</td></tr>\n";
}
?>
</tbody>
</table>
</body>
</html>

3640
lib/xmlrpc.inc Normal file

File diff suppressed because it is too large Load Diff

818
lib/xmlrpc_wrappers.inc Normal file
View File

@@ -0,0 +1,818 @@
<?php
/**
* PHP-XMLRPC "wrapper" functions
* Generate stubs to transparently access xmlrpc methods as php functions and viceversa
*
* @version $Id: xmlrpc_wrappers.inc,v 1.10 2006/09/01 21:49:19 ggiunta Exp $
* @copyright G. Giunta (C) 2006
* @author Gaetano Giunta
*
* @todo separate introspection from code generation for func-2-method wrapping
* @todo use some better templating system from code generation?
* @todo implement method wrapping with preservation of php objs in calls
* @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
* @todo implement self-parsing of php code for PHP <= 4
*/
// requires: xmlrpc.inc
/**
* Given a string defining a php type or phpxmlrpc type (loosely defined: strings
* accepted come from javadoc blocks), return corresponding phpxmlrpc type.
* NB: for php 'resource' types returns empty string, since resources cannot be serialized;
* for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
* @param string $phptype
* @return string
*/
function php_2_xmlrpc_type($phptype)
{
switch(strtolower($phptype))
{
case 'string':
return $GLOBALS['xmlrpcString'];
case 'integer':
case $GLOBALS['xmlrpcInt']: // 'int'
case $GLOBALS['xmlrpcI4']:
return $GLOBALS['xmlrpcInt'];
case 'double':
return $GLOBALS['xmlrpcDouble'];
case 'boolean':
return $GLOBALS['xmlrpcBoolean'];
case 'array':
return $GLOBALS['xmlrpcArray'];
case 'object':
return $GLOBALS['xmlrpcStruct'];
case $GLOBALS['xmlrpcBase64']:
case $GLOBALS['xmlrpcStruct']:
return strtolower($phptype);
case 'resource':
return '';
default:
if(class_exists($phptype))
{
return $GLOBALS['xmlrpcStruct'];
}
else
{
// unknown: might be any 'extended' xmlrpc type
return $GLOBALS['xmlrpcValue'];
}
}
}
/**
* Given a string defining a phpxmlrpc type return corresponding php type.
* @param string $xmlrpctype
* @return string
*/
function xmlrpc_2_php_type($xmlrpctype)
{
switch(strtolower($xmlrpctype))
{
case 'base64':
case 'datetime.iso8601':
case 'string':
return $GLOBALS['xmlrpcString'];
case 'int':
case 'i4':
return 'integer';
case 'struct':
case 'array':
return 'array';
case 'double':
return 'float';
case 'undefined':
return 'mixed';
case 'boolean':
case 'null':
default:
// unknown: might be any xmlrpc type
return strtolower($xmlrpctype);
}
}
/**
* Given a user-defined PHP function, create a PHP 'wrapper' function that can
* be exposed as xmlrpc method from an xmlrpc_server object and called from remote
* clients (as well as its corresponding signature info).
*
* Since php is a typeless language, to infer types of input and output parameters,
* it relies on parsing the javadoc-style comment block associated with the given
* function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
* in the @param tag is also allowed, if you need the php function to receive/send
* data in that particular format (note that base64 encoding/decoding is transparently
* carried out by the lib, while datetime vals are passed around as strings)
*
* Known limitations:
* - requires PHP 5.0.3 +
* - only works for user-defined functions, not for PHP internal functions
* (reflection does not support retrieving number/type of params for those)
* - functions returning php objects will generate special xmlrpc responses:
* when the xmlrpc decoding of those responses is carried out by this same lib, using
* the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
* In short: php objects can be serialized, too (except for their resource members),
* using this function.
* Other libs might choke on the very same xml that will be generated in this case
* (i.e. it has a nonstandard attribute on struct element tags)
* - usage of javadoc @param tags using param names in a different order from the
* function prototype is not considered valid (to be fixed?)
*
* Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
* php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)
* is by making use of the functions_parameters_type class member.
*
* @param string $funcname the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') might be ok too, in the future...
* @param string $newfuncname (optional) name for function to be created
* @param array $extra_options (optional) array of options for conversion. valid values include:
* bool return_source when true, php code w. function definition will be returned, not evaluated
* bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
* bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
* bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
* @return false on error, or an array containing the name of the new php function,
* its signature and docs, to be used in the server dispatch map
*
* @todo decide how to deal with params passed by ref: bomb out or allow?
* @todo finish using javadoc info to build method sig if all params are named but out of order
* @todo add a check for params of 'resource' type
* @todo add some trigger_errors / error_log when returning false?
* @todo what to do when the PHP function returns NULL? we are currently an empty string value...
* @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
*/
function wrap_php_function($funcname, $newfuncname='', $extra_options=array())
{
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
if(version_compare(phpversion(), '5.0.3') == -1)
{
// up to php 5.0.3 some useful reflection methods were missing
error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
return false;
}
if((is_array($funcname) && !method_exists($funcname[0], $funcname[1])) || !function_exists($funcname))
{
error_log('XML-RPC: function to be wrapped is not defined: '.$funcname);
return false;
}
else
{
// determine name of new php function
if($newfuncname == '')
{
if(is_array($funcname))
{
$xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);
}
else
{
$xmlrpcfuncname = "{$prefix}_$funcname";
}
}
else
{
$xmlrpcfuncname = $newfuncname;
}
while($buildit && function_exists($xmlrpcfuncname))
{
$xmlrpcfuncname .= 'x';
}
// start to introspect PHP code
$func =& new ReflectionFunction($funcname);
if($func->isInternal())
{
// Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
// instead of getparameters to fully reflect internal php functions ?
error_log('XML-RPC: function to be wrapped is internal: '.$funcname);
return false;
}
// retrieve parameter names, types and description from javadoc comments
// function description
$desc = '';
// type of return val: by default 'any'
$returns = $GLOBALS['xmlrpcValue'];
// desc of return val
$returnsDocs = '';
// type + name of function parameters
$paramDocs = array();
$docs = $func->getDocComment();
if($docs != '')
{
$docs = explode("\n", $docs);
$i = 0;
foreach($docs as $doc)
{
$doc = trim($doc, " \r\t/*");
if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)
{
if($desc)
{
$desc .= "\n";
}
$desc .= $doc;
}
elseif(strpos($doc, '@param') === 0)
{
// syntax: @param type [$name] desc
if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches))
{
if(strpos($matches[1], '|'))
{
//$paramDocs[$i]['type'] = explode('|', $matches[1]);
$paramDocs[$i]['type'] = 'mixed';
}
else
{
$paramDocs[$i]['type'] = $matches[1];
}
$paramDocs[$i]['name'] = trim($matches[2]);
$paramDocs[$i]['doc'] = $matches[3];
}
$i++;
}
elseif(strpos($doc, '@return') === 0)
{
// syntax: @return type desc
//$returns = preg_split('/\s+/', $doc);
if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))
{
$returns = php_2_xmlrpc_type($matches[1]);
if(isset($matches[2]))
{
$returnsDocs = $matches[2];
}
}
}
}
}
// execute introspection of actual function prototype
$params = array();
$i = 0;
foreach($func->getParameters() as $paramobj)
{
$params[$i] = array();
$params[$i]['name'] = '$'.$paramobj->getName();
$params[$i]['isoptional'] = $paramobj->isOptional();
$i++;
}
// start building of PHP code to be eval'd
$innercode = '';
$i = 0;
$parsvariations = array();
$pars = array();
$pnum = count($params);
foreach($params as $param)
{
if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name']))
{
// param name from phpdoc info does not match param definition!
$paramDocs[$i]['type'] = 'mixed';
}
if($param['isoptional'])
{
// this particular parameter is optional. save as valid previous list of parameters
$innercode .= "if (\$paramcount > $i) {\n";
$parsvariations[] = $pars;
}
$innercode .= "\$p$i = \$msg->getParam($i);\n";
if ($decode_php_objects)
{
$innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
}
else
{
$innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
}
$pars[] = "\$p$i";
$i++;
if($param['isoptional'])
{
$innercode .= "}\n";
}
if($i == $pnum)
{
// last allowed parameters combination
$parsvariations[] = $pars;
}
}
$sigs = array();
$psigs = array();
if(count($parsvariations) == 0)
{
// only known good synopsis = no parameters
$parsvariations[] = array();
$minpars = 0;
}
else
{
$minpars = count($parsvariations[0]);
}
if($minpars)
{
// add to code the check for min params number
// NB: this check needs to be done BEFORE decoding param values
$innercode = "\$paramcount = \$msg->getNumParams();\n" .
"if (\$paramcount < $minpars) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . $innercode;
}
else
{
$innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
}
$innercode .= "\$np = false;\n";
foreach($parsvariations as $pars)
{
$innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$funcname(" . implode(',', $pars) . "); else\n";
// build a 'generic' signature (only use an appropriate return type)
$sig = array($returns);
$psig = array($returnsDocs);
for($i=0; $i < count($pars); $i++)
{
if (isset($paramDocs[$i]['type']))
{
$sig[] = php_2_xmlrpc_type($paramDocs[$i]['type']);
}
else
{
$sig[] = $GLOBALS['xmlrpcValue'];
}
$psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
}
$sigs[] = $sig;
$psigs[] = $psig;
}
$innercode .= "\$np = true;\n";
$innercode .= "if (\$np) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n";
//$innercode .= "if (\$_xmlrpcs_error_occurred) return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
$innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
if($returns == $GLOBALS['xmlrpcDateTime'] || $returns == $GLOBALS['xmlrpcBase64'])
{
$innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
}
else
{
if ($encode_php_objects)
$innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
else
$innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
}
// shall we exclude functions returning by ref?
// if($func->returnsReference())
// return false;
$code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
//print_r($code);
if ($buildit)
{
$allOK = 0;
eval($code.'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if(!$allOK)
{
error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$funcname);
return false;
}
}
/// @todo examine if $paramDocs matches $parsvariations and build array for
/// usage as method signature, plus put together a nice string for docs
$ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
return $ret;
}
}
/**
* Given an xmlrpc client and a method name, register a php wrapper function
* that will call it and return results using native php types for both
* params and results. The generated php function will return an xmlrpcresp
* oject for failed xmlrpc calls
*
* Known limitations:
* - server must support system.methodsignature for the wanted xmlrpc method
* - for methods that expose many signatures, only one can be picked (we
* could in priciple check if signatures differ only by number of params
* and not by type, but it would be more complication than we can spare time)
* - nested xmlrpc params: the caller of the generated php function has to
* encode on its own the params passed to the php function if these are structs
* or arrays whose (sub)members include values of type datetime or base64
*
* Notes: the connection properties of the given client will be copied
* and reused for the connection used during the call to the generated
* php function.
* Calling the generated php function 'might' be slow: a new xmlrpc client
* is created on every invocation and an xmlrpc-connection opened+closed.
* An extra 'debug' param is appended to param list of xmlrpc method, useful
* for debugging purposes.
*
* @param xmlrpc_client $client an xmlrpc client set up correctly to communicate with target server
* @param string $methodname the xmlrpc method to be mapped to a php function
* @param array $extra_options array of options that specify conversion details. valid ptions include
* integer signum the index of the method signature to use in mapping (if method exposes many sigs)
* integer timeout timeout (in secs) to be used when executing function/calling remote method
* string protocol 'http' (default), 'http11' or 'https'
* string new_function_name the name of php function to create. If unsepcified, lib will pick an appropriate name
* string return_source if true return php code w. function definition instead fo function name
* bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
* bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
* mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the xmlrpcresp object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
* bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
* @return string the name of the generated php function (or false) - OR AN ARRAY...
*/
function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')
{
// mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
// OR the 2.0 calling convention (no ptions) - we really love backward compat, don't we?
if (!is_array($extra_options))
{
$signum = $extra_options;
$extra_options = array();
}
else
{
$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
$newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
}
//$encode_php_objects = in_array('encode_php_objects', $extra_options);
//$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
// in_array('build_class_code', $extra_options) ? 2 : 0;
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
if (isset($extra_options['return_on_fault']))
{
$decode_fault = true;
$fault_response = $extra_options['return_on_fault'];
}
else
{
$decode_fault = false;
$fault_response = '';
}
$debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
$msgclass = $prefix.'msg';
$valclass = $prefix.'val';
$decodefunc = 'php_'.$prefix.'_decode';
$msg =& new $msgclass('system.methodSignature');
$msg->addparam(new $valclass($methodname));
$client->setDebug($debug);
$response =& $client->send($msg, $timeout, $protocol);
if($response->faultCode())
{
error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);
return false;
}
else
{
$msig = $response->value();
if ($client->return_type != 'phpvals')
{
$msig = $decodefunc($msig);
}
if(!is_array($msig) || count($msig) <= $signum)
{
error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);
return false;
}
else
{
// pick a suitable name for the new function, avoiding collisions
if($newfuncname != '')
{
$xmlrpcfuncname = $newfuncname;
}
else
{
// take care to insure that methodname is translated to valid
// php function name
$xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $methodname);
}
while($buildit && function_exists($xmlrpcfuncname))
{
$xmlrpcfuncname .= 'x';
}
$msig = $msig[$signum];
$mdesc = '';
// if in 'offline' mode, get method description too.
// in online mode, favour speed of operation
if(!$buildit)
{
$msg =& new $msgclass('system.methodHelp');
$msg->addparam(new $valclass($methodname));
$response =& $client->send($msg, $timeout, $protocol);
if (!$response->faultCode())
{
$mdesc = $response->value();
if ($client->return_type != 'phpvals')
{
$mdesc = $mdesc->scalarval();
}
}
}
$results = build_remote_method_wrapper_code($client, $methodname,
$xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
$prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
$fault_response);
//print_r($code);
if ($buildit)
{
$allOK = 0;
eval($results['source'].'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if($allOK)
{
return $xmlrpcfuncname;
}
else
{
error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
return false;
}
}
else
{
$results['function'] = $xmlrpcfuncname;
return $results;
}
}
}
}
/**
* Similar to wrap_xmlrpc_method, but will generate a php class that wraps
* all xmlrpc methods exposed by the remote server as own methods.
* For more details see wrap_xmlrpc_method.
* @param xmlrpc_client $client the client obj all set to query the desired server
* @param array $extra_options list of options for wrapped code
* @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options)
*/
function wrap_xmlrpc_server($client, $extra_options=array())
{
$methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
$newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
$msgclass = $prefix.'msg';
//$valclass = $prefix.'val';
$decodefunc = 'php_'.$prefix.'_decode';
$msg =& new $msgclass('system.listMethods');
$response =& $client->send($msg, $timeout, $protocol);
if($response->faultCode())
{
error_log('XML-RPC: could not retrieve method list from remote server');
return false;
}
else
{
$mlist = $response->value();
if ($client->return_type != 'phpvals')
{
$mlist = $decodefunc($mlist);
}
if(!is_array($mlist) || !count($mlist))
{
error_log('XML-RPC: could not retrieve meaningful method list from remote server');
return false;
}
else
{
// pick a suitable name for the new function, avoiding collisions
if($newclassname != '')
{
$xmlrpcclassname = $newclassname;
}
else
{
$xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $client->server).'_client';
}
while($buildit && class_exists($xmlrpcclassname))
{
$xmlrpcclassname .= 'x';
}
/// @todo add function setdebug() to new class, to enable/disable debugging
$source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
$source .= "function $xmlrpcclassname()\n{\n";
$source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
$source .= "\$this->client =& \$client;\n}\n\n";
$opts = array('simple_client_copy' => 2, 'return_source' => true,
'timeout' => $timeout, 'protocol' => $protocol,
'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
'decode_php_objs' => $decode_php_objects
);
/// @todo build javadoc for class definition, too
foreach($mlist as $mname)
{
if ($methodfilter == '' || preg_match($methodfilter, $mname))
{
$opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $mname);
$methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
if ($methodwrap)
{
if (!$buildit)
{
$source .= $methodwrap['docstring'];
}
$source .= $methodwrap['source']."\n";
}
else
{
error_log('XML-RPC: will not create class method to wrap remote method '.$mname);
}
}
}
$source .= "}\n";
if ($buildit)
{
$allOK = 0;
eval($source.'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if($allOK)
{
return $xmlrpcclassname;
}
else
{
error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
return false;
}
}
else
{
return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
}
}
}
}
/**
* Given the necessary info, build php code that creates a new function to
* invoke a remote xmlrpc method.
* Take care that no full checking of input parameters is done to ensure that
* valid php code is emitted.
* Note: real spaghetti code follows...
* @access private
*/
function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
$msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',
$decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,
$fault_response='')
{
$code = "function $xmlrpcfuncname (";
if ($client_copy_mode < 2)
{
// client copy mode 0 or 1 == partial / full client copy in emitted code
$innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix);
$innercode .= "\$client->setDebug(\$debug);\n";
$this_ = '';
}
else
{
// client copy mode 2 == no client copy in emitted code
$innercode = '';
$this_ = 'this->';
}
$innercode .= "\$msg =& new {$prefix}msg('$methodname');\n";
if ($mdesc != '')
{
// take care that PHP comment is not terminated unwillingly by method description
$mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
}
else
{
$mdesc = "/**\nFunction $xmlrpcfuncname\n";
}
// param parsing
$plist = array();
$pcount = count($msig);
for($i = 1; $i < $pcount; $i++)
{
$plist[] = "\$p$i";
$ptype = $msig[$i];
if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
$ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')
{
// only build directly xmlrpcvals when type is known and scalar
$innercode .= "\$p$i =& new {$prefix}val(\$p$i, '$ptype');\n";
}
else
{
if ($encode_php_objects)
{
$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
}
else
{
$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n";
}
}
$innercode .= "\$msg->addparam(\$p$i);\n";
$mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n";
}
if ($client_copy_mode < 2)
{
$plist[] = '$debug=0';
$mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
}
$plist = implode(', ', $plist);
$mdesc .= '* @return '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";
$innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
if ($decode_fault)
{
if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))
{
$respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";
}
else
{
$respcode = var_export($fault_response, true);
}
}
else
{
$respcode = '$res';
}
if ($decode_php_objects)
{
$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
}
else
{
$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
}
$code = $code . $plist. ") {\n" . $innercode . "\n}\n";
return array('source' => $code, 'docstring' => $mdesc);
}
/**
* Given necessary info, generate php code that will rebuild a client object
* Take care that no full checking of input parameters is done to ensure that
* valid php code is emitted.
* @access private
*/
function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
{
$code = "\$client =& new {$prefix}_client('".str_replace("'", "\'", $client->path).
"', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
// copy all client fields to the client that will be generated runtime
// (this provides for future expansion or subclassing of client obj)
if ($verbatim_client_copy)
{
foreach($client as $fld => $val)
{
if($fld != 'debug' && $fld != 'return_type')
{
$val = var_export($val, true);
$code .= "\$client->$fld = $val;\n";
}
}
}
// only make sure that client always returns the correct data type
$code .= "\$client->return_type = '{$prefix}vals';\n";
//$code .= "\$client->setDebug(\$debug);\n";
return $code;
}
?>

1172
lib/xmlrpcs.inc Normal file

File diff suppressed because it is too large Load Diff