From 7bf4299d632ba89869f755cd849bed839841db45 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Wed, 21 May 2014 13:53:04 +0300 Subject: [PATCH 001/228] xmlrpc.inc: removed dl("xml.so") This function has been deprecated and removed from php-5.3 and upwards, and was only useful for PHP 4, which is not supported anymore. --- ChangeLog | 6 +++++- lib/xmlrpc.inc | 10 ---------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/ChangeLog b/ChangeLog index 2c6dda76..1ac38ee3 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,8 @@ -2014-02-3 - G. Giunta (giunta.gaetano@gmail.com) +2014-05-12 - Samu Voutilainen (smar@smar.fi) + + * removed obsolete xml.so open; dl() is deprecated and removed from 5.3.0 + +2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) * bumped up requirements to php 5.1.0 diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index aeaf4be2..d87f6ebc 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -34,16 +34,6 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. - if(!function_exists('xml_parser_create')) - { - // For PHP 4 onward, XML functionality is always compiled-in on windows: - // no more need to dl-open it. It might have been compiled out on *nix... - if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN')) - { - dl('xml.so'); - } - } - // G. Giunta 2005/01/29: declare global these variables, // so that xmlrpc.inc will work even if included from within a function // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used. From 9cfbf09561695e48ada528b83ecabb2a59c7c154 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Wed, 21 May 2014 14:31:10 +0300 Subject: [PATCH 002/228] xmlrpc.inc: remove deprecated xmlEntities --- ChangeLog | 1 + lib/xmlrpc.inc | 10 ---------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/ChangeLog b/ChangeLog index 1ac38ee3..f755e5ea 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,6 +1,7 @@ 2014-05-12 - Samu Voutilainen (smar@smar.fi) * removed obsolete xml.so open; dl() is deprecated and removed from 5.3.0 + * removed deprecated xmlEntities 2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index d87f6ebc..19e742e2 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -86,16 +86,6 @@ $GLOBALS['xmlrpcNull']='null'; $GLOBALS['xmlrpcTypes']['null']=1; - // Not in use anymore since 2.0. Shall we remove it? - /// @deprecated - $GLOBALS['xmlEntities']=array( - 'amp' => '&', - 'quot' => '"', - 'lt' => '<', - 'gt' => '>', - 'apos' => "'" - ); - // tables used for transcoding different charsets into us-ascii xml $GLOBALS['xml_iso88591_Entities']=array(); From 5651cff014a88d7d3b62ebddc708407033b8e3e5 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Wed, 21 May 2014 14:55:16 +0300 Subject: [PATCH 003/228] xmlrpc.inc: removed deprecated xmlrpc_backslash global --- ChangeLog | 1 + lib/xmlrpc.inc | 5 ----- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/ChangeLog b/ChangeLog index f755e5ea..a4ca76ec 100644 --- a/ChangeLog +++ b/ChangeLog @@ -2,6 +2,7 @@ * removed obsolete xml.so open; dl() is deprecated and removed from 5.3.0 * removed deprecated xmlEntities + * removed deprecated xmlrpc_backslash 2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 19e742e2..b7adaee5 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -195,11 +195,6 @@ // let XML parse errors start at 100 $GLOBALS['xmlrpcerrxml']=100; - // formulate backslashes for escaping regexp - // Not in use anymore since 2.0. Shall we remove it? - /// @deprecated - $GLOBALS['xmlrpc_backslash']=chr(92).chr(92); - // set to TRUE to enable correct decoding of and values $GLOBALS['xmlrpc_null_extension']=false; From 4cbf7668349fb59c22be5f912956d4f000936baf Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Wed, 21 May 2014 15:50:05 +0300 Subject: [PATCH 004/228] xmlrpc.inc: Converted $GLOBALS array to internal class Xmlrpc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This way $GLOBALS array won’t be polluted with internal data of us, and if something else does something to that array, it won’t affect us anymore. --- ChangeLog | 1 + lib/xmlrpc.inc | 732 ++++++++++++++++++++++++++----------------------- 2 files changed, 394 insertions(+), 339 deletions(-) diff --git a/ChangeLog b/ChangeLog index a4ca76ec..c4c793d2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,7 @@ * removed obsolete xml.so open; dl() is deprecated and removed from 5.3.0 * removed deprecated xmlEntities * removed deprecated xmlrpc_backslash + * converted $GLOBALS to internal class. This makes testing much easier and should be more flexible regarding other projects 2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index b7adaee5..52a1104f 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -34,33 +34,23 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. - // G. Giunta 2005/01/29: declare global these variables, - // so that xmlrpc.inc will work even if included from within a function - // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used. - $GLOBALS['xmlrpcI4']='i4'; - $GLOBALS['xmlrpcInt']='int'; - $GLOBALS['xmlrpcBoolean']='boolean'; - $GLOBALS['xmlrpcDouble']='double'; - $GLOBALS['xmlrpcString']='string'; - $GLOBALS['xmlrpcDateTime']='dateTime.iso8601'; - $GLOBALS['xmlrpcBase64']='base64'; - $GLOBALS['xmlrpcArray']='array'; - $GLOBALS['xmlrpcStruct']='struct'; - $GLOBALS['xmlrpcValue']='undefined'; - - $GLOBALS['xmlrpcTypes']=array( - $GLOBALS['xmlrpcI4'] => 1, - $GLOBALS['xmlrpcInt'] => 1, - $GLOBALS['xmlrpcBoolean'] => 1, - $GLOBALS['xmlrpcString'] => 1, - $GLOBALS['xmlrpcDouble'] => 1, - $GLOBALS['xmlrpcDateTime'] => 1, - $GLOBALS['xmlrpcBase64'] => 1, - $GLOBALS['xmlrpcArray'] => 2, - $GLOBALS['xmlrpcStruct'] => 3 - ); - - $GLOBALS['xmlrpc_valid_parents'] = array( +class Xmlrpc { + + public $xmlrpcI4 = "i4"; + public $xmlrpcInt = "int"; + public $xmlrpcBoolean = "boolean"; + public $xmlrpcDouble = "double"; + public $xmlrpcString = "string"; + public $xmlrpcDateTime = "dateTime.iso8601"; + public $xmlrpcBase64 = "base64"; + public $xmlrpcArray = "array"; + public $xmlrpcStruct = "struct"; + public $xmlrpcValue = "undefined"; + public $xmlrpcNull = "null"; + + public $xmlrpcTypes; + + public $xmlrpc_valid_parents = array( 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), 'BOOLEAN' => array('VALUE'), 'I4' => array('VALUE'), @@ -82,30 +72,13 @@ 'EX:NIL' => array('VALUE') // only used when extension activated ); - // define extra types for supporting NULL (useful for json or ) - $GLOBALS['xmlrpcNull']='null'; - $GLOBALS['xmlrpcTypes']['null']=1; - // tables used for transcoding different charsets into us-ascii xml - - $GLOBALS['xml_iso88591_Entities']=array(); - $GLOBALS['xml_iso88591_Entities']['in'] = array(); - $GLOBALS['xml_iso88591_Entities']['out'] = array(); - for ($i = 0; $i < 32; $i++) - { - $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i); - $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';'; - } - for ($i = 160; $i < 256; $i++) - { - $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i); - $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';'; - } + public $xml_iso88591_Entities = 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 reciving them...) - /* + /* $GLOBALS['xml_cp1252_Entities']=array(); for ($i = 128; $i < 160; $i++) { @@ -121,86 +94,87 @@ '˜', '™', 'š', '›', 'œ', '?', 'ž', 'Ÿ' ); - */ - - $GLOBALS['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 + */ + + 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 ); - $GLOBALS['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' + 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 messages and // by the client for received responses when received charset cannot be determined // or is not supported - $GLOBALS['xmlrpc_defencoding']='UTF-8'; + public $xmlrpc_defencoding = "UTF-8"; // 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 - $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1'; + public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? - $GLOBALS['xmlrpcName']='XML-RPC for PHP'; - $GLOBALS['xmlrpcVersion']='3.0.0.beta'; + public $xmlrpcName = "XML-RPC for PHP"; + public $xmlrpcVersion = "3.0.0.beta"; // let user errors start at 800 - $GLOBALS['xmlrpcerruser']=800; + public $xmlrpcerruser = 800; // let XML parse errors start at 100 - $GLOBALS['xmlrpcerrxml']=100; + public $xmlrpcerrxml = 100; // set to TRUE to enable correct decoding of and values - $GLOBALS['xmlrpc_null_extension']=false; + public $xmlrpc_null_extension = false; // set to TRUE to enable encoding of php NULL values to instead of - $GLOBALS['xmlrpc_null_apache_encoding']=false; - $GLOBALS['xmlrpc_null_apache_encoding_ns']='http://ws.apache.org/xmlrpc/namespaces/extensions'; + public $xmlrpc_null_apache_encoding = false; + + public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; // used to store state during parsing // quick explanation of components: @@ -213,7 +187,46 @@ // method - used to store method name // stack - array with genealogy of xml elements names: // used to validate nesting of xmlrpc elements - $GLOBALS['_xh']=null; + public $_xh = null; + + private static $instance = null; + + private function __construct() { + $this->xmlrpcTypes = array( + $this->xmlrpcI4 => 1, + $this->xmlrpcInt => 1, + $this->xmlrpcBoolean => 1, + $this->xmlrpcDouble => 1, + $this->xmlrpcString => 1, + $this->xmlrpcDateTime => 1, + $this->xmlrpcBase64 => 1, + $this->xmlrpcArray => 2, + $this->xmlrpcStruct => 3, + $this->xmlrpcNull => 1 + ); + + 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};"; + } + } + + /** + * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. + */ + public static function instance() { + if(Xmlrpc::$instance === null) { + Xmlrpc::$instance = new Xmlrpc(); + } + + return Xmlrpc::$instance; + } +} /** * Convert a string to the correct XML representation in a target charset @@ -231,10 +244,11 @@ */ function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') { + $xmlrpc = Xmlrpc::instance(); if ($src_encoding == '') { // lame, but we know no better... - $src_encoding = $GLOBALS['xmlrpc_internalencoding']; + $src_encoding = $xmlrpc->xmlrpc_internalencoding; } switch(strtoupper($src_encoding.'_'.$dest_encoding)) @@ -242,7 +256,7 @@ case 'ISO-8859-1_': case 'ISO-8859-1_US-ASCII': $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data); + $escaped_data = str_replace($xmlrpc->xml_iso88591_Entities['in'], $xmlrpc->xml_iso88591_Entities['out'], $escaped_data); break; case 'ISO-8859-1_UTF-8': $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); @@ -363,36 +377,37 @@ /// xml parser handler function for opening element tags function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) { + $xmlrpc = Xmlrpc::instance(); // if invalid xmlrpc already detected, skip all processing - if ($GLOBALS['_xh']['isf'] < 2) + if ($xmlrpc->_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($GLOBALS['_xh']['stack']) == 0) + if (count($xmlrpc->_xh['stack']) == 0) { if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( $name != 'VALUE' && !$accept_single_vals)) { - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element'; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = 'missing top level xmlrpc element'; return; } else { - $GLOBALS['_xh']['rt'] = strtolower($name); - $GLOBALS['_xh']['rt'] = strtolower($name); + $xmlrpc->_xh['rt'] = strtolower($name); + $xmlrpc->_xh['rt'] = strtolower($name); } } else { // not top level element: see if parent is OK - $parent = end($GLOBALS['_xh']['stack']); - if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name])) + $parent = end($xmlrpc->_xh['stack']); + if (!array_key_exists($name, $xmlrpc->xmlrpc_valid_parents) || !in_array($parent, $xmlrpc->xmlrpc_valid_parents[$name])) { - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent"; return; } } @@ -402,10 +417,10 @@ // 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 - $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet - $GLOBALS['_xh']['ac']=''; - $GLOBALS['_xh']['lv']=1; - $GLOBALS['_xh']['php_class']=null; + $xmlrpc->_xh['vt']='value'; // indicator: no value found yet + $xmlrpc->_xh['ac']=''; + $xmlrpc->_xh['lv']=1; + $xmlrpc->_xh['php_class']=null; break; case 'I4': case 'INT': @@ -414,22 +429,22 @@ case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - if ($GLOBALS['_xh']['vt']!='value') + if ($xmlrpc->_xh['vt']!='value') { //two data elements inside a value: an error occurred! - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; return; } - $GLOBALS['_xh']['ac']=''; // reset the accumulator + $xmlrpc->_xh['ac']=''; // reset the accumulator break; case 'STRUCT': case 'ARRAY': - if ($GLOBALS['_xh']['vt']!='value') + if ($xmlrpc->_xh['vt']!='value') { //two data elements inside a value: an error occurred! - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; return; } // create an empty array to hold child values, and push it onto appropriate stack @@ -442,15 +457,15 @@ { $cur_val['php_class'] = $attrs['PHP_CLASS']; } - $GLOBALS['_xh']['valuestack'][] = $cur_val; - $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next + $xmlrpc->_xh['valuestack'][] = $cur_val; + $xmlrpc->_xh['vt']='data'; // be prepared for a data element next break; case 'DATA': - if ($GLOBALS['_xh']['vt']!='data') + if ($xmlrpc->_xh['vt']!='data') { //two data elements inside a value: an error occurred! - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "found two data elements inside an array element"; return; } case 'METHODCALL': @@ -461,49 +476,49 @@ case 'METHODNAME': case 'NAME': /// @todo we could check for 2 NAME elements inside a MEMBER element - $GLOBALS['_xh']['ac']=''; + $xmlrpc->_xh['ac']=''; break; case 'FAULT': - $GLOBALS['_xh']['isf']=1; + $xmlrpc->_xh['isf']=1; break; case 'MEMBER': - $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on - //$GLOBALS['_xh']['ac']=''; + $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on + //$xmlrpc->_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 - $GLOBALS['_xh']['vt']=null; + $xmlrpc->_xh['vt']=null; break; case 'NIL': case 'EX:NIL': - if ($GLOBALS['xmlrpc_null_extension']) + if ($xmlrpc->xmlrpc_null_extension) { - if ($GLOBALS['_xh']['vt']!='value') + if ($xmlrpc->_xh['vt']!='value') { //two data elements inside a value: an error occurred! - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; return; } - $GLOBALS['_xh']['ac']=''; // reset the accumulator + $xmlrpc->_xh['ac']=''; // reset the accumulator break; } // we do not support the extension, so // drop through intentionally default: /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! - $GLOBALS['_xh']['isf'] = 2; - $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name"; + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "found not-xmlrpc xml element $name"; break; } // Save current element name to stack, to validate nesting - $GLOBALS['_xh']['stack'][] = $name; + $xmlrpc->_xh['stack'][] = $name; /// @todo optimization creep: move this inside the big switch() above if($name!='VALUE') { - $GLOBALS['_xh']['lv']=0; + $xmlrpc->_xh['lv']=0; } } } @@ -517,42 +532,44 @@ /// xml parser handler function for close element tags function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) { - if ($GLOBALS['_xh']['isf'] < 2) + $xmlrpc = Xmlrpc::instance(); + + if ($xmlrpc->_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 == $curr_elem. // we also checked for proper nesting at start of elements... - $curr_elem = array_pop($GLOBALS['_xh']['stack']); + $curr_elem = array_pop($xmlrpc->_xh['stack']); switch($name) { case 'VALUE': // This if() detects if no scalar was inside - if ($GLOBALS['_xh']['vt']=='value') + if ($xmlrpc->_xh['vt']=='value') { - $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; - $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString']; + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; + $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcString; } if ($rebuild_xmlrpcvals) { // build the xmlrpc val out of the data received, and substitute it - $temp = new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']); + $temp = new xmlrpcval($xmlrpc->_xh['value'], $xmlrpc->_xh['vt']); // in case we got info about underlying php class, save it // in the object we're rebuilding - if (isset($GLOBALS['_xh']['php_class'])) - $temp->_php_class = $GLOBALS['_xh']['php_class']; + if (isset($xmlrpc->_xh['php_class'])) + $temp->_php_class = $xmlrpc->_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($GLOBALS['_xh']['valuestack']); - if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY') + $vscount = count($xmlrpc->_xh['valuestack']); + if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') { - $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp; + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $temp; } else { - $GLOBALS['_xh']['value'] = $temp; + $xmlrpc->_xh['value'] = $temp; } } else @@ -560,16 +577,16 @@ /// @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($GLOBALS['_xh']['php_class'])) + if (isset($xmlrpc->_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($GLOBALS['_xh']['valuestack']); - if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY') + $vscount = count($xmlrpc->_xh['valuestack']); + if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') { - $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value']; + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $xmlrpc->_xh['value']; } } break; @@ -580,26 +597,26 @@ case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - $GLOBALS['_xh']['vt']=strtolower($name); + $xmlrpc->_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') { - $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; } elseif ($name=='DATETIME.ISO8601') { - if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac'])) + if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $xmlrpc->_xh['ac'])) { - error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']); + error_log('XML-RPC: invalid value received in DATETIME: '.$xmlrpc->_xh['ac']); } - $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime']; - $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac']; + $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcDateTime; + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; } elseif ($name=='BASE64') { /// @todo check for failure of base64 decoding / catch warnings - $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']); + $xmlrpc->_xh['value']=base64_decode($xmlrpc->_xh['ac']); } elseif ($name=='BOOLEAN') { @@ -609,16 +626,16 @@ // 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 ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0) + if ($xmlrpc->_xh['ac']=='1' || strcasecmp($xmlrpc->_xh['ac'], 'true') == 0) { - $GLOBALS['_xh']['value']=true; + $xmlrpc->_xh['value']=true; } else { // log if receiveing something strange, even though we set the value to false anyway - if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($GLOBALS['_xh']['ac'], 'false') != 0) - error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']); - $GLOBALS['_xh']['value']=false; + if ($xmlrpc->_xh['ac']!='0' && strcasecmp($xmlrpc->_xh['ac'], 'false') != 0) + error_log('XML-RPC: invalid value received in BOOLEAN: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']=false; } } elseif ($name=='DOUBLE') @@ -626,87 +643,87 @@ // we have a DOUBLE // we must check that only 0123456789-. are characters here // NOTE: regexp could be much stricter than this... - if (!preg_match('/^[+-eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac'])) + if (!preg_match('/^[+-eE0123456789 \t.]+$/', $xmlrpc->_xh['ac'])) { /// @todo: find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']); - $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND'; + error_log('XML-RPC: non numeric value received in DOUBLE: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; } else { // it's ok, add it on - $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac']; + $xmlrpc->_xh['value']=(double)$xmlrpc->_xh['ac']; } } else { // we have an I4/INT // we must check that only 0123456789- are characters here - if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac'])) + if (!preg_match('/^[+-]?[0123456789 \t]+$/', $xmlrpc->_xh['ac'])) { /// @todo find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']); - $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND'; + error_log('XML-RPC: non numeric value received in INT: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; } else { // it's ok, add it on - $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac']; + $xmlrpc->_xh['value']=(int)$xmlrpc->_xh['ac']; } } - //$GLOBALS['_xh']['ac']=''; // is this necessary? - $GLOBALS['_xh']['lv']=3; // indicate we've found a value + //$xmlrpc->_xh['ac']=''; // is this necessary? + $xmlrpc->_xh['lv']=3; // indicate we've found a value break; case 'NAME': - $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac']; + $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name'] = $xmlrpc->_xh['ac']; break; case 'MEMBER': - //$GLOBALS['_xh']['ac']=''; // is this necessary? + //$xmlrpc->_xh['ac']=''; // is this necessary? // add to array in the stack the last element built, // unless no VALUE was found - if ($GLOBALS['_xh']['vt']) + if ($xmlrpc->_xh['vt']) { - $vscount = count($GLOBALS['_xh']['valuestack']); - $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value']; + $vscount = count($xmlrpc->_xh['valuestack']); + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][$xmlrpc->_xh['valuestack'][$vscount-1]['name']] = $xmlrpc->_xh['value']; } else error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); break; case 'DATA': - //$GLOBALS['_xh']['ac']=''; // is this necessary? - $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty + //$xmlrpc->_xh['ac']=''; // is this necessary? + $xmlrpc->_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 - $curr_val = array_pop($GLOBALS['_xh']['valuestack']); - $GLOBALS['_xh']['value'] = $curr_val['values']; - $GLOBALS['_xh']['vt']=strtolower($name); + $curr_val = array_pop($xmlrpc->_xh['valuestack']); + $xmlrpc->_xh['value'] = $curr_val['values']; + $xmlrpc->_xh['vt']=strtolower($name); if (isset($curr_val['php_class'])) { - $GLOBALS['_xh']['php_class'] = $curr_val['php_class']; + $xmlrpc->_xh['php_class'] = $curr_val['php_class']; } break; case 'PARAM': // add to array of params the current value, // unless no VALUE was found - if ($GLOBALS['_xh']['vt']) + if ($xmlrpc->_xh['vt']) { - $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value']; - $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt']; + $xmlrpc->_xh['params'][]=$xmlrpc->_xh['value']; + $xmlrpc->_xh['pt'][]=$xmlrpc->_xh['vt']; } else error_log('XML-RPC: missing VALUE inside PARAM in received xml'); break; case 'METHODNAME': - $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']); + $xmlrpc->_xh['method']=preg_replace('/^[\n\r\t ]+/', '', $xmlrpc->_xh['ac']); break; case 'NIL': case 'EX:NIL': - if ($GLOBALS['xmlrpc_null_extension']) + if ($xmlrpc->xmlrpc_null_extension) { - $GLOBALS['_xh']['vt']='null'; - $GLOBALS['_xh']['value']=null; - $GLOBALS['_xh']['lv']=3; + $xmlrpc->_xh['vt']='null'; + $xmlrpc->_xh['value']=null; + $xmlrpc->_xh['lv']=3; break; } // drop through intentionally if nil extension not enabled @@ -732,26 +749,27 @@ /// xml parser handler function for character data function xmlrpc_cd($parser, $data) { + $xmlrpc = Xmlrpc::instance(); // skip processing if xml fault already detected - if ($GLOBALS['_xh']['isf'] < 2) + if ($xmlrpc->_xh['isf'] < 2) { // "lookforvalue==3" means that we've found an entire value // and should discard any further character data - if($GLOBALS['_xh']['lv']!=3) + if($xmlrpc->_xh['lv']!=3) { // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 - //if($GLOBALS['_xh']['lv']==1) + //if($xmlrpc->_xh['lv']==1) //{ // if we've found text and we're just in a then // say we've found a value - //$GLOBALS['_xh']['lv']=2; + //$xmlrpc->_xh['lv']=2; //} // we always initialize the accumulator before starting parsing, anyway... - //if(!@isset($GLOBALS['_xh']['ac'])) + //if(!@isset($xmlrpc->_xh['ac'])) //{ - // $GLOBALS['_xh']['ac'] = ''; + // $xmlrpc->_xh['ac'] = ''; //} - $GLOBALS['_xh']['ac'].=$data; + $xmlrpc->_xh['ac'].=$data; } } } @@ -760,17 +778,18 @@ /// element start/end tag. In fact it only gets called on unknown entities... function xmlrpc_dh($parser, $data) { + $xmlrpc = Xmlrpc::instance(); // skip processing if xml fault already detected - if ($GLOBALS['_xh']['isf'] < 2) + if ($xmlrpc->_xh['isf'] < 2) { if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') { // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 - //if($GLOBALS['_xh']['lv']==1) + //if($xmlrpc->_xh['lv']==1) //{ - // $GLOBALS['_xh']['lv']=2; + // $xmlrpc->_xh['lv']=2; //} - $GLOBALS['_xh']['ac'].=$data; + $xmlrpc->_xh['ac'].=$data; } } return true; @@ -849,6 +868,8 @@ */ function xmlrpc_client($path, $server='', $port='', $method='') { + $xmlrpc = Xmlrpc::instance(); + // allow user to specify all params in $path if($server == '' and $port == '' and $method == '') { @@ -914,7 +935,7 @@ $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); // initialize user_agent string - $this->user_agent = $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion']; + $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; } /** @@ -1211,6 +1232,8 @@ $username='', $password='', $authtype=1, $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) { + $xmlrpc = Xmlrpc::instance(); + if($port==0) { $port=80; @@ -1361,7 +1384,7 @@ else { $this->errstr='Connect error: '.$this->errstr; - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); return $r; } @@ -1369,7 +1392,7 @@ { fclose($fp); $this->errstr='Write error'; - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); return $r; } else @@ -1417,10 +1440,12 @@ $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', $keepalive=false, $key='', $keypass='') { + $xmlrpc = Xmlrpc::instance(); + if(!function_exists('curl_init')) { $this->errstr='CURL unavailable on this install'; - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); return $r; } if($method == 'https') @@ -1429,7 +1454,7 @@ ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) { $this->errstr='SSL unavailable on this install'; - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); return $r; } } @@ -1661,7 +1686,7 @@ if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? { $this->errstr='no response'; - $resp=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl)); + $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); curl_close($curl); if($keepalive) { @@ -1676,7 +1701,7 @@ } $resp =& $msg->parseResponse($result, true, $this->return_type); // if we got back a 302, we can not reuse the curl handle for later calls - if($resp->faultCode() == $GLOBALS['xmlrpcerr']['http_error'] && $keepalive) + if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) { curl_close($curl); $this->xmlrpc_curl_handle = null; @@ -1709,6 +1734,8 @@ */ function multicall($msgs, $timeout=0, $method='', $fallback=true) { + $xmlrpc = Xmlrpc::instance(); + if ($method == '') { $method = $this->method; @@ -1738,7 +1765,7 @@ } else { - $result = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']); + $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); } } } @@ -2028,13 +2055,15 @@ */ function serialize($charset_encoding='') { + $xmlrpc = Xmlrpc::instance(); + if ($charset_encoding != '') $this->content_type = 'text/xml; charset=' . $charset_encoding; else $this->content_type = 'text/xml'; - if ($GLOBALS['xmlrpc_null_apache_encoding']) + if ($xmlrpc->xmlrpc_null_apache_encoding) { - $result = "\n"; + $result = "xmlrpc_null_apache_encoding_ns."\">\n"; } else { @@ -2047,7 +2076,7 @@ $result .= "\n" . "\nfaultCode\n" . $this->errno . "\n\n\nfaultString\n" . -xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n\n" . +xmlrpc_encode_entitites($this->errstr, $xmlrpc->xmlrpc_internalencoding, $charset_encoding) . "\n\n" . "\n\n"; } else @@ -2249,6 +2278,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function &parseResponseHeaders(&$data, $headers_processed=false) { + $xmlrpc = Xmlrpc::instance(); // Support "web-proxy-tunelling" connections for https through proxies if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) { @@ -2281,7 +2311,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha else { error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed'); - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); return $r; } } @@ -2302,12 +2332,12 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha { $errstr= substr($data, 0, strpos($data, "\n")-1); error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr); - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); return $r; } - $GLOBALS['_xh']['headers'] = array(); - $GLOBALS['_xh']['cookies'] = array(); + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); // be tolerant to usage of \n instead of \r\n to separate headers and data // (even though it is not valid http) @@ -2341,7 +2371,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha $header_name = 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 $GLOBALS['_xh']['headers'][$header_name] + /// We should add content to $xmlrpc->_xh['headers'][$header_name] /// instead of replacing it for those... if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') { @@ -2359,10 +2389,10 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha { // glue together all received cookies, using a comma to separate them // (same as php does with getallheaders()) - if (isset($GLOBALS['_xh']['headers'][$header_name])) - $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie); + if (isset($xmlrpc->_xh['headers'][$header_name])) + $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); else - $GLOBALS['_xh']['headers'][$header_name] = trim($cookie); + $xmlrpc->_xh['headers'][$header_name] = 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 @@ -2376,14 +2406,14 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha if ($pos == 0) { $cookiename = $tag; - $GLOBALS['_xh']['cookies'][$tag] = array(); - $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val); + $xmlrpc->_xh['cookies'][$tag] = array(); + $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); } else { if ($tag != 'value') { - $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val; + $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; } } } @@ -2391,26 +2421,26 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } else { - $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]); + $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); } } elseif(isset($header_name)) { /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line); + $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); } } $data = substr($data, $bd); - if($this->debug && count($GLOBALS['_xh']['headers'])) + if($this->debug && count($xmlrpc->_xh['headers'])) { print '
';
-					foreach($GLOBALS['_xh']['headers'] as $header => $value)
+					foreach($xmlrpc->_xh['headers'] as $header => $value)
 					{
 						print htmlentities("HEADER: $header: $value\n");
 					}
-					foreach($GLOBALS['_xh']['cookies'] as $header => $value)
+					foreach($xmlrpc->_xh['cookies'] as $header => $value)
 					{
 						print htmlentities("COOKIE: $header={$value['value']}\n");
 					}
@@ -2422,33 +2452,33 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha
 				if(!$headers_processed)
 				{
 					// Decode chunked encoding sent by http 1.1 servers
-					if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
+					if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked')
 					{
 						if(!$data = decode_chunked($data))
 						{
 							error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
-							$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
+							$r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']);
 							return $r;
 						}
 					}
 
 					// Decode gzip-compressed stuff
 					// code shamelessly inspired from nusoap library by Dietrich Ayala
-					if(isset($GLOBALS['_xh']['headers']['content-encoding']))
+					if(isset($xmlrpc->_xh['headers']['content-encoding']))
 					{
-						$GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
-						if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
+						$xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']);
+						if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip')
 						{
 							// if decoding works, use it. else assume data wasn't gzencoded
 							if(function_exists('gzinflate'))
 							{
-								if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
+								if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
 								{
 									$data = $degzdata;
 									if($this->debug)
 									print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; } - elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; if($this->debug) @@ -2457,14 +2487,14 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha else { error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); return $r; } } else { error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); return $r; } } @@ -2487,6 +2517,8 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') { + $xmlrpc = Xmlrpc::instance(); + if($this->debug) { //by maHo, replaced htmlspecialchars with htmlentities @@ -2496,11 +2528,11 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha if($data == '') { error_log('XML-RPC: '.__METHOD__.': no response received from server.'); - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); return $r; } - $GLOBALS['_xh']=array(); + $xmlrpc->_xh=array(); $raw_data = $data; // parse the HTTP headers of the response, if present, and separate them from data @@ -2517,8 +2549,8 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } else { - $GLOBALS['_xh']['headers'] = array(); - $GLOBALS['_xh']['cookies'] = array(); + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); } if($this->debug) @@ -2550,22 +2582,22 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha if ($return_type == 'xml') { $r = new xmlrpcresp($data, 0, '', 'xml'); - $r->hdrs = $GLOBALS['_xh']['headers']; - $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; $r->raw_data = $raw_data; return $r; } // try to 'guestimate' the character encoding of the received response - $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data); + $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); - $GLOBALS['_xh']['ac']=''; - //$GLOBALS['_xh']['qt']=''; //unused... - $GLOBALS['_xh']['stack'] = array(); - $GLOBALS['_xh']['valuestack'] = array(); - $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc - $GLOBALS['_xh']['isf_reason']=''; - $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse' + $xmlrpc->_xh['ac']=''; + //$xmlrpc->_xh['qt']=''; //unused... + $xmlrpc->_xh['stack'] = array(); + $xmlrpc->_xh['valuestack'] = array(); + $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc + $xmlrpc->_xh['isf_reason']=''; + $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' // if response charset encoding is not known / supported, try to use // the default encoding and parse the xml anyway, but log a warning... @@ -2575,7 +2607,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); - $resp_encoding = $GLOBALS['xmlrpc_defencoding']; + $resp_encoding = $xmlrpc->xmlrpc_defencoding; } $parser = xml_parser_create($resp_encoding); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); @@ -2585,13 +2617,13 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha // we use the broadest one, ie. utf8 // This allows to send data which is native in various charset, // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding - if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + if (!in_array($xmlrpc->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, $GLOBALS['xmlrpc_internalencoding']); + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $xmlrpc->xmlrpc_internalencoding); } if ($return_type == 'phpvals') @@ -2621,38 +2653,38 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha xml_get_current_line_number($parser), xml_get_current_column_number($parser)); } error_log($errstr); - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); xml_parser_free($parser); if($this->debug) { print $errstr; } - $r->hdrs = $GLOBALS['_xh']['headers']; - $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; $r->raw_data = $raw_data; return $r; } xml_parser_free($parser); // second error check: xml well formed but not xml-rpc compliant - if ($GLOBALS['_xh']['isf'] > 1) + if ($xmlrpc->_xh['isf'] > 1) { if ($this->debug) { /// @todo echo something for user? } - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], - $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value'])) + elseif ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) { // something odd has happened // and it's time to generate a client side error // indicating something odd went on - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], - $GLOBALS['xmlrpcstr']['invalid_return']); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return']); } else { @@ -2660,15 +2692,15 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha { print "
---PARSED---\n";
 					// somehow htmlentities chokes on var_export, and some full html string...
-					//print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
-					print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));
+					//print htmlentitites(var_export($xmlrpc->_xh['value'], true));
+					print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
 					print "\n---END---
"; } - // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object. - $v =& $GLOBALS['_xh']['value']; + // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. + $v =& $xmlrpc->_xh['value']; - if($GLOBALS['_xh']['isf']) + if($xmlrpc->_xh['isf']) { /// @todo we should test here if server sent an int and a string, /// and/or coerce them into such... @@ -2699,8 +2731,8 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } } - $r->hdrs = $GLOBALS['_xh']['headers']; - $r->_cookies = $GLOBALS['_xh']['cookies']; + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; $r->raw_data = $raw_data; return $r; } @@ -2778,7 +2810,13 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function addScalar($val, $type='string') { - $typeof=@$GLOBALS['xmlrpcTypes'][$type]; + $xmlrpc = Xmlrpc::instance(); + + $typeof = null; + if(isset($xmlrpc->xmlrpcTypes[$type])) { + $typeof = $xmlrpc->xmlrpcTypes[$type]; + } + if($typeof!=1) { error_log("XML-RPC: ".__METHOD__.": not a scalar type ($type)"); @@ -2788,7 +2826,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha // coerce booleans into correct values // NB: we should either do it for datetimes, integers and doubles, too, // or just plain remove this check, implemented on booleans only... - if($type==$GLOBALS['xmlrpcBoolean']) + if($type==$xmlrpc->xmlrpcBoolean) { if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false'))) { @@ -2834,9 +2872,10 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function addArray($vals) { + $xmlrpc = Xmlrpc::instance(); if($this->mytype==0) { - $this->mytype=$GLOBALS['xmlrpcTypes']['array']; + $this->mytype=$xmlrpc->xmlrpcTypes['array']; $this->me['array']=$vals; return 1; } @@ -2863,9 +2902,11 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function addStruct($vals) { + $xmlrpc = Xmlrpc::instance(); + if($this->mytype==0) { - $this->mytype=$GLOBALS['xmlrpcTypes']['struct']; + $this->mytype=$xmlrpc->xmlrpcTypes['struct']; $this->me['struct']=$vals; return 1; } @@ -2927,28 +2968,34 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function serializedata($typ, $val, $charset_encoding='') { + $xmlrpc = Xmlrpc::instance(); $rs=''; - switch(@$GLOBALS['xmlrpcTypes'][$typ]) + + if(!isset($xmlrpc->xmlrpcTypes[$typ])) { + return $rs; + } + + switch($xmlrpc->xmlrpcTypes[$typ]) { case 1: switch($typ) { - case $GLOBALS['xmlrpcBase64']: + case $xmlrpc->xmlrpcBase64: $rs.="<${typ}>" . base64_encode($val) . ""; break; - case $GLOBALS['xmlrpcBoolean']: + case $xmlrpc->xmlrpcBoolean: $rs.="<${typ}>" . ($val ? '1' : '0') . ""; break; - case $GLOBALS['xmlrpcString']: + case $xmlrpc->xmlrpcString: // G. Giunta 2005/2/13: do NOT use htmlentities, since // it will produce named html entities, which are invalid xml - $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). ""; + $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; break; - case $GLOBALS['xmlrpcInt']: - case $GLOBALS['xmlrpcI4']: + case $xmlrpc->xmlrpcInt: + case $xmlrpc->xmlrpcI4: $rs.="<${typ}>".(int)$val.""; break; - case $GLOBALS['xmlrpcDouble']: + case $xmlrpc->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. @@ -2956,7 +3003,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha // 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, '.', '')).""; break; - case $GLOBALS['xmlrpcDateTime']: + case $xmlrpc->xmlrpcDateTime: if (is_string($val)) { $rs.="<${typ}>${val}"; @@ -2975,8 +3022,8 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha $rs.="<${typ}>${val}"; } break; - case $GLOBALS['xmlrpcNull']: - if ($GLOBALS['xmlrpc_null_apache_encoding']) + case $xmlrpc->xmlrpcNull: + if ($xmlrpc->xmlrpc_null_apache_encoding) { $rs.=""; } @@ -3003,7 +3050,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } foreach($val as $key2 => $val2) { - $rs.=''.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."\n"; + $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; //$rs.=$this->serializeval($val2); $rs.=$val2->serialize($charset_encoding); $rs.="\n"; @@ -3159,11 +3206,13 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function scalartyp() { + $xmlrpc = Xmlrpc::instance(); + reset($this->me); list($a,)=each($this->me); - if($a==$GLOBALS['xmlrpcI4']) + if($a==$xmlrpc->xmlrpcI4) { - $a=$GLOBALS['xmlrpcInt']; + $a=$xmlrpc->xmlrpcInt; } return $a; } @@ -3407,25 +3456,26 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function php_xmlrpc_encode($php_val, $options=array()) { + $xmlrpc = Xmlrpc::instance(); $type = gettype($php_val); 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}$/', $php_val)) - $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']); + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDateTime); else - $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcString']); + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcString); break; case 'integer': - $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']); + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcInt); break; case 'double': - $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']); + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDouble); break; // // Add support for encoding/decoding of booleans, since they are supported in PHP case 'boolean': - $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']); + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcBoolean); break; // case 'array': @@ -3448,11 +3498,11 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } if($ko) { - $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']); + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); } else { - $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcArray']); + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcArray); } break; case 'object': @@ -3462,7 +3512,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } else if(is_a($php_val, 'DateTime')) { - $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $GLOBALS['xmlrpcStruct']); + $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $xmlrpc->xmlrpcStruct); } else { @@ -3472,7 +3522,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha { $arr[$k] = php_xmlrpc_encode($v, $options); } - $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']); + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); if (in_array('encode_php_objs', $options)) { // let's save original class name into xmlrpcval: @@ -3484,11 +3534,11 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha case 'NULL': if (in_array('extension_api', $options)) { - $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcString']); + $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcString); } else if (in_array('null_extension', $options)) { - $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcNull']); + $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcNull); } else { @@ -3498,7 +3548,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha case 'resource': if (in_array('extension_api', $options)) { - $xmlrpc_val = new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']); + $xmlrpc_val = new xmlrpcval((int)$php_val, $xmlrpc->xmlrpcInt); } else { @@ -3524,28 +3574,30 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function php_xmlrpc_decode_xml($xml_val, $options=array()) { - $GLOBALS['_xh'] = array(); - $GLOBALS['_xh']['ac'] = ''; - $GLOBALS['_xh']['stack'] = array(); - $GLOBALS['_xh']['valuestack'] = array(); - $GLOBALS['_xh']['params'] = array(); - $GLOBALS['_xh']['pt'] = array(); - $GLOBALS['_xh']['isf'] = 0; - $GLOBALS['_xh']['isf_reason'] = ''; - $GLOBALS['_xh']['method'] = false; - $GLOBALS['_xh']['rt'] = ''; + $xmlrpc = Xmlrpc::instance(); + + $xmlrpc->_xh = array(); + $xmlrpc->_xh['ac'] = ''; + $xmlrpc->_xh['stack'] = array(); + $xmlrpc->_xh['valuestack'] = array(); + $xmlrpc->_xh['params'] = array(); + $xmlrpc->_xh['pt'] = array(); + $xmlrpc->_xh['isf'] = 0; + $xmlrpc->_xh['isf_reason'] = ''; + $xmlrpc->_xh['method'] = false; + $xmlrpc->_xh['rt'] = ''; /// @todo 'guestimate' encoding $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($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + if (!in_array($xmlrpc->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, $GLOBALS['xmlrpc_internalencoding']); + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $xmlrpc->xmlrpc_internalencoding); } xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee'); xml_set_character_data_handler($parser, 'xmlrpc_cd'); @@ -3560,16 +3612,16 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha return false; } xml_parser_free($parser); - if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too??? + if ($xmlrpc->_xh['isf'] > 1) // test that $xmlrpc->_xh['value'] is an obj, too??? { - error_log($GLOBALS['_xh']['isf_reason']); + error_log($xmlrpc->_xh['isf_reason']); return false; } - switch ($GLOBALS['_xh']['rt']) + switch ($xmlrpc->_xh['rt']) { case 'methodresponse': - $v =& $GLOBALS['_xh']['value']; - if ($GLOBALS['_xh']['isf'] == 1) + $v =& $xmlrpc->_xh['value']; + if ($xmlrpc->_xh['isf'] == 1) { $vc = $v->structmem('faultCode'); $vs = $v->structmem('faultString'); @@ -3581,14 +3633,14 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha } return $r; case 'methodcall': - $m = new xmlrpcmsg($GLOBALS['_xh']['method']); - for($i=0; $i < count($GLOBALS['_xh']['params']); $i++) + $m = new xmlrpcmsg($xmlrpc->_xh['method']); + for($i=0; $i < count($xmlrpc->_xh['params']); $i++) { - $m->addParam($GLOBALS['_xh']['params'][$i]); + $m->addParam($xmlrpc->_xh['params'][$i]); } return $m; case 'value': - return $GLOBALS['_xh']['value']; + return $xmlrpc->_xh['value']; default: return false; } @@ -3665,6 +3717,8 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha */ function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) { + $xmlrpc = Xmlrpc::instance(); + // discussion: see http://www.yale.edu/pclt/encoding/ // 1 - test if encoding is specified in HTTP HEADERS @@ -3743,7 +3797,7 @@ xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $cha // 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 $GLOBALS['xmlrpc_defencoding']; + return $xmlrpc->xmlrpc_defencoding; } } From ae97a6704edc1c6d0c4966a5f0e232d570635515 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Thu, 22 May 2014 11:32:23 +0300 Subject: [PATCH 005/228] xmlrpc.inc: changed verifyhost from 1 to 2. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New PHP versions (PHP 5.3 and so on) does not support CURL’s ssl host checking option 1 anymore, 2 is enforced or no checks. --- ChangeLog | 1 + lib/xmlrpc.inc | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index c4c793d2..fa261c51 100644 --- a/ChangeLog +++ b/ChangeLog @@ -4,6 +4,7 @@ * removed deprecated xmlEntities * removed deprecated xmlrpc_backslash * converted $GLOBALS to internal class. This makes testing much easier and should be more flexible regarding other projects + * changed verifyhost from 1 to 2. This makes modern php versions work properly. 2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 52a1104f..64f41419 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -814,7 +814,7 @@ class Xmlrpc { var $key=''; var $keypass=''; var $verifypeer=true; - var $verifyhost=1; + var $verifyhost=2; var $no_multicall=false; var $proxy=''; var $proxyport=0; From 99ba1306304684961b36aa997d77554db6c23a46 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:07:59 +0300 Subject: [PATCH 006/228] Renamed .inc files to .php files .inc extension for included PHP files is not recommended, instead standard .php should be PHP files extension. --- lib/{xmlrpc.inc => xmlrpc.php} | 0 lib/{xmlrpc_wrappers.inc => xmlrpc_wrappers.php} | 0 lib/{xmlrpcs.inc => xmlrpcs.php} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename lib/{xmlrpc.inc => xmlrpc.php} (100%) rename lib/{xmlrpc_wrappers.inc => xmlrpc_wrappers.php} (100%) rename lib/{xmlrpcs.inc => xmlrpcs.php} (100%) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.php similarity index 100% rename from lib/xmlrpc.inc rename to lib/xmlrpc.php diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.php similarity index 100% rename from lib/xmlrpc_wrappers.inc rename to lib/xmlrpc_wrappers.php diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.php similarity index 100% rename from lib/xmlrpcs.inc rename to lib/xmlrpcs.php From 48afb3ac762b04a5a33b99bd4fbdea612e7302f5 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:19:35 +0300 Subject: [PATCH 007/228] Convert tabs to spaces. --- lib/xmlrpc.php | 7573 ++++++++++++++++++++------------------- lib/xmlrpc_wrappers.php | 1798 +++++----- lib/xmlrpcs.php | 2403 ++++++------- 3 files changed, 5888 insertions(+), 5886 deletions(-) diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index 64f41419..e42571d8 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -36,3799 +36,3800 @@ class Xmlrpc { - public $xmlrpcI4 = "i4"; - public $xmlrpcInt = "int"; - public $xmlrpcBoolean = "boolean"; - public $xmlrpcDouble = "double"; - public $xmlrpcString = "string"; - public $xmlrpcDateTime = "dateTime.iso8601"; - public $xmlrpcBase64 = "base64"; - public $xmlrpcArray = "array"; - public $xmlrpcStruct = "struct"; - public $xmlrpcValue = "undefined"; - public $xmlrpcNull = "null"; - - public $xmlrpcTypes; - - public $xmlrpc_valid_parents = array( - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), - 'BOOLEAN' => array('VALUE'), - 'I4' => 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 - ); - - // tables used for transcoding different charsets into us-ascii xml - public $xml_iso88591_Entities = 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 reciving them...) - /* - $GLOBALS['xml_cp1252_Entities']=array(); - for ($i = 128; $i < 160; $i++) - { - $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i); - } - $GLOBALS['xml_cp1252_Entities']['out'] = array( - '€', '?', '‚', 'ƒ', - '„', '…', '†', '‡', - 'ˆ', '‰', 'Š', '‹', - 'Œ', '?', 'Ž', '?', - '?', '‘', '’', '“', - '”', '•', '–', '—', - '˜', '™', 'š', '›', - 'œ', '?', 'ž', 'Ÿ' - ); - */ - - 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 - ); - - 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 messages and - // by the client for received responses when received charset cannot be determined - // or is not supported - public $xmlrpc_defencoding = "UTF-8"; - - // 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 - public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? - - public $xmlrpcName = "XML-RPC for PHP"; - public $xmlrpcVersion = "3.0.0.beta"; - - // let user errors start at 800 - public $xmlrpcerruser = 800; - // let XML parse errors start at 100 - public $xmlrpcerrxml = 100; - - // set to TRUE to enable correct decoding of and values - public $xmlrpc_null_extension = false; - - // set to TRUE to enable encoding of php NULL values to instead of - public $xmlrpc_null_apache_encoding = false; - - public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; - - // used to store state during parsing - // quick explanation of components: - // ac - used to accumulate values - // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) - // isf_reason - used for storing xmlrpcresp fault string - // lv - used to indicate "looking for a value": implements - // the logic to allow values with no types to be strings - // params - used to store parameters in method calls - // method - used to store method name - // stack - array with genealogy of xml elements names: - // used to validate nesting of xmlrpc elements - public $_xh = null; - - private static $instance = null; - - private function __construct() { - $this->xmlrpcTypes = array( - $this->xmlrpcI4 => 1, - $this->xmlrpcInt => 1, - $this->xmlrpcBoolean => 1, - $this->xmlrpcDouble => 1, - $this->xmlrpcString => 1, - $this->xmlrpcDateTime => 1, - $this->xmlrpcBase64 => 1, - $this->xmlrpcArray => 2, - $this->xmlrpcStruct => 3, - $this->xmlrpcNull => 1 - ); - - 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};"; - } - } - - /** - * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. - */ - public static function instance() { - if(Xmlrpc::$instance === null) { - Xmlrpc::$instance = new Xmlrpc(); - } - - return Xmlrpc::$instance; - } + public $xmlrpcI4 = "i4"; + public $xmlrpcInt = "int"; + public $xmlrpcBoolean = "boolean"; + public $xmlrpcDouble = "double"; + public $xmlrpcString = "string"; + public $xmlrpcDateTime = "dateTime.iso8601"; + public $xmlrpcBase64 = "base64"; + public $xmlrpcArray = "array"; + public $xmlrpcStruct = "struct"; + public $xmlrpcValue = "undefined"; + public $xmlrpcNull = "null"; + + public $xmlrpcTypes; + + public $xmlrpc_valid_parents = array( + 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), + 'BOOLEAN' => array('VALUE'), + 'I4' => 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 + ); + + // tables used for transcoding different charsets into us-ascii xml + public $xml_iso88591_Entities = 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 reciving them...) + /* + $GLOBALS['xml_cp1252_Entities']=array(); + for ($i = 128; $i < 160; $i++) + { + $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i); + } + $GLOBALS['xml_cp1252_Entities']['out'] = array( + '€', '?', '‚', 'ƒ', + '„', '…', '†', '‡', + 'ˆ', '‰', 'Š', '‹', + 'Œ', '?', 'Ž', '?', + '?', '‘', '’', '“', + '”', '•', '–', '—', + '˜', '™', 'š', '›', + 'œ', '?', 'ž', 'Ÿ' + ); + */ + + 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 + ); + + 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 messages and + // by the client for received responses when received charset cannot be determined + // or is not supported + public $xmlrpc_defencoding = "UTF-8"; + + // 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 + public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? + + public $xmlrpcName = "XML-RPC for PHP"; + public $xmlrpcVersion = "3.0.0.beta"; + + // let user errors start at 800 + public $xmlrpcerruser = 800; + // let XML parse errors start at 100 + public $xmlrpcerrxml = 100; + + // set to TRUE to enable correct decoding of and values + public $xmlrpc_null_extension = false; + + // set to TRUE to enable encoding of php NULL values to instead of + public $xmlrpc_null_apache_encoding = false; + + public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; + + // used to store state during parsing + // quick explanation of components: + // ac - used to accumulate values + // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) + // isf_reason - used for storing xmlrpcresp fault string + // lv - used to indicate "looking for a value": implements + // the logic to allow values with no types to be strings + // params - used to store parameters in method calls + // method - used to store method name + // stack - array with genealogy of xml elements names: + // used to validate nesting of xmlrpc elements + public $_xh = null; + + private static $instance = null; + + private function __construct() { + $this->xmlrpcTypes = array( + $this->xmlrpcI4 => 1, + $this->xmlrpcInt => 1, + $this->xmlrpcBoolean => 1, + $this->xmlrpcDouble => 1, + $this->xmlrpcString => 1, + $this->xmlrpcDateTime => 1, + $this->xmlrpcBase64 => 1, + $this->xmlrpcArray => 2, + $this->xmlrpcStruct => 3, + $this->xmlrpcNull => 1 + ); + + 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};"; + } + } + + /** + * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. + */ + public static function instance() { + if(Xmlrpc::$instance === null) { + Xmlrpc::$instance = new Xmlrpc(); + } + + return Xmlrpc::$instance; + } } - /** - * 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 - */ - function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') - { - $xmlrpc = Xmlrpc::instance(); - if ($src_encoding == '') - { - // lame, but we know no better... - $src_encoding = $xmlrpc->xmlrpc_internalencoding; - } - - switch(strtoupper($src_encoding.'_'.$dest_encoding)) - { - case 'ISO-8859-1_': - case 'ISO-8859-1_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($xmlrpc->xml_iso88591_Entities['in'], $xmlrpc->xml_iso88591_Entities['out'], $escaped_data); - break; - case 'ISO-8859-1_UTF-8': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = utf8_encode($escaped_data); - 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': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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 - $escaped_data = ''; - // be kind to users creating string xmlrpcvals out of different php types - $data = (string) $data; - $ns = strlen ($data); - for ($nn = 0; $nn < $ns; $nn++) - { - $ch = $data[$nn]; - $ii = ord($ch); - //1 7 0bbbbbbb (127) - if ($ii < 128) - { - /// @todo shall we replace this with a (supposedly) faster str_replace? - switch($ii){ - case 34: - $escaped_data .= '"'; - break; - case 38: - $escaped_data .= '&'; - break; - case 39: - $escaped_data .= '''; - break; - case 60: - $escaped_data .= '<'; - break; - case 62: - $escaped_data .= '>'; - break; - default: - $escaped_data .= $ch; - } // switch - } - //2 11 110bbbbb 10bbbbbb (2047) - else if ($ii>>5 == 6) - { - $b1 = ($ii & 31); - $ii = ord($data[$nn+1]); - $b2 = ($ii & 63); - $ii = ($b1 * 64) + $b2; - $ent = sprintf ('&#%d;', $ii); - $escaped_data .= $ent; - $nn += 1; - } - //3 16 1110bbbb 10bbbbbb 10bbbbbb - else if ($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); - $escaped_data .= $ent; - $nn += 2; - } - //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - else if ($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); - $escaped_data .= $ent; - $nn += 3; - } - } - break; + +/** + * 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 + */ +function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') +{ + $xmlrpc = Xmlrpc::instance(); + if ($src_encoding == '') + { + // lame, but we know no better... + $src_encoding = $xmlrpc->xmlrpc_internalencoding; + } + + switch(strtoupper($src_encoding.'_'.$dest_encoding)) + { + case 'ISO-8859-1_': + case 'ISO-8859-1_US-ASCII': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = str_replace($xmlrpc->xml_iso88591_Entities['in'], $xmlrpc->xml_iso88591_Entities['out'], $escaped_data); + break; + case 'ISO-8859-1_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = utf8_encode($escaped_data); + 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': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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 +$escaped_data = ''; +// be kind to users creating string xmlrpcvals out of different php types +$data = (string) $data; +$ns = strlen ($data); +for ($nn = 0; $nn < $ns; $nn++) +{ + $ch = $data[$nn]; + $ii = ord($ch); + //1 7 0bbbbbbb (127) + if ($ii < 128) + { + /// @todo shall we replace this with a (supposedly) faster str_replace? + switch($ii){ + case 34: + $escaped_data .= '"'; + break; + case 38: + $escaped_data .= '&'; + break; + case 39: + $escaped_data .= '''; + break; + case 60: + $escaped_data .= '<'; + break; + case 62: + $escaped_data .= '>'; + break; + default: + $escaped_data .= $ch; + } // switch + } + //2 11 110bbbbb 10bbbbbb (2047) + else if ($ii>>5 == 6) + { + $b1 = ($ii & 31); + $ii = ord($data[$nn+1]); + $b2 = ($ii & 63); + $ii = ($b1 * 64) + $b2; + $ent = sprintf ('&#%d;', $ii); + $escaped_data .= $ent; + $nn += 1; + } + //3 16 1110bbbb 10bbbbbb 10bbbbbb + else if ($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); + $escaped_data .= $ent; + $nn += 2; + } + //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + else if ($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); + $escaped_data .= $ent; + $nn += 3; + } +} + break; /* - case 'CP1252_': - case 'CP1252_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data); - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - break; - case 'CP1252_UTF-8': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - $escaped_data = utf8_encode($escaped_data); - break; - case 'CP1252_ISO-8859-1': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - // we might as well replave 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... - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - break; + case 'CP1252_': + case 'CP1252_US-ASCII': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data); + $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); + break; + case 'CP1252_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) + $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); + $escaped_data = utf8_encode($escaped_data); + break; + case 'CP1252_ISO-8859-1': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + // we might as well replave 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... + $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); + break; */ - default: - $escaped_data = ''; - error_log("Converting from $src_encoding to $dest_encoding: not supported..."); - } - return $escaped_data; - } - - /// xml parser handler function for opening element tags - function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) - { - $xmlrpc = Xmlrpc::instance(); - // if invalid xmlrpc already detected, skip all processing - if ($xmlrpc->_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($xmlrpc->_xh['stack']) == 0) - { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( - $name != 'VALUE' && !$accept_single_vals)) - { - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = 'missing top level xmlrpc element'; - return; - } - else - { - $xmlrpc->_xh['rt'] = strtolower($name); - $xmlrpc->_xh['rt'] = strtolower($name); - } - } - else - { - // not top level element: see if parent is OK - $parent = end($xmlrpc->_xh['stack']); - if (!array_key_exists($name, $xmlrpc->xmlrpc_valid_parents) || !in_array($parent, $xmlrpc->xmlrpc_valid_parents[$name])) - { - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_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 - $xmlrpc->_xh['vt']='value'; // indicator: no value found yet - $xmlrpc->_xh['ac']=''; - $xmlrpc->_xh['lv']=1; - $xmlrpc->_xh['php_class']=null; - break; - case 'I4': - case 'INT': - case 'STRING': - case 'BOOLEAN': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - $xmlrpc->_xh['ac']=''; // reset the accumulator - break; - case 'STRUCT': - case 'ARRAY': - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - // create an empty array to hold child values, and push it onto appropriate stack - $cur_val = array(); - $cur_val['values'] = array(); - $cur_val['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'])) - { - $cur_val['php_class'] = $attrs['PHP_CLASS']; - } - $xmlrpc->_xh['valuestack'][] = $cur_val; - $xmlrpc->_xh['vt']='data'; // be prepared for a data element next - break; - case 'DATA': - if ($xmlrpc->_xh['vt']!='data') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_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 - $xmlrpc->_xh['ac']=''; - break; - case 'FAULT': - $xmlrpc->_xh['isf']=1; - break; - case 'MEMBER': - $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on - //$xmlrpc->_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 - $xmlrpc->_xh['vt']=null; - break; - case 'NIL': - case 'EX:NIL': - if ($xmlrpc->xmlrpc_null_extension) - { - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - $xmlrpc->_xh['ac']=''; // reset the accumulator - break; - } - // we do not support the extension, so - // drop through intentionally - default: - /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "found not-xmlrpc xml element $name"; - break; - } - - // Save current element name to stack, to validate nesting - $xmlrpc->_xh['stack'][] = $name; - - /// @todo optimization creep: move this inside the big switch() above - if($name!='VALUE') - { - $xmlrpc->_xh['lv']=0; - } - } - } - - /// Used in decoding xml chunks that might represent single xmlrpc values - function xmlrpc_se_any($parser, $name, $attrs) - { - xmlrpc_se($parser, $name, $attrs, true); - } - - /// xml parser handler function for close element tags - function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) - { - $xmlrpc = Xmlrpc::instance(); - - if ($xmlrpc->_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 == $curr_elem. - // we also checked for proper nesting at start of elements... - $curr_elem = array_pop($xmlrpc->_xh['stack']); - - switch($name) - { - case 'VALUE': - // This if() detects if no scalar was inside - if ($xmlrpc->_xh['vt']=='value') - { - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcString; - } - - if ($rebuild_xmlrpcvals) - { - // build the xmlrpc val out of the data received, and substitute it - $temp = new xmlrpcval($xmlrpc->_xh['value'], $xmlrpc->_xh['vt']); - // in case we got info about underlying php class, save it - // in the object we're rebuilding - if (isset($xmlrpc->_xh['php_class'])) - $temp->_php_class = $xmlrpc->_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($xmlrpc->_xh['valuestack']); - if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') - { - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $temp; - } - else - { - $xmlrpc->_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($xmlrpc->_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($xmlrpc->_xh['valuestack']); - if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') - { - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $xmlrpc->_xh['value']; - } - } - break; - case 'BOOLEAN': - case 'I4': - case 'INT': - case 'STRING': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - $xmlrpc->_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') - { - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - } - elseif ($name=='DATETIME.ISO8601') - { - if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $xmlrpc->_xh['ac'])) - { - error_log('XML-RPC: invalid value received in DATETIME: '.$xmlrpc->_xh['ac']); - } - $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcDateTime; - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - } - elseif ($name=='BASE64') - { - /// @todo check for failure of base64 decoding / catch warnings - $xmlrpc->_xh['value']=base64_decode($xmlrpc->_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 ($xmlrpc->_xh['ac']=='1' || strcasecmp($xmlrpc->_xh['ac'], 'true') == 0) - { - $xmlrpc->_xh['value']=true; - } - else - { - // log if receiveing something strange, even though we set the value to false anyway - if ($xmlrpc->_xh['ac']!='0' && strcasecmp($xmlrpc->_xh['ac'], 'false') != 0) - error_log('XML-RPC: invalid value received in BOOLEAN: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']=false; - } - } - elseif ($name=='DOUBLE') - { - // we have a DOUBLE - // we must check that only 0123456789-. are characters here - // NOTE: regexp could be much stricter than this... - if (!preg_match('/^[+-eE0123456789 \t.]+$/', $xmlrpc->_xh['ac'])) - { - /// @todo: find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in DOUBLE: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { - // it's ok, add it on - $xmlrpc->_xh['value']=(double)$xmlrpc->_xh['ac']; - } - } - else - { - // we have an I4/INT - // we must check that only 0123456789- are characters here - if (!preg_match('/^[+-]?[0123456789 \t]+$/', $xmlrpc->_xh['ac'])) - { - /// @todo find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in INT: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { - // it's ok, add it on - $xmlrpc->_xh['value']=(int)$xmlrpc->_xh['ac']; - } - } - //$xmlrpc->_xh['ac']=''; // is this necessary? - $xmlrpc->_xh['lv']=3; // indicate we've found a value - break; - case 'NAME': - $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name'] = $xmlrpc->_xh['ac']; - break; - case 'MEMBER': - //$xmlrpc->_xh['ac']=''; // is this necessary? - // add to array in the stack the last element built, - // unless no VALUE was found - if ($xmlrpc->_xh['vt']) - { - $vscount = count($xmlrpc->_xh['valuestack']); - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][$xmlrpc->_xh['valuestack'][$vscount-1]['name']] = $xmlrpc->_xh['value']; - } else - error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); - break; - case 'DATA': - //$xmlrpc->_xh['ac']=''; // is this necessary? - $xmlrpc->_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 - $curr_val = array_pop($xmlrpc->_xh['valuestack']); - $xmlrpc->_xh['value'] = $curr_val['values']; - $xmlrpc->_xh['vt']=strtolower($name); - if (isset($curr_val['php_class'])) - { - $xmlrpc->_xh['php_class'] = $curr_val['php_class']; - } - break; - case 'PARAM': - // add to array of params the current value, - // unless no VALUE was found - if ($xmlrpc->_xh['vt']) - { - $xmlrpc->_xh['params'][]=$xmlrpc->_xh['value']; - $xmlrpc->_xh['pt'][]=$xmlrpc->_xh['vt']; - } - else - error_log('XML-RPC: missing VALUE inside PARAM in received xml'); - break; - case 'METHODNAME': - $xmlrpc->_xh['method']=preg_replace('/^[\n\r\t ]+/', '', $xmlrpc->_xh['ac']); - break; - case 'NIL': - case 'EX:NIL': - if ($xmlrpc->xmlrpc_null_extension) - { - $xmlrpc->_xh['vt']='null'; - $xmlrpc->_xh['value']=null; - $xmlrpc->_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 - function xmlrpc_ee_fast($parser, $name) - { - xmlrpc_ee($parser, $name, false); - } - - /// xml parser handler function for character data - function xmlrpc_cd($parser, $data) - { - $xmlrpc = Xmlrpc::instance(); - // skip processing if xml fault already detected - if ($xmlrpc->_xh['isf'] < 2) - { - // "lookforvalue==3" means that we've found an entire value - // and should discard any further character data - if($xmlrpc->_xh['lv']!=3) - { - // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 - //if($xmlrpc->_xh['lv']==1) - //{ - // if we've found text and we're just in a then - // say we've found a value - //$xmlrpc->_xh['lv']=2; - //} - // we always initialize the accumulator before starting parsing, anyway... - //if(!@isset($xmlrpc->_xh['ac'])) - //{ - // $xmlrpc->_xh['ac'] = ''; - //} - $xmlrpc->_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... - function xmlrpc_dh($parser, $data) - { - $xmlrpc = Xmlrpc::instance(); - // skip processing if xml fault already detected - if ($xmlrpc->_xh['isf'] < 2) - { - if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') - { - // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 - //if($xmlrpc->_xh['lv']==1) - //{ - // $xmlrpc->_xh['lv']=2; - //} - $xmlrpc->_xh['ac'].=$data; - } - } - return true; - } - - class xmlrpc_client - { - var $path; - var $server; - var $port=0; - var $method='http'; - var $errno; - var $errstr; - var $debug=0; - var $username=''; - var $password=''; - var $authtype=1; - var $cert=''; - var $certpass=''; - var $cacert=''; - var $cacertdir=''; - var $key=''; - var $keypass=''; - var $verifypeer=true; - var $verifyhost=2; - var $no_multicall=false; - var $proxy=''; - var $proxyport=0; - var $proxy_user=''; - var $proxy_pass=''; - var $proxy_authtype=1; - var $cookies=array(); - var $extracurlopts=array(); - - /** - * List of http compression methods accepted by the client for responses. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib - * - * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since - * in those cases it will be up to CURL to decide the compression methods - * it supports. You might check for the presence of 'zlib' in the output of - * curl_version() to determine wheter compression is supported or not - */ - var $accepted_compression = array(); - /** - * Name of compression scheme to be used for sending requests. - * Either null, gzip or deflate - */ - var $request_compression = ''; - /** - * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see: - * http://curl.haxx.se/docs/faq.html#7.3) - */ - var $xmlrpc_curl_handle = null; - /// Whether to use persistent connections for http 1.1 and https - var $keepalive = false; - /// Charset encodings that can be decoded without problems by the client - var $accepted_charset_encodings = array(); - /// Charset encoding to be used in serializing request. NULL = use ASCII - var $request_charset_encoding = ''; - /** - * Decides the content of xmlrpcresp objects returned by calls to send() - * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' - */ - var $return_type = 'xmlrpcvals'; - /** - * Sent to servers in http headers - */ - var $user_agent; - - /** - * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php - * @param string $server the server name / ip address - * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used - * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed - */ - function xmlrpc_client($path, $server='', $port='', $method='') - { - $xmlrpc = Xmlrpc::instance(); - - // allow user to specify all params in $path - if($server == '' and $port == '' and $method == '') - { - $parts = parse_url($path); - $server = $parts['host']; - $path = isset($parts['path']) ? $parts['path'] : ''; - if(isset($parts['query'])) - { - $path .= '?'.$parts['query']; - } - if(isset($parts['fragment'])) - { - $path .= '#'.$parts['fragment']; - } - if(isset($parts['port'])) - { - $port = $parts['port']; - } - if(isset($parts['scheme'])) - { - $method = $parts['scheme']; - } - if(isset($parts['user'])) - { - $this->username = $parts['user']; - } - if(isset($parts['pass'])) - { - $this->password = $parts['pass']; - } - } - if($path == '' || $path[0] != '/') - { - $this->path='/'.$path; - } - else - { - $this->path=$path; - } - $this->server=$server; - if($port != '') - { - $this->port=$port; - } - if($method != '') - { - $this->method=$method; - } - - // if ZLIB is enabled, let the client by default accept compressed responses - if(function_exists('gzinflate') || ( - function_exists('curl_init') && (($info = curl_version()) && - ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) - )) - { - $this->accepted_compression = array('gzip', 'deflate'); - } - - // keepalives: enabled by default - $this->keepalive = true; - - // by default the xml parser can support these 3 charset encodings - $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); - - // initialize user_agent string - $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; - } - - /** - * Enables/disables the echoing to screen of the xmlrpc responses received - * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) - * @access public - */ - function setDebug($in) - { - $this->debug=$in; - } - - /** - * Add some http BASIC AUTH credentials, used by the client to authenticate - * @param string $u username - * @param string $p password - * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) - * @access public - */ - function setCredentials($u, $p, $t=1) - { - $this->username=$u; - $this->password=$p; - $this->authtype=$t; - } - - /** - * Add a client-side https certificate - * @param string $cert - * @param string $certpass - * @access public - */ - function setCertificate($cert, $certpass) - { - $this->cert = $cert; - $this->certpass = $certpass; - } - - /** - * Add a CA certificate to verify server with (see man page about - * CURLOPT_CAINFO for more details) - * @param string $cacert certificate file name (or dir holding certificates) - * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false - * @access public - */ - function setCaCertificate($cacert, $is_dir=false) - { - if ($is_dir) - { - $this->cacertdir = $cacert; - } - else - { - $this->cacert = $cacert; - } - } - - /** - * Set attributes for SSL communication: private SSL key - * NB: does not work in older php/curl installs - * Thanks to Daniel Convissor - * @param string $key The name of a file containing a private SSL key - * @param string $keypass The secret password needed to use the private SSL key - * @access public - */ - function setKey($key, $keypass) - { - $this->key = $key; - $this->keypass = $keypass; - } - - /** - * Set attributes for SSL communication: verify server certificate - * @param bool $i enable/disable verification of peer certificate - * @access public - */ - function setSSLVerifyPeer($i) - { - $this->verifypeer = $i; - } - - /** - * Set attributes for SSL communication: verify match of server cert w. hostname - * @param int $i - * @access public - */ - function setSSLVerifyHost($i) - { - $this->verifyhost = $i; - } - - /** - * Set proxy info - * @param string $proxyhost - * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS - * @param string $proxyusername Leave blank if proxy has public access - * @param string $proxypassword Leave blank if proxy has public access - * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) - { - $this->proxy = $proxyhost; - $this->proxyport = $proxyport; - $this->proxy_user = $proxyusername; - $this->proxy_pass = $proxypassword; - $this->proxy_authtype = $proxyauthtype; - } - - /** - * Enables/disables reception of compressed xmlrpc responses. - * Note that enabling reception of compressed responses merely adds some standard - * http headers to xmlrpc requests. It is up to the xmlrpc server to return - * compressed responses when receiving such requests. - * @param string $compmethod either 'gzip', 'deflate', 'any' or '' - * @access public - */ - function setAcceptedCompression($compmethod) - { - if ($compmethod == 'any') - $this->accepted_compression = array('gzip', 'deflate'); - else - if ($compmethod == false ) - $this->accepted_compression = array(); - else - $this->accepted_compression = array($compmethod); - } - - /** - * Enables/disables http compression of xmlrpc request. - * Take care when sending compressed requests: servers might not support them - * (and automatic fallback to uncompressed requests is not yet implemented) - * @param string $compmethod either 'gzip', 'deflate' or '' - * @access public - */ - function setRequestCompression($compmethod) - { - $this->request_compression = $compmethod; - } - - /** - * Adds a cookie to list of cookies that will be sent to server. - * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: - * do not do it unless you know what you are doing - * @param string $name - * @param string $value - * @param string $path - * @param string $domain - * @param int $port - * @access public - * - * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) - */ - function setCookie($name, $value='', $path='', $domain='', $port=null) - { - $this->cookies[$name]['value'] = urlencode($value); - if ($path || $domain || $port) - { - $this->cookies[$name]['path'] = $path; - $this->cookies[$name]['domain'] = $domain; - $this->cookies[$name]['port'] = $port; - $this->cookies[$name]['version'] = 1; - } - else - { - $this->cookies[$name]['version'] = 0; - } - } - - /** - * Directly set cURL options, for extra flexibility - * It allows eg. to bind client to a specific IP interface / address - * @param array $options - */ - function SetCurlOptions( $options ) - { - $this->extracurlopts = $options; - } - - /** - * Set user-agent string that will be used by this client instance - * in http headers sent to the server - */ - function SetUserAgent( $agentstring ) - { - $this->user_agent = $agentstring; - } - - /** - * Send an xmlrpc request - * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request - * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply - * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used - * @return xmlrpcresp - * @access public - */ - function& send($msg, $timeout=0, $method='') - { - // if user deos not specify http protocol, use native method of this client - // (i.e. method set during call to constructor) - if($method == '') - { - $method = $this->method; - } - - if(is_array($msg)) - { - // $msg is an array of xmlrpcmsg's - $r = $this->multicall($msg, $timeout, $method); - return $r; - } - elseif(is_string($msg)) - { - $n = new xmlrpcmsg(''); - $n->payload = $msg; - $msg = $n; - } - - // where msg is an xmlrpcmsg - $msg->debug=$this->debug; - - if($method == 'https') - { - $r =& $this->sendPayloadHTTPS( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - $this->cert, - $this->certpass, - $this->cacert, - $this->cacertdir, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype, - $this->keepalive, - $this->key, - $this->keypass - ); - } - elseif($method == 'http11') - { - $r =& $this->sendPayloadCURL( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - null, - null, - null, - null, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype, - 'http', - $this->keepalive - ); - } - else - { - $r =& $this->sendPayloadHTTP10( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype - ); - } - - return $r; - } - - /** - * @access private - */ - function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, - $username='', $password='', $authtype=1, $proxyhost='', - $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) - { - $xmlrpc = Xmlrpc::instance(); - - if($port==0) - { - $port=80; - } - - // Only create the payload if it was not created previously - if(empty($msg->payload)) - { - $msg->createPayload($this->request_charset_encoding); - } - - $payload = $msg->payload; - // Deflate request body and set appropriate request headers - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { - $a = @gzencode($payload); - if($a) - { - $payload = $a; - $encoding_hdr = "Content-Encoding: gzip\r\n"; - } - } - else - { - $a = @gzcompress($payload); - if($a) - { - $payload = $a; - $encoding_hdr = "Content-Encoding: deflate\r\n"; - } - } - } - else - { - $encoding_hdr = ''; - } - - // thanks to Grant Rauscher for this - $credentials=''; - if($username!='') - { - $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; - if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0'); - } - } - - $accepted_encoding = ''; - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { - $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; - } - - $proxy_credentials = ''; - if($proxyhost) - { - if($proxyport == 0) - { - $proxyport = 8080; - } - $connectserver = $proxyhost; - $connectport = $proxyport; - $uri = 'http://'.$server.':'.$port.$this->path; - if($proxyusername != '') - { - if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0'); - } - $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; - } - } - else - { - $connectserver = $server; - $connectport = $port; - $uri = $this->path; - } - - // Cookie generation, as per rfc2965 (version 1 cookies) or - // netscape's rules (version 0 cookies) - $cookieheader=''; - if (count($this->cookies)) - { - $version = ''; - foreach ($this->cookies as $name => $cookie) - { - if ($cookie['version']) - { - $version = ' $Version="' . $cookie['version'] . '";'; - $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; - if ($cookie['path']) - $cookieheader .= ' $Path="' . $cookie['path'] . '";'; - if ($cookie['domain']) - $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; - if ($cookie['port']) - $cookieheader .= ' $Port="' . $cookie['port'] . '";'; - } - else - { - $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; - } - } - $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n"; - } - - // omit port if 80 - $port = ($port == 80) ? '' : (':' . $port); - - $op= 'POST ' . $uri. " HTTP/1.0\r\n" . - 'User-Agent: ' . $this->user_agent . "\r\n" . - 'Host: '. $server . $port . "\r\n" . - $credentials . - $proxy_credentials . - $accepted_encoding . - $encoding_hdr . - 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . - $cookieheader . - 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . - strlen($payload) . "\r\n\r\n" . - $payload; - - if($this->debug > 1) - { - print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; - // let the client see this now in case http times out... - flush(); - } - - if($timeout>0) - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); - } - else - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); - } - if($fp) - { - if($timeout>0 && function_exists('stream_set_timeout')) - { - stream_set_timeout($fp, $timeout); - } - } - else - { - $this->errstr='Connect error: '.$this->errstr; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); - return $r; - } - - if(!fputs($fp, $op, strlen($op))) - { - fclose($fp); - $this->errstr='Write error'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); - return $r; - } - else - { - // reset errno and errstr on successful socket connection - $this->errstr = ''; - } - // G. Giunta 2005/10/24: close socket before parsing. - // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) - $ipd=''; - do - { - // shall we check for $data === FALSE? - // as per the manual, it signals an error - $ipd.=fread($fp, 32768); - } while(!feof($fp)); - fclose($fp); - $r =& $msg->parseResponse($ipd, false, $this->return_type); - return $r; - - } - - /** - * @access private - */ - function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, - $keepalive=false, $key='', $keypass='') - { - $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, - $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, - $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); - return $r; - } - - /** - * Contributed by Justin Miller - * Requires curl to be built into PHP - * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! - * @access private - */ - function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', - $keepalive=false, $key='', $keypass='') - { - $xmlrpc = Xmlrpc::instance(); - - if(!function_exists('curl_init')) - { - $this->errstr='CURL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); - return $r; - } - if($method == 'https') - { - if(($info = curl_version()) && - ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) - { - $this->errstr='SSL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); - return $r; - } - } - - if($port == 0) - { - if($method == 'http') - { - $port = 80; - } - else - { - $port = 443; - } - } - - // Only create the payload if it was not created previously - if(empty($msg->payload)) - { - $msg->createPayload($this->request_charset_encoding); - } - - // Deflate request body and set appropriate request headers - $payload = $msg->payload; - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { - $a = @gzencode($payload); - if($a) - { - $payload = $a; - $encoding_hdr = 'Content-Encoding: gzip'; - } - } - else - { - $a = @gzcompress($payload); - if($a) - { - $payload = $a; - $encoding_hdr = 'Content-Encoding: deflate'; - } - } - } - else - { - $encoding_hdr = ''; - } - - if($this->debug > 1) - { - print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; - // let the client see this now in case http times out... - flush(); - } - - if(!$keepalive || !$this->xmlrpc_curl_handle) - { - $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); - if($keepalive) - { - $this->xmlrpc_curl_handle = $curl; - } - } - else - { - $curl = $this->xmlrpc_curl_handle; - } - - // results into variable - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - - if($this->debug) - { - curl_setopt($curl, CURLOPT_VERBOSE, 1); - } - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - // required for XMLRPC: post the data - curl_setopt($curl, CURLOPT_POST, 1); - // the data - curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); - - // return the header too - curl_setopt($curl, CURLOPT_HEADER, 1); - - // NB: if we set an empty string, CURL will add http header indicating - // ALL methods it is supporting. This is possibly a better option than - // letting the user tell what curl can / cannot do... - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { - //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); - // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if (count($this->accepted_compression) == 1) - { - curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); - } - else - curl_setopt($curl, CURLOPT_ENCODING, ''); - } - // extra headers - $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); - // if no keepalive is wanted, let the server know it in advance - if(!$keepalive) - { - $headers[] = 'Connection: close'; - } - // request compression header - if($encoding_hdr) - { - $headers[] = $encoding_hdr; - } - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - // timeout is borked - if($timeout) - { - curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); - } - - if($username && $password) - { - curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); - if (defined('CURLOPT_HTTPAUTH')) - { - curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); - } - else if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install'); - } - } - - if($method == 'https') - { - // set cert file - if($cert) - { - curl_setopt($curl, CURLOPT_SSLCERT, $cert); - } - // set cert password - if($certpass) - { - curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); - } - // whether to verify remote host's cert - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); - // set ca certificates file/dir - if($cacert) - { - curl_setopt($curl, CURLOPT_CAINFO, $cacert); - } - if($cacertdir) - { - curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); - } - // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($key) - { - curl_setopt($curl, CURLOPT_SSLKEY, $key); - } - // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($keypass) - { - curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); - } - // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); - } - - // proxy info - if($proxyhost) - { - if($proxyport == 0) - { - $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 - } - curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport); - //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); - if($proxyusername) - { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); - if (defined('CURLOPT_PROXYAUTH')) - { - curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); - } - else if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); - } - } - } - - // NB: should we build cookie http headers by hand rather than let CURL do it? - // the following code does not honour 'expires', 'path' and 'domain' cookie attributes - // set to client obj the the user... - if (count($this->cookies)) - { - $cookieheader = ''; - foreach ($this->cookies as $name => $cookie) - { - $cookieheader .= $name . '=' . $cookie['value'] . '; '; - } - curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); - } - - foreach ($this->extracurlopts as $opt => $val) - { - curl_setopt($curl, $opt, $val); - } - - $result = curl_exec($curl); - - if ($this->debug > 1) - { - print "
\n---CURL INFO---\n";
-				foreach(curl_getinfo($curl) as $name => $val)
-				{
-					if (is_array($val))
-					{
-						$val = implode("\n", $val);
-					}
-					print $name . ': ' . htmlentities($val) . "\n";
-				}
-
-				print "---END---\n
"; - } - - if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? - { - $this->errstr='no response'; - $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); - curl_close($curl); - if($keepalive) - { - $this->xmlrpc_curl_handle = null; - } - } - else - { - if(!$keepalive) - { - curl_close($curl); - } - $resp =& $msg->parseResponse($result, true, $this->return_type); - // if we got back a 302, we can not reuse the curl handle for later calls - if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) - { - curl_close($curl); - $this->xmlrpc_curl_handle = null; - } - } - return $resp; - } - - /** - * Send an array of request messages and return an array of responses. - * Unless $this->no_multicall has been set to true, it will try first - * to use one single xmlrpc call to server method system.multicall, and - * revert to sending many successive calls in case of failure. - * This failure is also stored in $this->no_multicall for subsequent calls. - * Unfortunately, there is no server error code universally used to denote - * the fact that multicall is unsupported, so there is no way to reliably - * distinguish between that and a temporary failure. - * If you are sure that server supports multicall and do not want to - * fallback to using many single calls, set the fourth parameter to FALSE. - * - * NB: trying to shoehorn extra functionality into existing syntax has resulted - * in pretty much convoluted code... - * - * @param array $msgs an array of xmlrpcmsg objects - * @param integer $timeout connection timeout (in seconds) - * @param string $method the http protocol variant to be used - * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted - * @return array - * @access public - */ - function multicall($msgs, $timeout=0, $method='', $fallback=true) - { - $xmlrpc = Xmlrpc::instance(); - - if ($method == '') - { - $method = $this->method; - } - if(!$this->no_multicall) - { - $results = $this->_try_multicall($msgs, $timeout, $method); - if(is_array($results)) - { - // System.multicall succeeded - return $results; - } - else - { - // either system.multicall is unsupported by server, - // or call failed for some other reason. - if ($fallback) - { - // Don't try it next time... - $this->no_multicall = true; - } - else - { - if (is_a($results, 'xmlrpcresp')) - { - $result = $results; - } - else - { - $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); - } - } - } - } - else - { - // override fallback, in case careless user tries to do two - // opposite things at the same time - $fallback = true; - } - - $results = array(); - if ($fallback) - { - // system.multicall is (probably) unsupported by server: - // emulate multicall via multiple requests - foreach($msgs as $msg) - { - $results[] =& $this->send($msg, $timeout, $method); - } - } - else - { - // user does NOT want to fallback on many single calls: - // since we should always return an array of responses, - // return an array with the same error repeated n times - foreach($msgs as $msg) - { - $results[] = $result; - } - } - return $results; - } - - /** - * Attempt to boxcar $msgs via system.multicall. - * Returns either an array of xmlrpcreponses, an xmlrpc error response - * or false (when received response does not respect valid multicall syntax) - * @access private - */ - function _try_multicall($msgs, $timeout, $method) - { - // Construct multicall message - $calls = array(); - foreach($msgs as $msg) - { - $call['methodName'] = new xmlrpcval($msg->method(),'string'); - $numParams = $msg->getNumParams(); - $params = array(); - for($i = 0; $i < $numParams; $i++) - { - $params[$i] = $msg->getParam($i); - } - $call['params'] = new xmlrpcval($params, 'array'); - $calls[] = new xmlrpcval($call, 'struct'); - } - $multicall = new xmlrpcmsg('system.multicall'); - $multicall->addParam(new xmlrpcval($calls, 'array')); - - // Attempt RPC call - $result =& $this->send($multicall, $timeout, $method); - - if($result->faultCode() != 0) - { - // call to system.multicall failed - return $result; - } - - // Unpack responses. - $rets = $result->value(); - - if ($this->return_type == 'xml') - { - return $rets; - } - else if ($this->return_type == 'phpvals') - { - ///@todo test this code branch... - $rets = $result->value(); - if(!is_array($rets)) - { - return false; // bad return type from system.multicall - } - $numRets = count($rets); - if($numRets != count($msgs)) - { - return false; // wrong number of return values. - } - - $response = array(); - for($i = 0; $i < $numRets; $i++) - { - $val = $rets[$i]; - if (!is_array($val)) { - return false; - } - switch(count($val)) - { - case 1: - if(!isset($val[0])) - { - return false; // Bad value - } - // Normal return value - $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals'); - break; - case 2: - /// @todo remove usage of @: it is apparently quite slow - $code = @$val['faultCode']; - if(!is_int($code)) - { - return false; - } - $str = @$val['faultString']; - if(!is_string($str)) - { - return false; - } - $response[$i] = new xmlrpcresp(0, $code, $str); - break; - default: - return false; - } - } - return $response; - } - else // return type == 'xmlrpcvals' - { - $rets = $result->value(); - if($rets->kindOf() != 'array') - { - return false; // bad return type from system.multicall - } - $numRets = $rets->arraysize(); - if($numRets != count($msgs)) - { - return false; // wrong number of return values. - } - - $response = array(); - for($i = 0; $i < $numRets; $i++) - { - $val = $rets->arraymem($i); - switch($val->kindOf()) - { - case 'array': - if($val->arraysize() != 1) - { - return false; // Bad value - } - // Normal return value - $response[$i] = new xmlrpcresp($val->arraymem(0)); - break; - case 'struct': - $code = $val->structmem('faultCode'); - if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') - { - return false; - } - $str = $val->structmem('faultString'); - if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') - { - return false; - } - $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); - break; - default: - return false; - } - } - return $response; - } - } - } // end class xmlrpc_client - - class xmlrpcresp - { - var $val = 0; - var $valtyp; - var $errno = 0; - var $errstr = ''; - var $payload; - var $hdrs = array(); - var $_cookies = array(); - var $content_type = 'text/xml'; - var $raw_data = ''; - - /** - * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) - * @param integer $fcode set it to anything but 0 to create an error response - * @param string $fstr the error string, in case of an error response - * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml' - * - * @todo add check that $val / $fcode / $fstr is of correct type??? - * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain - * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called... - */ - function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='') - { - if($fcode != 0) - { - // error response - $this->errno = $fcode; - $this->errstr = $fstr; - //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. - } - else - { - // successful response - $this->val = $val; - if ($valtyp == '') - { - // user did not declare type of response value: try to guess it - if (is_object($this->val) && is_a($this->val, 'xmlrpcval')) - { - $this->valtyp = 'xmlrpcvals'; - } - else if (is_string($this->val)) - { - $this->valtyp = 'xml'; - - } - else - { - $this->valtyp = 'phpvals'; - } - } - else - { - // user declares type of resp value: believe him - $this->valtyp = $valtyp; - } - } - } - - /** - * Returns the error code of the response. - * @return integer the error code of this response (0 for not-error responses) - * @access 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) - * @access public - */ - function faultString() - { - return $this->errstr; - } - - /** - * Returns the value received by the server. - * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects - * @access 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 xmlrpc_client::setCookie) or not - * @return array array of cookies received from the server - * @access public - */ - function cookies() - { - return $this->_cookies; - } - - /** - * Returns xml representation of the response. XML prologue not included - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string the xml representation of the response - * @access public - */ - function serialize($charset_encoding='') - { - $xmlrpc = Xmlrpc::instance(); - - if ($charset_encoding != '') - $this->content_type = 'text/xml; charset=' . $charset_encoding; - else - $this->content_type = 'text/xml'; - if ($xmlrpc->xmlrpc_null_apache_encoding) - { - $result = "xmlrpc_null_apache_encoding_ns."\">\n"; - } - else - { - $result = "\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 .= "\n" . + default: + $escaped_data = ''; + error_log("Converting from $src_encoding to $dest_encoding: not supported..."); + } + return $escaped_data; +} + +/// xml parser handler function for opening element tags +function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) +{ + $xmlrpc = Xmlrpc::instance(); + // if invalid xmlrpc already detected, skip all processing + if ($xmlrpc->_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($xmlrpc->_xh['stack']) == 0) + { + if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( + $name != 'VALUE' && !$accept_single_vals)) + { + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = 'missing top level xmlrpc element'; + return; + } + else + { + $xmlrpc->_xh['rt'] = strtolower($name); + $xmlrpc->_xh['rt'] = strtolower($name); + } + } + else + { + // not top level element: see if parent is OK + $parent = end($xmlrpc->_xh['stack']); + if (!array_key_exists($name, $xmlrpc->xmlrpc_valid_parents) || !in_array($parent, $xmlrpc->xmlrpc_valid_parents[$name])) + { + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_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 + $xmlrpc->_xh['vt']='value'; // indicator: no value found yet + $xmlrpc->_xh['ac']=''; + $xmlrpc->_xh['lv']=1; + $xmlrpc->_xh['php_class']=null; + break; + case 'I4': + case 'INT': + case 'STRING': + case 'BOOLEAN': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + if ($xmlrpc->_xh['vt']!='value') + { + //two data elements inside a value: an error occurred! + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; + return; + } + $xmlrpc->_xh['ac']=''; // reset the accumulator + break; + case 'STRUCT': + case 'ARRAY': + if ($xmlrpc->_xh['vt']!='value') + { + //two data elements inside a value: an error occurred! + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; + return; + } + // create an empty array to hold child values, and push it onto appropriate stack + $cur_val = array(); + $cur_val['values'] = array(); + $cur_val['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'])) + { + $cur_val['php_class'] = $attrs['PHP_CLASS']; + } + $xmlrpc->_xh['valuestack'][] = $cur_val; + $xmlrpc->_xh['vt']='data'; // be prepared for a data element next + break; + case 'DATA': + if ($xmlrpc->_xh['vt']!='data') + { + //two data elements inside a value: an error occurred! + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_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 + $xmlrpc->_xh['ac']=''; + break; + case 'FAULT': + $xmlrpc->_xh['isf']=1; + break; + case 'MEMBER': + $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on + //$xmlrpc->_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 + $xmlrpc->_xh['vt']=null; + break; + case 'NIL': + case 'EX:NIL': + if ($xmlrpc->xmlrpc_null_extension) + { + if ($xmlrpc->_xh['vt']!='value') + { + //two data elements inside a value: an error occurred! + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; + return; + } + $xmlrpc->_xh['ac']=''; // reset the accumulator + break; + } + // we do not support the extension, so + // drop through intentionally + default: + /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! + $xmlrpc->_xh['isf'] = 2; + $xmlrpc->_xh['isf_reason'] = "found not-xmlrpc xml element $name"; + break; + } + + // Save current element name to stack, to validate nesting + $xmlrpc->_xh['stack'][] = $name; + + /// @todo optimization creep: move this inside the big switch() above + if($name!='VALUE') + { + $xmlrpc->_xh['lv']=0; + } + } +} + +/// Used in decoding xml chunks that might represent single xmlrpc values +function xmlrpc_se_any($parser, $name, $attrs) +{ + xmlrpc_se($parser, $name, $attrs, true); +} + +/// xml parser handler function for close element tags +function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) +{ + $xmlrpc = Xmlrpc::instance(); + + if ($xmlrpc->_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 == $curr_elem. + // we also checked for proper nesting at start of elements... + $curr_elem = array_pop($xmlrpc->_xh['stack']); + + switch($name) + { + case 'VALUE': + // This if() detects if no scalar was inside + if ($xmlrpc->_xh['vt']=='value') + { + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; + $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcString; + } + + if ($rebuild_xmlrpcvals) + { + // build the xmlrpc val out of the data received, and substitute it + $temp = new xmlrpcval($xmlrpc->_xh['value'], $xmlrpc->_xh['vt']); + // in case we got info about underlying php class, save it + // in the object we're rebuilding + if (isset($xmlrpc->_xh['php_class'])) + $temp->_php_class = $xmlrpc->_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($xmlrpc->_xh['valuestack']); + if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') + { + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $temp; + } + else + { + $xmlrpc->_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($xmlrpc->_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($xmlrpc->_xh['valuestack']); + if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') + { + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $xmlrpc->_xh['value']; + } + } + break; + case 'BOOLEAN': + case 'I4': + case 'INT': + case 'STRING': + case 'DOUBLE': + case 'DATETIME.ISO8601': + case 'BASE64': + $xmlrpc->_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') + { + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; + } + elseif ($name=='DATETIME.ISO8601') + { + if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $xmlrpc->_xh['ac'])) + { + error_log('XML-RPC: invalid value received in DATETIME: '.$xmlrpc->_xh['ac']); + } + $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcDateTime; + $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; + } + elseif ($name=='BASE64') + { + /// @todo check for failure of base64 decoding / catch warnings + $xmlrpc->_xh['value']=base64_decode($xmlrpc->_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 ($xmlrpc->_xh['ac']=='1' || strcasecmp($xmlrpc->_xh['ac'], 'true') == 0) + { + $xmlrpc->_xh['value']=true; + } + else + { + // log if receiveing something strange, even though we set the value to false anyway + if ($xmlrpc->_xh['ac']!='0' && strcasecmp($xmlrpc->_xh['ac'], 'false') != 0) + error_log('XML-RPC: invalid value received in BOOLEAN: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']=false; + } + } + elseif ($name=='DOUBLE') + { + // we have a DOUBLE + // we must check that only 0123456789-. are characters here + // NOTE: regexp could be much stricter than this... + if (!preg_match('/^[+-eE0123456789 \t.]+$/', $xmlrpc->_xh['ac'])) + { + /// @todo: find a better way of throwing an error than this! + error_log('XML-RPC: non numeric value received in DOUBLE: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; + } + else + { + // it's ok, add it on + $xmlrpc->_xh['value']=(double)$xmlrpc->_xh['ac']; + } + } + else + { + // we have an I4/INT + // we must check that only 0123456789- are characters here + if (!preg_match('/^[+-]?[0123456789 \t]+$/', $xmlrpc->_xh['ac'])) + { + /// @todo find a better way of throwing an error than this! + error_log('XML-RPC: non numeric value received in INT: '.$xmlrpc->_xh['ac']); + $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; + } + else + { + // it's ok, add it on + $xmlrpc->_xh['value']=(int)$xmlrpc->_xh['ac']; + } + } + //$xmlrpc->_xh['ac']=''; // is this necessary? + $xmlrpc->_xh['lv']=3; // indicate we've found a value + break; + case 'NAME': + $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name'] = $xmlrpc->_xh['ac']; + break; + case 'MEMBER': + //$xmlrpc->_xh['ac']=''; // is this necessary? + // add to array in the stack the last element built, + // unless no VALUE was found + if ($xmlrpc->_xh['vt']) + { + $vscount = count($xmlrpc->_xh['valuestack']); + $xmlrpc->_xh['valuestack'][$vscount-1]['values'][$xmlrpc->_xh['valuestack'][$vscount-1]['name']] = $xmlrpc->_xh['value']; + } else + error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); + break; + case 'DATA': + //$xmlrpc->_xh['ac']=''; // is this necessary? + $xmlrpc->_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 + $curr_val = array_pop($xmlrpc->_xh['valuestack']); + $xmlrpc->_xh['value'] = $curr_val['values']; + $xmlrpc->_xh['vt']=strtolower($name); + if (isset($curr_val['php_class'])) + { + $xmlrpc->_xh['php_class'] = $curr_val['php_class']; + } + break; + case 'PARAM': + // add to array of params the current value, + // unless no VALUE was found + if ($xmlrpc->_xh['vt']) + { + $xmlrpc->_xh['params'][]=$xmlrpc->_xh['value']; + $xmlrpc->_xh['pt'][]=$xmlrpc->_xh['vt']; + } + else + error_log('XML-RPC: missing VALUE inside PARAM in received xml'); + break; + case 'METHODNAME': + $xmlrpc->_xh['method']=preg_replace('/^[\n\r\t ]+/', '', $xmlrpc->_xh['ac']); + break; + case 'NIL': + case 'EX:NIL': + if ($xmlrpc->xmlrpc_null_extension) + { + $xmlrpc->_xh['vt']='null'; + $xmlrpc->_xh['value']=null; + $xmlrpc->_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 +function xmlrpc_ee_fast($parser, $name) +{ + xmlrpc_ee($parser, $name, false); +} + +/// xml parser handler function for character data +function xmlrpc_cd($parser, $data) +{ + $xmlrpc = Xmlrpc::instance(); + // skip processing if xml fault already detected + if ($xmlrpc->_xh['isf'] < 2) + { + // "lookforvalue==3" means that we've found an entire value + // and should discard any further character data + if($xmlrpc->_xh['lv']!=3) + { + // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 + //if($xmlrpc->_xh['lv']==1) + //{ + // if we've found text and we're just in a then + // say we've found a value + //$xmlrpc->_xh['lv']=2; + //} + // we always initialize the accumulator before starting parsing, anyway... + //if(!@isset($xmlrpc->_xh['ac'])) + //{ + // $xmlrpc->_xh['ac'] = ''; + //} + $xmlrpc->_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... +function xmlrpc_dh($parser, $data) +{ + $xmlrpc = Xmlrpc::instance(); + // skip processing if xml fault already detected + if ($xmlrpc->_xh['isf'] < 2) + { + if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') + { + // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 + //if($xmlrpc->_xh['lv']==1) + //{ + // $xmlrpc->_xh['lv']=2; + //} + $xmlrpc->_xh['ac'].=$data; + } + } + return true; +} + +class xmlrpc_client +{ + var $path; + var $server; + var $port=0; + var $method='http'; + var $errno; + var $errstr; + var $debug=0; + var $username=''; + var $password=''; + var $authtype=1; + var $cert=''; + var $certpass=''; + var $cacert=''; + var $cacertdir=''; + var $key=''; + var $keypass=''; + var $verifypeer=true; + var $verifyhost=2; + var $no_multicall=false; + var $proxy=''; + var $proxyport=0; + var $proxy_user=''; + var $proxy_pass=''; + var $proxy_authtype=1; + var $cookies=array(); + var $extracurlopts=array(); + + /** + * List of http compression methods accepted by the client for responses. + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + * + * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since + * in those cases it will be up to CURL to decide the compression methods + * it supports. You might check for the presence of 'zlib' in the output of + * curl_version() to determine wheter compression is supported or not + */ + var $accepted_compression = array(); + /** + * Name of compression scheme to be used for sending requests. + * Either null, gzip or deflate + */ + var $request_compression = ''; + /** + * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see: + * http://curl.haxx.se/docs/faq.html#7.3) + */ + var $xmlrpc_curl_handle = null; + /// Whether to use persistent connections for http 1.1 and https + var $keepalive = false; + /// Charset encodings that can be decoded without problems by the client + var $accepted_charset_encodings = array(); + /// Charset encoding to be used in serializing request. NULL = use ASCII + var $request_charset_encoding = ''; + /** + * Decides the content of xmlrpcresp objects returned by calls to send() + * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' + */ + var $return_type = 'xmlrpcvals'; + /** + * Sent to servers in http headers + */ + var $user_agent; + + /** + * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php + * @param string $server the server name / ip address + * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used + * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed + */ + function xmlrpc_client($path, $server='', $port='', $method='') + { + $xmlrpc = Xmlrpc::instance(); + + // allow user to specify all params in $path + if($server == '' and $port == '' and $method == '') + { + $parts = parse_url($path); + $server = $parts['host']; + $path = isset($parts['path']) ? $parts['path'] : ''; + if(isset($parts['query'])) + { + $path .= '?'.$parts['query']; + } + if(isset($parts['fragment'])) + { + $path .= '#'.$parts['fragment']; + } + if(isset($parts['port'])) + { + $port = $parts['port']; + } + if(isset($parts['scheme'])) + { + $method = $parts['scheme']; + } + if(isset($parts['user'])) + { + $this->username = $parts['user']; + } + if(isset($parts['pass'])) + { + $this->password = $parts['pass']; + } + } + if($path == '' || $path[0] != '/') + { + $this->path='/'.$path; + } + else + { + $this->path=$path; + } + $this->server=$server; + if($port != '') + { + $this->port=$port; + } + if($method != '') + { + $this->method=$method; + } + + // if ZLIB is enabled, let the client by default accept compressed responses + if(function_exists('gzinflate') || ( + function_exists('curl_init') && (($info = curl_version()) && + ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) + )) + { + $this->accepted_compression = array('gzip', 'deflate'); + } + + // keepalives: enabled by default + $this->keepalive = true; + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // initialize user_agent string + $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; + } + + /** + * Enables/disables the echoing to screen of the xmlrpc responses received + * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) + * @access public + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Add some http BASIC AUTH credentials, used by the client to authenticate + * @param string $u username + * @param string $p password + * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) + * @access public + */ + function setCredentials($u, $p, $t=1) + { + $this->username=$u; + $this->password=$p; + $this->authtype=$t; + } + + /** + * Add a client-side https certificate + * @param string $cert + * @param string $certpass + * @access public + */ + function setCertificate($cert, $certpass) + { + $this->cert = $cert; + $this->certpass = $certpass; + } + + /** + * Add a CA certificate to verify server with (see man page about + * CURLOPT_CAINFO for more details) + * @param string $cacert certificate file name (or dir holding certificates) + * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false + * @access public + */ + function setCaCertificate($cacert, $is_dir=false) + { + if ($is_dir) + { + $this->cacertdir = $cacert; + } + else + { + $this->cacert = $cacert; + } + } + + /** + * Set attributes for SSL communication: private SSL key + * NB: does not work in older php/curl installs + * Thanks to Daniel Convissor + * @param string $key The name of a file containing a private SSL key + * @param string $keypass The secret password needed to use the private SSL key + * @access public + */ + function setKey($key, $keypass) + { + $this->key = $key; + $this->keypass = $keypass; + } + + /** + * Set attributes for SSL communication: verify server certificate + * @param bool $i enable/disable verification of peer certificate + * @access public + */ + function setSSLVerifyPeer($i) + { + $this->verifypeer = $i; + } + + /** + * Set attributes for SSL communication: verify match of server cert w. hostname + * @param int $i + * @access public + */ + function setSSLVerifyHost($i) + { + $this->verifyhost = $i; + } + + /** + * Set proxy info + * @param string $proxyhost + * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyusername Leave blank if proxy has public access + * @param string $proxypassword Leave blank if proxy has public access + * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy + * @access public + */ + function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + { + $this->proxy = $proxyhost; + $this->proxyport = $proxyport; + $this->proxy_user = $proxyusername; + $this->proxy_pass = $proxypassword; + $this->proxy_authtype = $proxyauthtype; + } + + /** + * Enables/disables reception of compressed xmlrpc responses. + * Note that enabling reception of compressed responses merely adds some standard + * http headers to xmlrpc requests. It is up to the xmlrpc server to return + * compressed responses when receiving such requests. + * @param string $compmethod either 'gzip', 'deflate', 'any' or '' + * @access public + */ + function setAcceptedCompression($compmethod) + { + if ($compmethod == 'any') + $this->accepted_compression = array('gzip', 'deflate'); + else + if ($compmethod == false ) + $this->accepted_compression = array(); + else + $this->accepted_compression = array($compmethod); + } + + /** + * Enables/disables http compression of xmlrpc request. + * Take care when sending compressed requests: servers might not support them + * (and automatic fallback to uncompressed requests is not yet implemented) + * @param string $compmethod either 'gzip', 'deflate' or '' + * @access public + */ + function setRequestCompression($compmethod) + { + $this->request_compression = $compmethod; + } + + /** + * Adds a cookie to list of cookies that will be sent to server. + * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: + * do not do it unless you know what you are doing + * @param string $name + * @param string $value + * @param string $path + * @param string $domain + * @param int $port + * @access public + * + * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) + */ + function setCookie($name, $value='', $path='', $domain='', $port=null) + { + $this->cookies[$name]['value'] = urlencode($value); + if ($path || $domain || $port) + { + $this->cookies[$name]['path'] = $path; + $this->cookies[$name]['domain'] = $domain; + $this->cookies[$name]['port'] = $port; + $this->cookies[$name]['version'] = 1; + } + else + { + $this->cookies[$name]['version'] = 0; + } + } + + /** + * Directly set cURL options, for extra flexibility + * It allows eg. to bind client to a specific IP interface / address + * @param array $options + */ + function SetCurlOptions( $options ) + { + $this->extracurlopts = $options; + } + + /** + * Set user-agent string that will be used by this client instance + * in http headers sent to the server + */ + function SetUserAgent( $agentstring ) + { + $this->user_agent = $agentstring; + } + + /** + * Send an xmlrpc request + * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request + * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply + * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used + * @return xmlrpcresp + * @access public + */ + function& send($msg, $timeout=0, $method='') + { + // if user deos not specify http protocol, use native method of this client + // (i.e. method set during call to constructor) + if($method == '') + { + $method = $this->method; + } + + if(is_array($msg)) + { + // $msg is an array of xmlrpcmsg's + $r = $this->multicall($msg, $timeout, $method); + return $r; + } + elseif(is_string($msg)) + { + $n = new xmlrpcmsg(''); + $n->payload = $msg; + $msg = $n; + } + + // where msg is an xmlrpcmsg + $msg->debug=$this->debug; + + if($method == 'https') + { + $r =& $this->sendPayloadHTTPS( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->cert, + $this->certpass, + $this->cacert, + $this->cacertdir, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + $this->keepalive, + $this->key, + $this->keypass + ); + } + elseif($method == 'http11') + { + $r =& $this->sendPayloadCURL( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + null, + null, + null, + null, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + 'http', + $this->keepalive + ); + } + else + { + $r =& $this->sendPayloadHTTP10( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype + ); + } + + return $r; + } + + /** + * @access private + */ + function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, + $username='', $password='', $authtype=1, $proxyhost='', + $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) + { + $xmlrpc = Xmlrpc::instance(); + + if($port==0) + { + $port=80; + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + $payload = $msg->payload; + // Deflate request body and set appropriate request headers + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: gzip\r\n"; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: deflate\r\n"; + } + } + } + else + { + $encoding_hdr = ''; + } + + // thanks to Grant Rauscher for this + $credentials=''; + if($username!='') + { + $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; + if ($authtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0'); + } + } + + $accepted_encoding = ''; + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; + } + + $proxy_credentials = ''; + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; + } + $connectserver = $proxyhost; + $connectport = $proxyport; + $uri = 'http://'.$server.':'.$port.$this->path; + if($proxyusername != '') + { + if ($proxyauthtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0'); + } + $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; + } + } + else + { + $connectserver = $server; + $connectport = $port; + $uri = $this->path; + } + + // Cookie generation, as per rfc2965 (version 1 cookies) or + // netscape's rules (version 0 cookies) + $cookieheader=''; + if (count($this->cookies)) + { + $version = ''; + foreach ($this->cookies as $name => $cookie) + { + if ($cookie['version']) + { + $version = ' $Version="' . $cookie['version'] . '";'; + $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; + if ($cookie['path']) + $cookieheader .= ' $Path="' . $cookie['path'] . '";'; + if ($cookie['domain']) + $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; + if ($cookie['port']) + $cookieheader .= ' $Port="' . $cookie['port'] . '";'; + } + else + { + $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; + } + } + $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n"; + } + + // omit port if 80 + $port = ($port == 80) ? '' : (':' . $port); + + $op= 'POST ' . $uri. " HTTP/1.0\r\n" . + 'User-Agent: ' . $this->user_agent . "\r\n" . + 'Host: '. $server . $port . "\r\n" . + $credentials . + $proxy_credentials . + $accepted_encoding . + $encoding_hdr . + 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . + $cookieheader . + 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . + strlen($payload) . "\r\n\r\n" . + $payload; + + if($this->debug > 1) + { + print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; + // let the client see this now in case http times out... + flush(); + } + + if($timeout>0) + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); + } + else + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); + } + if($fp) + { + if($timeout>0 && function_exists('stream_set_timeout')) + { + stream_set_timeout($fp, $timeout); + } + } + else + { + $this->errstr='Connect error: '.$this->errstr; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + return $r; + } + + if(!fputs($fp, $op, strlen($op))) + { + fclose($fp); + $this->errstr='Write error'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); + return $r; + } + else + { + // reset errno and errstr on successful socket connection + $this->errstr = ''; + } + // G. Giunta 2005/10/24: close socket before parsing. + // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) + $ipd=''; + do + { + // shall we check for $data === FALSE? + // as per the manual, it signals an error + $ipd.=fread($fp, 32768); + } while(!feof($fp)); + fclose($fp); + $r =& $msg->parseResponse($ipd, false, $this->return_type); + return $r; + + } + + /** + * @access private + */ + function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, + $keepalive=false, $key='', $keypass='') + { + $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, + $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, + $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); + return $r; + } + + /** + * Contributed by Justin Miller + * Requires curl to be built into PHP + * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + * @access private + */ + function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', + $keepalive=false, $key='', $keypass='') + { + $xmlrpc = Xmlrpc::instance(); + + if(!function_exists('curl_init')) + { + $this->errstr='CURL unavailable on this install'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); + return $r; + } + if($method == 'https') + { + if(($info = curl_version()) && + ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) + { + $this->errstr='SSL unavailable on this install'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); + return $r; + } + } + + if($port == 0) + { + if($method == 'http') + { + $port = 80; + } + else + { + $port = 443; + } + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + // Deflate request body and set appropriate request headers + $payload = $msg->payload; + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: gzip'; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: deflate'; + } + } + } + else + { + $encoding_hdr = ''; + } + + if($this->debug > 1) + { + print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; + // let the client see this now in case http times out... + flush(); + } + + if(!$keepalive || !$this->xmlrpc_curl_handle) + { + $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); + if($keepalive) + { + $this->xmlrpc_curl_handle = $curl; + } + } + else + { + $curl = $this->xmlrpc_curl_handle; + } + + // results into variable + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + + if($this->debug) + { + curl_setopt($curl, CURLOPT_VERBOSE, 1); + } + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + // required for XMLRPC: post the data + curl_setopt($curl, CURLOPT_POST, 1); + // the data + curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); + + // return the header too + curl_setopt($curl, CURLOPT_HEADER, 1); + + // NB: if we set an empty string, CURL will add http header indicating + // ALL methods it is supporting. This is possibly a better option than + // letting the user tell what curl can / cannot do... + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); + // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if (count($this->accepted_compression) == 1) + { + curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); + } + else + curl_setopt($curl, CURLOPT_ENCODING, ''); + } + // extra headers + $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + // if no keepalive is wanted, let the server know it in advance + if(!$keepalive) + { + $headers[] = 'Connection: close'; + } + // request compression header + if($encoding_hdr) + { + $headers[] = $encoding_hdr; + } + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + // timeout is borked + if($timeout) + { + curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); + } + + if($username && $password) + { + curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); + if (defined('CURLOPT_HTTPAUTH')) + { + curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); + } + else if ($authtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install'); + } + } + + if($method == 'https') + { + // set cert file + if($cert) + { + curl_setopt($curl, CURLOPT_SSLCERT, $cert); + } + // set cert password + if($certpass) + { + curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); + } + // whether to verify remote host's cert + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); + // set ca certificates file/dir + if($cacert) + { + curl_setopt($curl, CURLOPT_CAINFO, $cacert); + } + if($cacertdir) + { + curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); + } + // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($key) + { + curl_setopt($curl, CURLOPT_SSLKEY, $key); + } + // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($keypass) + { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); + } + // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); + } + + // proxy info + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 + } + curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport); + //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); + if($proxyusername) + { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); + if (defined('CURLOPT_PROXYAUTH')) + { + curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); + } + else if ($proxyauthtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); + } + } + } + + // NB: should we build cookie http headers by hand rather than let CURL do it? + // the following code does not honour 'expires', 'path' and 'domain' cookie attributes + // set to client obj the the user... + if (count($this->cookies)) + { + $cookieheader = ''; + foreach ($this->cookies as $name => $cookie) + { + $cookieheader .= $name . '=' . $cookie['value'] . '; '; + } + curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); + } + + foreach ($this->extracurlopts as $opt => $val) + { + curl_setopt($curl, $opt, $val); + } + + $result = curl_exec($curl); + + if ($this->debug > 1) + { + print "
\n---CURL INFO---\n";
+            foreach(curl_getinfo($curl) as $name => $val)
+            {
+                if (is_array($val))
+                {
+                    $val = implode("\n", $val);
+                }
+                print $name . ': ' . htmlentities($val) . "\n";
+            }
+
+            print "---END---\n
"; + } + + if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? + { + $this->errstr='no response'; + $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); + curl_close($curl); + if($keepalive) + { + $this->xmlrpc_curl_handle = null; + } + } + else + { + if(!$keepalive) + { + curl_close($curl); + } + $resp =& $msg->parseResponse($result, true, $this->return_type); + // if we got back a 302, we can not reuse the curl handle for later calls + if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) + { + curl_close($curl); + $this->xmlrpc_curl_handle = null; + } + } + return $resp; + } + + /** + * Send an array of request messages and return an array of responses. + * Unless $this->no_multicall has been set to true, it will try first + * to use one single xmlrpc call to server method system.multicall, and + * revert to sending many successive calls in case of failure. + * This failure is also stored in $this->no_multicall for subsequent calls. + * Unfortunately, there is no server error code universally used to denote + * the fact that multicall is unsupported, so there is no way to reliably + * distinguish between that and a temporary failure. + * If you are sure that server supports multicall and do not want to + * fallback to using many single calls, set the fourth parameter to FALSE. + * + * NB: trying to shoehorn extra functionality into existing syntax has resulted + * in pretty much convoluted code... + * + * @param array $msgs an array of xmlrpcmsg objects + * @param integer $timeout connection timeout (in seconds) + * @param string $method the http protocol variant to be used + * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted + * @return array + * @access public + */ + function multicall($msgs, $timeout=0, $method='', $fallback=true) + { + $xmlrpc = Xmlrpc::instance(); + + if ($method == '') + { + $method = $this->method; + } + if(!$this->no_multicall) + { + $results = $this->_try_multicall($msgs, $timeout, $method); + if(is_array($results)) + { + // System.multicall succeeded + return $results; + } + else + { + // either system.multicall is unsupported by server, + // or call failed for some other reason. + if ($fallback) + { + // Don't try it next time... + $this->no_multicall = true; + } + else + { + if (is_a($results, 'xmlrpcresp')) + { + $result = $results; + } + else + { + $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); + } + } + } + } + else + { + // override fallback, in case careless user tries to do two + // opposite things at the same time + $fallback = true; + } + + $results = array(); + if ($fallback) + { + // system.multicall is (probably) unsupported by server: + // emulate multicall via multiple requests + foreach($msgs as $msg) + { + $results[] =& $this->send($msg, $timeout, $method); + } + } + else + { + // user does NOT want to fallback on many single calls: + // since we should always return an array of responses, + // return an array with the same error repeated n times + foreach($msgs as $msg) + { + $results[] = $result; + } + } + return $results; + } + + /** + * Attempt to boxcar $msgs via system.multicall. + * Returns either an array of xmlrpcreponses, an xmlrpc error response + * or false (when received response does not respect valid multicall syntax) + * @access private + */ + function _try_multicall($msgs, $timeout, $method) + { + // Construct multicall message + $calls = array(); + foreach($msgs as $msg) + { + $call['methodName'] = new xmlrpcval($msg->method(),'string'); + $numParams = $msg->getNumParams(); + $params = array(); + for($i = 0; $i < $numParams; $i++) + { + $params[$i] = $msg->getParam($i); + } + $call['params'] = new xmlrpcval($params, 'array'); + $calls[] = new xmlrpcval($call, 'struct'); + } + $multicall = new xmlrpcmsg('system.multicall'); + $multicall->addParam(new xmlrpcval($calls, 'array')); + + // Attempt RPC call + $result =& $this->send($multicall, $timeout, $method); + + if($result->faultCode() != 0) + { + // call to system.multicall failed + return $result; + } + + // Unpack responses. + $rets = $result->value(); + + if ($this->return_type == 'xml') + { + return $rets; + } + else if ($this->return_type == 'phpvals') + { + ///@todo test this code branch... + $rets = $result->value(); + if(!is_array($rets)) + { + return false; // bad return type from system.multicall + } + $numRets = count($rets); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets[$i]; + if (!is_array($val)) { + return false; + } + switch(count($val)) + { + case 1: + if(!isset($val[0])) + { + return false; // Bad value + } + // Normal return value + $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals'); + break; + case 2: + /// @todo remove usage of @: it is apparently quite slow + $code = @$val['faultCode']; + if(!is_int($code)) + { + return false; + } + $str = @$val['faultString']; + if(!is_string($str)) + { + return false; + } + $response[$i] = new xmlrpcresp(0, $code, $str); + break; + default: + return false; + } + } + return $response; + } + else // return type == 'xmlrpcvals' + { + $rets = $result->value(); + if($rets->kindOf() != 'array') + { + return false; // bad return type from system.multicall + } + $numRets = $rets->arraysize(); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets->arraymem($i); + switch($val->kindOf()) + { + case 'array': + if($val->arraysize() != 1) + { + return false; // Bad value + } + // Normal return value + $response[$i] = new xmlrpcresp($val->arraymem(0)); + break; + case 'struct': + $code = $val->structmem('faultCode'); + if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') + { + return false; + } + $str = $val->structmem('faultString'); + if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') + { + return false; + } + $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); + break; + default: + return false; + } + } + return $response; + } + } +} // end class xmlrpc_client + +class xmlrpcresp +{ + var $val = 0; + var $valtyp; + var $errno = 0; + var $errstr = ''; + var $payload; + var $hdrs = array(); + var $_cookies = array(); + var $content_type = 'text/xml'; + var $raw_data = ''; + + /** + * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) + * @param integer $fcode set it to anything but 0 to create an error response + * @param string $fstr the error string, in case of an error response + * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml' + * + * @todo add check that $val / $fcode / $fstr is of correct type??? + * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain + * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called... + */ + function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='') + { + if($fcode != 0) + { + // error response + $this->errno = $fcode; + $this->errstr = $fstr; + //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. + } + else + { + // successful response + $this->val = $val; + if ($valtyp == '') + { + // user did not declare type of response value: try to guess it + if (is_object($this->val) && is_a($this->val, 'xmlrpcval')) + { + $this->valtyp = 'xmlrpcvals'; + } + else if (is_string($this->val)) + { + $this->valtyp = 'xml'; + + } + else + { + $this->valtyp = 'phpvals'; + } + } + else + { + // user declares type of resp value: believe him + $this->valtyp = $valtyp; + } + } + } + + /** + * Returns the error code of the response. + * @return integer the error code of this response (0 for not-error responses) + * @access 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) + * @access public + */ + function faultString() + { + return $this->errstr; + } + + /** + * Returns the value received by the server. + * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects + * @access 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 xmlrpc_client::setCookie) or not + * @return array array of cookies received from the server + * @access public + */ + function cookies() + { + return $this->_cookies; + } + + /** + * Returns xml representation of the response. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string the xml representation of the response + * @access public + */ + function serialize($charset_encoding='') + { + $xmlrpc = Xmlrpc::instance(); + + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + if ($xmlrpc->xmlrpc_null_apache_encoding) + { + $result = "xmlrpc_null_apache_encoding_ns."\">\n"; + } + else + { + $result = "\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 .= "\n" . "\nfaultCode\n" . $this->errno . "\n\n\nfaultString\n" . xmlrpc_encode_entitites($this->errstr, $xmlrpc->xmlrpc_internalencoding, $charset_encoding) . "\n\n" . "\n\n"; - } - else - { - if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) - { - if (is_string($this->val) && $this->valtyp == 'xml') - { - $result .= "\n\n" . - $this->val . - "\n"; - } - else - { - /// @todo try to build something serializable? - die('cannot serialize xmlrpcresp objects whose content is native php values'); - } - } - else - { - $result .= "\n\n" . - $this->val->serialize($charset_encoding) . - "\n"; - } - } - $result .= "\n"; - $this->payload = $result; - return $result; - } - } - - class xmlrpcmsg - { - var $payload; - var $methodname; - var $params=array(); - var $debug=0; - var $content_type = 'text/xml'; - - /** - * @param string $meth the name of the method to invoke - * @param array $pars array of parameters to be passed to the method (xmlrpcval objects) - */ - function xmlrpcmsg($meth, $pars=0) - { - $this->methodname=$meth; - if(is_array($pars) && count($pars)>0) - { - for($i=0; $iaddParam($pars[$i]); - } - } - } - - /** - * @access private - */ - function xml_header($charset_encoding='') - { - if ($charset_encoding != '') - { - return "\n\n"; - } - else - { - return "\n\n"; - } - } - - /** - * @access private - */ - function xml_footer() - { - return ''; - } - - /** - * @access private - */ - function kindOf() - { - return 'msg'; - } - - /** - * @access private - */ - function createPayload($charset_encoding='') - { - if ($charset_encoding != '') - $this->content_type = 'text/xml; charset=' . $charset_encoding; - else - $this->content_type = 'text/xml'; - $this->payload=$this->xml_header($charset_encoding); - $this->payload.='' . $this->methodname . "\n"; - $this->payload.="\n"; - for($i=0; $iparams); $i++) - { - $p=$this->params[$i]; - $this->payload.="\n" . $p->serialize($charset_encoding) . - "\n"; - } - $this->payload.="\n"; - $this->payload.=$this->xml_footer(); - } - - /** - * Gets/sets the xmlrpc method to be invoked - * @param string $meth the method to be set (leave empty not to set it) - * @return string the method that will be invoked - * @access public - */ - function method($meth='') - { - if($meth!='') - { - $this->methodname=$meth; - } - return $this->methodname; - } - - /** - * Returns xml representation of the message. XML prologue included - * @param string $charset_encoding - * @return string the xml representation of the message, xml prologue included - * @access public - */ - function serialize($charset_encoding='') - { - $this->createPayload($charset_encoding); - return $this->payload; - } - - /** - * Add a parameter to the list of parameters to be used upon method invocation - * @param xmlrpcval $par - * @return boolean false on failure - * @access public - */ - function addParam($par) - { - // add check: do not add to self params which are not xmlrpcvals - if(is_object($par) && is_a($par, 'xmlrpcval')) - { - $this->params[]=$par; - return true; - } - else - { - return false; - } - } - - /** - * Returns the nth parameter in the message. The index zero-based. - * @param integer $i the index of the parameter to fetch (zero based) - * @return xmlrpcval the i-th parameter - * @access public - */ - function getParam($i) { return $this->params[$i]; } - - /** - * Returns the number of parameters in the messge. - * @return integer the number of parameters currently set - * @access public - */ - function getNumParams() { return count($this->params); } - - /** - * Given an open file handle, read all data available and parse it as axmlrpc 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... - * @access public - * @param resource $fp stream pointer - * @return xmlrpcresp - * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? - */ - function &parseResponseFile($fp) - { - $ipd=''; - while($data=fread($fp, 32768)) - { - $ipd.=$data; - } - //fclose($fp); - $r =& $this->parseResponse($ipd); - return $r; - } - - /** - * Parses HTTP headers and separates them from data. - * @access private - */ - function &parseResponseHeaders(&$data, $headers_processed=false) - { - $xmlrpc = Xmlrpc::instance(); - // 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'); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); - return $r; - } - } - - // 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); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; - } - - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - - // 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) - { - $header_name = 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'][$header_name] - /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') - { - if ($header_name == '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($xmlrpc->_xh['headers'][$header_name])) - $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); - else - $xmlrpc->_xh['headers'][$header_name] = 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; - $xmlrpc->_xh['cookies'][$tag] = array(); - $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); - } - else - { - if ($tag != 'value') - { - $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; - } - } - } - } - } - else - { - $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); - } - } - elseif(isset($header_name)) - { - /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); - } - } - - $data = substr($data, $bd); - - if($this->debug && count($xmlrpc->_xh['headers'])) - { - print '
';
-					foreach($xmlrpc->_xh['headers'] as $header => $value)
-					{
-						print htmlentities("HEADER: $header: $value\n");
-					}
-					foreach($xmlrpc->_xh['cookies'] as $header => $value)
-					{
-						print htmlentities("COOKIE: $header={$value['value']}\n");
-					}
-					print "
\n"; - } - - // if CURL was used for the call, http headers have been processed, - // and dechunking + reinflating have been carried out - if(!$headers_processed) - { - // Decode chunked encoding sent by http 1.1 servers - if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked') - { - if(!$data = decode_chunked($data)) - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']); - return $r; - } - } - - // Decode gzip-compressed stuff - // code shamelessly inspired from nusoap library by Dietrich Ayala - if(isset($xmlrpc->_xh['headers']['content-encoding'])) - { - $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']); - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip') - { - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')) - { - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - else - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); - return $r; - } - } - else - { - error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); - return $r; - } - } - } - } // end of 'if needed, de-chunk, re-inflate response' - - // real stupid hack to avoid PHP complaining about returning NULL by ref - $r = null; - $r =& $r; - return $r; - } - - /** - * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. - * @param string $data the xmlrpc response, eventually including http headers - * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding - * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' - * @return xmlrpcresp - * @access public - */ - function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') - { - $xmlrpc = Xmlrpc::instance(); - - if($this->debug) - { - //by maHo, replaced htmlspecialchars with htmlentities - print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; - } - - if($data == '') - { - error_log('XML-RPC: '.__METHOD__.': no response received from server.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); - return $r; - } - - $xmlrpc->_xh=array(); - - $raw_data = $data; - // parse the HTTP headers of the response, if present, and separate them from data - if(substr($data, 0, 4) == 'HTTP') - { - $r =& $this->parseResponseHeaders($data, $headers_processed); - if ($r) - { - // failed processing of HTTP response headers - // save into response obj the full payload received, for debugging - $r->raw_data = $data; - return $r; - } - } - else - { - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - } - - if($this->debug) - { - $start = strpos($data, '', $start); - $comments = substr($data, $start, $end-$start); - print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; - } - } - - // 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 originally in PEARified version of the lib - $pos = strrpos($data, '
'); - if($pos !== false) - { - $data = substr($data, 0, $pos+17); - } - - // if user wants back raw xml, give it to him - if ($return_type == 'xml') - { - $r = new xmlrpcresp($data, 0, '', 'xml'); - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - - // try to 'guestimate' the character encoding of the received response - $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); - - $xmlrpc->_xh['ac']=''; - //$xmlrpc->_xh['qt']=''; //unused... - $xmlrpc->_xh['stack'] = array(); - $xmlrpc->_xh['valuestack'] = array(); - $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc - $xmlrpc->_xh['isf_reason']=''; - $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' - - // if response charset encoding is not known / supported, try to use - // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); - $resp_encoding = $xmlrpc->xmlrpc_defencoding; - } - $parser = xml_parser_create($resp_encoding); - 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_entitites() and setting xmlrpc_internalencoding - if (!in_array($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); - } - - if ($return_type == '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 - 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 xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); - xml_parser_free($parser); - if($this->debug) - { - print $errstr; - } - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - xml_parser_free($parser); - // second error check: xml well formed but not xml-rpc compliant - if ($xmlrpc->_xh['isf'] > 1) - { - if ($this->debug) - { - /// @todo echo something for user? - } - - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) - { - // something odd has happened - // and it's time to generate a client side error - // indicating something odd went on - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return']); - } - else - { - if ($this->debug) - { - print "
---PARSED---\n";
-					// somehow htmlentities chokes on var_export, and some full html string...
-					//print htmlentitites(var_export($xmlrpc->_xh['value'], true));
-					print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
-					print "\n---END---
"; - } - - // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. - $v =& $xmlrpc->_xh['value']; - - if($xmlrpc->_xh['isf']) - { - /// @todo we should test here if server sent an int and a string, - /// and/or coerce them into such... - if ($return_type == 'xmlrpcvals') - { - $errno_v = $v->structmem('faultCode'); - $errstr_v = $v->structmem('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 xmlrpcresp(0, $errno, $errstr); - } - else - { - $r=new xmlrpcresp($v, 0, '', $return_type); - } - } - - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - } - - class xmlrpcval - { - var $me=array(); - var $mytype=0; - var $_php_class=null; - - /** - * @param mixed $val - * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed - */ - function xmlrpcval($val=-1, $type='') - { - /// @todo: optimization creep - do not call addXX, do it all inline. - /// downside: booleans will not be coerced anymore - if($val!==-1 || $type!='') - { - // optimization creep: inlined all work done by constructor - switch($type) - { - case '': - $this->mytype=1; - $this->me['string']=$val; - break; - case 'i4': - 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)"); - } - /*if($type=='') - { - $type='string'; - } - if($GLOBALS['xmlrpcTypes'][$type]==1) - { - $this->addScalar($val,$type); - } - elseif($GLOBALS['xmlrpcTypes'][$type]==2) - { - $this->addArray($val); - } - elseif($GLOBALS['xmlrpcTypes'][$type]==3) - { - $this->addStruct($val); - }*/ - } - } - - /** - * Add a single php value to an (unitialized) xmlrpcval - * @param mixed $val - * @param string $type - * @return int 1 or 0 on failure - */ - function addScalar($val, $type='string') - { - $xmlrpc = Xmlrpc::instance(); - - $typeof = null; - if(isset($xmlrpc->xmlrpcTypes[$type])) { - $typeof = $xmlrpc->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 and doubles, too, - // or just plain remove this check, implemented on booleans only... - if($type==$xmlrpc->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 xmlrpcval can have only one value'); - return 0; - case 3: - error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval'); - return 0; - case 2: - // we're adding a scalar value to an array here - //$ar=$this->me['array']; - //$ar[]=new xmlrpcval($val, $type); - //$this->me['array']=$ar; - // Faster (?) avoid all the costly array-copy-by-val done here... - $this->me['array'][]=new xmlrpcval($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 xmlrpcval objects to an xmlrpcval - * @param array $vals - * @return int 1 or 0 on failure - * @access public - * - * @todo add some checking for $vals to be an array of xmlrpcvals? - */ - function addArray($vals) - { - $xmlrpc = Xmlrpc::instance(); - if($this->mytype==0) - { - $this->mytype=$xmlrpc->xmlrpcTypes['array']; - $this->me['array']=$vals; - return 1; - } - elseif($this->mytype==2) - { - // we're adding to an array here - $this->me['array'] = array_merge($this->me['array'], $vals); - return 1; - } - else - { - error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); - return 0; - } - } - - /** - * Add an array of named xmlrpcval objects to an xmlrpcval - * @param array $vals - * @return int 1 or 0 on failure - * @access public - * - * @todo add some checking for $vals to be an array? - */ - function addStruct($vals) - { - $xmlrpc = Xmlrpc::instance(); - - if($this->mytype==0) - { - $this->mytype=$xmlrpc->xmlrpcTypes['struct']; - $this->me['struct']=$vals; - return 1; - } - elseif($this->mytype==3) - { - // we're adding to a struct here - $this->me['struct'] = array_merge($this->me['struct'], $vals); - return 1; - } - else - { - error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); - return 0; - } - } - - // poor man's version of print_r ??? - // DEPRECATED! - function dump($ar) - { - foreach($ar as $key => $val) - { - echo "$key => $val
"; - if($key == 'array') - { - while(list($key2, $val2) = each($val)) - { - echo "-- $key2 => $val2
"; - } - } - } - } - - /** - * Returns a string containing "struct", "array" or "scalar" describing the base type of the value - * @return string - * @access public - */ - function kindOf() - { - switch($this->mytype) - { - case 3: - return 'struct'; - break; - case 2: - return 'array'; - break; - case 1: - return 'scalar'; - break; - default: - return 'undef'; - } - } - - /** - * @access private - */ - function serializedata($typ, $val, $charset_encoding='') - { - $xmlrpc = Xmlrpc::instance(); - $rs=''; - - if(!isset($xmlrpc->xmlrpcTypes[$typ])) { - return $rs; - } - - switch($xmlrpc->xmlrpcTypes[$typ]) - { - case 1: - switch($typ) - { - case $xmlrpc->xmlrpcBase64: - $rs.="<${typ}>" . base64_encode($val) . ""; - break; - case $xmlrpc->xmlrpcBoolean: - $rs.="<${typ}>" . ($val ? '1' : '0') . ""; - break; - case $xmlrpc->xmlrpcString: - // G. Giunta 2005/2/13: do NOT use htmlentities, since - // it will produce named html entities, which are invalid xml - $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; - break; - case $xmlrpc->xmlrpcInt: - case $xmlrpc->xmlrpcI4: - $rs.="<${typ}>".(int)$val.""; - break; - case $xmlrpc->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, '.', '')).""; - break; - case $xmlrpc->xmlrpcDateTime: - if (is_string($val)) - { - $rs.="<${typ}>${val}"; - } - else if(is_a($val, 'DateTime')) - { - $rs.="<${typ}>".$val->format('Ymd\TH:i:s').""; - } - else if(is_int($val)) - { - $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val).""; - } - else - { - // not really a good idea here: but what shall we output anyway? left for backward compat... - $rs.="<${typ}>${val}"; - } - break; - case $xmlrpc->xmlrpcNull: - if ($xmlrpc->xmlrpc_null_apache_encoding) - { - $rs.=""; - } - else - { - $rs.=""; - } - break; - default: - // no standard type value should arrive here, but provide a possibility - // for xmlrpcvals of unknown type... - $rs.="<${typ}>${val}"; - } - break; - case 3: - // struct - if ($this->_php_class) - { - $rs.='\n"; - } - else - { - $rs.="\n"; - } - foreach($val as $key2 => $val2) - { - $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; - //$rs.=$this->serializeval($val2); - $rs.=$val2->serialize($charset_encoding); - $rs.="\n"; - } - $rs.=''; - break; - case 2: - // array - $rs.="\n\n"; - for($i=0; $iserializeval($val[$i]); - $rs.=$val[$i]->serialize($charset_encoding); - } - $rs.="\n"; - break; - default: - break; - } - return $rs; - } - - /** - * Returns xml representation of the value. XML prologue not included - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string - * @access public - */ - function serialize($charset_encoding='') - { - // 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'))) - //{ - reset($this->me); - list($typ, $val) = each($this->me); - return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; - //} - } - - // DEPRECATED - 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 '' . $this->serializedata($typ, $val) . "\n"; - //} - } - - /** - * Checks whether a struct member with a given name is present. - * Works only on xmlrpcvals of type struct. - * @param string $m the name of the struct member to be looked up - * @return boolean - * @access public - */ - function structmemexists($m) - { - return array_key_exists($m, $this->me['struct']); - } - - /** - * Returns the value of a given struct member (an xmlrpcval object in itself). - * Will raise a php warning if struct member of given name does not exist - * @param string $m the name of the struct member to be looked up - * @return xmlrpcval - * @access public - */ - function structmem($m) - { - return $this->me['struct'][$m]; - } - - /** - * Reset internal pointer for xmlrpcvals of type struct. - * @access public - */ - function structreset() - { - reset($this->me['struct']); - } - - /** - * Return next member element for xmlrpcvals of type struct. - * @return xmlrpcval - * @access public - */ - function structeach() - { - return each($this->me['struct']); - } - - // 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? - 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; - } - - /** - * Returns the value of a scalar xmlrpcval - * @return mixed - * @access public - */ - function scalarval() - { - reset($this->me); - list(,$b)=each($this->me); - return $b; - } - - /** - * Returns the type of the xmlrpcval. - * For integers, 'int' is always returned in place of 'i4' - * @return string - * @access public - */ - function scalartyp() - { - $xmlrpc = Xmlrpc::instance(); - - reset($this->me); - list($a,)=each($this->me); - if($a==$xmlrpc->xmlrpcI4) - { - $a=$xmlrpc->xmlrpcInt; - } - return $a; - } - - /** - * Returns the m-th member of an xmlrpcval of struct type - * @param integer $m the index of the value to be retrieved (zero based) - * @return xmlrpcval - * @access public - */ - function arraymem($m) - { - return $this->me['array'][$m]; - } - - /** - * Returns the number of members in an xmlrpcval of array type - * @return integer - * @access public - */ - function arraysize() - { - return count($this->me['array']); - } - - /** - * Returns the number of members in an xmlrpcval of struct type - * @return integer - * @access public - */ - function structsize() - { - return count($this->me['struct']); - } - } - - - // date helpers - - /** - * 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 - */ - function iso8601_encode($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) - */ - function iso8601_decode($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; - } - - /** - * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types. - * - * Works with xmlrpc message 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 xmlrpcval $xmlrpc_val - * @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 - */ - function php_xmlrpc_decode($xmlrpc_val, $options=array()) - { - switch($xmlrpc_val->kindOf()) - { - case 'scalar': - if (in_array('extension_api', $options)) - { - reset($xmlrpc_val->me); - list($typ,$val) = each($xmlrpc_val->me); - switch ($typ) - { - case 'dateTime.iso8601': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->xmlrpc_type = 'datetime'; - $xmlrpc_val->timestamp = iso8601_decode($val); - return $xmlrpc_val; - case 'base64': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->type = $typ; - return $xmlrpc_val; - default: - return $xmlrpc_val->scalarval(); - } - } - if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') - { - // we return a Datetime object instead of a string - // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, - // we cater to all 3 cases here - $out = $xmlrpc_val->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 $xmlrpc_val->scalarval(); - case 'array': - $size = $xmlrpc_val->arraysize(); - $arr = array(); - for($i = 0; $i < $size; $i++) - { - $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options); - } - return $arr; - case 'struct': - $xmlrpc_val->structreset(); - // 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 xmlrpcval instead of - // presence of _php_class to detect what we can do? - if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' - && class_exists($xmlrpc_val->_php_class)) - { - $obj = @new $xmlrpc_val->_php_class; - while(list($key,$value)=$xmlrpc_val->structeach()) - { - $obj->$key = php_xmlrpc_decode($value, $options); - } - return $obj; - } - else - { - $arr = array(); - while(list($key,$value)=$xmlrpc_val->structeach()) - { - $arr[$key] = php_xmlrpc_decode($value, $options); - } - return $arr; - } - case 'msg': - $paramcount = $xmlrpc_val->getNumParams(); - $arr = array(); - for($i = 0; $i < $paramcount; $i++) - { - $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i)); - } - return $arr; - } - } - - // This constant left here only for historical reasons... - // it was used to decide if we have to define xmlrpc_encode on our own, but - // we do not do it anymore - if(function_exists('xmlrpc_decode')) - { - define('XMLRPC_EPI_ENABLED','1'); - } - else - { - define('XMLRPC_EPI_ENABLED','0'); - } - - /** - * Takes native php types and encodes them into xmlrpc PHP object format. - * It will not re-encode xmlrpcval 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 $php_val the value to be converted into an xmlrpcval object - * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' - * @return xmlrpcval - */ - function php_xmlrpc_encode($php_val, $options=array()) - { - $xmlrpc = Xmlrpc::instance(); - $type = gettype($php_val); - 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}$/', $php_val)) - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDateTime); - else - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcString); - break; - case 'integer': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcInt); - break; - case 'double': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDouble); - break; - // - // Add support for encoding/decoding of booleans, since they are supported in PHP - case 'boolean': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcBoolean); - break; - // - 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($php_val), range(0, count($php_val)-1)); - // but execution time skyrockets! - $j = 0; - $arr = array(); - $ko = false; - foreach($php_val as $key => $val) - { - $arr[$key] = php_xmlrpc_encode($val, $options); - if(!$ko && $key !== $j) - { - $ko = true; - } - $j++; - } - if($ko) - { - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); - } - else - { - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcArray); - } - break; - case 'object': - if(is_a($php_val, 'xmlrpcval')) - { - $xmlrpc_val = $php_val; - } - else if(is_a($php_val, 'DateTime')) - { - $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $xmlrpc->xmlrpcStruct); - } - else - { - $arr = array(); - reset($php_val); - while(list($k,$v) = each($php_val)) - { - $arr[$k] = php_xmlrpc_encode($v, $options); - } - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); - if (in_array('encode_php_objs', $options)) - { - // let's save original class name into xmlrpcval: - // might be useful later on... - $xmlrpc_val->_php_class = get_class($php_val); - } - } - break; - case 'NULL': - if (in_array('extension_api', $options)) - { - $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcString); - } - else if (in_array('null_extension', $options)) - { - $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcNull); - } - else - { - $xmlrpc_val = new xmlrpcval(); - } - break; - case 'resource': - if (in_array('extension_api', $options)) - { - $xmlrpc_val = new xmlrpcval((int)$php_val, $xmlrpc->xmlrpcInt); - } - else - { - $xmlrpc_val = new xmlrpcval(); - } - // catch "user function", "unknown type" - default: - // giancarlo pinerolo - // it has to return - // an empty object in case, not a boolean. - $xmlrpc_val = new xmlrpcval(); - break; - } - return $xmlrpc_val; - } - - /** - * Convert the xml representation of a method response, method request or single - * xmlrpc value into the appropriate object (a.k.a. deserialize) - * @param string $xml_val - * @param array $options - * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp - */ - function php_xmlrpc_decode_xml($xml_val, $options=array()) - { - $xmlrpc = Xmlrpc::instance(); - - $xmlrpc->_xh = array(); - $xmlrpc->_xh['ac'] = ''; - $xmlrpc->_xh['stack'] = array(); - $xmlrpc->_xh['valuestack'] = array(); - $xmlrpc->_xh['params'] = array(); - $xmlrpc->_xh['pt'] = array(); - $xmlrpc->_xh['isf'] = 0; - $xmlrpc->_xh['isf_reason'] = ''; - $xmlrpc->_xh['method'] = false; - $xmlrpc->_xh['rt'] = ''; - /// @todo 'guestimate' encoding - $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($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); - } - 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, $xml_val, 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 ($xmlrpc->_xh['isf'] > 1) // test that $xmlrpc->_xh['value'] is an obj, too??? - { - error_log($xmlrpc->_xh['isf_reason']); - return false; - } - switch ($xmlrpc->_xh['rt']) - { - case 'methodresponse': - $v =& $xmlrpc->_xh['value']; - if ($xmlrpc->_xh['isf'] == 1) - { - $vc = $v->structmem('faultCode'); - $vs = $v->structmem('faultString'); - $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval()); - } - else - { - $r = new xmlrpcresp($v); - } - return $r; - case 'methodcall': - $m = new xmlrpcmsg($xmlrpc->_xh['method']); - for($i=0; $i < count($xmlrpc->_xh['params']); $i++) - { - $m->addParam($xmlrpc->_xh['params'][$i]); - } - return $m; - case 'value': - return $xmlrpc->_xh['value']; - default: - return false; - } - } - - /** - * decode a string that is encoded w/ "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 - */ - function decode_chunked($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); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - while($chunk_size > 0) - { - $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); - - // 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); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; - } - - /** - * 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 unconforming (legacy?) clients/servers, - * which will be most probably using UTF-8 anyway... - * - * @param string $httpheader the http Content-type header - * @param string $xmlchunk xml content buffer - * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) - * @return string - * - * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! - */ - function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) - { - $xmlrpc = Xmlrpc::instance(); - - // 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 cointrol 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 - // NB: we favour finding an encoding that is compatible with what we can process - if(extension_loaded('mbstring')) - { - if($encoding_prefs) - { - $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); - } - 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 $xmlrpc->xmlrpc_defencoding; - } - } - - /** - * 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 mixed $validlist comma separated list of valid charsets (or array of charsets) - * @return bool - */ - function is_valid_charset($encoding, $validlist) - { - $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') - ); - if (is_string($validlist)) - $validlist = explode(',', $validlist); - if (@in_array(strtoupper($encoding), $validlist)) - return true; - else - { - if (array_key_exists($encoding, $charset_supersets)) - foreach ($validlist as $allowed) - if (in_array($allowed, $charset_supersets[$encoding])) - return true; - return false; - } - } + } + else + { + if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) + { + if (is_string($this->val) && $this->valtyp == 'xml') + { + $result .= "\n\n" . + $this->val . + "\n"; + } + else + { + /// @todo try to build something serializable? + die('cannot serialize xmlrpcresp objects whose content is native php values'); + } + } + else + { + $result .= "\n\n" . + $this->val->serialize($charset_encoding) . + "\n"; + } + } + $result .= "\n
"; + $this->payload = $result; + return $result; + } +} + +class xmlrpcmsg +{ + var $payload; + var $methodname; + var $params=array(); + var $debug=0; + var $content_type = 'text/xml'; + + /** + * @param string $meth the name of the method to invoke + * @param array $pars array of parameters to be passed to the method (xmlrpcval objects) + */ + function xmlrpcmsg($meth, $pars=0) + { + $this->methodname=$meth; + if(is_array($pars) && count($pars)>0) + { + for($i=0; $iaddParam($pars[$i]); + } + } + } + + /** + * @access private + */ + function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n\n"; + } + else + { + return "\n\n"; + } + } + + /** + * @access private + */ + function xml_footer() + { + return ''; + } + + /** + * @access private + */ + function kindOf() + { + return 'msg'; + } + + /** + * @access private + */ + function createPayload($charset_encoding='') + { + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + $this->payload=$this->xml_header($charset_encoding); + $this->payload.='' . $this->methodname . "\n"; + $this->payload.="\n"; + for($i=0; $iparams); $i++) + { + $p=$this->params[$i]; + $this->payload.="\n" . $p->serialize($charset_encoding) . + "\n"; + } + $this->payload.="\n"; + $this->payload.=$this->xml_footer(); + } + + /** + * Gets/sets the xmlrpc method to be invoked + * @param string $meth the method to be set (leave empty not to set it) + * @return string the method that will be invoked + * @access public + */ + function method($meth='') + { + if($meth!='') + { + $this->methodname=$meth; + } + return $this->methodname; + } + + /** + * Returns xml representation of the message. XML prologue included + * @param string $charset_encoding + * @return string the xml representation of the message, xml prologue included + * @access public + */ + function serialize($charset_encoding='') + { + $this->createPayload($charset_encoding); + return $this->payload; + } + + /** + * Add a parameter to the list of parameters to be used upon method invocation + * @param xmlrpcval $par + * @return boolean false on failure + * @access public + */ + function addParam($par) + { + // add check: do not add to self params which are not xmlrpcvals + if(is_object($par) && is_a($par, 'xmlrpcval')) + { + $this->params[]=$par; + return true; + } + else + { + return false; + } + } + + /** + * Returns the nth parameter in the message. The index zero-based. + * @param integer $i the index of the parameter to fetch (zero based) + * @return xmlrpcval the i-th parameter + * @access public + */ + function getParam($i) { return $this->params[$i]; } + + /** + * Returns the number of parameters in the messge. + * @return integer the number of parameters currently set + * @access public + */ + function getNumParams() { return count($this->params); } + + /** + * Given an open file handle, read all data available and parse it as axmlrpc 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... + * @access public + * @param resource $fp stream pointer + * @return xmlrpcresp + * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? + */ + function &parseResponseFile($fp) + { + $ipd=''; + while($data=fread($fp, 32768)) + { + $ipd.=$data; + } + //fclose($fp); + $r =& $this->parseResponse($ipd); + return $r; + } + + /** + * Parses HTTP headers and separates them from data. + * @access private + */ + function &parseResponseHeaders(&$data, $headers_processed=false) + { + $xmlrpc = Xmlrpc::instance(); + // 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'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + return $r; + } + } + + // 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); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); + return $r; + } + + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); + + // 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) + { + $header_name = 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'][$header_name] + /// instead of replacing it for those... + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') + { + if ($header_name == '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($xmlrpc->_xh['headers'][$header_name])) + $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); + else + $xmlrpc->_xh['headers'][$header_name] = 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; + $xmlrpc->_xh['cookies'][$tag] = array(); + $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); + } + else + { + if ($tag != 'value') + { + $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; + } + } + } + } + } + else + { + $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); + } + } + elseif(isset($header_name)) + { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + if($this->debug && count($xmlrpc->_xh['headers'])) + { + print '
';
+                foreach($xmlrpc->_xh['headers'] as $header => $value)
+                {
+                    print htmlentities("HEADER: $header: $value\n");
+                }
+                foreach($xmlrpc->_xh['cookies'] as $header => $value)
+                {
+                    print htmlentities("COOKIE: $header={$value['value']}\n");
+                }
+                print "
\n"; + } + + // if CURL was used for the call, http headers have been processed, + // and dechunking + reinflating have been carried out + if(!$headers_processed) + { + // Decode chunked encoding sent by http 1.1 servers + if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked') + { + if(!$data = decode_chunked($data)) + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']); + return $r; + } + } + + // Decode gzip-compressed stuff + // code shamelessly inspired from nusoap library by Dietrich Ayala + if(isset($xmlrpc->_xh['headers']['content-encoding'])) + { + $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']); + if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate')) + { + if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + else + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); + return $r; + } + } + else + { + error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); + return $r; + } + } + } + } // end of 'if needed, de-chunk, re-inflate response' + + // real stupid hack to avoid PHP complaining about returning NULL by ref + $r = null; + $r =& $r; + return $r; + } + + /** + * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. + * @param string $data the xmlrpc response, eventually including http headers + * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding + * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @return xmlrpcresp + * @access public + */ + function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + { + $xmlrpc = Xmlrpc::instance(); + + if($this->debug) + { + //by maHo, replaced htmlspecialchars with htmlentities + print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; + } + + if($data == '') + { + error_log('XML-RPC: '.__METHOD__.': no response received from server.'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); + return $r; + } + + $xmlrpc->_xh=array(); + + $raw_data = $data; + // parse the HTTP headers of the response, if present, and separate them from data + if(substr($data, 0, 4) == 'HTTP') + { + $r =& $this->parseResponseHeaders($data, $headers_processed); + if ($r) + { + // failed processing of HTTP response headers + // save into response obj the full payload received, for debugging + $r->raw_data = $data; + return $r; + } + } + else + { + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); + } + + if($this->debug) + { + $start = strpos($data, '', $start); + $comments = substr($data, $start, $end-$start); + print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; + } + } + + // 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 originally in PEARified version of the lib + $pos = strrpos($data, '
'); + if($pos !== false) + { + $data = substr($data, 0, $pos+17); + } + + // if user wants back raw xml, give it to him + if ($return_type == 'xml') + { + $r = new xmlrpcresp($data, 0, '', 'xml'); + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } + + // try to 'guestimate' the character encoding of the received response + $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); + + $xmlrpc->_xh['ac']=''; + //$xmlrpc->_xh['qt']=''; //unused... + $xmlrpc->_xh['stack'] = array(); + $xmlrpc->_xh['valuestack'] = array(); + $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc + $xmlrpc->_xh['isf_reason']=''; + $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' + + // if response charset encoding is not known / supported, try to use + // the default encoding and parse the xml anyway, but log a warning... + if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); + $resp_encoding = $xmlrpc->xmlrpc_defencoding; + } + $parser = xml_parser_create($resp_encoding); + 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_entitites() and setting xmlrpc_internalencoding + if (!in_array($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); + } + + if ($return_type == '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 + 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 xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); + xml_parser_free($parser); + if($this->debug) + { + print $errstr; + } + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } + xml_parser_free($parser); + // second error check: xml well formed but not xml-rpc compliant + if ($xmlrpc->_xh['isf'] > 1) + { + if ($this->debug) + { + /// @todo echo something for user? + } + + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) + { + // something odd has happened + // and it's time to generate a client side error + // indicating something odd went on + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return']); + } + else + { + if ($this->debug) + { + print "
---PARSED---\n";
+                // somehow htmlentities chokes on var_export, and some full html string...
+                //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
+                print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
+                print "\n---END---
"; + } + + // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. + $v =& $xmlrpc->_xh['value']; + + if($xmlrpc->_xh['isf']) + { + /// @todo we should test here if server sent an int and a string, + /// and/or coerce them into such... + if ($return_type == 'xmlrpcvals') + { + $errno_v = $v->structmem('faultCode'); + $errstr_v = $v->structmem('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 xmlrpcresp(0, $errno, $errstr); + } + else + { + $r=new xmlrpcresp($v, 0, '', $return_type); + } + } + + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } +} + +class xmlrpcval +{ + var $me=array(); + var $mytype=0; + var $_php_class=null; + + /** + * @param mixed $val + * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed + */ + function xmlrpcval($val=-1, $type='') + { + /// @todo: optimization creep - do not call addXX, do it all inline. + /// downside: booleans will not be coerced anymore + if($val!==-1 || $type!='') + { + // optimization creep: inlined all work done by constructor + switch($type) + { + case '': + $this->mytype=1; + $this->me['string']=$val; + break; + case 'i4': + 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)"); + } + /*if($type=='') + { + $type='string'; + } + if($GLOBALS['xmlrpcTypes'][$type]==1) + { + $this->addScalar($val,$type); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==2) + { + $this->addArray($val); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==3) + { + $this->addStruct($val); + }*/ + } + } + + /** + * Add a single php value to an (unitialized) xmlrpcval + * @param mixed $val + * @param string $type + * @return int 1 or 0 on failure + */ + function addScalar($val, $type='string') + { + $xmlrpc = Xmlrpc::instance(); + + $typeof = null; + if(isset($xmlrpc->xmlrpcTypes[$type])) { + $typeof = $xmlrpc->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 and doubles, too, + // or just plain remove this check, implemented on booleans only... + if($type==$xmlrpc->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 xmlrpcval can have only one value'); + return 0; + case 3: + error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval'); + return 0; + case 2: + // we're adding a scalar value to an array here + //$ar=$this->me['array']; + //$ar[]=new xmlrpcval($val, $type); + //$this->me['array']=$ar; + // Faster (?) avoid all the costly array-copy-by-val done here... + $this->me['array'][]=new xmlrpcval($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 xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array of xmlrpcvals? + */ + function addArray($vals) + { + $xmlrpc = Xmlrpc::instance(); + if($this->mytype==0) + { + $this->mytype=$xmlrpc->xmlrpcTypes['array']; + $this->me['array']=$vals; + return 1; + } + elseif($this->mytype==2) + { + // we're adding to an array here + $this->me['array'] = array_merge($this->me['array'], $vals); + return 1; + } + else + { + error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + /** + * Add an array of named xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array? + */ + function addStruct($vals) + { + $xmlrpc = Xmlrpc::instance(); + + if($this->mytype==0) + { + $this->mytype=$xmlrpc->xmlrpcTypes['struct']; + $this->me['struct']=$vals; + return 1; + } + elseif($this->mytype==3) + { + // we're adding to a struct here + $this->me['struct'] = array_merge($this->me['struct'], $vals); + return 1; + } + else + { + error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + // poor man's version of print_r ??? + // DEPRECATED! + function dump($ar) + { + foreach($ar as $key => $val) + { + echo "$key => $val
"; + if($key == 'array') + { + while(list($key2, $val2) = each($val)) + { + echo "-- $key2 => $val2
"; + } + } + } + } + + /** + * Returns a string containing "struct", "array" or "scalar" describing the base type of the value + * @return string + * @access public + */ + function kindOf() + { + switch($this->mytype) + { + case 3: + return 'struct'; + break; + case 2: + return 'array'; + break; + case 1: + return 'scalar'; + break; + default: + return 'undef'; + } + } + + /** + * @access private + */ + function serializedata($typ, $val, $charset_encoding='') + { + $xmlrpc = Xmlrpc::instance(); + $rs=''; + + if(!isset($xmlrpc->xmlrpcTypes[$typ])) { + return $rs; + } + + switch($xmlrpc->xmlrpcTypes[$typ]) + { + case 1: + switch($typ) + { + case $xmlrpc->xmlrpcBase64: + $rs.="<${typ}>" . base64_encode($val) . ""; + break; + case $xmlrpc->xmlrpcBoolean: + $rs.="<${typ}>" . ($val ? '1' : '0') . ""; + break; + case $xmlrpc->xmlrpcString: + // G. Giunta 2005/2/13: do NOT use htmlentities, since + // it will produce named html entities, which are invalid xml + $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; + break; + case $xmlrpc->xmlrpcInt: + case $xmlrpc->xmlrpcI4: + $rs.="<${typ}>".(int)$val.""; + break; + case $xmlrpc->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, '.', '')).""; + break; + case $xmlrpc->xmlrpcDateTime: + if (is_string($val)) + { + $rs.="<${typ}>${val}"; + } + else if(is_a($val, 'DateTime')) + { + $rs.="<${typ}>".$val->format('Ymd\TH:i:s').""; + } + else if(is_int($val)) + { + $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val).""; + } + else + { + // not really a good idea here: but what shall we output anyway? left for backward compat... + $rs.="<${typ}>${val}"; + } + break; + case $xmlrpc->xmlrpcNull: + if ($xmlrpc->xmlrpc_null_apache_encoding) + { + $rs.=""; + } + else + { + $rs.=""; + } + break; + default: + // no standard type value should arrive here, but provide a possibility + // for xmlrpcvals of unknown type... + $rs.="<${typ}>${val}"; + } + break; + case 3: + // struct + if ($this->_php_class) + { + $rs.='\n"; + } + else + { + $rs.="\n"; + } + foreach($val as $key2 => $val2) + { + $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; + //$rs.=$this->serializeval($val2); + $rs.=$val2->serialize($charset_encoding); + $rs.="\n"; + } + $rs.=''; + break; + case 2: + // array + $rs.="\n\n"; + for($i=0; $iserializeval($val[$i]); + $rs.=$val[$i]->serialize($charset_encoding); + } + $rs.="\n"; + break; + default: + break; + } + return $rs; + } + + /** + * Returns xml representation of the value. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string + * @access public + */ + function serialize($charset_encoding='') + { + // 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'))) + //{ + reset($this->me); + list($typ, $val) = each($this->me); + return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; + //} + } + + // DEPRECATED + 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 '' . $this->serializedata($typ, $val) . "\n"; + //} + } + + /** + * Checks whether a struct member with a given name is present. + * Works only on xmlrpcvals of type struct. + * @param string $m the name of the struct member to be looked up + * @return boolean + * @access public + */ + function structmemexists($m) + { + return array_key_exists($m, $this->me['struct']); + } + + /** + * Returns the value of a given struct member (an xmlrpcval object in itself). + * Will raise a php warning if struct member of given name does not exist + * @param string $m the name of the struct member to be looked up + * @return xmlrpcval + * @access public + */ + function structmem($m) + { + return $this->me['struct'][$m]; + } + + /** + * Reset internal pointer for xmlrpcvals of type struct. + * @access public + */ + function structreset() + { + reset($this->me['struct']); + } + + /** + * Return next member element for xmlrpcvals of type struct. + * @return xmlrpcval + * @access public + */ + function structeach() + { + return each($this->me['struct']); + } + + // 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? + 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; + } + + /** + * Returns the value of a scalar xmlrpcval + * @return mixed + * @access public + */ + function scalarval() + { + reset($this->me); + list(,$b)=each($this->me); + return $b; + } + + /** + * Returns the type of the xmlrpcval. + * For integers, 'int' is always returned in place of 'i4' + * @return string + * @access public + */ + function scalartyp() + { + $xmlrpc = Xmlrpc::instance(); + + reset($this->me); + list($a,)=each($this->me); + if($a==$xmlrpc->xmlrpcI4) + { + $a=$xmlrpc->xmlrpcInt; + } + return $a; + } + + /** + * Returns the m-th member of an xmlrpcval of struct type + * @param integer $m the index of the value to be retrieved (zero based) + * @return xmlrpcval + * @access public + */ + function arraymem($m) + { + return $this->me['array'][$m]; + } + + /** + * Returns the number of members in an xmlrpcval of array type + * @return integer + * @access public + */ + function arraysize() + { + return count($this->me['array']); + } + + /** + * Returns the number of members in an xmlrpcval of struct type + * @return integer + * @access public + */ + function structsize() + { + return count($this->me['struct']); + } +} + + +// date helpers + +/** + * 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 + */ +function iso8601_encode($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) + */ +function iso8601_decode($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; +} + +/** + * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types. + * + * Works with xmlrpc message 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 xmlrpcval $xmlrpc_val + * @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 + */ +function php_xmlrpc_decode($xmlrpc_val, $options=array()) +{ + switch($xmlrpc_val->kindOf()) + { + case 'scalar': + if (in_array('extension_api', $options)) + { + reset($xmlrpc_val->me); + list($typ,$val) = each($xmlrpc_val->me); + switch ($typ) + { + case 'dateTime.iso8601': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->xmlrpc_type = 'datetime'; + $xmlrpc_val->timestamp = iso8601_decode($val); + return $xmlrpc_val; + case 'base64': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->type = $typ; + return $xmlrpc_val; + default: + return $xmlrpc_val->scalarval(); + } + } + if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') + { + // we return a Datetime object instead of a string + // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, + // we cater to all 3 cases here + $out = $xmlrpc_val->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 $xmlrpc_val->scalarval(); + case 'array': + $size = $xmlrpc_val->arraysize(); + $arr = array(); + for($i = 0; $i < $size; $i++) + { + $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options); + } + return $arr; + case 'struct': + $xmlrpc_val->structreset(); + // 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 xmlrpcval instead of + // presence of _php_class to detect what we can do? + if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' + && class_exists($xmlrpc_val->_php_class)) + { + $obj = @new $xmlrpc_val->_php_class; + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $obj->$key = php_xmlrpc_decode($value, $options); + } + return $obj; + } + else + { + $arr = array(); + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $arr[$key] = php_xmlrpc_decode($value, $options); + } + return $arr; + } + case 'msg': + $paramcount = $xmlrpc_val->getNumParams(); + $arr = array(); + for($i = 0; $i < $paramcount; $i++) + { + $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i)); + } + return $arr; + } +} + +// This constant left here only for historical reasons... +// it was used to decide if we have to define xmlrpc_encode on our own, but +// we do not do it anymore +if(function_exists('xmlrpc_decode')) +{ + define('XMLRPC_EPI_ENABLED','1'); +} +else +{ + define('XMLRPC_EPI_ENABLED','0'); +} + +/** + * Takes native php types and encodes them into xmlrpc PHP object format. + * It will not re-encode xmlrpcval 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 $php_val the value to be converted into an xmlrpcval object + * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * @return xmlrpcval + */ +function php_xmlrpc_encode($php_val, $options=array()) +{ + $xmlrpc = Xmlrpc::instance(); + $type = gettype($php_val); + 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}$/', $php_val)) + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDateTime); + else + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcString); + break; + case 'integer': + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcInt); + break; + case 'double': + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDouble); + break; + // + // Add support for encoding/decoding of booleans, since they are supported in PHP + case 'boolean': + $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcBoolean); + break; + // + 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($php_val), range(0, count($php_val)-1)); + // but execution time skyrockets! + $j = 0; + $arr = array(); + $ko = false; + foreach($php_val as $key => $val) + { + $arr[$key] = php_xmlrpc_encode($val, $options); + if(!$ko && $key !== $j) + { + $ko = true; + } + $j++; + } + if($ko) + { + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); + } + else + { + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcArray); + } + break; + case 'object': + if(is_a($php_val, 'xmlrpcval')) + { + $xmlrpc_val = $php_val; + } + else if(is_a($php_val, 'DateTime')) + { + $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $xmlrpc->xmlrpcStruct); + } + else + { + $arr = array(); + reset($php_val); + while(list($k,$v) = each($php_val)) + { + $arr[$k] = php_xmlrpc_encode($v, $options); + } + $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); + if (in_array('encode_php_objs', $options)) + { + // let's save original class name into xmlrpcval: + // might be useful later on... + $xmlrpc_val->_php_class = get_class($php_val); + } + } + break; + case 'NULL': + if (in_array('extension_api', $options)) + { + $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcString); + } + else if (in_array('null_extension', $options)) + { + $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcNull); + } + else + { + $xmlrpc_val = new xmlrpcval(); + } + break; + case 'resource': + if (in_array('extension_api', $options)) + { + $xmlrpc_val = new xmlrpcval((int)$php_val, $xmlrpc->xmlrpcInt); + } + else + { + $xmlrpc_val = new xmlrpcval(); + } + // catch "user function", "unknown type" + default: + // giancarlo pinerolo + // it has to return + // an empty object in case, not a boolean. + $xmlrpc_val = new xmlrpcval(); + break; + } + return $xmlrpc_val; +} + +/** + * Convert the xml representation of a method response, method request or single + * xmlrpc value into the appropriate object (a.k.a. deserialize) + * @param string $xml_val + * @param array $options + * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp + */ +function php_xmlrpc_decode_xml($xml_val, $options=array()) +{ + $xmlrpc = Xmlrpc::instance(); + + $xmlrpc->_xh = array(); + $xmlrpc->_xh['ac'] = ''; + $xmlrpc->_xh['stack'] = array(); + $xmlrpc->_xh['valuestack'] = array(); + $xmlrpc->_xh['params'] = array(); + $xmlrpc->_xh['pt'] = array(); + $xmlrpc->_xh['isf'] = 0; + $xmlrpc->_xh['isf_reason'] = ''; + $xmlrpc->_xh['method'] = false; + $xmlrpc->_xh['rt'] = ''; + /// @todo 'guestimate' encoding + $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($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); + } + 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, $xml_val, 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 ($xmlrpc->_xh['isf'] > 1) // test that $xmlrpc->_xh['value'] is an obj, too??? + { + error_log($xmlrpc->_xh['isf_reason']); + return false; + } + switch ($xmlrpc->_xh['rt']) + { + case 'methodresponse': + $v =& $xmlrpc->_xh['value']; + if ($xmlrpc->_xh['isf'] == 1) + { + $vc = $v->structmem('faultCode'); + $vs = $v->structmem('faultString'); + $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval()); + } + else + { + $r = new xmlrpcresp($v); + } + return $r; + case 'methodcall': + $m = new xmlrpcmsg($xmlrpc->_xh['method']); + for($i=0; $i < count($xmlrpc->_xh['params']); $i++) + { + $m->addParam($xmlrpc->_xh['params'][$i]); + } + return $m; + case 'value': + return $xmlrpc->_xh['value']; + default: + return false; + } +} + +/** + * decode a string that is encoded w/ "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 + */ +function decode_chunked($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); + $chunk_size = hexdec( trim($temp) ); + $chunkstart = $chunkend; + while($chunk_size > 0) + { + $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); + + // 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); + $chunk_size = hexdec( trim($temp) ); + $chunkstart = $chunkend; + } + return $new; +} + +/** + * 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 unconforming (legacy?) clients/servers, + * which will be most probably using UTF-8 anyway... + * + * @param string $httpheader the http Content-type header + * @param string $xmlchunk xml content buffer + * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) + * @return string + * + * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! + */ +function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) +{ + $xmlrpc = Xmlrpc::instance(); + + // 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 cointrol 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 + // NB: we favour finding an encoding that is compatible with what we can process + if(extension_loaded('mbstring')) + { + if($encoding_prefs) + { + $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + } + 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 $xmlrpc->xmlrpc_defencoding; + } +} + +/** + * 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 mixed $validlist comma separated list of valid charsets (or array of charsets) + * @return bool + */ +function is_valid_charset($encoding, $validlist) +{ + $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') + ); + if (is_string($validlist)) + $validlist = explode(',', $validlist); + if (@in_array(strtoupper($encoding), $validlist)) + return true; + else + { + if (array_key_exists($encoding, $charset_supersets)) + foreach ($validlist as $allowed) + if (in_array($allowed, $charset_supersets[$encoding])) + return true; + return false; + } +} ?> \ No newline at end of file diff --git a/lib/xmlrpc_wrappers.php b/lib/xmlrpc_wrappers.php index 1fbf5cea..01dfbcaa 100644 --- a/lib/xmlrpc_wrappers.php +++ b/lib/xmlrpc_wrappers.php @@ -14,920 +14,920 @@ * @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 - * for php arrays always return array, even though arrays sometiles serialize as json 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: - * - 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') and array('class', 'methodname') are ok too - * @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 returning an empty string value... - * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? - * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster - * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance? - */ - 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'] ? '@' : ''; - - $exists = false; - if (is_string($funcname) && strpos($funcname, '::') !== false) - { - $funcname = explode('::', $funcname); - } +// 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 +* for php arrays always return array, even though arrays sometiles serialize as json 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: +* - 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') and array('class', 'methodname') are ok too +* @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 returning an empty string value... +* @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? +* @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster +* @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance? +*/ +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'] ? '@' : ''; + + $exists = false; + if (is_string($funcname) && strpos($funcname, '::') !== false) + { + $funcname = explode('::', $funcname); + } + if(is_array($funcname)) + { + if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) + { + error_log('XML-RPC: syntax for function to be wrapped is wrong'); + return false; + } + if(is_string($funcname[0])) + { + $plainfuncname = implode('::', $funcname); + } + elseif(is_object($funcname[0])) + { + $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1]; + } + $exists = method_exists($funcname[0], $funcname[1]); + } + else + { + $plainfuncname = $funcname; + $exists = function_exists($funcname); + } + + if(!$exists) + { + error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); + return false; + } + else + { + // determine name of new php function + if($newfuncname == '') + { + if(is_array($funcname)) + { + if(is_string($funcname[0])) + $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); + else + $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; + } + else + { + $xmlrpcfuncname = "{$prefix}_$funcname"; + } + } + else + { + $xmlrpcfuncname = $newfuncname; + } + while($buildit && function_exists($xmlrpcfuncname)) + { + $xmlrpcfuncname .= 'x'; + } + + // start to introspect PHP code if(is_array($funcname)) { - if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) + $func = new ReflectionMethod($funcname[0], $funcname[1]); + if($func->isPrivate()) + { + error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); + return false; + } + if($func->isProtected()) + { + error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); + return false; + } + if($func->isConstructor()) { - error_log('XML-RPC: syntax for function to be wrapped is wrong'); - return false; + error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); + return false; } - if(is_string($funcname[0])) + if($func->isDestructor()) + { + error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); + return false; + } + if($func->isAbstract()) + { + error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); + return false; + } + /// @todo add more checks for static vs. nonstatic? + } + else + { + $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: '.$plainfuncname); + 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"; + // since there are no closures in php, if we are given an object instance, + // we store a pointer to it in a global var... + if ( is_array($funcname) && is_object($funcname[0]) ) + { + $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; + $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; + $realfuncname = '$obj->'.$funcname[1]; + } + else + { + $realfuncname = $plainfuncname; + } + foreach($parsvariations as $pars) + { + $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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) { - $plainfuncname = implode('::', $funcname); + error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$plainfuncname); + return false; } - elseif(is_object($funcname[0])) + } + + /// @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 a user-defined PHP class or php object, map its methods onto a list of +* PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server +* object and called from remote clients (as well as their corresponding signature info). +* +* @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class +* @param array $extra_options see the docs for wrap_php_method for more options +* string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance +* @return array or false on failure +* +* @todo get_class_methods will return both static and non-static methods. +* we have to differentiate the action, depending on wheter we recived a class name or object +*/ +function wrap_php_class($classname, $extra_options=array()) +{ + $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; + $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; + + $result = array(); + $mlist = get_class_methods($classname); + foreach($mlist as $mname) + { + if ($methodfilter == '' || preg_match($methodfilter, $mname)) + { + // echo $mlist."\n"; + $func = new ReflectionMethod($classname, $mname); + if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) { - $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1]; + if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || + (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) + { + $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); + if ( $methodwrap ) + { + $result[$methodwrap['function']] = $methodwrap['function']; + } + } } - $exists = method_exists($funcname[0], $funcname[1]); + } + } + return $result; +} + +/** +* 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 options) - 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 { - $plainfuncname = $funcname; - $exists = function_exists($funcname); - } - - if(!$exists) - { - error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); - return false; - } - else - { - // determine name of new php function - if($newfuncname == '') - { - if(is_array($funcname)) - { - if(is_string($funcname[0])) - $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); - else - $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; - } - else - { - $xmlrpcfuncname = "{$prefix}_$funcname"; - } - } - else - { - $xmlrpcfuncname = $newfuncname; - } - while($buildit && function_exists($xmlrpcfuncname)) - { - $xmlrpcfuncname .= 'x'; - } - - // start to introspect PHP code - if(is_array($funcname)) - { - $func = new ReflectionMethod($funcname[0], $funcname[1]); - if($func->isPrivate()) - { - error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); - return false; - } - if($func->isProtected()) - { - error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); - return false; - } - if($func->isConstructor()) - { - error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); - return false; - } - if($func->isDestructor()) - { - error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); - return false; - } - if($func->isAbstract()) - { - error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); - return false; - } - /// @todo add more checks for static vs. nonstatic? - } - else - { - $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: '.$plainfuncname); - 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"; - // since there are no closures in php, if we are given an object instance, - // we store a pointer to it in a global var... - if ( is_array($funcname) && is_object($funcname[0]) ) - { - $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; - $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; - $realfuncname = '$obj->'.$funcname[1]; - } - else - { - $realfuncname = $plainfuncname; - } - foreach($parsvariations as $pars) - { - $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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 '.$plainfuncname); - 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 a user-defined PHP class or php object, map its methods onto a list of - * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server - * object and called from remote clients (as well as their corresponding signature info). - * - * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class - * @param array $extra_options see the docs for wrap_php_method for more options - * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance - * @return array or false on failure - * - * @todo get_class_methods will return both static and non-static methods. - * we have to differentiate the action, depending on wheter we recived a class name or object - */ - function wrap_php_class($classname, $extra_options=array()) + // 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()) { - $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; - $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; - - $result = array(); - $mlist = get_class_methods($classname); - foreach($mlist as $mname) - { - if ($methodfilter == '' || preg_match($methodfilter, $mname)) - { - // echo $mlist."\n"; - $func = new ReflectionMethod($classname, $mname); - if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) - { - if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || - (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) - { - $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); - if ( $methodwrap ) + 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) { - $result[$methodwrap['function']] = $methodwrap['function']; + $source .= $methodwrap['docstring']; } + $source .= $methodwrap['source']."\n"; + } + else + { + error_log('XML-RPC: will not create class method to wrap remote method '.$mname); } - } - } - } - return $result; + } + } + $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 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 options) - 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; - } +/** +* 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; +} ?> \ No newline at end of file diff --git a/lib/xmlrpcs.php b/lib/xmlrpcs.php index 180595c7..27efd630 100644 --- a/lib/xmlrpcs.php +++ b/lib/xmlrpcs.php @@ -34,1205 +34,1206 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. - // XML RPC Server class - // requires: xmlrpc.inc - - $GLOBALS['xmlrpcs_capabilities'] = array( - // xmlrpc spec: always supported - 'xmlrpc' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'), - // if we support system.xxx functions, we always support multicall, too... - // Note that, as of 2006/09/17, the following URL does not respond anymore - 'system.multicall' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'), - // introspection: version 2! we support 'mixed', too - 'introspection' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), - 'specVersion' => new xmlrpcval(2, 'int') - ), 'struct') - ); - - /* Functions that implement system.XXX methods of xmlrpc servers */ - $_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct'])); - $_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to'; - $_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec')); - function _xmlrpcs_getCapabilities($server, $m=null) - { - $outAr = $GLOBALS['xmlrpcs_capabilities']; - // NIL extension - if ($GLOBALS['xmlrpc_null_extension']) { - $outAr['nil'] = new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'); - } - return new xmlrpcresp(new xmlrpcval($outAr, 'struct')); - } - - // listMethods: signature was either a string, or nothing. - // The useless string variant has been removed - $_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 - { - - $outAr=array(); - foreach($server->dmap as $key => $val) - { - $outAr[]=new xmlrpcval($key, 'string'); - } - if($server->allow_system_funcs) - { - foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) - { - $outAr[]=new xmlrpcval($key, 'string'); - } - } - return new xmlrpcresp(new xmlrpcval($outAr, 'array')); - } - - $_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) - { - // let accept as parameter both an xmlrpcval or string - if (is_object($m)) - { - $methName=$m->getParam(0); - $methName=$methName->scalarval(); - } - else - { - $methName=$m; - } - if(strpos($methName, "system.") === 0) - { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; - } - else - { - $dmap=$server->dmap; $sysCall=0; - } - if(isset($dmap[$methName])) - { - if(isset($dmap[$methName]['signature'])) - { - $sigs=array(); - foreach($dmap[$methName]['signature'] as $inSig) - { - $cursig=array(); - foreach($inSig as $sig) - { - $cursig[]=new xmlrpcval($sig, 'string'); - } - $sigs[]=new xmlrpcval($cursig, 'array'); - } - $r=new xmlrpcresp(new xmlrpcval($sigs, 'array')); - } - else - { - // NB: according to the official docs, we should be returning a - // "none-array" here, which means not-an-array - $r=new xmlrpcresp(new xmlrpcval('undef', 'string')); - } - } - else - { - $r=new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); - } - return $r; - } - - $_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) - { - // let accept as parameter both an xmlrpcval or string - if (is_object($m)) - { - $methName=$m->getParam(0); - $methName=$methName->scalarval(); - } - else - { - $methName=$m; - } - if(strpos($methName, "system.") === 0) - { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; - } - else - { - $dmap=$server->dmap; $sysCall=0; - } - if(isset($dmap[$methName])) - { - if(isset($dmap[$methName]['docstring'])) - { - $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string'); - } - else - { - $r=new xmlrpcresp(new xmlrpcval('', 'string')); - } - } - else - { - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); - } - return $r; - } - - $_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_error($err) - { - if(is_string($err)) - { - $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; - $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; - } - else - { - $code = $err->faultCode(); - $str = $err->faultString(); - } - $struct = array(); - $struct['faultCode'] = new xmlrpcval($code, 'int'); - $struct['faultString'] = new xmlrpcval($str, 'string'); - return new xmlrpcval($struct, 'struct'); - } - - function _xmlrpcs_multicall_do_call($server, $call) - { - if($call->kindOf() != 'struct') - { - return _xmlrpcs_multicall_error('notstruct'); - } - $methName = @$call->structmem('methodName'); - if(!$methName) - { - return _xmlrpcs_multicall_error('nomethod'); - } - if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') - { - return _xmlrpcs_multicall_error('notstring'); - } - if($methName->scalarval() == 'system.multicall') - { - return _xmlrpcs_multicall_error('recursion'); - } - - $params = @$call->structmem('params'); - if(!$params) - { - return _xmlrpcs_multicall_error('noparams'); - } - if($params->kindOf() != 'array') - { - return _xmlrpcs_multicall_error('notarray'); - } - $numParams = $params->arraysize(); - - $msg = new xmlrpcmsg($methName->scalarval()); - for($i = 0; $i < $numParams; $i++) - { - if(!$msg->addParam($params->arraymem($i))) - { - $i++; - return _xmlrpcs_multicall_error(new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); - } - } - - $result = $server->execute($msg); - - if($result->faultCode() != 0) - { - return _xmlrpcs_multicall_error($result); // Method returned fault. - } - - return new xmlrpcval(array($result->value()), 'array'); - } - - function _xmlrpcs_multicall_do_call_phpvals($server, $call) - { - if(!is_array($call)) - { - return _xmlrpcs_multicall_error('notstruct'); - } - if(!array_key_exists('methodName', $call)) - { - return _xmlrpcs_multicall_error('nomethod'); - } - if (!is_string($call['methodName'])) - { - return _xmlrpcs_multicall_error('notstring'); - } - if($call['methodName'] == 'system.multicall') - { - return _xmlrpcs_multicall_error('recursion'); - } - if(!array_key_exists('params', $call)) - { - return _xmlrpcs_multicall_error('noparams'); - } - if(!is_array($call['params'])) - { - return _xmlrpcs_multicall_error('notarray'); - } - - // this is a real dirty and simplistic hack, since we might have received a - // base64 or datetime values, but they will be listed as strings here... - $numParams = count($call['params']); - $pt = array(); - foreach($call['params'] as $val) - $pt[] = php_2_xmlrpc_type(gettype($val)); - - $result = $server->execute($call['methodName'], $call['params'], $pt); - - if($result->faultCode() != 0) - { - return _xmlrpcs_multicall_error($result); // Method returned fault. - } - - return new xmlrpcval(array($result->value()), 'array'); - } - - function _xmlrpcs_multicall($server, $m) - { - $result = array(); - // let accept a plain list of php parameters, beside a single xmlrpc msg object - if (is_object($m)) - { - $calls = $m->getParam(0); - $numCalls = $calls->arraysize(); - for($i = 0; $i < $numCalls; $i++) - { - $call = $calls->arraymem($i); - $result[$i] = _xmlrpcs_multicall_do_call($server, $call); - } - } - else - { - $numCalls=count($m); - for($i = 0; $i < $numCalls; $i++) - { - $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); - } - } - - return new xmlrpcresp(new xmlrpcval($result, 'array')); - } - - $GLOBALS['_xmlrpcs_dmap']=array( - 'system.listMethods' => array( - 'function' => '_xmlrpcs_listMethods', - 'signature' => $_xmlrpcs_listMethods_sig, - 'docstring' => $_xmlrpcs_listMethods_doc, - 'signature_docs' => $_xmlrpcs_listMethods_sdoc), - 'system.methodHelp' => array( - 'function' => '_xmlrpcs_methodHelp', - 'signature' => $_xmlrpcs_methodHelp_sig, - 'docstring' => $_xmlrpcs_methodHelp_doc, - 'signature_docs' => $_xmlrpcs_methodHelp_sdoc), - 'system.methodSignature' => array( - 'function' => '_xmlrpcs_methodSignature', - 'signature' => $_xmlrpcs_methodSignature_sig, - 'docstring' => $_xmlrpcs_methodSignature_doc, - 'signature_docs' => $_xmlrpcs_methodSignature_sdoc), - 'system.multicall' => array( - 'function' => '_xmlrpcs_multicall', - 'signature' => $_xmlrpcs_multicall_sig, - 'docstring' => $_xmlrpcs_multicall_doc, - 'signature_docs' => $_xmlrpcs_multicall_sdoc), - 'system.getCapabilities' => array( - 'function' => '_xmlrpcs_getCapabilities', - 'signature' => $_xmlrpcs_getCapabilities_sig, - 'docstring' => $_xmlrpcs_getCapabilities_doc, - 'signature_docs' => $_xmlrpcs_getCapabilities_sdoc) - ); - - $GLOBALS['_xmlrpcs_occurred_errors'] = ''; - $GLOBALS['_xmlrpcs_prev_ehandler'] = ''; - - /** - * Error handler used to track errors that occur during server-side execution of PHP code. - * This allows to report back to the client whether an internal error has occurred or not - * using an xmlrpc response object, instead of letting the client deal with the html junk - * that a PHP execution error on the server generally entails. - * - * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. - * - */ - function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) - { - // obey the @ protocol - if (error_reporting() == 0) - return; - - //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) - if($errcode != E_STRICT) - { - $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n"; - } - // Try to avoid as much as possible disruption to the previous error handling - // mechanism in place - if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') - { - // The previous error handler was the default: all we should do is log error - // to the default error log (if level high enough) - if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) - { - error_log($errstring); - } - } - else - { - // Pass control on to previous error handler, trying to avoid loops... - if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler') - { - // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers - if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) - { - // the following works both with static class methods and plain object methods as error handler - call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); - } - else - { - $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); - } - } - } - } - - $GLOBALS['_xmlrpc_debuginfo']=''; - - /** - * Add a string to the debug info that can be later seralized by the server - * as part of the response message. - * Note that for best compatibility, the debug string should be encoded using - * the $GLOBALS['xmlrpc_internalencoding'] character set. - * @param string $m - * @access public - */ - function xmlrpc_debugmsg($m) - { - $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n"; - } - - class xmlrpc_server - { - /** - * Array defining php functions exposed as xmlrpc methods by this server - * @access private - */ - var $dmap=array(); - /** - * Defines how functions in dmap will be invoked: either using an xmlrpc msg object - * or plain php values. - * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' - */ - var $functions_parameters_type='xmlrpcvals'; - /** - * Option used for fine-tuning the encoding the php values returned from - * functions registered in the dispatch map when the functions_parameters_types - * member is set to 'phpvals' - * @see php_xmlrpc_encode for a list of values - */ - var $phpvals_encoding_options = array( 'auto_dates' ); - /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3 - var $debug = 1; - /** - * Controls behaviour of server when invoked user function throws an exception: - * 0 = catch it and return an 'internal error' xmlrpc response (default) - * 1 = catch it and return an xmlrpc response with the error corresponding to the exception - * 2 = allow the exception to float to the upper layers - */ - var $exception_handling = 0; - /** - * When set to true, it will enable HTTP compression of the response, in case - * the client has declared its support for compression in the request. - */ - var $compress_response = false; - /** - * List of http compression methods accepted by the server for requests. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib - */ - var $accepted_compression = array(); - /// shall we serve calls to system.* methods? - var $allow_system_funcs = true; - /// list of charset encodings natively accepted for requests - var $accepted_charset_encodings = array(); - /** - * charset encoding to be used for response. - * NB: if we can, we will convert the generated response from internal_encoding to the intended one. - * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), - * null (leave unspecified in response, convert output stream to US_ASCII), - * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), - * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). - * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) - */ - var $response_charset_encoding = ''; - /** - * Storage for internal debug info - * @access private - */ - var $debug_info = ''; - /** - * Extra data passed at runtime to method handling functions. Used only by EPI layer - */ - var $user_data = null; - - /** - * @param array $dispmap the dispatch map with definition of exposed services - * @param boolean $servicenow set to false to prevent the server from running upon construction - */ - function xmlrpc_server($dispMap=null, $serviceNow=true) - { - // if ZLIB is enabled, let the server by default accept compressed requests, - // and compress responses sent to clients that support them - if(function_exists('gzinflate')) - { - $this->accepted_compression = array('gzip', 'deflate'); - $this->compress_response = true; - } - - // by default the xml parser can support these 3 charset encodings - $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); - - // dispMap is a dispatch array of methods - // mapped to function names and signatures - // if a method - // doesn't appear in the map then an unknown - // method error is generated - /* milosch - changed to make passing dispMap optional. - * instead, you can use the class add_to_map() function - * to add functions manually (borrowed from SOAPX4) - */ - if($dispMap) - { - $this->dmap = $dispMap; - if($serviceNow) - { - $this->service(); - } - } - } - - /** - * Set debug level of server. - * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) - * 0 = no debug info, - * 1 = msgs set from user with debugmsg(), - * 2 = add complete xmlrpc request (headers and body), - * 3 = add also all processing warnings happened during method processing - * (NB: this involves setting a custom error handler, and might interfere - * with the standard processing of the php function exposed as method. In - * particular, triggering an USER_ERROR level error will not halt script - * execution anymore, but just end up logged in the xmlrpc response) - * Note that info added at level 2 and 3 will be base64 encoded - * @access public - */ - function setDebug($in) - { - $this->debug=$in; - } - - /** - * Return a string with the serialized representation of all debug info - * @param string $charset_encoding the target charset encoding for the serialization - * @return string an XML comment (or two) - */ - function serializeDebug($charset_encoding='') - { - // Tough encoding problem: which internal charset should we assume for debug info? - // It might contain a copy of raw data received from client, ie with unknown encoding, - // intermixed with php generated data and user generated data... - // so we split it: system debug is base 64 encoded, - // user debug info should be encoded by the end user using the INTERNAL_ENCODING - $out = ''; - if ($this->debug_info != '') - { - $out .= "\n"; - } - if($GLOBALS['_xmlrpc_debuginfo']!='') - { - - $out .= "\n"; - // NB: a better solution MIGHT be to use CDATA, but we need to insert it - // into return payload AFTER the beginning tag - //$out .= "', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n"; - } - return $out; - } - - /** - * Execute the xmlrpc request, printing the response - * @param string $data the request body. If null, the http POST request will be examined - * @return xmlrpcresp the response object (usually not used by caller...) - * @access public - */ - function service($data=null, $return_payload=false) - { - if ($data === null) - { - // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA - $data = file_get_contents('php://input'); - } - $raw_data = $data; - - // reset internal debug info - $this->debug_info = ''; - - // Echo back what we received, before parsing it - if($this->debug > 1) - { - $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); - } - - $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); - if (!$r) - { - $r=$this->parseRequest($data, $req_charset); - } - - // save full body of request into response, for more debugging usages - $r->raw_data = $raw_data; - - if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) - { - $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . - $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); - } - - $payload=$this->xml_header($resp_charset); - if($this->debug > 0) - { - $payload = $payload . $this->serializeDebug($resp_charset); - } - - // G. Giunta 2006-01-27: do not create response serialization if it has - // already happened. Helps building json magic - if (empty($r->payload)) - { - $r->serialize($resp_charset); - } - $payload = $payload . $r->payload; - - if ($return_payload) - { - return $payload; - } - - // if we get a warning/error that has output some text before here, then we cannot - // add a new header. We cannot say we are sending xml, either... - if(!headers_sent()) - { - header('Content-Type: '.$r->content_type); - // we do not know if client actually told us an accepted charset, but if he did - // we have to tell him what we did - header("Vary: Accept-Charset"); - - // http compression of output: only - // if we can do it, and we want to do it, and client asked us to, - // and php ini settings do not force it already - $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); - if($this->compress_response && function_exists('gzencode') && $resp_encoding != '' - && $php_no_self_compress) - { - if(strpos($resp_encoding, 'gzip') !== false) - { - $payload = gzencode($payload); - header("Content-Encoding: gzip"); - header("Vary: Accept-Encoding"); - } - elseif (strpos($resp_encoding, 'deflate') !== false) - { - $payload = gzcompress($payload); - header("Content-Encoding: deflate"); - header("Vary: Accept-Encoding"); - } - } - - // do not ouput content-length header if php is compressing output for us: - // it will mess up measurements - if($php_no_self_compress) - { - header('Content-Length: ' . (int)strlen($payload)); - } - } - else - { - error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages'); - } - - print $payload; - - // return request, in case subclasses want it - return $r; - } - - /** - * Add a method to the dispatch map - * @param string $methodname the name with which the method will be made available - * @param string $function the php function that will get invoked - * @param array $sig the array of valid method signatures - * @param string $doc method documentation - * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type) - * @access public - */ - function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false) - { - $this->dmap[$methodname] = array( - 'function' => $function, - 'docstring' => $doc - ); - if ($sig) - { - $this->dmap[$methodname]['signature'] = $sig; - } - if ($sigdoc) - { - $this->dmap[$methodname]['signature_docs'] = $sigdoc; - } - } - - /** - * Verify type and number of parameters received against a list of known signatures - * @param array $in array of either xmlrpcval objects or xmlrpc type definitions - * @param array $sig array of known signatures to match against - * @return array - * @access private - */ - function verifySignature($in, $sig) - { - // check each possible signature in turn - if (is_object($in)) - { - $numParams = $in->getNumParams(); - } - else - { - $numParams = count($in); - } - foreach($sig as $cursig) - { - if(count($cursig)==$numParams+1) - { - $itsOK=1; - for($n=0; $n<$numParams; $n++) - { - if (is_object($in)) - { - $p=$in->getParam($n); - if($p->kindOf() == 'scalar') - { - $pt=$p->scalartyp(); - } - else - { - $pt=$p->kindOf(); - } - } - else - { - $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4... - } - - // param index is $n+1, as first member of sig is return type - if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) - { - $itsOK=0; - $pno=$n+1; - $wanted=$cursig[$n+1]; - $got=$pt; - break; - } - } - if($itsOK) - { - return array(1,''); - } - } - } - if(isset($wanted)) - { - return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); - } - else - { - return array(0, "No method signature matches number of parameters"); - } - } - - /** - * Parse http headers received along with xmlrpc request. If needed, inflate request - * @return mixed null on success or an xmlrpcresp - * @access private - */ - function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) - { - // check if $_SERVER is populated: it might have been disabled via ini file - // (this is true even when in CLI mode) - if (count($_SERVER) == 0) - { - error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated'); - } - - if($this->debug > 1) - { - if(function_exists('getallheaders')) - { - $this->debugmsg(''); // empty line - foreach(getallheaders() as $name => $val) - { - $this->debugmsg("HEADER: $name: $val"); - } - } - - } - - if(isset($_SERVER['HTTP_CONTENT_ENCODING'])) - { - $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); - } - else - { - $content_encoding = ''; - } - - // check if request body has been compressed and decompress it - if($content_encoding != '' && strlen($data)) - { - if($content_encoding == 'deflate' || $content_encoding == 'gzip') - { - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) - { - if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) - { - $data = $degzdata; - if($this->debug > 1) - { - $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); - } - } - elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { - $data = $degzdata; - if($this->debug > 1) - $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); - } - else - { - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); - return $r; - } - } - else - { - //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); - return $r; - } - } - } - - // check if client specified accepted charsets, and if we know how to fulfill - // the request - if ($this->response_charset_encoding == 'auto') - { - $resp_encoding = ''; - if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) - { - // here we should check if we can match the client-requested encoding - // with the encodings we know we can generate. - /// @todo we should parse q=0.x preferences instead of getting first charset specified... - $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); - // Give preference to internal encoding - $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII'); - foreach ($known_charsets as $charset) - { - foreach ($client_accepted_charsets as $accepted) - if (strpos($accepted, $charset) === 0) - { - $resp_encoding = $charset; - break; - } - if ($resp_encoding) - break; - } - } - } - else - { - $resp_encoding = $this->response_charset_encoding; - } - - if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) - { - $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; - } - else - { - $resp_compression = ''; - } - - // 'guestimate' request encoding - /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? - $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', - $data); - - return null; - } - - /** - * Parse an xml chunk containing an xmlrpc request and execute the corresponding - * php function registered with the server - * @param string $data the xml request - * @param string $req_encoding (optional) the charset encoding of the xml request - * @return xmlrpcresp - * @access private - */ - function parseRequest($data, $req_encoding='') - { - // 2005/05/07 commented and moved into caller function code - //if($data=='') - //{ - // $data=$GLOBALS['HTTP_RAW_POST_DATA']; - //} - - // G. Giunta 2005/02/13: we do NOT expect to receive html entities - // so we do not try to convert them into xml character entities - //$data = xmlrpc_html_entity_xlate($data); - - $GLOBALS['_xh']=array(); - $GLOBALS['_xh']['ac']=''; - $GLOBALS['_xh']['stack']=array(); - $GLOBALS['_xh']['valuestack'] = array(); - $GLOBALS['_xh']['params']=array(); - $GLOBALS['_xh']['pt']=array(); - $GLOBALS['_xh']['isf']=0; - $GLOBALS['_xh']['isf_reason']=''; - $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not - $GLOBALS['_xh']['rt']=''; - - // decompose incoming XML into request structure - if ($req_encoding != '') - { - if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding); - $req_encoding = $GLOBALS['xmlrpc_defencoding']; - } - /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, - // the encoding is not UTF8 and there are non-ascii chars in the text... - /// @todo use an empty string for php 5 ??? - $parser = xml_parser_create($req_encoding); - } - else - { - $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_entitites() and setting xmlrpc_internalencoding - if (!in_array($GLOBALS['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, $GLOBALS['xmlrpc_internalencoding']); - } - - if ($this->functions_parameters_type != 'xmlrpcvals') - 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'); - if(!xml_parse($parser, $data, 1)) - { - // return XML error as a faultCode - $r=new xmlrpcresp(0, - $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser), - 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))); - xml_parser_free($parser); - } - elseif ($GLOBALS['_xh']['isf']) - { - xml_parser_free($parser); - $r=new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['invalid_request'], - $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']); - } - else - { - xml_parser_free($parser); - // small layering violation in favor of speed and memory usage: - // we should allow the 'execute' method handle this, but in the - // most common scenario (xmlrpcvals type server with some methods - // registered as phpvals) that would mean a useless encode+decode pass - if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals'))) - { - if($this->debug > 1) - { - $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++"); - } - $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']); - } - else - { - // build an xmlrpcmsg object with data parsed from xml - $m=new xmlrpcmsg($GLOBALS['_xh']['method']); - // now add parameters in - for($i=0; $iaddParam($GLOBALS['_xh']['params'][$i]); - } - - if($this->debug > 1) - { - $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++"); - } - $r = $this->execute($m); - } - } - return $r; - } - - /** - * Execute a method invoked by the client, checking parameters used - * @param mixed $m either an xmlrpcmsg obj or a method name - * @param array $params array with method parameters as php types (if m is method name only) - * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) - * @return xmlrpcresp - * @access private - */ - function execute($m, $params=null, $paramtypes=null) - { - if (is_object($m)) - { - $methName = $m->method(); - } - else - { - $methName = $m; - } - $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); - $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; - - if(!isset($dmap[$methName]['function'])) - { - // No such method - return new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['unknown_method'], - $GLOBALS['xmlrpcstr']['unknown_method']); - } - - // Check signature - if(isset($dmap[$methName]['signature'])) - { - $sig = $dmap[$methName]['signature']; - if (is_object($m)) - { - list($ok, $errstr) = $this->verifySignature($m, $sig); - } - else - { - list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); - } - if(!$ok) - { - // Didn't match. - return new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" - ); - } - } - - $func = $dmap[$methName]['function']; - // let the 'class::function' syntax be accepted in dispatch maps - if(is_string($func) && strpos($func, '::')) - { - $func = explode('::', $func); - } - // verify that function to be invoked is in fact callable - if(!is_callable($func)) - { - error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable"); - return new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" - ); - } - - // If debug level is 3, we should catch all errors generated during - // processing of user function, and log them as part of response - if($this->debug > 2) - { - $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); - } - try - { - // Allow mixed-convention servers - if (is_object($m)) - { - if($sysCall) - { - $r = call_user_func($func, $this, $m); - } - else - { - $r = call_user_func($func, $m); - } - if (!is_a($r, 'xmlrpcresp')) - { - error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); - if (is_a($r, 'xmlrpcval')) - { - $r = new xmlrpcresp($r); - } - else - { - $r = new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" - ); - } - } - } - else - { - // call a 'plain php' function - if($sysCall) - { - array_unshift($params, $this); - $r = call_user_func_array($func, $params); - } - else - { - // 3rd API convention for method-handling functions: EPI-style - if ($this->functions_parameters_type == 'epivals') - { - $r = call_user_func_array($func, array($methName, $params, $this->user_data)); - // mimic EPI behaviour: if we get an array that looks like an error, make it - // an eror response - if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) - { - $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']); - } - else - { - // functions using EPI api should NOT return resp objects, - // so make sure we encode the return type correctly - $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api'))); - } - } - else - { - $r = call_user_func_array($func, $params); - } - } - // the return type can be either an xmlrpcresp object or a plain php value... - if (!is_a($r, 'xmlrpcresp')) - { - // what should we assume here about automatic encoding of datetimes - // and php classes instances??? - $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options)); - } - } - } - catch(Exception $e) - { - // (barring errors in the lib) an uncatched exception happened - // in the called function, we wrap it in a proper error-response - switch($this->exception_handling) - { - case 2: - throw $e; - break; - case 1: - $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage()); - break; - default: - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']); - } - } - if($this->debug > 2) - { - // note: restore the error handler we found before calling the - // user func, even if it has been changed inside the func itself - if($GLOBALS['_xmlrpcs_prev_ehandler']) - { - set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); - } - else - { - restore_error_handler(); - } - } - return $r; - } - - /** - * add a string to the 'internal debug message' (separate from 'user debug message') - * @param string $string - * @access private - */ - function debugmsg($string) - { - $this->debug_info .= $string."\n"; - } - - /** - * @access private - */ - function xml_header($charset_encoding='') - { - if ($charset_encoding != '') - { - return "\n"; - } - else - { - return "\n"; - } - } - - /** - * A debugging routine: just echoes back the input packet as a string value - * DEPRECATED! - */ - function echoInput() - { - $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); - print $r->serialize(); - } - } + +// XML RPC Server class +// requires: xmlrpc.inc + +$GLOBALS['xmlrpcs_capabilities'] = array( + // xmlrpc spec: always supported + 'xmlrpc' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'), + // if we support system.xxx functions, we always support multicall, too... + // Note that, as of 2006/09/17, the following URL does not respond anymore + 'system.multicall' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'), + // introspection: version 2! we support 'mixed', too + 'introspection' => new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), + 'specVersion' => new xmlrpcval(2, 'int') + ), 'struct') +); + +/* Functions that implement system.XXX methods of xmlrpc servers */ +$_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct'])); +$_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to'; +$_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec')); +function _xmlrpcs_getCapabilities($server, $m=null) +{ + $outAr = $GLOBALS['xmlrpcs_capabilities']; + // NIL extension + if ($GLOBALS['xmlrpc_null_extension']) { + $outAr['nil'] = new xmlrpcval(array( + 'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), + 'specVersion' => new xmlrpcval(1, 'int') + ), 'struct'); + } + return new xmlrpcresp(new xmlrpcval($outAr, 'struct')); +} + +// listMethods: signature was either a string, or nothing. +// The useless string variant has been removed +$_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 +{ + + $outAr=array(); + foreach($server->dmap as $key => $val) + { + $outAr[]=new xmlrpcval($key, 'string'); + } + if($server->allow_system_funcs) + { + foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) + { + $outAr[]=new xmlrpcval($key, 'string'); + } + } + return new xmlrpcresp(new xmlrpcval($outAr, 'array')); +} + +$_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) +{ + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['signature'])) + { + $sigs=array(); + foreach($dmap[$methName]['signature'] as $inSig) + { + $cursig=array(); + foreach($inSig as $sig) + { + $cursig[]=new xmlrpcval($sig, 'string'); + } + $sigs[]=new xmlrpcval($cursig, 'array'); + } + $r=new xmlrpcresp(new xmlrpcval($sigs, 'array')); + } + else + { + // NB: according to the official docs, we should be returning a + // "none-array" here, which means not-an-array + $r=new xmlrpcresp(new xmlrpcval('undef', 'string')); + } + } + else + { + $r=new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; +} + +$_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) +{ + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['docstring'])) + { + $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string'); + } + else + { + $r=new xmlrpcresp(new xmlrpcval('', 'string')); + } + } + else + { + $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; +} + +$_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_error($err) +{ + if(is_string($err)) + { + $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; + $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; + } + else + { + $code = $err->faultCode(); + $str = $err->faultString(); + } + $struct = array(); + $struct['faultCode'] = new xmlrpcval($code, 'int'); + $struct['faultString'] = new xmlrpcval($str, 'string'); + return new xmlrpcval($struct, 'struct'); +} + +function _xmlrpcs_multicall_do_call($server, $call) +{ + if($call->kindOf() != 'struct') + { + return _xmlrpcs_multicall_error('notstruct'); + } + $methName = @$call->structmem('methodName'); + if(!$methName) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') + { + return _xmlrpcs_multicall_error('notstring'); + } + if($methName->scalarval() == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + + $params = @$call->structmem('params'); + if(!$params) + { + return _xmlrpcs_multicall_error('noparams'); + } + if($params->kindOf() != 'array') + { + return _xmlrpcs_multicall_error('notarray'); + } + $numParams = $params->arraysize(); + + $msg = new xmlrpcmsg($methName->scalarval()); + for($i = 0; $i < $numParams; $i++) + { + if(!$msg->addParam($params->arraymem($i))) + { + $i++; + return _xmlrpcs_multicall_error(new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); + } + } + + $result = $server->execute($msg); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new xmlrpcval(array($result->value()), 'array'); +} + +function _xmlrpcs_multicall_do_call_phpvals($server, $call) +{ + if(!is_array($call)) + { + return _xmlrpcs_multicall_error('notstruct'); + } + if(!array_key_exists('methodName', $call)) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if (!is_string($call['methodName'])) + { + return _xmlrpcs_multicall_error('notstring'); + } + if($call['methodName'] == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + if(!array_key_exists('params', $call)) + { + return _xmlrpcs_multicall_error('noparams'); + } + if(!is_array($call['params'])) + { + return _xmlrpcs_multicall_error('notarray'); + } + + // this is a real dirty and simplistic hack, since we might have received a + // base64 or datetime values, but they will be listed as strings here... + $numParams = count($call['params']); + $pt = array(); + foreach($call['params'] as $val) + $pt[] = php_2_xmlrpc_type(gettype($val)); + + $result = $server->execute($call['methodName'], $call['params'], $pt); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new xmlrpcval(array($result->value()), 'array'); +} + +function _xmlrpcs_multicall($server, $m) +{ + $result = array(); + // let accept a plain list of php parameters, beside a single xmlrpc msg object + if (is_object($m)) + { + $calls = $m->getParam(0); + $numCalls = $calls->arraysize(); + for($i = 0; $i < $numCalls; $i++) + { + $call = $calls->arraymem($i); + $result[$i] = _xmlrpcs_multicall_do_call($server, $call); + } + } + else + { + $numCalls=count($m); + for($i = 0; $i < $numCalls; $i++) + { + $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); + } + } + + return new xmlrpcresp(new xmlrpcval($result, 'array')); +} + +$GLOBALS['_xmlrpcs_dmap']=array( + 'system.listMethods' => array( + 'function' => '_xmlrpcs_listMethods', + 'signature' => $_xmlrpcs_listMethods_sig, + 'docstring' => $_xmlrpcs_listMethods_doc, + 'signature_docs' => $_xmlrpcs_listMethods_sdoc), + 'system.methodHelp' => array( + 'function' => '_xmlrpcs_methodHelp', + 'signature' => $_xmlrpcs_methodHelp_sig, + 'docstring' => $_xmlrpcs_methodHelp_doc, + 'signature_docs' => $_xmlrpcs_methodHelp_sdoc), + 'system.methodSignature' => array( + 'function' => '_xmlrpcs_methodSignature', + 'signature' => $_xmlrpcs_methodSignature_sig, + 'docstring' => $_xmlrpcs_methodSignature_doc, + 'signature_docs' => $_xmlrpcs_methodSignature_sdoc), + 'system.multicall' => array( + 'function' => '_xmlrpcs_multicall', + 'signature' => $_xmlrpcs_multicall_sig, + 'docstring' => $_xmlrpcs_multicall_doc, + 'signature_docs' => $_xmlrpcs_multicall_sdoc), + 'system.getCapabilities' => array( + 'function' => '_xmlrpcs_getCapabilities', + 'signature' => $_xmlrpcs_getCapabilities_sig, + 'docstring' => $_xmlrpcs_getCapabilities_doc, + 'signature_docs' => $_xmlrpcs_getCapabilities_sdoc) +); + +$GLOBALS['_xmlrpcs_occurred_errors'] = ''; +$GLOBALS['_xmlrpcs_prev_ehandler'] = ''; + +/** +* Error handler used to track errors that occur during server-side execution of PHP code. +* This allows to report back to the client whether an internal error has occurred or not +* using an xmlrpc response object, instead of letting the client deal with the html junk +* that a PHP execution error on the server generally entails. +* +* NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. +* +*/ +function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) +{ + // obey the @ protocol + if (error_reporting() == 0) + return; + + //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) + if($errcode != E_STRICT) + { + $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n"; + } + // Try to avoid as much as possible disruption to the previous error handling + // mechanism in place + if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') + { + // The previous error handler was the default: all we should do is log error + // to the default error log (if level high enough) + if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) + { + error_log($errstring); + } + } + else + { + // Pass control on to previous error handler, trying to avoid loops... + if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler') + { + // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers + if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) + { + // the following works both with static class methods and plain object methods as error handler + call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); + } + else + { + $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); + } + } + } +} + +$GLOBALS['_xmlrpc_debuginfo']=''; + +/** +* Add a string to the debug info that can be later seralized by the server +* as part of the response message. +* Note that for best compatibility, the debug string should be encoded using +* the $GLOBALS['xmlrpc_internalencoding'] character set. +* @param string $m +* @access public +*/ +function xmlrpc_debugmsg($m) +{ + $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n"; +} + +class xmlrpc_server +{ + /** + * Array defining php functions exposed as xmlrpc methods by this server + * @access private + */ + var $dmap=array(); + /** + * Defines how functions in dmap will be invoked: either using an xmlrpc msg object + * or plain php values. + * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' + */ + var $functions_parameters_type='xmlrpcvals'; + /** + * Option used for fine-tuning the encoding the php values returned from + * functions registered in the dispatch map when the functions_parameters_types + * member is set to 'phpvals' + * @see php_xmlrpc_encode for a list of values + */ + var $phpvals_encoding_options = array( 'auto_dates' ); + /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3 + var $debug = 1; + /** + * Controls behaviour of server when invoked user function throws an exception: + * 0 = catch it and return an 'internal error' xmlrpc response (default) + * 1 = catch it and return an xmlrpc response with the error corresponding to the exception + * 2 = allow the exception to float to the upper layers + */ + var $exception_handling = 0; + /** + * When set to true, it will enable HTTP compression of the response, in case + * the client has declared its support for compression in the request. + */ + var $compress_response = false; + /** + * List of http compression methods accepted by the server for requests. + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + */ + var $accepted_compression = array(); + /// shall we serve calls to system.* methods? + var $allow_system_funcs = true; + /// list of charset encodings natively accepted for requests + var $accepted_charset_encodings = array(); + /** + * charset encoding to be used for response. + * NB: if we can, we will convert the generated response from internal_encoding to the intended one. + * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), + * null (leave unspecified in response, convert output stream to US_ASCII), + * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), + * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). + * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) + */ + var $response_charset_encoding = ''; + /** + * Storage for internal debug info + * @access private + */ + var $debug_info = ''; + /** + * Extra data passed at runtime to method handling functions. Used only by EPI layer + */ + var $user_data = null; + + /** + * @param array $dispmap the dispatch map with definition of exposed services + * @param boolean $servicenow set to false to prevent the server from running upon construction + */ + function xmlrpc_server($dispMap=null, $serviceNow=true) + { + // if ZLIB is enabled, let the server by default accept compressed requests, + // and compress responses sent to clients that support them + if(function_exists('gzinflate')) + { + $this->accepted_compression = array('gzip', 'deflate'); + $this->compress_response = true; + } + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // dispMap is a dispatch array of methods + // mapped to function names and signatures + // if a method + // doesn't appear in the map then an unknown + // method error is generated + /* milosch - changed to make passing dispMap optional. + * instead, you can use the class add_to_map() function + * to add functions manually (borrowed from SOAPX4) + */ + if($dispMap) + { + $this->dmap = $dispMap; + if($serviceNow) + { + $this->service(); + } + } + } + + /** + * Set debug level of server. + * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) + * 0 = no debug info, + * 1 = msgs set from user with debugmsg(), + * 2 = add complete xmlrpc request (headers and body), + * 3 = add also all processing warnings happened during method processing + * (NB: this involves setting a custom error handler, and might interfere + * with the standard processing of the php function exposed as method. In + * particular, triggering an USER_ERROR level error will not halt script + * execution anymore, but just end up logged in the xmlrpc response) + * Note that info added at level 2 and 3 will be base64 encoded + * @access public + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Return a string with the serialized representation of all debug info + * @param string $charset_encoding the target charset encoding for the serialization + * @return string an XML comment (or two) + */ + function serializeDebug($charset_encoding='') + { + // Tough encoding problem: which internal charset should we assume for debug info? + // It might contain a copy of raw data received from client, ie with unknown encoding, + // intermixed with php generated data and user generated data... + // so we split it: system debug is base 64 encoded, + // user debug info should be encoded by the end user using the INTERNAL_ENCODING + $out = ''; + if ($this->debug_info != '') + { + $out .= "\n"; + } + if($GLOBALS['_xmlrpc_debuginfo']!='') + { + + $out .= "\n"; + // NB: a better solution MIGHT be to use CDATA, but we need to insert it + // into return payload AFTER the beginning tag + //$out .= "', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n"; + } + return $out; + } + + /** + * Execute the xmlrpc request, printing the response + * @param string $data the request body. If null, the http POST request will be examined + * @return xmlrpcresp the response object (usually not used by caller...) + * @access public + */ + function service($data=null, $return_payload=false) + { + if ($data === null) + { + // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA + $data = file_get_contents('php://input'); + } + $raw_data = $data; + + // reset internal debug info + $this->debug_info = ''; + + // Echo back what we received, before parsing it + if($this->debug > 1) + { + $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); + } + + $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); + if (!$r) + { + $r=$this->parseRequest($data, $req_charset); + } + + // save full body of request into response, for more debugging usages + $r->raw_data = $raw_data; + + if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) + { + $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . + $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); + } + + $payload=$this->xml_header($resp_charset); + if($this->debug > 0) + { + $payload = $payload . $this->serializeDebug($resp_charset); + } + + // G. Giunta 2006-01-27: do not create response serialization if it has + // already happened. Helps building json magic + if (empty($r->payload)) + { + $r->serialize($resp_charset); + } + $payload = $payload . $r->payload; + + if ($return_payload) + { + return $payload; + } + + // if we get a warning/error that has output some text before here, then we cannot + // add a new header. We cannot say we are sending xml, either... + if(!headers_sent()) + { + header('Content-Type: '.$r->content_type); + // we do not know if client actually told us an accepted charset, but if he did + // we have to tell him what we did + header("Vary: Accept-Charset"); + + // http compression of output: only + // if we can do it, and we want to do it, and client asked us to, + // and php ini settings do not force it already + $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); + if($this->compress_response && function_exists('gzencode') && $resp_encoding != '' + && $php_no_self_compress) + { + if(strpos($resp_encoding, 'gzip') !== false) + { + $payload = gzencode($payload); + header("Content-Encoding: gzip"); + header("Vary: Accept-Encoding"); + } + elseif (strpos($resp_encoding, 'deflate') !== false) + { + $payload = gzcompress($payload); + header("Content-Encoding: deflate"); + header("Vary: Accept-Encoding"); + } + } + + // do not ouput content-length header if php is compressing output for us: + // it will mess up measurements + if($php_no_self_compress) + { + header('Content-Length: ' . (int)strlen($payload)); + } + } + else + { + error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages'); + } + + print $payload; + + // return request, in case subclasses want it + return $r; + } + + /** + * Add a method to the dispatch map + * @param string $methodname the name with which the method will be made available + * @param string $function the php function that will get invoked + * @param array $sig the array of valid method signatures + * @param string $doc method documentation + * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type) + * @access public + */ + function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false) + { + $this->dmap[$methodname] = array( + 'function' => $function, + 'docstring' => $doc + ); + if ($sig) + { + $this->dmap[$methodname]['signature'] = $sig; + } + if ($sigdoc) + { + $this->dmap[$methodname]['signature_docs'] = $sigdoc; + } + } + + /** + * Verify type and number of parameters received against a list of known signatures + * @param array $in array of either xmlrpcval objects or xmlrpc type definitions + * @param array $sig array of known signatures to match against + * @return array + * @access private + */ + function verifySignature($in, $sig) + { + // check each possible signature in turn + if (is_object($in)) + { + $numParams = $in->getNumParams(); + } + else + { + $numParams = count($in); + } + foreach($sig as $cursig) + { + if(count($cursig)==$numParams+1) + { + $itsOK=1; + for($n=0; $n<$numParams; $n++) + { + if (is_object($in)) + { + $p=$in->getParam($n); + if($p->kindOf() == 'scalar') + { + $pt=$p->scalartyp(); + } + else + { + $pt=$p->kindOf(); + } + } + else + { + $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4... + } + + // param index is $n+1, as first member of sig is return type + if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) + { + $itsOK=0; + $pno=$n+1; + $wanted=$cursig[$n+1]; + $got=$pt; + break; + } + } + if($itsOK) + { + return array(1,''); + } + } + } + if(isset($wanted)) + { + return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); + } + else + { + return array(0, "No method signature matches number of parameters"); + } + } + + /** + * Parse http headers received along with xmlrpc request. If needed, inflate request + * @return mixed null on success or an xmlrpcresp + * @access private + */ + function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) + { + // check if $_SERVER is populated: it might have been disabled via ini file + // (this is true even when in CLI mode) + if (count($_SERVER) == 0) + { + error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated'); + } + + if($this->debug > 1) + { + if(function_exists('getallheaders')) + { + $this->debugmsg(''); // empty line + foreach(getallheaders() as $name => $val) + { + $this->debugmsg("HEADER: $name: $val"); + } + } + + } + + if(isset($_SERVER['HTTP_CONTENT_ENCODING'])) + { + $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); + } + else + { + $content_encoding = ''; + } + + // check if request body has been compressed and decompress it + if($content_encoding != '' && strlen($data)) + { + if($content_encoding == 'deflate' || $content_encoding == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) + { + if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug > 1) + { + $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + } + elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug > 1) + $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + else + { + $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); + return $r; + } + } + else + { + //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); + return $r; + } + } + } + + // check if client specified accepted charsets, and if we know how to fulfill + // the request + if ($this->response_charset_encoding == 'auto') + { + $resp_encoding = ''; + if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) + { + // here we should check if we can match the client-requested encoding + // with the encodings we know we can generate. + /// @todo we should parse q=0.x preferences instead of getting first charset specified... + $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); + // Give preference to internal encoding + $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + foreach ($known_charsets as $charset) + { + foreach ($client_accepted_charsets as $accepted) + if (strpos($accepted, $charset) === 0) + { + $resp_encoding = $charset; + break; + } + if ($resp_encoding) + break; + } + } + } + else + { + $resp_encoding = $this->response_charset_encoding; + } + + if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) + { + $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; + } + else + { + $resp_compression = ''; + } + + // 'guestimate' request encoding + /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? + $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $data); + + return null; + } + + /** + * Parse an xml chunk containing an xmlrpc request and execute the corresponding + * php function registered with the server + * @param string $data the xml request + * @param string $req_encoding (optional) the charset encoding of the xml request + * @return xmlrpcresp + * @access private + */ + function parseRequest($data, $req_encoding='') + { + // 2005/05/07 commented and moved into caller function code + //if($data=='') + //{ + // $data=$GLOBALS['HTTP_RAW_POST_DATA']; + //} + + // G. Giunta 2005/02/13: we do NOT expect to receive html entities + // so we do not try to convert them into xml character entities + //$data = xmlrpc_html_entity_xlate($data); + + $GLOBALS['_xh']=array(); + $GLOBALS['_xh']['ac']=''; + $GLOBALS['_xh']['stack']=array(); + $GLOBALS['_xh']['valuestack'] = array(); + $GLOBALS['_xh']['params']=array(); + $GLOBALS['_xh']['pt']=array(); + $GLOBALS['_xh']['isf']=0; + $GLOBALS['_xh']['isf_reason']=''; + $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not + $GLOBALS['_xh']['rt']=''; + + // decompose incoming XML into request structure + if ($req_encoding != '') + { + if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding); + $req_encoding = $GLOBALS['xmlrpc_defencoding']; + } + /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text... + /// @todo use an empty string for php 5 ??? + $parser = xml_parser_create($req_encoding); + } + else + { + $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_entitites() and setting xmlrpc_internalencoding + if (!in_array($GLOBALS['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, $GLOBALS['xmlrpc_internalencoding']); + } + + if ($this->functions_parameters_type != 'xmlrpcvals') + 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'); + if(!xml_parse($parser, $data, 1)) + { + // return XML error as a faultCode + $r=new xmlrpcresp(0, + $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser), + 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))); + xml_parser_free($parser); + } + elseif ($GLOBALS['_xh']['isf']) + { + xml_parser_free($parser); + $r=new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['invalid_request'], + $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']); + } + else + { + xml_parser_free($parser); + // small layering violation in favor of speed and memory usage: + // we should allow the 'execute' method handle this, but in the + // most common scenario (xmlrpcvals type server with some methods + // registered as phpvals) that would mean a useless encode+decode pass + if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals'))) + { + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++"); + } + $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']); + } + else + { + // build an xmlrpcmsg object with data parsed from xml + $m=new xmlrpcmsg($GLOBALS['_xh']['method']); + // now add parameters in + for($i=0; $iaddParam($GLOBALS['_xh']['params'][$i]); + } + + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++"); + } + $r = $this->execute($m); + } + } + return $r; + } + + /** + * Execute a method invoked by the client, checking parameters used + * @param mixed $m either an xmlrpcmsg obj or a method name + * @param array $params array with method parameters as php types (if m is method name only) + * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) + * @return xmlrpcresp + * @access private + */ + function execute($m, $params=null, $paramtypes=null) + { + if (is_object($m)) + { + $methName = $m->method(); + } + else + { + $methName = $m; + } + $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); + $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; + + if(!isset($dmap[$methName]['function'])) + { + // No such method + return new xmlrpcresp(0, + $GLOBALS['xmlrpcerr']['unknown_method'], + $GLOBALS['xmlrpcstr']['unknown_method']); + } + + // Check signature + if(isset($dmap[$methName]['signature'])) + { + $sig = $dmap[$methName]['signature']; + if (is_object($m)) + { + list($ok, $errstr) = $this->verifySignature($m, $sig); + } + else + { + list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); + } + if(!$ok) + { + // Didn't match. + return new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" + ); + } + } + + $func = $dmap[$methName]['function']; + // let the 'class::function' syntax be accepted in dispatch maps + if(is_string($func) && strpos($func, '::')) + { + $func = explode('::', $func); + } + // verify that function to be invoked is in fact callable + if(!is_callable($func)) + { + error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable"); + return new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" + ); + } + + // If debug level is 3, we should catch all errors generated during + // processing of user function, and log them as part of response + if($this->debug > 2) + { + $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); + } + try + { + // Allow mixed-convention servers + if (is_object($m)) + { + if($sysCall) + { + $r = call_user_func($func, $this, $m); + } + else + { + $r = call_user_func($func, $m); + } + if (!is_a($r, 'xmlrpcresp')) + { + error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); + if (is_a($r, 'xmlrpcval')) + { + $r = new xmlrpcresp($r); + } + else + { + $r = new xmlrpcresp( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" + ); + } + } + } + else + { + // call a 'plain php' function + if($sysCall) + { + array_unshift($params, $this); + $r = call_user_func_array($func, $params); + } + else + { + // 3rd API convention for method-handling functions: EPI-style + if ($this->functions_parameters_type == 'epivals') + { + $r = call_user_func_array($func, array($methName, $params, $this->user_data)); + // mimic EPI behaviour: if we get an array that looks like an error, make it + // an eror response + if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) + { + $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']); + } + else + { + // functions using EPI api should NOT return resp objects, + // so make sure we encode the return type correctly + $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api'))); + } + } + else + { + $r = call_user_func_array($func, $params); + } + } + // the return type can be either an xmlrpcresp object or a plain php value... + if (!is_a($r, 'xmlrpcresp')) + { + // what should we assume here about automatic encoding of datetimes + // and php classes instances??? + $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options)); + } + } + } + catch(Exception $e) + { + // (barring errors in the lib) an uncatched exception happened + // in the called function, we wrap it in a proper error-response + switch($this->exception_handling) + { + case 2: + throw $e; + break; + case 1: + $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage()); + break; + default: + $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']); + } + } + if($this->debug > 2) + { + // note: restore the error handler we found before calling the + // user func, even if it has been changed inside the func itself + if($GLOBALS['_xmlrpcs_prev_ehandler']) + { + set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); + } + else + { + restore_error_handler(); + } + } + return $r; + } + + /** + * add a string to the 'internal debug message' (separate from 'user debug message') + * @param string $string + * @access private + */ + function debugmsg($string) + { + $this->debug_info .= $string."\n"; + } + + /** + * @access private + */ + function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n"; + } + else + { + return "\n"; + } + } + + /** + * A debugging routine: just echoes back the input packet as a string value + * DEPRECATED! + */ + function echoInput() + { + $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); + print $r->serialize(); + } +} ?> \ No newline at end of file From e320d0cc8d27e028129e1c46c687ef811f134238 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:26:09 +0300 Subject: [PATCH 008/228] Splitted classes from xmlrpc.php to separate files --- lib/xmlrpc.php | 2460 +---------------------------------------- lib/xmlrpc_client.php | 1147 +++++++++++++++++++ lib/xmlrpcmsg.php | 632 +++++++++++ lib/xmlrpcresp.php | 170 +++ lib/xmlrpcval.php | 514 +++++++++ 5 files changed, 2468 insertions(+), 2455 deletions(-) create mode 100644 lib/xmlrpc_client.php create mode 100644 lib/xmlrpcmsg.php create mode 100644 lib/xmlrpcresp.php create mode 100644 lib/xmlrpcval.php diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index e42571d8..fb94bf32 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -34,6 +34,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. +require_once __DIR__ . "/xmlrpc_client.php"; +require_once __DIR__ . "/xmlrpcresp.php"; +require_once __DIR__ . "/xmlrpcmsg.php"; +require_once __DIR__ . "/xmlrpcval.php"; + class Xmlrpc { public $xmlrpcI4 = "i4"; @@ -796,2461 +801,6 @@ function xmlrpc_dh($parser, $data) return true; } -class xmlrpc_client -{ - var $path; - var $server; - var $port=0; - var $method='http'; - var $errno; - var $errstr; - var $debug=0; - var $username=''; - var $password=''; - var $authtype=1; - var $cert=''; - var $certpass=''; - var $cacert=''; - var $cacertdir=''; - var $key=''; - var $keypass=''; - var $verifypeer=true; - var $verifyhost=2; - var $no_multicall=false; - var $proxy=''; - var $proxyport=0; - var $proxy_user=''; - var $proxy_pass=''; - var $proxy_authtype=1; - var $cookies=array(); - var $extracurlopts=array(); - - /** - * List of http compression methods accepted by the client for responses. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib - * - * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since - * in those cases it will be up to CURL to decide the compression methods - * it supports. You might check for the presence of 'zlib' in the output of - * curl_version() to determine wheter compression is supported or not - */ - var $accepted_compression = array(); - /** - * Name of compression scheme to be used for sending requests. - * Either null, gzip or deflate - */ - var $request_compression = ''; - /** - * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see: - * http://curl.haxx.se/docs/faq.html#7.3) - */ - var $xmlrpc_curl_handle = null; - /// Whether to use persistent connections for http 1.1 and https - var $keepalive = false; - /// Charset encodings that can be decoded without problems by the client - var $accepted_charset_encodings = array(); - /// Charset encoding to be used in serializing request. NULL = use ASCII - var $request_charset_encoding = ''; - /** - * Decides the content of xmlrpcresp objects returned by calls to send() - * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' - */ - var $return_type = 'xmlrpcvals'; - /** - * Sent to servers in http headers - */ - var $user_agent; - - /** - * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php - * @param string $server the server name / ip address - * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used - * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed - */ - function xmlrpc_client($path, $server='', $port='', $method='') - { - $xmlrpc = Xmlrpc::instance(); - - // allow user to specify all params in $path - if($server == '' and $port == '' and $method == '') - { - $parts = parse_url($path); - $server = $parts['host']; - $path = isset($parts['path']) ? $parts['path'] : ''; - if(isset($parts['query'])) - { - $path .= '?'.$parts['query']; - } - if(isset($parts['fragment'])) - { - $path .= '#'.$parts['fragment']; - } - if(isset($parts['port'])) - { - $port = $parts['port']; - } - if(isset($parts['scheme'])) - { - $method = $parts['scheme']; - } - if(isset($parts['user'])) - { - $this->username = $parts['user']; - } - if(isset($parts['pass'])) - { - $this->password = $parts['pass']; - } - } - if($path == '' || $path[0] != '/') - { - $this->path='/'.$path; - } - else - { - $this->path=$path; - } - $this->server=$server; - if($port != '') - { - $this->port=$port; - } - if($method != '') - { - $this->method=$method; - } - - // if ZLIB is enabled, let the client by default accept compressed responses - if(function_exists('gzinflate') || ( - function_exists('curl_init') && (($info = curl_version()) && - ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) - )) - { - $this->accepted_compression = array('gzip', 'deflate'); - } - - // keepalives: enabled by default - $this->keepalive = true; - - // by default the xml parser can support these 3 charset encodings - $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); - - // initialize user_agent string - $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; - } - - /** - * Enables/disables the echoing to screen of the xmlrpc responses received - * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) - * @access public - */ - function setDebug($in) - { - $this->debug=$in; - } - - /** - * Add some http BASIC AUTH credentials, used by the client to authenticate - * @param string $u username - * @param string $p password - * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) - * @access public - */ - function setCredentials($u, $p, $t=1) - { - $this->username=$u; - $this->password=$p; - $this->authtype=$t; - } - - /** - * Add a client-side https certificate - * @param string $cert - * @param string $certpass - * @access public - */ - function setCertificate($cert, $certpass) - { - $this->cert = $cert; - $this->certpass = $certpass; - } - - /** - * Add a CA certificate to verify server with (see man page about - * CURLOPT_CAINFO for more details) - * @param string $cacert certificate file name (or dir holding certificates) - * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false - * @access public - */ - function setCaCertificate($cacert, $is_dir=false) - { - if ($is_dir) - { - $this->cacertdir = $cacert; - } - else - { - $this->cacert = $cacert; - } - } - - /** - * Set attributes for SSL communication: private SSL key - * NB: does not work in older php/curl installs - * Thanks to Daniel Convissor - * @param string $key The name of a file containing a private SSL key - * @param string $keypass The secret password needed to use the private SSL key - * @access public - */ - function setKey($key, $keypass) - { - $this->key = $key; - $this->keypass = $keypass; - } - - /** - * Set attributes for SSL communication: verify server certificate - * @param bool $i enable/disable verification of peer certificate - * @access public - */ - function setSSLVerifyPeer($i) - { - $this->verifypeer = $i; - } - - /** - * Set attributes for SSL communication: verify match of server cert w. hostname - * @param int $i - * @access public - */ - function setSSLVerifyHost($i) - { - $this->verifyhost = $i; - } - - /** - * Set proxy info - * @param string $proxyhost - * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS - * @param string $proxyusername Leave blank if proxy has public access - * @param string $proxypassword Leave blank if proxy has public access - * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) - { - $this->proxy = $proxyhost; - $this->proxyport = $proxyport; - $this->proxy_user = $proxyusername; - $this->proxy_pass = $proxypassword; - $this->proxy_authtype = $proxyauthtype; - } - - /** - * Enables/disables reception of compressed xmlrpc responses. - * Note that enabling reception of compressed responses merely adds some standard - * http headers to xmlrpc requests. It is up to the xmlrpc server to return - * compressed responses when receiving such requests. - * @param string $compmethod either 'gzip', 'deflate', 'any' or '' - * @access public - */ - function setAcceptedCompression($compmethod) - { - if ($compmethod == 'any') - $this->accepted_compression = array('gzip', 'deflate'); - else - if ($compmethod == false ) - $this->accepted_compression = array(); - else - $this->accepted_compression = array($compmethod); - } - - /** - * Enables/disables http compression of xmlrpc request. - * Take care when sending compressed requests: servers might not support them - * (and automatic fallback to uncompressed requests is not yet implemented) - * @param string $compmethod either 'gzip', 'deflate' or '' - * @access public - */ - function setRequestCompression($compmethod) - { - $this->request_compression = $compmethod; - } - - /** - * Adds a cookie to list of cookies that will be sent to server. - * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: - * do not do it unless you know what you are doing - * @param string $name - * @param string $value - * @param string $path - * @param string $domain - * @param int $port - * @access public - * - * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) - */ - function setCookie($name, $value='', $path='', $domain='', $port=null) - { - $this->cookies[$name]['value'] = urlencode($value); - if ($path || $domain || $port) - { - $this->cookies[$name]['path'] = $path; - $this->cookies[$name]['domain'] = $domain; - $this->cookies[$name]['port'] = $port; - $this->cookies[$name]['version'] = 1; - } - else - { - $this->cookies[$name]['version'] = 0; - } - } - - /** - * Directly set cURL options, for extra flexibility - * It allows eg. to bind client to a specific IP interface / address - * @param array $options - */ - function SetCurlOptions( $options ) - { - $this->extracurlopts = $options; - } - - /** - * Set user-agent string that will be used by this client instance - * in http headers sent to the server - */ - function SetUserAgent( $agentstring ) - { - $this->user_agent = $agentstring; - } - - /** - * Send an xmlrpc request - * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request - * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply - * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used - * @return xmlrpcresp - * @access public - */ - function& send($msg, $timeout=0, $method='') - { - // if user deos not specify http protocol, use native method of this client - // (i.e. method set during call to constructor) - if($method == '') - { - $method = $this->method; - } - - if(is_array($msg)) - { - // $msg is an array of xmlrpcmsg's - $r = $this->multicall($msg, $timeout, $method); - return $r; - } - elseif(is_string($msg)) - { - $n = new xmlrpcmsg(''); - $n->payload = $msg; - $msg = $n; - } - - // where msg is an xmlrpcmsg - $msg->debug=$this->debug; - - if($method == 'https') - { - $r =& $this->sendPayloadHTTPS( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - $this->cert, - $this->certpass, - $this->cacert, - $this->cacertdir, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype, - $this->keepalive, - $this->key, - $this->keypass - ); - } - elseif($method == 'http11') - { - $r =& $this->sendPayloadCURL( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - null, - null, - null, - null, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype, - 'http', - $this->keepalive - ); - } - else - { - $r =& $this->sendPayloadHTTP10( - $msg, - $this->server, - $this->port, - $timeout, - $this->username, - $this->password, - $this->authtype, - $this->proxy, - $this->proxyport, - $this->proxy_user, - $this->proxy_pass, - $this->proxy_authtype - ); - } - - return $r; - } - - /** - * @access private - */ - function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, - $username='', $password='', $authtype=1, $proxyhost='', - $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) - { - $xmlrpc = Xmlrpc::instance(); - - if($port==0) - { - $port=80; - } - - // Only create the payload if it was not created previously - if(empty($msg->payload)) - { - $msg->createPayload($this->request_charset_encoding); - } - - $payload = $msg->payload; - // Deflate request body and set appropriate request headers - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { - $a = @gzencode($payload); - if($a) - { - $payload = $a; - $encoding_hdr = "Content-Encoding: gzip\r\n"; - } - } - else - { - $a = @gzcompress($payload); - if($a) - { - $payload = $a; - $encoding_hdr = "Content-Encoding: deflate\r\n"; - } - } - } - else - { - $encoding_hdr = ''; - } - - // thanks to Grant Rauscher for this - $credentials=''; - if($username!='') - { - $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; - if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0'); - } - } - - $accepted_encoding = ''; - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { - $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; - } - - $proxy_credentials = ''; - if($proxyhost) - { - if($proxyport == 0) - { - $proxyport = 8080; - } - $connectserver = $proxyhost; - $connectport = $proxyport; - $uri = 'http://'.$server.':'.$port.$this->path; - if($proxyusername != '') - { - if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0'); - } - $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; - } - } - else - { - $connectserver = $server; - $connectport = $port; - $uri = $this->path; - } - - // Cookie generation, as per rfc2965 (version 1 cookies) or - // netscape's rules (version 0 cookies) - $cookieheader=''; - if (count($this->cookies)) - { - $version = ''; - foreach ($this->cookies as $name => $cookie) - { - if ($cookie['version']) - { - $version = ' $Version="' . $cookie['version'] . '";'; - $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; - if ($cookie['path']) - $cookieheader .= ' $Path="' . $cookie['path'] . '";'; - if ($cookie['domain']) - $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; - if ($cookie['port']) - $cookieheader .= ' $Port="' . $cookie['port'] . '";'; - } - else - { - $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; - } - } - $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n"; - } - - // omit port if 80 - $port = ($port == 80) ? '' : (':' . $port); - - $op= 'POST ' . $uri. " HTTP/1.0\r\n" . - 'User-Agent: ' . $this->user_agent . "\r\n" . - 'Host: '. $server . $port . "\r\n" . - $credentials . - $proxy_credentials . - $accepted_encoding . - $encoding_hdr . - 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . - $cookieheader . - 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . - strlen($payload) . "\r\n\r\n" . - $payload; - - if($this->debug > 1) - { - print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; - // let the client see this now in case http times out... - flush(); - } - - if($timeout>0) - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); - } - else - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); - } - if($fp) - { - if($timeout>0 && function_exists('stream_set_timeout')) - { - stream_set_timeout($fp, $timeout); - } - } - else - { - $this->errstr='Connect error: '.$this->errstr; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); - return $r; - } - - if(!fputs($fp, $op, strlen($op))) - { - fclose($fp); - $this->errstr='Write error'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); - return $r; - } - else - { - // reset errno and errstr on successful socket connection - $this->errstr = ''; - } - // G. Giunta 2005/10/24: close socket before parsing. - // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) - $ipd=''; - do - { - // shall we check for $data === FALSE? - // as per the manual, it signals an error - $ipd.=fread($fp, 32768); - } while(!feof($fp)); - fclose($fp); - $r =& $msg->parseResponse($ipd, false, $this->return_type); - return $r; - - } - - /** - * @access private - */ - function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, - $keepalive=false, $key='', $keypass='') - { - $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, - $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, - $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); - return $r; - } - - /** - * Contributed by Justin Miller - * Requires curl to be built into PHP - * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! - * @access private - */ - function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', - $keepalive=false, $key='', $keypass='') - { - $xmlrpc = Xmlrpc::instance(); - - if(!function_exists('curl_init')) - { - $this->errstr='CURL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); - return $r; - } - if($method == 'https') - { - if(($info = curl_version()) && - ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) - { - $this->errstr='SSL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); - return $r; - } - } - - if($port == 0) - { - if($method == 'http') - { - $port = 80; - } - else - { - $port = 443; - } - } - - // Only create the payload if it was not created previously - if(empty($msg->payload)) - { - $msg->createPayload($this->request_charset_encoding); - } - - // Deflate request body and set appropriate request headers - $payload = $msg->payload; - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { - $a = @gzencode($payload); - if($a) - { - $payload = $a; - $encoding_hdr = 'Content-Encoding: gzip'; - } - } - else - { - $a = @gzcompress($payload); - if($a) - { - $payload = $a; - $encoding_hdr = 'Content-Encoding: deflate'; - } - } - } - else - { - $encoding_hdr = ''; - } - - if($this->debug > 1) - { - print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; - // let the client see this now in case http times out... - flush(); - } - - if(!$keepalive || !$this->xmlrpc_curl_handle) - { - $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); - if($keepalive) - { - $this->xmlrpc_curl_handle = $curl; - } - } - else - { - $curl = $this->xmlrpc_curl_handle; - } - - // results into variable - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - - if($this->debug) - { - curl_setopt($curl, CURLOPT_VERBOSE, 1); - } - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - // required for XMLRPC: post the data - curl_setopt($curl, CURLOPT_POST, 1); - // the data - curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); - - // return the header too - curl_setopt($curl, CURLOPT_HEADER, 1); - - // NB: if we set an empty string, CURL will add http header indicating - // ALL methods it is supporting. This is possibly a better option than - // letting the user tell what curl can / cannot do... - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { - //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); - // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if (count($this->accepted_compression) == 1) - { - curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); - } - else - curl_setopt($curl, CURLOPT_ENCODING, ''); - } - // extra headers - $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); - // if no keepalive is wanted, let the server know it in advance - if(!$keepalive) - { - $headers[] = 'Connection: close'; - } - // request compression header - if($encoding_hdr) - { - $headers[] = $encoding_hdr; - } - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - // timeout is borked - if($timeout) - { - curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); - } - - if($username && $password) - { - curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); - if (defined('CURLOPT_HTTPAUTH')) - { - curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); - } - else if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install'); - } - } - - if($method == 'https') - { - // set cert file - if($cert) - { - curl_setopt($curl, CURLOPT_SSLCERT, $cert); - } - // set cert password - if($certpass) - { - curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); - } - // whether to verify remote host's cert - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); - // set ca certificates file/dir - if($cacert) - { - curl_setopt($curl, CURLOPT_CAINFO, $cacert); - } - if($cacertdir) - { - curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); - } - // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($key) - { - curl_setopt($curl, CURLOPT_SSLKEY, $key); - } - // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($keypass) - { - curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); - } - // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); - } - - // proxy info - if($proxyhost) - { - if($proxyport == 0) - { - $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 - } - curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport); - //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); - if($proxyusername) - { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); - if (defined('CURLOPT_PROXYAUTH')) - { - curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); - } - else if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); - } - } - } - - // NB: should we build cookie http headers by hand rather than let CURL do it? - // the following code does not honour 'expires', 'path' and 'domain' cookie attributes - // set to client obj the the user... - if (count($this->cookies)) - { - $cookieheader = ''; - foreach ($this->cookies as $name => $cookie) - { - $cookieheader .= $name . '=' . $cookie['value'] . '; '; - } - curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); - } - - foreach ($this->extracurlopts as $opt => $val) - { - curl_setopt($curl, $opt, $val); - } - - $result = curl_exec($curl); - - if ($this->debug > 1) - { - print "
\n---CURL INFO---\n";
-            foreach(curl_getinfo($curl) as $name => $val)
-            {
-                if (is_array($val))
-                {
-                    $val = implode("\n", $val);
-                }
-                print $name . ': ' . htmlentities($val) . "\n";
-            }
-
-            print "---END---\n
"; - } - - if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? - { - $this->errstr='no response'; - $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); - curl_close($curl); - if($keepalive) - { - $this->xmlrpc_curl_handle = null; - } - } - else - { - if(!$keepalive) - { - curl_close($curl); - } - $resp =& $msg->parseResponse($result, true, $this->return_type); - // if we got back a 302, we can not reuse the curl handle for later calls - if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) - { - curl_close($curl); - $this->xmlrpc_curl_handle = null; - } - } - return $resp; - } - - /** - * Send an array of request messages and return an array of responses. - * Unless $this->no_multicall has been set to true, it will try first - * to use one single xmlrpc call to server method system.multicall, and - * revert to sending many successive calls in case of failure. - * This failure is also stored in $this->no_multicall for subsequent calls. - * Unfortunately, there is no server error code universally used to denote - * the fact that multicall is unsupported, so there is no way to reliably - * distinguish between that and a temporary failure. - * If you are sure that server supports multicall and do not want to - * fallback to using many single calls, set the fourth parameter to FALSE. - * - * NB: trying to shoehorn extra functionality into existing syntax has resulted - * in pretty much convoluted code... - * - * @param array $msgs an array of xmlrpcmsg objects - * @param integer $timeout connection timeout (in seconds) - * @param string $method the http protocol variant to be used - * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted - * @return array - * @access public - */ - function multicall($msgs, $timeout=0, $method='', $fallback=true) - { - $xmlrpc = Xmlrpc::instance(); - - if ($method == '') - { - $method = $this->method; - } - if(!$this->no_multicall) - { - $results = $this->_try_multicall($msgs, $timeout, $method); - if(is_array($results)) - { - // System.multicall succeeded - return $results; - } - else - { - // either system.multicall is unsupported by server, - // or call failed for some other reason. - if ($fallback) - { - // Don't try it next time... - $this->no_multicall = true; - } - else - { - if (is_a($results, 'xmlrpcresp')) - { - $result = $results; - } - else - { - $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); - } - } - } - } - else - { - // override fallback, in case careless user tries to do two - // opposite things at the same time - $fallback = true; - } - - $results = array(); - if ($fallback) - { - // system.multicall is (probably) unsupported by server: - // emulate multicall via multiple requests - foreach($msgs as $msg) - { - $results[] =& $this->send($msg, $timeout, $method); - } - } - else - { - // user does NOT want to fallback on many single calls: - // since we should always return an array of responses, - // return an array with the same error repeated n times - foreach($msgs as $msg) - { - $results[] = $result; - } - } - return $results; - } - - /** - * Attempt to boxcar $msgs via system.multicall. - * Returns either an array of xmlrpcreponses, an xmlrpc error response - * or false (when received response does not respect valid multicall syntax) - * @access private - */ - function _try_multicall($msgs, $timeout, $method) - { - // Construct multicall message - $calls = array(); - foreach($msgs as $msg) - { - $call['methodName'] = new xmlrpcval($msg->method(),'string'); - $numParams = $msg->getNumParams(); - $params = array(); - for($i = 0; $i < $numParams; $i++) - { - $params[$i] = $msg->getParam($i); - } - $call['params'] = new xmlrpcval($params, 'array'); - $calls[] = new xmlrpcval($call, 'struct'); - } - $multicall = new xmlrpcmsg('system.multicall'); - $multicall->addParam(new xmlrpcval($calls, 'array')); - - // Attempt RPC call - $result =& $this->send($multicall, $timeout, $method); - - if($result->faultCode() != 0) - { - // call to system.multicall failed - return $result; - } - - // Unpack responses. - $rets = $result->value(); - - if ($this->return_type == 'xml') - { - return $rets; - } - else if ($this->return_type == 'phpvals') - { - ///@todo test this code branch... - $rets = $result->value(); - if(!is_array($rets)) - { - return false; // bad return type from system.multicall - } - $numRets = count($rets); - if($numRets != count($msgs)) - { - return false; // wrong number of return values. - } - - $response = array(); - for($i = 0; $i < $numRets; $i++) - { - $val = $rets[$i]; - if (!is_array($val)) { - return false; - } - switch(count($val)) - { - case 1: - if(!isset($val[0])) - { - return false; // Bad value - } - // Normal return value - $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals'); - break; - case 2: - /// @todo remove usage of @: it is apparently quite slow - $code = @$val['faultCode']; - if(!is_int($code)) - { - return false; - } - $str = @$val['faultString']; - if(!is_string($str)) - { - return false; - } - $response[$i] = new xmlrpcresp(0, $code, $str); - break; - default: - return false; - } - } - return $response; - } - else // return type == 'xmlrpcvals' - { - $rets = $result->value(); - if($rets->kindOf() != 'array') - { - return false; // bad return type from system.multicall - } - $numRets = $rets->arraysize(); - if($numRets != count($msgs)) - { - return false; // wrong number of return values. - } - - $response = array(); - for($i = 0; $i < $numRets; $i++) - { - $val = $rets->arraymem($i); - switch($val->kindOf()) - { - case 'array': - if($val->arraysize() != 1) - { - return false; // Bad value - } - // Normal return value - $response[$i] = new xmlrpcresp($val->arraymem(0)); - break; - case 'struct': - $code = $val->structmem('faultCode'); - if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') - { - return false; - } - $str = $val->structmem('faultString'); - if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') - { - return false; - } - $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); - break; - default: - return false; - } - } - return $response; - } - } -} // end class xmlrpc_client - -class xmlrpcresp -{ - var $val = 0; - var $valtyp; - var $errno = 0; - var $errstr = ''; - var $payload; - var $hdrs = array(); - var $_cookies = array(); - var $content_type = 'text/xml'; - var $raw_data = ''; - - /** - * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) - * @param integer $fcode set it to anything but 0 to create an error response - * @param string $fstr the error string, in case of an error response - * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml' - * - * @todo add check that $val / $fcode / $fstr is of correct type??? - * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain - * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called... - */ - function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='') - { - if($fcode != 0) - { - // error response - $this->errno = $fcode; - $this->errstr = $fstr; - //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. - } - else - { - // successful response - $this->val = $val; - if ($valtyp == '') - { - // user did not declare type of response value: try to guess it - if (is_object($this->val) && is_a($this->val, 'xmlrpcval')) - { - $this->valtyp = 'xmlrpcvals'; - } - else if (is_string($this->val)) - { - $this->valtyp = 'xml'; - - } - else - { - $this->valtyp = 'phpvals'; - } - } - else - { - // user declares type of resp value: believe him - $this->valtyp = $valtyp; - } - } - } - - /** - * Returns the error code of the response. - * @return integer the error code of this response (0 for not-error responses) - * @access 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) - * @access public - */ - function faultString() - { - return $this->errstr; - } - - /** - * Returns the value received by the server. - * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects - * @access 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 xmlrpc_client::setCookie) or not - * @return array array of cookies received from the server - * @access public - */ - function cookies() - { - return $this->_cookies; - } - - /** - * Returns xml representation of the response. XML prologue not included - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string the xml representation of the response - * @access public - */ - function serialize($charset_encoding='') - { - $xmlrpc = Xmlrpc::instance(); - - if ($charset_encoding != '') - $this->content_type = 'text/xml; charset=' . $charset_encoding; - else - $this->content_type = 'text/xml'; - if ($xmlrpc->xmlrpc_null_apache_encoding) - { - $result = "xmlrpc_null_apache_encoding_ns."\">\n"; - } - else - { - $result = "\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 .= "\n" . -"\nfaultCode\n" . $this->errno . -"\n\n\nfaultString\n" . -xmlrpc_encode_entitites($this->errstr, $xmlrpc->xmlrpc_internalencoding, $charset_encoding) . "\n\n" . -"\n\n"; - } - else - { - if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) - { - if (is_string($this->val) && $this->valtyp == 'xml') - { - $result .= "\n\n" . - $this->val . - "\n"; - } - else - { - /// @todo try to build something serializable? - die('cannot serialize xmlrpcresp objects whose content is native php values'); - } - } - else - { - $result .= "\n\n" . - $this->val->serialize($charset_encoding) . - "\n"; - } - } - $result .= "\n"; - $this->payload = $result; - return $result; - } -} - -class xmlrpcmsg -{ - var $payload; - var $methodname; - var $params=array(); - var $debug=0; - var $content_type = 'text/xml'; - - /** - * @param string $meth the name of the method to invoke - * @param array $pars array of parameters to be passed to the method (xmlrpcval objects) - */ - function xmlrpcmsg($meth, $pars=0) - { - $this->methodname=$meth; - if(is_array($pars) && count($pars)>0) - { - for($i=0; $iaddParam($pars[$i]); - } - } - } - - /** - * @access private - */ - function xml_header($charset_encoding='') - { - if ($charset_encoding != '') - { - return "\n\n"; - } - else - { - return "\n\n"; - } - } - - /** - * @access private - */ - function xml_footer() - { - return ''; - } - - /** - * @access private - */ - function kindOf() - { - return 'msg'; - } - - /** - * @access private - */ - function createPayload($charset_encoding='') - { - if ($charset_encoding != '') - $this->content_type = 'text/xml; charset=' . $charset_encoding; - else - $this->content_type = 'text/xml'; - $this->payload=$this->xml_header($charset_encoding); - $this->payload.='' . $this->methodname . "\n"; - $this->payload.="\n"; - for($i=0; $iparams); $i++) - { - $p=$this->params[$i]; - $this->payload.="\n" . $p->serialize($charset_encoding) . - "\n"; - } - $this->payload.="\n"; - $this->payload.=$this->xml_footer(); - } - - /** - * Gets/sets the xmlrpc method to be invoked - * @param string $meth the method to be set (leave empty not to set it) - * @return string the method that will be invoked - * @access public - */ - function method($meth='') - { - if($meth!='') - { - $this->methodname=$meth; - } - return $this->methodname; - } - - /** - * Returns xml representation of the message. XML prologue included - * @param string $charset_encoding - * @return string the xml representation of the message, xml prologue included - * @access public - */ - function serialize($charset_encoding='') - { - $this->createPayload($charset_encoding); - return $this->payload; - } - - /** - * Add a parameter to the list of parameters to be used upon method invocation - * @param xmlrpcval $par - * @return boolean false on failure - * @access public - */ - function addParam($par) - { - // add check: do not add to self params which are not xmlrpcvals - if(is_object($par) && is_a($par, 'xmlrpcval')) - { - $this->params[]=$par; - return true; - } - else - { - return false; - } - } - - /** - * Returns the nth parameter in the message. The index zero-based. - * @param integer $i the index of the parameter to fetch (zero based) - * @return xmlrpcval the i-th parameter - * @access public - */ - function getParam($i) { return $this->params[$i]; } - - /** - * Returns the number of parameters in the messge. - * @return integer the number of parameters currently set - * @access public - */ - function getNumParams() { return count($this->params); } - - /** - * Given an open file handle, read all data available and parse it as axmlrpc 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... - * @access public - * @param resource $fp stream pointer - * @return xmlrpcresp - * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? - */ - function &parseResponseFile($fp) - { - $ipd=''; - while($data=fread($fp, 32768)) - { - $ipd.=$data; - } - //fclose($fp); - $r =& $this->parseResponse($ipd); - return $r; - } - - /** - * Parses HTTP headers and separates them from data. - * @access private - */ - function &parseResponseHeaders(&$data, $headers_processed=false) - { - $xmlrpc = Xmlrpc::instance(); - // 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'); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); - return $r; - } - } - - // 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); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; - } - - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - - // 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) - { - $header_name = 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'][$header_name] - /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') - { - if ($header_name == '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($xmlrpc->_xh['headers'][$header_name])) - $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); - else - $xmlrpc->_xh['headers'][$header_name] = 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; - $xmlrpc->_xh['cookies'][$tag] = array(); - $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); - } - else - { - if ($tag != 'value') - { - $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; - } - } - } - } - } - else - { - $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); - } - } - elseif(isset($header_name)) - { - /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); - } - } - - $data = substr($data, $bd); - - if($this->debug && count($xmlrpc->_xh['headers'])) - { - print '
';
-                foreach($xmlrpc->_xh['headers'] as $header => $value)
-                {
-                    print htmlentities("HEADER: $header: $value\n");
-                }
-                foreach($xmlrpc->_xh['cookies'] as $header => $value)
-                {
-                    print htmlentities("COOKIE: $header={$value['value']}\n");
-                }
-                print "
\n"; - } - - // if CURL was used for the call, http headers have been processed, - // and dechunking + reinflating have been carried out - if(!$headers_processed) - { - // Decode chunked encoding sent by http 1.1 servers - if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked') - { - if(!$data = decode_chunked($data)) - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']); - return $r; - } - } - - // Decode gzip-compressed stuff - // code shamelessly inspired from nusoap library by Dietrich Ayala - if(isset($xmlrpc->_xh['headers']['content-encoding'])) - { - $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']); - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip') - { - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')) - { - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - else - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); - return $r; - } - } - else - { - error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); - return $r; - } - } - } - } // end of 'if needed, de-chunk, re-inflate response' - - // real stupid hack to avoid PHP complaining about returning NULL by ref - $r = null; - $r =& $r; - return $r; - } - - /** - * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. - * @param string $data the xmlrpc response, eventually including http headers - * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding - * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' - * @return xmlrpcresp - * @access public - */ - function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') - { - $xmlrpc = Xmlrpc::instance(); - - if($this->debug) - { - //by maHo, replaced htmlspecialchars with htmlentities - print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; - } - - if($data == '') - { - error_log('XML-RPC: '.__METHOD__.': no response received from server.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); - return $r; - } - - $xmlrpc->_xh=array(); - - $raw_data = $data; - // parse the HTTP headers of the response, if present, and separate them from data - if(substr($data, 0, 4) == 'HTTP') - { - $r =& $this->parseResponseHeaders($data, $headers_processed); - if ($r) - { - // failed processing of HTTP response headers - // save into response obj the full payload received, for debugging - $r->raw_data = $data; - return $r; - } - } - else - { - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - } - - if($this->debug) - { - $start = strpos($data, '', $start); - $comments = substr($data, $start, $end-$start); - print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; - } - } - - // 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 originally in PEARified version of the lib - $pos = strrpos($data, '
'); - if($pos !== false) - { - $data = substr($data, 0, $pos+17); - } - - // if user wants back raw xml, give it to him - if ($return_type == 'xml') - { - $r = new xmlrpcresp($data, 0, '', 'xml'); - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - - // try to 'guestimate' the character encoding of the received response - $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); - - $xmlrpc->_xh['ac']=''; - //$xmlrpc->_xh['qt']=''; //unused... - $xmlrpc->_xh['stack'] = array(); - $xmlrpc->_xh['valuestack'] = array(); - $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc - $xmlrpc->_xh['isf_reason']=''; - $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' - - // if response charset encoding is not known / supported, try to use - // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); - $resp_encoding = $xmlrpc->xmlrpc_defencoding; - } - $parser = xml_parser_create($resp_encoding); - 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_entitites() and setting xmlrpc_internalencoding - if (!in_array($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); - } - - if ($return_type == '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 - 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 xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); - xml_parser_free($parser); - if($this->debug) - { - print $errstr; - } - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - xml_parser_free($parser); - // second error check: xml well formed but not xml-rpc compliant - if ($xmlrpc->_xh['isf'] > 1) - { - if ($this->debug) - { - /// @todo echo something for user? - } - - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) - { - // something odd has happened - // and it's time to generate a client side error - // indicating something odd went on - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return']); - } - else - { - if ($this->debug) - { - print "
---PARSED---\n";
-                // somehow htmlentities chokes on var_export, and some full html string...
-                //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
-                print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
-                print "\n---END---
"; - } - - // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. - $v =& $xmlrpc->_xh['value']; - - if($xmlrpc->_xh['isf']) - { - /// @todo we should test here if server sent an int and a string, - /// and/or coerce them into such... - if ($return_type == 'xmlrpcvals') - { - $errno_v = $v->structmem('faultCode'); - $errstr_v = $v->structmem('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 xmlrpcresp(0, $errno, $errstr); - } - else - { - $r=new xmlrpcresp($v, 0, '', $return_type); - } - } - - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } -} - -class xmlrpcval -{ - var $me=array(); - var $mytype=0; - var $_php_class=null; - - /** - * @param mixed $val - * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed - */ - function xmlrpcval($val=-1, $type='') - { - /// @todo: optimization creep - do not call addXX, do it all inline. - /// downside: booleans will not be coerced anymore - if($val!==-1 || $type!='') - { - // optimization creep: inlined all work done by constructor - switch($type) - { - case '': - $this->mytype=1; - $this->me['string']=$val; - break; - case 'i4': - 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)"); - } - /*if($type=='') - { - $type='string'; - } - if($GLOBALS['xmlrpcTypes'][$type]==1) - { - $this->addScalar($val,$type); - } - elseif($GLOBALS['xmlrpcTypes'][$type]==2) - { - $this->addArray($val); - } - elseif($GLOBALS['xmlrpcTypes'][$type]==3) - { - $this->addStruct($val); - }*/ - } - } - - /** - * Add a single php value to an (unitialized) xmlrpcval - * @param mixed $val - * @param string $type - * @return int 1 or 0 on failure - */ - function addScalar($val, $type='string') - { - $xmlrpc = Xmlrpc::instance(); - - $typeof = null; - if(isset($xmlrpc->xmlrpcTypes[$type])) { - $typeof = $xmlrpc->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 and doubles, too, - // or just plain remove this check, implemented on booleans only... - if($type==$xmlrpc->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 xmlrpcval can have only one value'); - return 0; - case 3: - error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval'); - return 0; - case 2: - // we're adding a scalar value to an array here - //$ar=$this->me['array']; - //$ar[]=new xmlrpcval($val, $type); - //$this->me['array']=$ar; - // Faster (?) avoid all the costly array-copy-by-val done here... - $this->me['array'][]=new xmlrpcval($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 xmlrpcval objects to an xmlrpcval - * @param array $vals - * @return int 1 or 0 on failure - * @access public - * - * @todo add some checking for $vals to be an array of xmlrpcvals? - */ - function addArray($vals) - { - $xmlrpc = Xmlrpc::instance(); - if($this->mytype==0) - { - $this->mytype=$xmlrpc->xmlrpcTypes['array']; - $this->me['array']=$vals; - return 1; - } - elseif($this->mytype==2) - { - // we're adding to an array here - $this->me['array'] = array_merge($this->me['array'], $vals); - return 1; - } - else - { - error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); - return 0; - } - } - - /** - * Add an array of named xmlrpcval objects to an xmlrpcval - * @param array $vals - * @return int 1 or 0 on failure - * @access public - * - * @todo add some checking for $vals to be an array? - */ - function addStruct($vals) - { - $xmlrpc = Xmlrpc::instance(); - - if($this->mytype==0) - { - $this->mytype=$xmlrpc->xmlrpcTypes['struct']; - $this->me['struct']=$vals; - return 1; - } - elseif($this->mytype==3) - { - // we're adding to a struct here - $this->me['struct'] = array_merge($this->me['struct'], $vals); - return 1; - } - else - { - error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); - return 0; - } - } - - // poor man's version of print_r ??? - // DEPRECATED! - function dump($ar) - { - foreach($ar as $key => $val) - { - echo "$key => $val
"; - if($key == 'array') - { - while(list($key2, $val2) = each($val)) - { - echo "-- $key2 => $val2
"; - } - } - } - } - - /** - * Returns a string containing "struct", "array" or "scalar" describing the base type of the value - * @return string - * @access public - */ - function kindOf() - { - switch($this->mytype) - { - case 3: - return 'struct'; - break; - case 2: - return 'array'; - break; - case 1: - return 'scalar'; - break; - default: - return 'undef'; - } - } - - /** - * @access private - */ - function serializedata($typ, $val, $charset_encoding='') - { - $xmlrpc = Xmlrpc::instance(); - $rs=''; - - if(!isset($xmlrpc->xmlrpcTypes[$typ])) { - return $rs; - } - - switch($xmlrpc->xmlrpcTypes[$typ]) - { - case 1: - switch($typ) - { - case $xmlrpc->xmlrpcBase64: - $rs.="<${typ}>" . base64_encode($val) . ""; - break; - case $xmlrpc->xmlrpcBoolean: - $rs.="<${typ}>" . ($val ? '1' : '0') . ""; - break; - case $xmlrpc->xmlrpcString: - // G. Giunta 2005/2/13: do NOT use htmlentities, since - // it will produce named html entities, which are invalid xml - $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; - break; - case $xmlrpc->xmlrpcInt: - case $xmlrpc->xmlrpcI4: - $rs.="<${typ}>".(int)$val.""; - break; - case $xmlrpc->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, '.', '')).""; - break; - case $xmlrpc->xmlrpcDateTime: - if (is_string($val)) - { - $rs.="<${typ}>${val}"; - } - else if(is_a($val, 'DateTime')) - { - $rs.="<${typ}>".$val->format('Ymd\TH:i:s').""; - } - else if(is_int($val)) - { - $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val).""; - } - else - { - // not really a good idea here: but what shall we output anyway? left for backward compat... - $rs.="<${typ}>${val}"; - } - break; - case $xmlrpc->xmlrpcNull: - if ($xmlrpc->xmlrpc_null_apache_encoding) - { - $rs.=""; - } - else - { - $rs.=""; - } - break; - default: - // no standard type value should arrive here, but provide a possibility - // for xmlrpcvals of unknown type... - $rs.="<${typ}>${val}"; - } - break; - case 3: - // struct - if ($this->_php_class) - { - $rs.='\n"; - } - else - { - $rs.="\n"; - } - foreach($val as $key2 => $val2) - { - $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; - //$rs.=$this->serializeval($val2); - $rs.=$val2->serialize($charset_encoding); - $rs.="\n"; - } - $rs.=''; - break; - case 2: - // array - $rs.="\n\n"; - for($i=0; $iserializeval($val[$i]); - $rs.=$val[$i]->serialize($charset_encoding); - } - $rs.="\n"; - break; - default: - break; - } - return $rs; - } - - /** - * Returns xml representation of the value. XML prologue not included - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string - * @access public - */ - function serialize($charset_encoding='') - { - // 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'))) - //{ - reset($this->me); - list($typ, $val) = each($this->me); - return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; - //} - } - - // DEPRECATED - 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 '' . $this->serializedata($typ, $val) . "\n"; - //} - } - - /** - * Checks whether a struct member with a given name is present. - * Works only on xmlrpcvals of type struct. - * @param string $m the name of the struct member to be looked up - * @return boolean - * @access public - */ - function structmemexists($m) - { - return array_key_exists($m, $this->me['struct']); - } - - /** - * Returns the value of a given struct member (an xmlrpcval object in itself). - * Will raise a php warning if struct member of given name does not exist - * @param string $m the name of the struct member to be looked up - * @return xmlrpcval - * @access public - */ - function structmem($m) - { - return $this->me['struct'][$m]; - } - - /** - * Reset internal pointer for xmlrpcvals of type struct. - * @access public - */ - function structreset() - { - reset($this->me['struct']); - } - - /** - * Return next member element for xmlrpcvals of type struct. - * @return xmlrpcval - * @access public - */ - function structeach() - { - return each($this->me['struct']); - } - - // 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? - 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; - } - - /** - * Returns the value of a scalar xmlrpcval - * @return mixed - * @access public - */ - function scalarval() - { - reset($this->me); - list(,$b)=each($this->me); - return $b; - } - - /** - * Returns the type of the xmlrpcval. - * For integers, 'int' is always returned in place of 'i4' - * @return string - * @access public - */ - function scalartyp() - { - $xmlrpc = Xmlrpc::instance(); - - reset($this->me); - list($a,)=each($this->me); - if($a==$xmlrpc->xmlrpcI4) - { - $a=$xmlrpc->xmlrpcInt; - } - return $a; - } - - /** - * Returns the m-th member of an xmlrpcval of struct type - * @param integer $m the index of the value to be retrieved (zero based) - * @return xmlrpcval - * @access public - */ - function arraymem($m) - { - return $this->me['array'][$m]; - } - - /** - * Returns the number of members in an xmlrpcval of array type - * @return integer - * @access public - */ - function arraysize() - { - return count($this->me['array']); - } - - /** - * Returns the number of members in an xmlrpcval of struct type - * @return integer - * @access public - */ - function structsize() - { - return count($this->me['struct']); - } -} - - // date helpers /** diff --git a/lib/xmlrpc_client.php b/lib/xmlrpc_client.php new file mode 100644 index 00000000..66226a07 --- /dev/null +++ b/lib/xmlrpc_client.php @@ -0,0 +1,1147 @@ +username = $parts['user']; + } + if(isset($parts['pass'])) + { + $this->password = $parts['pass']; + } + } + if($path == '' || $path[0] != '/') + { + $this->path='/'.$path; + } + else + { + $this->path=$path; + } + $this->server=$server; + if($port != '') + { + $this->port=$port; + } + if($method != '') + { + $this->method=$method; + } + + // if ZLIB is enabled, let the client by default accept compressed responses + if(function_exists('gzinflate') || ( + function_exists('curl_init') && (($info = curl_version()) && + ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) + )) + { + $this->accepted_compression = array('gzip', 'deflate'); + } + + // keepalives: enabled by default + $this->keepalive = true; + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // initialize user_agent string + $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; + } + + /** + * Enables/disables the echoing to screen of the xmlrpc responses received + * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) + * @access public + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Add some http BASIC AUTH credentials, used by the client to authenticate + * @param string $u username + * @param string $p password + * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) + * @access public + */ + function setCredentials($u, $p, $t=1) + { + $this->username=$u; + $this->password=$p; + $this->authtype=$t; + } + + /** + * Add a client-side https certificate + * @param string $cert + * @param string $certpass + * @access public + */ + function setCertificate($cert, $certpass) + { + $this->cert = $cert; + $this->certpass = $certpass; + } + + /** + * Add a CA certificate to verify server with (see man page about + * CURLOPT_CAINFO for more details) + * @param string $cacert certificate file name (or dir holding certificates) + * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false + * @access public + */ + function setCaCertificate($cacert, $is_dir=false) + { + if ($is_dir) + { + $this->cacertdir = $cacert; + } + else + { + $this->cacert = $cacert; + } + } + + /** + * Set attributes for SSL communication: private SSL key + * NB: does not work in older php/curl installs + * Thanks to Daniel Convissor + * @param string $key The name of a file containing a private SSL key + * @param string $keypass The secret password needed to use the private SSL key + * @access public + */ + function setKey($key, $keypass) + { + $this->key = $key; + $this->keypass = $keypass; + } + + /** + * Set attributes for SSL communication: verify server certificate + * @param bool $i enable/disable verification of peer certificate + * @access public + */ + function setSSLVerifyPeer($i) + { + $this->verifypeer = $i; + } + + /** + * Set attributes for SSL communication: verify match of server cert w. hostname + * @param int $i + * @access public + */ + function setSSLVerifyHost($i) + { + $this->verifyhost = $i; + } + + /** + * Set proxy info + * @param string $proxyhost + * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyusername Leave blank if proxy has public access + * @param string $proxypassword Leave blank if proxy has public access + * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy + * @access public + */ + function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + { + $this->proxy = $proxyhost; + $this->proxyport = $proxyport; + $this->proxy_user = $proxyusername; + $this->proxy_pass = $proxypassword; + $this->proxy_authtype = $proxyauthtype; + } + + /** + * Enables/disables reception of compressed xmlrpc responses. + * Note that enabling reception of compressed responses merely adds some standard + * http headers to xmlrpc requests. It is up to the xmlrpc server to return + * compressed responses when receiving such requests. + * @param string $compmethod either 'gzip', 'deflate', 'any' or '' + * @access public + */ + function setAcceptedCompression($compmethod) + { + if ($compmethod == 'any') + $this->accepted_compression = array('gzip', 'deflate'); + else + if ($compmethod == false ) + $this->accepted_compression = array(); + else + $this->accepted_compression = array($compmethod); + } + + /** + * Enables/disables http compression of xmlrpc request. + * Take care when sending compressed requests: servers might not support them + * (and automatic fallback to uncompressed requests is not yet implemented) + * @param string $compmethod either 'gzip', 'deflate' or '' + * @access public + */ + function setRequestCompression($compmethod) + { + $this->request_compression = $compmethod; + } + + /** + * Adds a cookie to list of cookies that will be sent to server. + * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: + * do not do it unless you know what you are doing + * @param string $name + * @param string $value + * @param string $path + * @param string $domain + * @param int $port + * @access public + * + * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) + */ + function setCookie($name, $value='', $path='', $domain='', $port=null) + { + $this->cookies[$name]['value'] = urlencode($value); + if ($path || $domain || $port) + { + $this->cookies[$name]['path'] = $path; + $this->cookies[$name]['domain'] = $domain; + $this->cookies[$name]['port'] = $port; + $this->cookies[$name]['version'] = 1; + } + else + { + $this->cookies[$name]['version'] = 0; + } + } + + /** + * Directly set cURL options, for extra flexibility + * It allows eg. to bind client to a specific IP interface / address + * @param array $options + */ + function SetCurlOptions( $options ) + { + $this->extracurlopts = $options; + } + + /** + * Set user-agent string that will be used by this client instance + * in http headers sent to the server + */ + function SetUserAgent( $agentstring ) + { + $this->user_agent = $agentstring; + } + + /** + * Send an xmlrpc request + * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request + * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply + * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used + * @return xmlrpcresp + * @access public + */ + function& send($msg, $timeout=0, $method='') + { + // if user deos not specify http protocol, use native method of this client + // (i.e. method set during call to constructor) + if($method == '') + { + $method = $this->method; + } + + if(is_array($msg)) + { + // $msg is an array of xmlrpcmsg's + $r = $this->multicall($msg, $timeout, $method); + return $r; + } + elseif(is_string($msg)) + { + $n = new xmlrpcmsg(''); + $n->payload = $msg; + $msg = $n; + } + + // where msg is an xmlrpcmsg + $msg->debug=$this->debug; + + if($method == 'https') + { + $r =& $this->sendPayloadHTTPS( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->cert, + $this->certpass, + $this->cacert, + $this->cacertdir, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + $this->keepalive, + $this->key, + $this->keypass + ); + } + elseif($method == 'http11') + { + $r =& $this->sendPayloadCURL( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + null, + null, + null, + null, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype, + 'http', + $this->keepalive + ); + } + else + { + $r =& $this->sendPayloadHTTP10( + $msg, + $this->server, + $this->port, + $timeout, + $this->username, + $this->password, + $this->authtype, + $this->proxy, + $this->proxyport, + $this->proxy_user, + $this->proxy_pass, + $this->proxy_authtype + ); + } + + return $r; + } + + /** + * @access private + */ + function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, + $username='', $password='', $authtype=1, $proxyhost='', + $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) + { + $xmlrpc = Xmlrpc::instance(); + + if($port==0) + { + $port=80; + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + $payload = $msg->payload; + // Deflate request body and set appropriate request headers + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: gzip\r\n"; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = "Content-Encoding: deflate\r\n"; + } + } + } + else + { + $encoding_hdr = ''; + } + + // thanks to Grant Rauscher for this + $credentials=''; + if($username!='') + { + $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; + if ($authtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0'); + } + } + + $accepted_encoding = ''; + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; + } + + $proxy_credentials = ''; + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; + } + $connectserver = $proxyhost; + $connectport = $proxyport; + $uri = 'http://'.$server.':'.$port.$this->path; + if($proxyusername != '') + { + if ($proxyauthtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0'); + } + $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; + } + } + else + { + $connectserver = $server; + $connectport = $port; + $uri = $this->path; + } + + // Cookie generation, as per rfc2965 (version 1 cookies) or + // netscape's rules (version 0 cookies) + $cookieheader=''; + if (count($this->cookies)) + { + $version = ''; + foreach ($this->cookies as $name => $cookie) + { + if ($cookie['version']) + { + $version = ' $Version="' . $cookie['version'] . '";'; + $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; + if ($cookie['path']) + $cookieheader .= ' $Path="' . $cookie['path'] . '";'; + if ($cookie['domain']) + $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; + if ($cookie['port']) + $cookieheader .= ' $Port="' . $cookie['port'] . '";'; + } + else + { + $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; + } + } + $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n"; + } + + // omit port if 80 + $port = ($port == 80) ? '' : (':' . $port); + + $op= 'POST ' . $uri. " HTTP/1.0\r\n" . + 'User-Agent: ' . $this->user_agent . "\r\n" . + 'Host: '. $server . $port . "\r\n" . + $credentials . + $proxy_credentials . + $accepted_encoding . + $encoding_hdr . + 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . + $cookieheader . + 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . + strlen($payload) . "\r\n\r\n" . + $payload; + + if($this->debug > 1) + { + print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; + // let the client see this now in case http times out... + flush(); + } + + if($timeout>0) + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); + } + else + { + $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); + } + if($fp) + { + if($timeout>0 && function_exists('stream_set_timeout')) + { + stream_set_timeout($fp, $timeout); + } + } + else + { + $this->errstr='Connect error: '.$this->errstr; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + return $r; + } + + if(!fputs($fp, $op, strlen($op))) + { + fclose($fp); + $this->errstr='Write error'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); + return $r; + } + else + { + // reset errno and errstr on successful socket connection + $this->errstr = ''; + } + // G. Giunta 2005/10/24: close socket before parsing. + // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) + $ipd=''; + do + { + // shall we check for $data === FALSE? + // as per the manual, it signals an error + $ipd.=fread($fp, 32768); + } while(!feof($fp)); + fclose($fp); + $r =& $msg->parseResponse($ipd, false, $this->return_type); + return $r; + + } + + /** + * @access private + */ + function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, + $keepalive=false, $key='', $keypass='') + { + $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, + $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, + $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); + return $r; + } + + /** + * Contributed by Justin Miller + * Requires curl to be built into PHP + * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + * @access private + */ + function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', + $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', + $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', + $keepalive=false, $key='', $keypass='') + { + $xmlrpc = Xmlrpc::instance(); + + if(!function_exists('curl_init')) + { + $this->errstr='CURL unavailable on this install'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); + return $r; + } + if($method == 'https') + { + if(($info = curl_version()) && + ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) + { + $this->errstr='SSL unavailable on this install'; + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); + return $r; + } + } + + if($port == 0) + { + if($method == 'http') + { + $port = 80; + } + else + { + $port = 443; + } + } + + // Only create the payload if it was not created previously + if(empty($msg->payload)) + { + $msg->createPayload($this->request_charset_encoding); + } + + // Deflate request body and set appropriate request headers + $payload = $msg->payload; + if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) + { + if($this->request_compression == 'gzip') + { + $a = @gzencode($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: gzip'; + } + } + else + { + $a = @gzcompress($payload); + if($a) + { + $payload = $a; + $encoding_hdr = 'Content-Encoding: deflate'; + } + } + } + else + { + $encoding_hdr = ''; + } + + if($this->debug > 1) + { + print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; + // let the client see this now in case http times out... + flush(); + } + + if(!$keepalive || !$this->xmlrpc_curl_handle) + { + $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); + if($keepalive) + { + $this->xmlrpc_curl_handle = $curl; + } + } + else + { + $curl = $this->xmlrpc_curl_handle; + } + + // results into variable + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + + if($this->debug) + { + curl_setopt($curl, CURLOPT_VERBOSE, 1); + } + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + // required for XMLRPC: post the data + curl_setopt($curl, CURLOPT_POST, 1); + // the data + curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); + + // return the header too + curl_setopt($curl, CURLOPT_HEADER, 1); + + // NB: if we set an empty string, CURL will add http header indicating + // ALL methods it is supporting. This is possibly a better option than + // letting the user tell what curl can / cannot do... + if(is_array($this->accepted_compression) && count($this->accepted_compression)) + { + //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); + // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if (count($this->accepted_compression) == 1) + { + curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); + } + else + curl_setopt($curl, CURLOPT_ENCODING, ''); + } + // extra headers + $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + // if no keepalive is wanted, let the server know it in advance + if(!$keepalive) + { + $headers[] = 'Connection: close'; + } + // request compression header + if($encoding_hdr) + { + $headers[] = $encoding_hdr; + } + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + // timeout is borked + if($timeout) + { + curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); + } + + if($username && $password) + { + curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); + if (defined('CURLOPT_HTTPAUTH')) + { + curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); + } + else if ($authtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install'); + } + } + + if($method == 'https') + { + // set cert file + if($cert) + { + curl_setopt($curl, CURLOPT_SSLCERT, $cert); + } + // set cert password + if($certpass) + { + curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); + } + // whether to verify remote host's cert + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); + // set ca certificates file/dir + if($cacert) + { + curl_setopt($curl, CURLOPT_CAINFO, $cacert); + } + if($cacertdir) + { + curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); + } + // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($key) + { + curl_setopt($curl, CURLOPT_SSLKEY, $key); + } + // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) + if($keypass) + { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); + } + // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); + } + + // proxy info + if($proxyhost) + { + if($proxyport == 0) + { + $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 + } + curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport); + //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); + if($proxyusername) + { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); + if (defined('CURLOPT_PROXYAUTH')) + { + curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); + } + else if ($proxyauthtype != 1) + { + error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); + } + } + } + + // NB: should we build cookie http headers by hand rather than let CURL do it? + // the following code does not honour 'expires', 'path' and 'domain' cookie attributes + // set to client obj the the user... + if (count($this->cookies)) + { + $cookieheader = ''; + foreach ($this->cookies as $name => $cookie) + { + $cookieheader .= $name . '=' . $cookie['value'] . '; '; + } + curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); + } + + foreach ($this->extracurlopts as $opt => $val) + { + curl_setopt($curl, $opt, $val); + } + + $result = curl_exec($curl); + + if ($this->debug > 1) + { + print "
\n---CURL INFO---\n";
+            foreach(curl_getinfo($curl) as $name => $val)
+            {
+                if (is_array($val))
+                {
+                    $val = implode("\n", $val);
+                }
+                print $name . ': ' . htmlentities($val) . "\n";
+            }
+
+            print "---END---\n
"; + } + + if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? + { + $this->errstr='no response'; + $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); + curl_close($curl); + if($keepalive) + { + $this->xmlrpc_curl_handle = null; + } + } + else + { + if(!$keepalive) + { + curl_close($curl); + } + $resp =& $msg->parseResponse($result, true, $this->return_type); + // if we got back a 302, we can not reuse the curl handle for later calls + if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) + { + curl_close($curl); + $this->xmlrpc_curl_handle = null; + } + } + return $resp; + } + + /** + * Send an array of request messages and return an array of responses. + * Unless $this->no_multicall has been set to true, it will try first + * to use one single xmlrpc call to server method system.multicall, and + * revert to sending many successive calls in case of failure. + * This failure is also stored in $this->no_multicall for subsequent calls. + * Unfortunately, there is no server error code universally used to denote + * the fact that multicall is unsupported, so there is no way to reliably + * distinguish between that and a temporary failure. + * If you are sure that server supports multicall and do not want to + * fallback to using many single calls, set the fourth parameter to FALSE. + * + * NB: trying to shoehorn extra functionality into existing syntax has resulted + * in pretty much convoluted code... + * + * @param array $msgs an array of xmlrpcmsg objects + * @param integer $timeout connection timeout (in seconds) + * @param string $method the http protocol variant to be used + * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted + * @return array + * @access public + */ + function multicall($msgs, $timeout=0, $method='', $fallback=true) + { + $xmlrpc = Xmlrpc::instance(); + + if ($method == '') + { + $method = $this->method; + } + if(!$this->no_multicall) + { + $results = $this->_try_multicall($msgs, $timeout, $method); + if(is_array($results)) + { + // System.multicall succeeded + return $results; + } + else + { + // either system.multicall is unsupported by server, + // or call failed for some other reason. + if ($fallback) + { + // Don't try it next time... + $this->no_multicall = true; + } + else + { + if (is_a($results, 'xmlrpcresp')) + { + $result = $results; + } + else + { + $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); + } + } + } + } + else + { + // override fallback, in case careless user tries to do two + // opposite things at the same time + $fallback = true; + } + + $results = array(); + if ($fallback) + { + // system.multicall is (probably) unsupported by server: + // emulate multicall via multiple requests + foreach($msgs as $msg) + { + $results[] =& $this->send($msg, $timeout, $method); + } + } + else + { + // user does NOT want to fallback on many single calls: + // since we should always return an array of responses, + // return an array with the same error repeated n times + foreach($msgs as $msg) + { + $results[] = $result; + } + } + return $results; + } + + /** + * Attempt to boxcar $msgs via system.multicall. + * Returns either an array of xmlrpcreponses, an xmlrpc error response + * or false (when received response does not respect valid multicall syntax) + * @access private + */ + function _try_multicall($msgs, $timeout, $method) + { + // Construct multicall message + $calls = array(); + foreach($msgs as $msg) + { + $call['methodName'] = new xmlrpcval($msg->method(),'string'); + $numParams = $msg->getNumParams(); + $params = array(); + for($i = 0; $i < $numParams; $i++) + { + $params[$i] = $msg->getParam($i); + } + $call['params'] = new xmlrpcval($params, 'array'); + $calls[] = new xmlrpcval($call, 'struct'); + } + $multicall = new xmlrpcmsg('system.multicall'); + $multicall->addParam(new xmlrpcval($calls, 'array')); + + // Attempt RPC call + $result =& $this->send($multicall, $timeout, $method); + + if($result->faultCode() != 0) + { + // call to system.multicall failed + return $result; + } + + // Unpack responses. + $rets = $result->value(); + + if ($this->return_type == 'xml') + { + return $rets; + } + else if ($this->return_type == 'phpvals') + { + ///@todo test this code branch... + $rets = $result->value(); + if(!is_array($rets)) + { + return false; // bad return type from system.multicall + } + $numRets = count($rets); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets[$i]; + if (!is_array($val)) { + return false; + } + switch(count($val)) + { + case 1: + if(!isset($val[0])) + { + return false; // Bad value + } + // Normal return value + $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals'); + break; + case 2: + /// @todo remove usage of @: it is apparently quite slow + $code = @$val['faultCode']; + if(!is_int($code)) + { + return false; + } + $str = @$val['faultString']; + if(!is_string($str)) + { + return false; + } + $response[$i] = new xmlrpcresp(0, $code, $str); + break; + default: + return false; + } + } + return $response; + } + else // return type == 'xmlrpcvals' + { + $rets = $result->value(); + if($rets->kindOf() != 'array') + { + return false; // bad return type from system.multicall + } + $numRets = $rets->arraysize(); + if($numRets != count($msgs)) + { + return false; // wrong number of return values. + } + + $response = array(); + for($i = 0; $i < $numRets; $i++) + { + $val = $rets->arraymem($i); + switch($val->kindOf()) + { + case 'array': + if($val->arraysize() != 1) + { + return false; // Bad value + } + // Normal return value + $response[$i] = new xmlrpcresp($val->arraymem(0)); + break; + case 'struct': + $code = $val->structmem('faultCode'); + if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') + { + return false; + } + $str = $val->structmem('faultString'); + if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') + { + return false; + } + $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); + break; + default: + return false; + } + } + return $response; + } + } +} // end class xmlrpc_client +?> \ No newline at end of file diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php new file mode 100644 index 00000000..2bf2aaea --- /dev/null +++ b/lib/xmlrpcmsg.php @@ -0,0 +1,632 @@ +methodname=$meth; + if(is_array($pars) && count($pars)>0) + { + for($i=0; $iaddParam($pars[$i]); + } + } + } + + /** + * @access private + */ + function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n\n"; + } + else + { + return "\n\n"; + } + } + + /** + * @access private + */ + function xml_footer() + { + return ''; + } + + /** + * @access private + */ + function kindOf() + { + return 'msg'; + } + + /** + * @access private + */ + function createPayload($charset_encoding='') + { + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + $this->payload=$this->xml_header($charset_encoding); + $this->payload.='' . $this->methodname . "\n"; + $this->payload.="\n"; + for($i=0; $iparams); $i++) + { + $p=$this->params[$i]; + $this->payload.="\n" . $p->serialize($charset_encoding) . + "\n"; + } + $this->payload.="\n"; + $this->payload.=$this->xml_footer(); + } + + /** + * Gets/sets the xmlrpc method to be invoked + * @param string $meth the method to be set (leave empty not to set it) + * @return string the method that will be invoked + * @access public + */ + function method($meth='') + { + if($meth!='') + { + $this->methodname=$meth; + } + return $this->methodname; + } + + /** + * Returns xml representation of the message. XML prologue included + * @param string $charset_encoding + * @return string the xml representation of the message, xml prologue included + * @access public + */ + function serialize($charset_encoding='') + { + $this->createPayload($charset_encoding); + return $this->payload; + } + + /** + * Add a parameter to the list of parameters to be used upon method invocation + * @param xmlrpcval $par + * @return boolean false on failure + * @access public + */ + function addParam($par) + { + // add check: do not add to self params which are not xmlrpcvals + if(is_object($par) && is_a($par, 'xmlrpcval')) + { + $this->params[]=$par; + return true; + } + else + { + return false; + } + } + + /** + * Returns the nth parameter in the message. The index zero-based. + * @param integer $i the index of the parameter to fetch (zero based) + * @return xmlrpcval the i-th parameter + * @access public + */ + function getParam($i) { return $this->params[$i]; } + + /** + * Returns the number of parameters in the messge. + * @return integer the number of parameters currently set + * @access public + */ + function getNumParams() { return count($this->params); } + + /** + * Given an open file handle, read all data available and parse it as axmlrpc 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... + * @access public + * @param resource $fp stream pointer + * @return xmlrpcresp + * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? + */ + function &parseResponseFile($fp) + { + $ipd=''; + while($data=fread($fp, 32768)) + { + $ipd.=$data; + } + //fclose($fp); + $r =& $this->parseResponse($ipd); + return $r; + } + + /** + * Parses HTTP headers and separates them from data. + * @access private + */ + function &parseResponseHeaders(&$data, $headers_processed=false) + { + $xmlrpc = Xmlrpc::instance(); + // 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'); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + return $r; + } + } + + // 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); + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); + return $r; + } + + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); + + // 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) + { + $header_name = 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'][$header_name] + /// instead of replacing it for those... + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') + { + if ($header_name == '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($xmlrpc->_xh['headers'][$header_name])) + $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); + else + $xmlrpc->_xh['headers'][$header_name] = 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; + $xmlrpc->_xh['cookies'][$tag] = array(); + $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); + } + else + { + if ($tag != 'value') + { + $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; + } + } + } + } + } + else + { + $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); + } + } + elseif(isset($header_name)) + { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + if($this->debug && count($xmlrpc->_xh['headers'])) + { + print '
';
+                foreach($xmlrpc->_xh['headers'] as $header => $value)
+                {
+                    print htmlentities("HEADER: $header: $value\n");
+                }
+                foreach($xmlrpc->_xh['cookies'] as $header => $value)
+                {
+                    print htmlentities("COOKIE: $header={$value['value']}\n");
+                }
+                print "
\n"; + } + + // if CURL was used for the call, http headers have been processed, + // and dechunking + reinflating have been carried out + if(!$headers_processed) + { + // Decode chunked encoding sent by http 1.1 servers + if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked') + { + if(!$data = decode_chunked($data)) + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']); + return $r; + } + } + + // Decode gzip-compressed stuff + // code shamelessly inspired from nusoap library by Dietrich Ayala + if(isset($xmlrpc->_xh['headers']['content-encoding'])) + { + $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']); + if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate')) + { + if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + else + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); + return $r; + } + } + else + { + error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); + return $r; + } + } + } + } // end of 'if needed, de-chunk, re-inflate response' + + // real stupid hack to avoid PHP complaining about returning NULL by ref + $r = null; + $r =& $r; + return $r; + } + + /** + * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. + * @param string $data the xmlrpc response, eventually including http headers + * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding + * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @return xmlrpcresp + * @access public + */ + function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + { + $xmlrpc = Xmlrpc::instance(); + + if($this->debug) + { + //by maHo, replaced htmlspecialchars with htmlentities + print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; + } + + if($data == '') + { + error_log('XML-RPC: '.__METHOD__.': no response received from server.'); + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); + return $r; + } + + $xmlrpc->_xh=array(); + + $raw_data = $data; + // parse the HTTP headers of the response, if present, and separate them from data + if(substr($data, 0, 4) == 'HTTP') + { + $r =& $this->parseResponseHeaders($data, $headers_processed); + if ($r) + { + // failed processing of HTTP response headers + // save into response obj the full payload received, for debugging + $r->raw_data = $data; + return $r; + } + } + else + { + $xmlrpc->_xh['headers'] = array(); + $xmlrpc->_xh['cookies'] = array(); + } + + if($this->debug) + { + $start = strpos($data, '', $start); + $comments = substr($data, $start, $end-$start); + print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; + } + } + + // 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 originally in PEARified version of the lib + $pos = strrpos($data, ''); + if($pos !== false) + { + $data = substr($data, 0, $pos+17); + } + + // if user wants back raw xml, give it to him + if ($return_type == 'xml') + { + $r = new xmlrpcresp($data, 0, '', 'xml'); + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } + + // try to 'guestimate' the character encoding of the received response + $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); + + $xmlrpc->_xh['ac']=''; + //$xmlrpc->_xh['qt']=''; //unused... + $xmlrpc->_xh['stack'] = array(); + $xmlrpc->_xh['valuestack'] = array(); + $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc + $xmlrpc->_xh['isf_reason']=''; + $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' + + // if response charset encoding is not known / supported, try to use + // the default encoding and parse the xml anyway, but log a warning... + if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); + $resp_encoding = $xmlrpc->xmlrpc_defencoding; + } + $parser = xml_parser_create($resp_encoding); + 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_entitites() and setting xmlrpc_internalencoding + if (!in_array($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); + } + + if ($return_type == '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 + 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 xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); + xml_parser_free($parser); + if($this->debug) + { + print $errstr; + } + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } + xml_parser_free($parser); + // second error check: xml well formed but not xml-rpc compliant + if ($xmlrpc->_xh['isf'] > 1) + { + if ($this->debug) + { + /// @todo echo something for user? + } + + $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) + { + // something odd has happened + // and it's time to generate a client side error + // indicating something odd went on + $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], + $xmlrpc->xmlrpcstr['invalid_return']); + } + else + { + if ($this->debug) + { + print "
---PARSED---\n";
+                // somehow htmlentities chokes on var_export, and some full html string...
+                //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
+                print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
+                print "\n---END---
"; + } + + // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. + $v =& $xmlrpc->_xh['value']; + + if($xmlrpc->_xh['isf']) + { + /// @todo we should test here if server sent an int and a string, + /// and/or coerce them into such... + if ($return_type == 'xmlrpcvals') + { + $errno_v = $v->structmem('faultCode'); + $errstr_v = $v->structmem('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 xmlrpcresp(0, $errno, $errstr); + } + else + { + $r=new xmlrpcresp($v, 0, '', $return_type); + } + } + + $r->hdrs = $xmlrpc->_xh['headers']; + $r->_cookies = $xmlrpc->_xh['cookies']; + $r->raw_data = $raw_data; + return $r; + } +} +?> \ No newline at end of file diff --git a/lib/xmlrpcresp.php b/lib/xmlrpcresp.php new file mode 100644 index 00000000..f9d5286b --- /dev/null +++ b/lib/xmlrpcresp.php @@ -0,0 +1,170 @@ +errno = $fcode; + $this->errstr = $fstr; + //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. + } + else + { + // successful response + $this->val = $val; + if ($valtyp == '') + { + // user did not declare type of response value: try to guess it + if (is_object($this->val) && is_a($this->val, 'xmlrpcval')) + { + $this->valtyp = 'xmlrpcvals'; + } + else if (is_string($this->val)) + { + $this->valtyp = 'xml'; + + } + else + { + $this->valtyp = 'phpvals'; + } + } + else + { + // user declares type of resp value: believe him + $this->valtyp = $valtyp; + } + } + } + + /** + * Returns the error code of the response. + * @return integer the error code of this response (0 for not-error responses) + * @access 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) + * @access public + */ + function faultString() + { + return $this->errstr; + } + + /** + * Returns the value received by the server. + * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects + * @access 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 xmlrpc_client::setCookie) or not + * @return array array of cookies received from the server + * @access public + */ + function cookies() + { + return $this->_cookies; + } + + /** + * Returns xml representation of the response. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string the xml representation of the response + * @access public + */ + function serialize($charset_encoding='') + { + $xmlrpc = Xmlrpc::instance(); + + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + if ($xmlrpc->xmlrpc_null_apache_encoding) + { + $result = "xmlrpc_null_apache_encoding_ns."\">\n"; + } + else + { + $result = "\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 .= "\n" . +"\nfaultCode\n" . $this->errno . +"\n\n\nfaultString\n" . +xmlrpc_encode_entitites($this->errstr, $xmlrpc->xmlrpc_internalencoding, $charset_encoding) . "\n\n" . +"\n\n"; + } + else + { + if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) + { + if (is_string($this->val) && $this->valtyp == 'xml') + { + $result .= "\n\n" . + $this->val . + "\n"; + } + else + { + /// @todo try to build something serializable? + die('cannot serialize xmlrpcresp objects whose content is native php values'); + } + } + else + { + $result .= "\n\n" . + $this->val->serialize($charset_encoding) . + "\n"; + } + } + $result .= "\n"; + $this->payload = $result; + return $result; + } +} + +?> \ No newline at end of file diff --git a/lib/xmlrpcval.php b/lib/xmlrpcval.php new file mode 100644 index 00000000..df30eb48 --- /dev/null +++ b/lib/xmlrpcval.php @@ -0,0 +1,514 @@ +mytype=1; + $this->me['string']=$val; + break; + case 'i4': + 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)"); + } + /*if($type=='') + { + $type='string'; + } + if($GLOBALS['xmlrpcTypes'][$type]==1) + { + $this->addScalar($val,$type); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==2) + { + $this->addArray($val); + } + elseif($GLOBALS['xmlrpcTypes'][$type]==3) + { + $this->addStruct($val); + }*/ + } + } + + /** + * Add a single php value to an (unitialized) xmlrpcval + * @param mixed $val + * @param string $type + * @return int 1 or 0 on failure + */ + function addScalar($val, $type='string') + { + $xmlrpc = Xmlrpc::instance(); + + $typeof = null; + if(isset($xmlrpc->xmlrpcTypes[$type])) { + $typeof = $xmlrpc->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 and doubles, too, + // or just plain remove this check, implemented on booleans only... + if($type==$xmlrpc->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 xmlrpcval can have only one value'); + return 0; + case 3: + error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval'); + return 0; + case 2: + // we're adding a scalar value to an array here + //$ar=$this->me['array']; + //$ar[]=new xmlrpcval($val, $type); + //$this->me['array']=$ar; + // Faster (?) avoid all the costly array-copy-by-val done here... + $this->me['array'][]=new xmlrpcval($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 xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array of xmlrpcvals? + */ + function addArray($vals) + { + $xmlrpc = Xmlrpc::instance(); + if($this->mytype==0) + { + $this->mytype=$xmlrpc->xmlrpcTypes['array']; + $this->me['array']=$vals; + return 1; + } + elseif($this->mytype==2) + { + // we're adding to an array here + $this->me['array'] = array_merge($this->me['array'], $vals); + return 1; + } + else + { + error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + /** + * Add an array of named xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * @access public + * + * @todo add some checking for $vals to be an array? + */ + function addStruct($vals) + { + $xmlrpc = Xmlrpc::instance(); + + if($this->mytype==0) + { + $this->mytype=$xmlrpc->xmlrpcTypes['struct']; + $this->me['struct']=$vals; + return 1; + } + elseif($this->mytype==3) + { + // we're adding to a struct here + $this->me['struct'] = array_merge($this->me['struct'], $vals); + return 1; + } + else + { + error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']'); + return 0; + } + } + + // poor man's version of print_r ??? + // DEPRECATED! + function dump($ar) + { + foreach($ar as $key => $val) + { + echo "$key => $val
"; + if($key == 'array') + { + while(list($key2, $val2) = each($val)) + { + echo "-- $key2 => $val2
"; + } + } + } + } + + /** + * Returns a string containing "struct", "array" or "scalar" describing the base type of the value + * @return string + * @access public + */ + function kindOf() + { + switch($this->mytype) + { + case 3: + return 'struct'; + break; + case 2: + return 'array'; + break; + case 1: + return 'scalar'; + break; + default: + return 'undef'; + } + } + + /** + * @access private + */ + function serializedata($typ, $val, $charset_encoding='') + { + $xmlrpc = Xmlrpc::instance(); + $rs=''; + + if(!isset($xmlrpc->xmlrpcTypes[$typ])) { + return $rs; + } + + switch($xmlrpc->xmlrpcTypes[$typ]) + { + case 1: + switch($typ) + { + case $xmlrpc->xmlrpcBase64: + $rs.="<${typ}>" . base64_encode($val) . ""; + break; + case $xmlrpc->xmlrpcBoolean: + $rs.="<${typ}>" . ($val ? '1' : '0') . ""; + break; + case $xmlrpc->xmlrpcString: + // G. Giunta 2005/2/13: do NOT use htmlentities, since + // it will produce named html entities, which are invalid xml + $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; + break; + case $xmlrpc->xmlrpcInt: + case $xmlrpc->xmlrpcI4: + $rs.="<${typ}>".(int)$val.""; + break; + case $xmlrpc->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, '.', '')).""; + break; + case $xmlrpc->xmlrpcDateTime: + if (is_string($val)) + { + $rs.="<${typ}>${val}"; + } + else if(is_a($val, 'DateTime')) + { + $rs.="<${typ}>".$val->format('Ymd\TH:i:s').""; + } + else if(is_int($val)) + { + $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val).""; + } + else + { + // not really a good idea here: but what shall we output anyway? left for backward compat... + $rs.="<${typ}>${val}"; + } + break; + case $xmlrpc->xmlrpcNull: + if ($xmlrpc->xmlrpc_null_apache_encoding) + { + $rs.=""; + } + else + { + $rs.=""; + } + break; + default: + // no standard type value should arrive here, but provide a possibility + // for xmlrpcvals of unknown type... + $rs.="<${typ}>${val}"; + } + break; + case 3: + // struct + if ($this->_php_class) + { + $rs.='\n"; + } + else + { + $rs.="\n"; + } + foreach($val as $key2 => $val2) + { + $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; + //$rs.=$this->serializeval($val2); + $rs.=$val2->serialize($charset_encoding); + $rs.="\n"; + } + $rs.=''; + break; + case 2: + // array + $rs.="\n\n"; + for($i=0; $iserializeval($val[$i]); + $rs.=$val[$i]->serialize($charset_encoding); + } + $rs.="\n"; + break; + default: + break; + } + return $rs; + } + + /** + * Returns xml representation of the value. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string + * @access public + */ + function serialize($charset_encoding='') + { + // 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'))) + //{ + reset($this->me); + list($typ, $val) = each($this->me); + return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; + //} + } + + // DEPRECATED + 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 '' . $this->serializedata($typ, $val) . "\n"; + //} + } + + /** + * Checks whether a struct member with a given name is present. + * Works only on xmlrpcvals of type struct. + * @param string $m the name of the struct member to be looked up + * @return boolean + * @access public + */ + function structmemexists($m) + { + return array_key_exists($m, $this->me['struct']); + } + + /** + * Returns the value of a given struct member (an xmlrpcval object in itself). + * Will raise a php warning if struct member of given name does not exist + * @param string $m the name of the struct member to be looked up + * @return xmlrpcval + * @access public + */ + function structmem($m) + { + return $this->me['struct'][$m]; + } + + /** + * Reset internal pointer for xmlrpcvals of type struct. + * @access public + */ + function structreset() + { + reset($this->me['struct']); + } + + /** + * Return next member element for xmlrpcvals of type struct. + * @return xmlrpcval + * @access public + */ + function structeach() + { + return each($this->me['struct']); + } + + // 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? + 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; + } + + /** + * Returns the value of a scalar xmlrpcval + * @return mixed + * @access public + */ + function scalarval() + { + reset($this->me); + list(,$b)=each($this->me); + return $b; + } + + /** + * Returns the type of the xmlrpcval. + * For integers, 'int' is always returned in place of 'i4' + * @return string + * @access public + */ + function scalartyp() + { + $xmlrpc = Xmlrpc::instance(); + + reset($this->me); + list($a,)=each($this->me); + if($a==$xmlrpc->xmlrpcI4) + { + $a=$xmlrpc->xmlrpcInt; + } + return $a; + } + + /** + * Returns the m-th member of an xmlrpcval of struct type + * @param integer $m the index of the value to be retrieved (zero based) + * @return xmlrpcval + * @access public + */ + function arraymem($m) + { + return $this->me['array'][$m]; + } + + /** + * Returns the number of members in an xmlrpcval of array type + * @return integer + * @access public + */ + function arraysize() + { + return count($this->me['array']); + } + + /** + * Returns the number of members in an xmlrpcval of struct type + * @return integer + * @access public + */ + function structsize() + { + return count($this->me['struct']); + } +} + +?> \ No newline at end of file From 380a2b3ff7b7aa685fa4897f44d0c7ed61363889 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:28:03 +0300 Subject: [PATCH 009/228] Renamed Xmlrpc class to Phpxmlrpc --- lib/xmlrpc.php | 24 ++++++++++++------------ lib/xmlrpc_client.php | 8 ++++---- lib/xmlrpcmsg.php | 4 ++-- lib/xmlrpcresp.php | 2 +- lib/xmlrpcval.php | 10 +++++----- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index fb94bf32..66ee6ab2 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -39,7 +39,7 @@ require_once __DIR__ . "/xmlrpcmsg.php"; require_once __DIR__ . "/xmlrpcval.php"; -class Xmlrpc { +class Phpxmlrpc { public $xmlrpcI4 = "i4"; public $xmlrpcInt = "int"; @@ -225,11 +225,11 @@ private function __construct() { * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. */ public static function instance() { - if(Xmlrpc::$instance === null) { - Xmlrpc::$instance = new Xmlrpc(); + if(Phpxmlrpc::$instance === null) { + Phpxmlrpc::$instance = new Xmlrpc(); } - return Xmlrpc::$instance; + return Phpxmlrpc::$instance; } } @@ -250,7 +250,7 @@ public static function instance() { */ function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if ($src_encoding == '') { // lame, but we know no better... @@ -383,7 +383,7 @@ function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') /// xml parser handler function for opening element tags function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // if invalid xmlrpc already detected, skip all processing if ($xmlrpc->_xh['isf'] < 2) { @@ -538,7 +538,7 @@ function xmlrpc_se_any($parser, $name, $attrs) /// xml parser handler function for close element tags function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if ($xmlrpc->_xh['isf'] < 2) { @@ -755,7 +755,7 @@ function xmlrpc_ee_fast($parser, $name) /// xml parser handler function for character data function xmlrpc_cd($parser, $data) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // skip processing if xml fault already detected if ($xmlrpc->_xh['isf'] < 2) { @@ -784,7 +784,7 @@ function xmlrpc_cd($parser, $data) /// element start/end tag. In fact it only gets called on unknown entities... function xmlrpc_dh($parser, $data) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // skip processing if xml fault already detected if ($xmlrpc->_xh['isf'] < 2) { @@ -1007,7 +1007,7 @@ function php_xmlrpc_decode($xmlrpc_val, $options=array()) */ function php_xmlrpc_encode($php_val, $options=array()) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); $type = gettype($php_val); switch($type) { @@ -1125,7 +1125,7 @@ function php_xmlrpc_encode($php_val, $options=array()) */ function php_xmlrpc_decode_xml($xml_val, $options=array()) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); $xmlrpc->_xh = array(); $xmlrpc->_xh['ac'] = ''; @@ -1268,7 +1268,7 @@ function decode_chunked($buffer) */ function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // discussion: see http://www.yale.edu/pclt/encoding/ // 1 - test if encoding is specified in HTTP HEADERS diff --git a/lib/xmlrpc_client.php b/lib/xmlrpc_client.php index 66226a07..eac05d0a 100644 --- a/lib/xmlrpc_client.php +++ b/lib/xmlrpc_client.php @@ -72,7 +72,7 @@ class xmlrpc_client */ function xmlrpc_client($path, $server='', $port='', $method='') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // allow user to specify all params in $path if($server == '' and $port == '' and $method == '') @@ -436,7 +436,7 @@ function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if($port==0) { @@ -644,7 +644,7 @@ function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', $keepalive=false, $key='', $keypass='') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if(!function_exists('curl_init')) { @@ -938,7 +938,7 @@ function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', */ function multicall($msgs, $timeout=0, $method='', $fallback=true) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if ($method == '') { diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php index 2bf2aaea..7a6d32aa 100644 --- a/lib/xmlrpcmsg.php +++ b/lib/xmlrpcmsg.php @@ -170,7 +170,7 @@ function &parseResponseFile($fp) */ function &parseResponseHeaders(&$data, $headers_processed=false) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); // Support "web-proxy-tunelling" connections for https through proxies if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) { @@ -409,7 +409,7 @@ function &parseResponseHeaders(&$data, $headers_processed=false) */ function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if($this->debug) { diff --git a/lib/xmlrpcresp.php b/lib/xmlrpcresp.php index f9d5286b..df4c2657 100644 --- a/lib/xmlrpcresp.php +++ b/lib/xmlrpcresp.php @@ -114,7 +114,7 @@ function cookies() */ function serialize($charset_encoding='') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if ($charset_encoding != '') $this->content_type = 'text/xml; charset=' . $charset_encoding; diff --git a/lib/xmlrpcval.php b/lib/xmlrpcval.php index df30eb48..dd845ed9 100644 --- a/lib/xmlrpcval.php +++ b/lib/xmlrpcval.php @@ -72,7 +72,7 @@ function xmlrpcval($val=-1, $type='') */ function addScalar($val, $type='string') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); $typeof = null; if(isset($xmlrpc->xmlrpcTypes[$type])) { @@ -134,7 +134,7 @@ function addScalar($val, $type='string') */ function addArray($vals) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if($this->mytype==0) { $this->mytype=$xmlrpc->xmlrpcTypes['array']; @@ -164,7 +164,7 @@ function addArray($vals) */ function addStruct($vals) { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); if($this->mytype==0) { @@ -230,7 +230,7 @@ function kindOf() */ function serializedata($typ, $val, $charset_encoding='') { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); $rs=''; if(!isset($xmlrpc->xmlrpcTypes[$typ])) { @@ -468,7 +468,7 @@ function scalarval() */ function scalartyp() { - $xmlrpc = Xmlrpc::instance(); + $xmlrpc = Phpxmlrpc::instance(); reset($this->me); list($a,)=each($this->me); From 6342265bbc87e4221bf9bc5d09a13cb6f374ef25 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:50:35 +0300 Subject: [PATCH 010/228] Moved Phpxmlrpc class to own file --- lib/phpxmlrpc.php | 197 ++++++++++++++++++++++++++++++++++++++++++++++ lib/xmlrpc.php | 196 +-------------------------------------------- 2 files changed, 198 insertions(+), 195 deletions(-) create mode 100644 lib/phpxmlrpc.php diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php new file mode 100644 index 00000000..5edc2eec --- /dev/null +++ b/lib/phpxmlrpc.php @@ -0,0 +1,197 @@ + array('MEMBER', 'DATA', 'PARAM', 'FAULT'), + 'BOOLEAN' => array('VALUE'), + 'I4' => 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 + ); + + // tables used for transcoding different charsets into us-ascii xml + public $xml_iso88591_Entities = 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 reciving them...) + /* + $GLOBALS['xml_cp1252_Entities']=array(); + for ($i = 128; $i < 160; $i++) + { + $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i); + } + $GLOBALS['xml_cp1252_Entities']['out'] = array( + '€', '?', '‚', 'ƒ', + '„', '…', '†', '‡', + 'ˆ', '‰', 'Š', '‹', + 'Œ', '?', 'Ž', '?', + '?', '‘', '’', '“', + '”', '•', '–', '—', + '˜', '™', 'š', '›', + 'œ', '?', 'ž', 'Ÿ' + ); + */ + + 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 + ); + + 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 messages and + // by the client for received responses when received charset cannot be determined + // or is not supported + public $xmlrpc_defencoding = "UTF-8"; + + // 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 + public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? + + public $xmlrpcName = "XML-RPC for PHP"; + public $xmlrpcVersion = "3.0.0.beta"; + + // let user errors start at 800 + public $xmlrpcerruser = 800; + // let XML parse errors start at 100 + public $xmlrpcerrxml = 100; + + // set to TRUE to enable correct decoding of and values + public $xmlrpc_null_extension = false; + + // set to TRUE to enable encoding of php NULL values to instead of + public $xmlrpc_null_apache_encoding = false; + + public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; + + // used to store state during parsing + // quick explanation of components: + // ac - used to accumulate values + // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) + // isf_reason - used for storing xmlrpcresp fault string + // lv - used to indicate "looking for a value": implements + // the logic to allow values with no types to be strings + // params - used to store parameters in method calls + // method - used to store method name + // stack - array with genealogy of xml elements names: + // used to validate nesting of xmlrpc elements + public $_xh = null; + + private static $instance = null; + + private function __construct() { + $this->xmlrpcTypes = array( + $this->xmlrpcI4 => 1, + $this->xmlrpcInt => 1, + $this->xmlrpcBoolean => 1, + $this->xmlrpcDouble => 1, + $this->xmlrpcString => 1, + $this->xmlrpcDateTime => 1, + $this->xmlrpcBase64 => 1, + $this->xmlrpcArray => 2, + $this->xmlrpcStruct => 3, + $this->xmlrpcNull => 1 + ); + + 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};"; + } + } + + /** + * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. + */ + public static function instance() { + if(Phpxmlrpc::$instance === null) { + Phpxmlrpc::$instance = new Phpxmlrpc(); + } + + return Phpxmlrpc::$instance; + } +} + +?> \ No newline at end of file diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index 66ee6ab2..efc56228 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -34,206 +34,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. +require_once __DIR__ . "/phpxmlrpc.php"; require_once __DIR__ . "/xmlrpc_client.php"; require_once __DIR__ . "/xmlrpcresp.php"; require_once __DIR__ . "/xmlrpcmsg.php"; require_once __DIR__ . "/xmlrpcval.php"; -class Phpxmlrpc { - - public $xmlrpcI4 = "i4"; - public $xmlrpcInt = "int"; - public $xmlrpcBoolean = "boolean"; - public $xmlrpcDouble = "double"; - public $xmlrpcString = "string"; - public $xmlrpcDateTime = "dateTime.iso8601"; - public $xmlrpcBase64 = "base64"; - public $xmlrpcArray = "array"; - public $xmlrpcStruct = "struct"; - public $xmlrpcValue = "undefined"; - public $xmlrpcNull = "null"; - - public $xmlrpcTypes; - - public $xmlrpc_valid_parents = array( - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), - 'BOOLEAN' => array('VALUE'), - 'I4' => 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 - ); - - // tables used for transcoding different charsets into us-ascii xml - public $xml_iso88591_Entities = 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 reciving them...) - /* - $GLOBALS['xml_cp1252_Entities']=array(); - for ($i = 128; $i < 160; $i++) - { - $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i); - } - $GLOBALS['xml_cp1252_Entities']['out'] = array( - '€', '?', '‚', 'ƒ', - '„', '…', '†', '‡', - 'ˆ', '‰', 'Š', '‹', - 'Œ', '?', 'Ž', '?', - '?', '‘', '’', '“', - '”', '•', '–', '—', - '˜', '™', 'š', '›', - 'œ', '?', 'ž', 'Ÿ' - ); - */ - - 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 - ); - - 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 messages and - // by the client for received responses when received charset cannot be determined - // or is not supported - public $xmlrpc_defencoding = "UTF-8"; - - // 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 - public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? - - public $xmlrpcName = "XML-RPC for PHP"; - public $xmlrpcVersion = "3.0.0.beta"; - - // let user errors start at 800 - public $xmlrpcerruser = 800; - // let XML parse errors start at 100 - public $xmlrpcerrxml = 100; - - // set to TRUE to enable correct decoding of and values - public $xmlrpc_null_extension = false; - - // set to TRUE to enable encoding of php NULL values to instead of - public $xmlrpc_null_apache_encoding = false; - - public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; - - // used to store state during parsing - // quick explanation of components: - // ac - used to accumulate values - // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) - // isf_reason - used for storing xmlrpcresp fault string - // lv - used to indicate "looking for a value": implements - // the logic to allow values with no types to be strings - // params - used to store parameters in method calls - // method - used to store method name - // stack - array with genealogy of xml elements names: - // used to validate nesting of xmlrpc elements - public $_xh = null; - - private static $instance = null; - - private function __construct() { - $this->xmlrpcTypes = array( - $this->xmlrpcI4 => 1, - $this->xmlrpcInt => 1, - $this->xmlrpcBoolean => 1, - $this->xmlrpcDouble => 1, - $this->xmlrpcString => 1, - $this->xmlrpcDateTime => 1, - $this->xmlrpcBase64 => 1, - $this->xmlrpcArray => 2, - $this->xmlrpcStruct => 3, - $this->xmlrpcNull => 1 - ); - - 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};"; - } - } - - /** - * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. - */ - public static function instance() { - if(Phpxmlrpc::$instance === null) { - Phpxmlrpc::$instance = new Xmlrpc(); - } - - return Phpxmlrpc::$instance; - } -} - - /** * Convert a string to the correct XML representation in a target charset * To help correct communication of non-ascii chars inside strings, regardless From 3a6bf43c16f185b6082e08153fbf262716649450 Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 12:50:51 +0300 Subject: [PATCH 011/228] Modernized old classes --- lib/xmlrpc_client.php | 372 ++++++++++++++++++++---------------------- lib/xmlrpcmsg.php | 142 +++++++--------- lib/xmlrpcresp.php | 101 ++++++------ lib/xmlrpcval.php | 193 +++++++++------------- 4 files changed, 365 insertions(+), 443 deletions(-) diff --git a/lib/xmlrpc_client.php b/lib/xmlrpc_client.php index eac05d0a..7e58aeee 100644 --- a/lib/xmlrpc_client.php +++ b/lib/xmlrpc_client.php @@ -1,76 +1,77 @@ debug=$in; } /** - * Add some http BASIC AUTH credentials, used by the client to authenticate - * @param string $u username - * @param string $p password - * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) - * @access public - */ - function setCredentials($u, $p, $t=1) + * Add some http BASIC AUTH credentials, used by the client to authenticate + * @param string $u username + * @param string $p password + * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) + */ + public function setCredentials($u, $p, $t=1) { $this->username=$u; $this->password=$p; @@ -167,25 +166,23 @@ function setCredentials($u, $p, $t=1) } /** - * Add a client-side https certificate - * @param string $cert - * @param string $certpass - * @access public - */ - function setCertificate($cert, $certpass) + * Add a client-side https certificate + * @param string $cert + * @param string $certpass + */ + public function setCertificate($cert, $certpass) { $this->cert = $cert; $this->certpass = $certpass; } /** - * Add a CA certificate to verify server with (see man page about - * CURLOPT_CAINFO for more details) - * @param string $cacert certificate file name (or dir holding certificates) - * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false - * @access public - */ - function setCaCertificate($cacert, $is_dir=false) + * Add a CA certificate to verify server with (see man page about + * CURLOPT_CAINFO for more details) + * @param string $cacert certificate file name (or dir holding certificates) + * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false + */ + public function setCaCertificate($cacert, $is_dir=false) { if ($is_dir) { @@ -198,49 +195,45 @@ function setCaCertificate($cacert, $is_dir=false) } /** - * Set attributes for SSL communication: private SSL key - * NB: does not work in older php/curl installs - * Thanks to Daniel Convissor - * @param string $key The name of a file containing a private SSL key - * @param string $keypass The secret password needed to use the private SSL key - * @access public - */ - function setKey($key, $keypass) + * Set attributes for SSL communication: private SSL key + * NB: does not work in older php/curl installs + * Thanks to Daniel Convissor + * @param string $key The name of a file containing a private SSL key + * @param string $keypass The secret password needed to use the private SSL key + */ + public function setKey($key, $keypass) { $this->key = $key; $this->keypass = $keypass; } /** - * Set attributes for SSL communication: verify server certificate - * @param bool $i enable/disable verification of peer certificate - * @access public - */ - function setSSLVerifyPeer($i) + * Set attributes for SSL communication: verify server certificate + * @param bool $i enable/disable verification of peer certificate + */ + public function setSSLVerifyPeer($i) { $this->verifypeer = $i; } /** - * Set attributes for SSL communication: verify match of server cert w. hostname - * @param int $i - * @access public - */ - function setSSLVerifyHost($i) + * Set attributes for SSL communication: verify match of server cert w. hostname + * @param int $i + */ + public function setSSLVerifyHost($i) { $this->verifyhost = $i; } /** - * Set proxy info - * @param string $proxyhost - * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS - * @param string $proxyusername Leave blank if proxy has public access - * @param string $proxypassword Leave blank if proxy has public access - * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + * Set proxy info + * @param string $proxyhost + * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyusername Leave blank if proxy has public access + * @param string $proxypassword Leave blank if proxy has public access + * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy + */ + public function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) { $this->proxy = $proxyhost; $this->proxyport = $proxyport; @@ -250,14 +243,13 @@ function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = } /** - * Enables/disables reception of compressed xmlrpc responses. - * Note that enabling reception of compressed responses merely adds some standard - * http headers to xmlrpc requests. It is up to the xmlrpc server to return - * compressed responses when receiving such requests. - * @param string $compmethod either 'gzip', 'deflate', 'any' or '' - * @access public - */ - function setAcceptedCompression($compmethod) + * Enables/disables reception of compressed xmlrpc responses. + * Note that enabling reception of compressed responses merely adds some standard + * http headers to xmlrpc requests. It is up to the xmlrpc server to return + * compressed responses when receiving such requests. + * @param string $compmethod either 'gzip', 'deflate', 'any' or '' + */ + public function setAcceptedCompression($compmethod) { if ($compmethod == 'any') $this->accepted_compression = array('gzip', 'deflate'); @@ -269,31 +261,29 @@ function setAcceptedCompression($compmethod) } /** - * Enables/disables http compression of xmlrpc request. - * Take care when sending compressed requests: servers might not support them - * (and automatic fallback to uncompressed requests is not yet implemented) - * @param string $compmethod either 'gzip', 'deflate' or '' - * @access public - */ - function setRequestCompression($compmethod) + * Enables/disables http compression of xmlrpc request. + * Take care when sending compressed requests: servers might not support them + * (and automatic fallback to uncompressed requests is not yet implemented) + * @param string $compmethod either 'gzip', 'deflate' or '' + */ + public function setRequestCompression($compmethod) { $this->request_compression = $compmethod; } /** - * Adds a cookie to list of cookies that will be sent to server. - * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: - * do not do it unless you know what you are doing - * @param string $name - * @param string $value - * @param string $path - * @param string $domain - * @param int $port - * @access public - * - * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) - */ - function setCookie($name, $value='', $path='', $domain='', $port=null) + * Adds a cookie to list of cookies that will be sent to server. + * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: + * do not do it unless you know what you are doing + * @param string $name + * @param string $value + * @param string $path + * @param string $domain + * @param int $port + * + * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) + */ + public function setCookie($name, $value='', $path='', $domain='', $port=null) { $this->cookies[$name]['value'] = urlencode($value); if ($path || $domain || $port) @@ -310,33 +300,32 @@ function setCookie($name, $value='', $path='', $domain='', $port=null) } /** - * Directly set cURL options, for extra flexibility - * It allows eg. to bind client to a specific IP interface / address - * @param array $options - */ + * Directly set cURL options, for extra flexibility + * It allows eg. to bind client to a specific IP interface / address + * @param array $options + */ function SetCurlOptions( $options ) { $this->extracurlopts = $options; } /** - * Set user-agent string that will be used by this client instance - * in http headers sent to the server - */ + * Set user-agent string that will be used by this client instance + * in http headers sent to the server + */ function SetUserAgent( $agentstring ) { $this->user_agent = $agentstring; } /** - * Send an xmlrpc request - * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request - * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply - * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used - * @return xmlrpcresp - * @access public - */ - function& send($msg, $timeout=0, $method='') + * Send an xmlrpc request + * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request + * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply + * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used + * @return xmlrpcresp + */ + public function& send($msg, $timeout=0, $method='') { // if user deos not specify http protocol, use native method of this client // (i.e. method set during call to constructor) @@ -429,10 +418,7 @@ function& send($msg, $timeout=0, $method='') return $r; } - /** - * @access private - */ - function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, + private function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) { @@ -619,10 +605,7 @@ function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, } - /** - * @access private - */ - function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', + private function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $keepalive=false, $key='', $keypass='') @@ -634,12 +617,11 @@ function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', } /** - * Contributed by Justin Miller - * Requires curl to be built into PHP - * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! - * @access private - */ - function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', + * Contributed by Justin Miller + * Requires curl to be built into PHP + * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + */ + private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', $keepalive=false, $key='', $keypass='') @@ -915,28 +897,27 @@ function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', } /** - * Send an array of request messages and return an array of responses. - * Unless $this->no_multicall has been set to true, it will try first - * to use one single xmlrpc call to server method system.multicall, and - * revert to sending many successive calls in case of failure. - * This failure is also stored in $this->no_multicall for subsequent calls. - * Unfortunately, there is no server error code universally used to denote - * the fact that multicall is unsupported, so there is no way to reliably - * distinguish between that and a temporary failure. - * If you are sure that server supports multicall and do not want to - * fallback to using many single calls, set the fourth parameter to FALSE. - * - * NB: trying to shoehorn extra functionality into existing syntax has resulted - * in pretty much convoluted code... - * - * @param array $msgs an array of xmlrpcmsg objects - * @param integer $timeout connection timeout (in seconds) - * @param string $method the http protocol variant to be used - * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted - * @return array - * @access public - */ - function multicall($msgs, $timeout=0, $method='', $fallback=true) + * Send an array of request messages and return an array of responses. + * Unless $this->no_multicall has been set to true, it will try first + * to use one single xmlrpc call to server method system.multicall, and + * revert to sending many successive calls in case of failure. + * This failure is also stored in $this->no_multicall for subsequent calls. + * Unfortunately, there is no server error code universally used to denote + * the fact that multicall is unsupported, so there is no way to reliably + * distinguish between that and a temporary failure. + * If you are sure that server supports multicall and do not want to + * fallback to using many single calls, set the fourth parameter to FALSE. + * + * NB: trying to shoehorn extra functionality into existing syntax has resulted + * in pretty much convoluted code... + * + * @param array $msgs an array of xmlrpcmsg objects + * @param integer $timeout connection timeout (in seconds) + * @param string $method the http protocol variant to be used + * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted + * @return array + */ + public function multicall($msgs, $timeout=0, $method='', $fallback=true) { $xmlrpc = Phpxmlrpc::instance(); @@ -1005,12 +986,11 @@ function multicall($msgs, $timeout=0, $method='', $fallback=true) } /** - * Attempt to boxcar $msgs via system.multicall. - * Returns either an array of xmlrpcreponses, an xmlrpc error response - * or false (when received response does not respect valid multicall syntax) - * @access private - */ - function _try_multicall($msgs, $timeout, $method) + * Attempt to boxcar $msgs via system.multicall. + * Returns either an array of xmlrpcreponses, an xmlrpc error response + * or false (when received response does not respect valid multicall syntax) + */ + private function _try_multicall($msgs, $timeout, $method) { // Construct multicall message $calls = array(); diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php index 7a6d32aa..428acc58 100644 --- a/lib/xmlrpcmsg.php +++ b/lib/xmlrpcmsg.php @@ -1,18 +1,18 @@ methodname=$meth; if(is_array($pars) && count($pars)>0) @@ -24,10 +24,7 @@ function xmlrpcmsg($meth, $pars=0) } } - /** - * @access private - */ - function xml_header($charset_encoding='') + private function xml_header($charset_encoding='') { if ($charset_encoding != '') { @@ -39,26 +36,17 @@ function xml_header($charset_encoding='') } } - /** - * @access private - */ - function xml_footer() + private function xml_footer() { return '
'; } - /** - * @access private - */ - function kindOf() + private function kindOf() { return 'msg'; } - /** - * @access private - */ - function createPayload($charset_encoding='') + private function createPayload($charset_encoding='') { if ($charset_encoding != '') $this->content_type = 'text/xml; charset=' . $charset_encoding; @@ -78,12 +66,11 @@ function createPayload($charset_encoding='') } /** - * Gets/sets the xmlrpc method to be invoked - * @param string $meth the method to be set (leave empty not to set it) - * @return string the method that will be invoked - * @access public - */ - function method($meth='') + * Gets/sets the xmlrpc method to be invoked + * @param string $meth the method to be set (leave empty not to set it) + * @return string the method that will be invoked + */ + public function method($meth='') { if($meth!='') { @@ -93,24 +80,22 @@ function method($meth='') } /** - * Returns xml representation of the message. XML prologue included - * @param string $charset_encoding - * @return string the xml representation of the message, xml prologue included - * @access public - */ - function serialize($charset_encoding='') + * Returns xml representation of the message. XML prologue included + * @param string $charset_encoding + * @return string the xml representation of the message, xml prologue included + */ + public function serialize($charset_encoding='') { $this->createPayload($charset_encoding); return $this->payload; } /** - * Add a parameter to the list of parameters to be used upon method invocation - * @param xmlrpcval $par - * @return boolean false on failure - * @access public - */ - function addParam($par) + * Add a parameter to the list of parameters to be used upon method invocation + * @param xmlrpcval $par + * @return boolean false on failure + */ + public function addParam($par) { // add check: do not add to self params which are not xmlrpcvals if(is_object($par) && is_a($par, 'xmlrpcval')) @@ -125,34 +110,31 @@ function addParam($par) } /** - * Returns the nth parameter in the message. The index zero-based. - * @param integer $i the index of the parameter to fetch (zero based) - * @return xmlrpcval the i-th parameter - * @access public - */ - function getParam($i) { return $this->params[$i]; } + * Returns the nth parameter in the message. The index zero-based. + * @param integer $i the index of the parameter to fetch (zero based) + * @return xmlrpcval the i-th parameter + */ + public function getParam($i) { return $this->params[$i]; } /** - * Returns the number of parameters in the messge. - * @return integer the number of parameters currently set - * @access public - */ - function getNumParams() { return count($this->params); } + * Returns the number of parameters in the messge. + * @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 axmlrpc 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... - * @access public - * @param resource $fp stream pointer - * @return xmlrpcresp - * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? - */ - function &parseResponseFile($fp) + * Given an open file handle, read all data available and parse it as axmlrpc 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 xmlrpcresp + * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? + */ + public function &parseResponseFile($fp) { $ipd=''; while($data=fread($fp, 32768)) @@ -165,10 +147,9 @@ function &parseResponseFile($fp) } /** - * Parses HTTP headers and separates them from data. - * @access private - */ - function &parseResponseHeaders(&$data, $headers_processed=false) + * Parses HTTP headers and separates them from data. + */ + private function &parseResponseHeaders(&$data, $headers_processed=false) { $xmlrpc = Phpxmlrpc::instance(); // Support "web-proxy-tunelling" connections for https through proxies @@ -400,14 +381,13 @@ function &parseResponseHeaders(&$data, $headers_processed=false) } /** - * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. - * @param string $data the xmlrpc response, eventually including http headers - * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding - * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' - * @return xmlrpcresp - * @access public - */ - function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. + * @param string $data the xmlrpc response, eventually including http headers + * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding + * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @return xmlrpcresp + */ + public function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') { $xmlrpc = Phpxmlrpc::instance(); diff --git a/lib/xmlrpcresp.php b/lib/xmlrpcresp.php index df4c2657..98981739 100644 --- a/lib/xmlrpcresp.php +++ b/lib/xmlrpcresp.php @@ -1,28 +1,28 @@ errno; } /** - * Returns the error code of the response. - * @return string the error string of this response ('' for not-error responses) - * @access public - */ - function faultString() + * 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. - * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects - * @access public - */ - function value() + * Returns the value received by the server. + * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects + */ + 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 xmlrpc_client::setCookie) or not - * @return array array of cookies received from the server - * @access public - */ - function cookies() + * 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 xmlrpc_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 $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string the xml representation of the response - * @access public - */ - function serialize($charset_encoding='') + * Returns xml representation of the response. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string the xml representation of the response + */ + public function serialize($charset_encoding='') { $xmlrpc = Phpxmlrpc::instance(); diff --git a/lib/xmlrpcval.php b/lib/xmlrpcval.php index dd845ed9..59ef28b7 100644 --- a/lib/xmlrpcval.php +++ b/lib/xmlrpcval.php @@ -1,17 +1,17 @@ mytype==0) @@ -155,14 +154,13 @@ function addArray($vals) } /** - * Add an array of named xmlrpcval objects to an xmlrpcval - * @param array $vals - * @return int 1 or 0 on failure - * @access public - * - * @todo add some checking for $vals to be an array? - */ - function addStruct($vals) + * Add an array of named xmlrpcval objects to an xmlrpcval + * @param array $vals + * @return int 1 or 0 on failure + * + * @todo add some checking for $vals to be an array? + */ + public function addStruct($vals) { $xmlrpc = Phpxmlrpc::instance(); @@ -185,29 +183,11 @@ function addStruct($vals) } } - // poor man's version of print_r ??? - // DEPRECATED! - function dump($ar) - { - foreach($ar as $key => $val) - { - echo "$key => $val
"; - if($key == 'array') - { - while(list($key2, $val2) = each($val)) - { - echo "-- $key2 => $val2
"; - } - } - } - } - /** - * Returns a string containing "struct", "array" or "scalar" describing the base type of the value - * @return string - * @access public - */ - function kindOf() + * Returns a string containing "struct", "array" or "scalar" describing the base type of the value + * @return string + */ + public function kindOf() { switch($this->mytype) { @@ -225,10 +205,7 @@ function kindOf() } } - /** - * @access private - */ - function serializedata($typ, $val, $charset_encoding='') + private function serializedata($typ, $val, $charset_encoding='') { $xmlrpc = Phpxmlrpc::instance(); $rs=''; @@ -336,12 +313,11 @@ function serializedata($typ, $val, $charset_encoding='') } /** - * Returns xml representation of the value. XML prologue not included - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed - * @return string - * @access public - */ - function serialize($charset_encoding='') + * Returns xml representation of the value. XML prologue not included + * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @return string + */ + public function serialize($charset_encoding='') { // 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'))) @@ -366,44 +342,40 @@ function serializeval($o) } /** - * Checks whether a struct member with a given name is present. - * Works only on xmlrpcvals of type struct. - * @param string $m the name of the struct member to be looked up - * @return boolean - * @access public - */ - function structmemexists($m) + * Checks whether a struct member with a given name is present. + * Works only on xmlrpcvals of type struct. + * @param string $m the name of the struct member to be looked up + * @return boolean + */ + public function structmemexists($m) { return array_key_exists($m, $this->me['struct']); } /** - * Returns the value of a given struct member (an xmlrpcval object in itself). - * Will raise a php warning if struct member of given name does not exist - * @param string $m the name of the struct member to be looked up - * @return xmlrpcval - * @access public - */ - function structmem($m) + * Returns the value of a given struct member (an xmlrpcval object in itself). + * Will raise a php warning if struct member of given name does not exist + * @param string $m the name of the struct member to be looked up + * @return xmlrpcval + */ + public function structmem($m) { return $this->me['struct'][$m]; } /** - * Reset internal pointer for xmlrpcvals of type struct. - * @access public - */ - function structreset() + * Reset internal pointer for xmlrpcvals of type struct. + */ + public function structreset() { reset($this->me['struct']); } /** - * Return next member element for xmlrpcvals of type struct. - * @return xmlrpcval - * @access public - */ - function structeach() + * Return next member element for xmlrpcvals of type struct. + * @return xmlrpcval + */ + public function structeach() { return each($this->me['struct']); } @@ -449,11 +421,10 @@ function getval() } /** - * Returns the value of a scalar xmlrpcval - * @return mixed - * @access public - */ - function scalarval() + * Returns the value of a scalar xmlrpcval + * @return mixed + */ + public function scalarval() { reset($this->me); list(,$b)=each($this->me); @@ -461,12 +432,11 @@ function scalarval() } /** - * Returns the type of the xmlrpcval. - * For integers, 'int' is always returned in place of 'i4' - * @return string - * @access public - */ - function scalartyp() + * Returns the type of the xmlrpcval. + * For integers, 'int' is always returned in place of 'i4' + * @return string + */ + public function scalartyp() { $xmlrpc = Phpxmlrpc::instance(); @@ -480,32 +450,29 @@ function scalartyp() } /** - * Returns the m-th member of an xmlrpcval of struct type - * @param integer $m the index of the value to be retrieved (zero based) - * @return xmlrpcval - * @access public - */ - function arraymem($m) + * Returns the m-th member of an xmlrpcval of struct type + * @param integer $m the index of the value to be retrieved (zero based) + * @return xmlrpcval + */ + public function arraymem($m) { return $this->me['array'][$m]; } /** - * Returns the number of members in an xmlrpcval of array type - * @return integer - * @access public - */ - function arraysize() + * Returns the number of members in an xmlrpcval of array type + * @return integer + */ + public function arraysize() { return count($this->me['array']); } /** - * Returns the number of members in an xmlrpcval of struct type - * @return integer - * @access public - */ - function structsize() + * Returns the number of members in an xmlrpcval of struct type + * @return integer + */ + public function structsize() { return count($this->me['struct']); } From 2ac04ba958c24613d634c79cfd06835a4210975b Mon Sep 17 00:00:00 2001 From: Samu Voutilainen Date: Fri, 23 May 2014 13:11:41 +0300 Subject: [PATCH 012/228] xmlrpcmsg: Convert createPayload() from private to public Apparently this was used elsewhere, even when it was marked as private. Adjusting to that now... --- lib/xmlrpcmsg.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php index 428acc58..05e627d7 100644 --- a/lib/xmlrpcmsg.php +++ b/lib/xmlrpcmsg.php @@ -46,7 +46,7 @@ private function kindOf() return 'msg'; } - private function createPayload($charset_encoding='') + public function createPayload($charset_encoding='') { if ($charset_encoding != '') $this->content_type = 'text/xml; charset=' . $charset_encoding; From 703405e3618c751b3e9e69321e878ea9573449a4 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 26 May 2014 22:31:28 +0100 Subject: [PATCH 013/228] More tabs/to/spaces conversion, plus remove closing php tags as they are not considered good style anymore --- Makefile | 14 +- debugger/controller.php | 24 +- demo/client/client.php | 72 +- demo/client/comment.php | 182 ++-- demo/client/introspect.php | 109 +-- demo/client/mail.php | 58 +- demo/client/simple_call.php | 94 +- demo/client/which.php | 33 +- demo/client/wrap.php | 84 +- demo/client/zopetest.php | 38 +- demo/server/discuss.php | 217 +++-- demo/server/proxy.php | 139 ++- demo/server/server.php | 1626 +++++++++++++++++------------------ demo/vardemo.php | 142 +-- doc/convert.php | 1 - doc/highlight.php | 22 +- doc/xmlrpc_php.xml | 24 +- lib/phpxmlrpc.php | 2 - lib/xmlrpc.php | 8 +- lib/xmlrpc_client.php | 4 +- lib/xmlrpc_wrappers.php | 3 +- lib/xmlrpcmsg.php | 1 - lib/xmlrpcresp.php | 2 - lib/xmlrpcs.php | 9 +- lib/xmlrpcval.php | 2 - test/benchmark.php | 519 ++++++----- test/parse_args.php | 231 +++-- test/testsuite.php | 1 - 28 files changed, 1754 insertions(+), 1907 deletions(-) diff --git a/Makefile b/Makefile index b5760a26..bcb4a906 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Makefile for phpxmlrpc library -### USER EDITABLE VARS ### +### USER EDITABLE VARS - can be passed as command-line options ### # path to PHP executable, preferably CLI version PHP=/usr/local/bin/php @@ -14,13 +14,15 @@ MKDIR=mkdir #find too FIND=find +DOS2UNIX=dos2unix #### DO NOT TOUCH FROM HERE ONWARDS ### # recover version number from code # thanks to Firman Pribadi for unix command line help # on unix shells lasts char should be \\2/g ) -export VERSION=$(shell egrep "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) +###export VERSION=$(shell grep -E "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) +export VERSION=3.0.0 LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc @@ -79,10 +81,10 @@ test: ### the following targets are to be used for library development ### -# make tag target: tag existing working copy as release in cvs. -# todo: convert dots in underscore in $VERSION +# make tag target: tag existing working copy as release in git. tag: - cvs -q tag -p release_${VERSION} + git tag v${VERSION} + git push origin --tags dist: xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz @@ -108,7 +110,7 @@ xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz: ${LIBFILES} ${DEBUGGERFILES} ${I cp ${INFOFILES} xmlrpc-${VERSION} cd doc && $(MAKE) dist # on unix shells last char should be \; - ${FIND} xmlrpc-${VERSION} -type f ! -name "*.fttb" ! -name "*.pdf" ! -name "*.gif" -exec dos2unix {} ; + ${FIND} xmlrpc-${VERSION} -type f ! -name "*.fttb" ! -name "*.pdf" ! -name "*.gif" -exec ${DOS2UNIX} {} ; -rm xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz tar -cvf xmlrpc-${VERSION}.tar xmlrpc-${VERSION} gzip xmlrpc-${VERSION}.tar diff --git a/debugger/controller.php b/debugger/controller.php index 98550c9d..e903be44 100644 --- a/debugger/controller.php +++ b/debugger/controller.php @@ -172,20 +172,20 @@ function displaydialogeditorbtn(show) { if (show && ((typeof base64_decode) == 'function')) { - document.getElementById('methodpayloadbtn').innerHTML = '[Edit]'; - } - else + document.getElementById('methodpayloadbtn').innerHTML = '[Edit]'; + } + else { - document.getElementById('methodpayloadbtn').innerHTML = ''; - } + document.getElementById('methodpayloadbtn').innerHTML = ''; + } } function activateeditor() { - var url = 'visualeditor.php?params='; - 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'); + var url = 'visualeditor.php?params='; + 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 @@ -193,9 +193,9 @@ function buildparams(base64data) { if (typeof base64_decode == 'function') { - if (base64data == '0') // workaround for bug in base64_encode... - document.getElementById('methodpayload').value = ''; - else + if (base64data == '0') // workaround for bug in base64_encode... + document.getElementById('methodpayload').value = ''; + else document.getElementById('methodpayload').value = base64_decode(base64data); } } diff --git a/demo/client/client.php b/demo/client/client.php index b5ec0017..c457a41a 100644 --- a/demo/client/client.php +++ b/demo/client/client.php @@ -5,45 +5,45 @@

Send a U.S. state number to the server and get back the state name

The code demonstrates usage of the php_xmlrpc_encode function

Sending the following request:\n\n" . htmlentities($f->serialize()) . "\n\nDebug info of server data follows...\n\n"; - $c=new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); - $c->setDebug(1); - $r=&$c->send($f); - if(!$r->faultCode()) - { - $v=$r->value(); - print "

State number " . $stateno . " is " - . htmlspecialchars($v->scalarval()) . "
"; - // print "
I got this value back
" .
-			//  htmlentities($r->serialize()). "

\n"; - } - else - { - print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) - . " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; - } - } - else - { - $stateno = ""; - } + if(isset($HTTP_POST_VARS["stateno"]) && $HTTP_POST_VARS["stateno"]!="") + { + $stateno=(integer)$HTTP_POST_VARS["stateno"]; + $f=new xmlrpcmsg('examples.getStateName', + array(php_xmlrpc_encode($stateno)) + ); + print "
Sending the following request:\n\n" . htmlentities($f->serialize()) . "\n\nDebug info of server data follows...\n\n";
+        $c=new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80);
+        $c->setDebug(1);
+        $r=&$c->send($f);
+        if(!$r->faultCode())
+        {
+            $v=$r->value();
+            print "

State number " . $stateno . " is " + . htmlspecialchars($v->scalarval()) . "
"; + // print "
I got this value back
" .
+            //  htmlentities($r->serialize()). "

\n"; + } + else + { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) + . " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; + } + } + else + { + $stateno = ""; + } - print "
+ print "

Enter a state number to query its name

"; diff --git a/demo/client/comment.php b/demo/client/comment.php index 7133cf95..914c92ca 100644 --- a/demo/client/comment.php +++ b/demo/client/comment.php @@ -6,41 +6,41 @@ // define some utility functions function bomb() { print ""; exit(); } function dispatch($client, $method, $args) { - $msg=new xmlrpcmsg($method, $args); - $resp=$client->send($msg); - if (!$resp) { print "

IO error: ".$client->errstr."

"; bomb(); } - if ($resp->faultCode()) { - print "

There was an error: " . $resp->faultCode() . " " . - $resp->faultString() . "

"; - bomb(); - } - return php_xmlrpc_decode($resp->value()); + $msg=new xmlrpcmsg($method, $args); + $resp=$client->send($msg); + if (!$resp) { print "

IO error: ".$client->errstr."

"; bomb(); } + if ($resp->faultCode()) { + print "

There was an error: " . $resp->faultCode() . " " . + $resp->faultString() . "

"; + bomb(); + } + return php_xmlrpc_decode($resp->value()); } // create client for discussion server $dclient=new xmlrpc_client("${mydir}/discuss.php", - "xmlrpc.usefulinc.com", 80); + "xmlrpc.usefulinc.com", 80); // check if we're posting a comment, and send it if so @$storyid=$_POST["storyid"]; if ($storyid) { - // print "Returning to " . $HTTP_POST_VARS["returnto"]; + // print "Returning to " . $HTTP_POST_VARS["returnto"]; - $res=dispatch($dclient, "discuss.addComment", - array(new xmlrpcval($storyid), - new xmlrpcval(stripslashes - (@$_POST["name"])), - new xmlrpcval(stripslashes - (@$_POST["commenttext"])))); + $res=dispatch($dclient, "discuss.addComment", + array(new xmlrpcval($storyid), + new xmlrpcval(stripslashes + (@$_POST["name"])), + new xmlrpcval(stripslashes + (@$_POST["commenttext"])))); - // send the browser back to the originating page - Header("Location: ${mydir}/comment.php?catid=" . - $_POST["catid"] . "&chanid=" . - $_POST["chanid"] . "&oc=" . - $_POST["catid"]); - exit(0); + // send the browser back to the originating page + Header("Location: ${mydir}/comment.php?catid=" . + $_POST["catid"] . "&chanid=" . + $_POST["chanid"] . "&oc=" . + $_POST["catid"]); + exit(0); } // now we've got here, we're exploring the story store @@ -52,17 +52,17 @@ function dispatch($client, $method, $args) {

Make a comment on the story

@@ -80,54 +80,54 @@ function dispatch($client, $method, $args) {
new xmlrpcval($chanid, "int"), - "ids" => new xmlrpcval(1, "int"), - "descriptions" => new xmlrpcval(200, "int"), - "num_items" => new xmlrpcval(5, "int"), - "dates" => new xmlrpcval(0, "int") - ), "struct"))); - } + $categories=dispatch($client, "meerkat.getCategories", array()); + if ($catid) + $sources = dispatch($client, "meerkat.getChannelsByCategory", + array(new xmlrpcval($catid, "int"))); + if ($chanid) { + $stories = dispatch($client, "meerkat.getItems", + array(new xmlrpcval( + array( + "channel" => new xmlrpcval($chanid, "int"), + "ids" => new xmlrpcval(1, "int"), + "descriptions" => new xmlrpcval(200, "int"), + "num_items" => new xmlrpcval(5, "int"), + "dates" => new xmlrpcval(0, "int") + ), "struct"))); + } ?>

Subject area:

News source:

@@ -135,51 +135,51 @@ function dispatch($client, $method, $args) {

Stories available

"; - print ""; - print "\n"; - // now look for existing comments - $res=dispatch($dclient, "discuss.getComments", - array(new xmlrpcval($v['id']))); - if (sizeof($res)>0) { - print "\n"; - } - print "\n"; - } + while(list($k,$v) = each($stories)) { + print ""; + print ""; + print "\n"; + // now look for existing comments + $res=dispatch($dclient, "discuss.getComments", + array(new xmlrpcval($v['id']))); + if (sizeof($res)>0) { + print "\n"; + } + print "\n"; + } ?>
" . $v['title'] . "
"; - print $v['description'] . "
"; - print "Read full story "; - print "Comment on this story"; - print ""; - print "

" . - "Comments on this story:

"; - for($i=0; $iFrom: " . htmlentities($s['name']) . "
"; - print "Comment: " . htmlentities($s['comment']) . "

"; - } - print "

" . $v['title'] . "
"; + print $v['description'] . "
"; + print "Read full story "; + print "Comment on this story"; + print ""; + print "

" . + "Comments on this story:

"; + for($i=0; $iFrom: " . htmlentities($s['name']) . "
"; + print "Comment: " . htmlentities($s['comment']) . "

"; + } + print "


Meerkat powered, yeah! + src="http://meerkat.oreillynet.com/icons/meerkat-powered.jpg" + height="31" width="88" alt="Meerkat powered, yeah!" + border="0" hspace="8" /> $Id$

diff --git a/demo/client/introspect.php b/demo/client/introspect.php index 818e04c6..0633bc7c 100644 --- a/demo/client/introspect.php +++ b/demo/client/introspect.php @@ -1,108 +1 @@ - -xmlrpc - -

Introspect demo

-

Query server for available methods and their description

-

The code demonstrates usage of multicall and introspection methods

-faultCode() - . " Reason: '" .$r->faultString()."'
"; - } - - // 'new style' client constuctor - $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); - print "

methods available at http://" . $c->server . $c->path . "

\n"; - - $m = new xmlrpcmsg('system.listMethods'); - $r =& $c->send($m); - if($r->faultCode()) - { - display_error($r); - } - else - { - $v=$r->value(); - for($i=0; $i<$v->arraysize(); $i++) - { - $mname=$v->arraymem($i); - print "

" . $mname->scalarval() . "

\n"; - - // build messages first, add params later - $m1 = new xmlrpcmsg('system.methodHelp'); - $m2 = new xmlrpcmsg('system.methodSignature'); - $val = new xmlrpcval($mname->scalarval(), "string"); - $m1->addParam($val); - $m2->addParam($val); - - // send multiple messages in one pass. - // If server does not support multicall, client will fall back to 2 separate calls - $ms = array($m1, $m2); - $rs =& $c->send($ms); - - if($rs[0]->faultCode()) - { - display_error($rs[0]); - } - else - { - $val=$rs[0]->value(); - $txt=$val->scalarval(); - if($txt != "") - { - print "

Documentation

${txt}

\n"; - } - else - { - print "

No documentation available.

\n"; - } - } - - if($rs[1]->faultCode()) - { - display_error($rs[1]); - } - else - { - print "

Signature

\n"; - $val = $rs[1]->value(); - if($val->kindOf()=="array") - { - for($j=0; $j<$val->arraysize(); $j++) - { - $x = $val->arraymem($j); - $ret = $x->arraymem(0); - print "" . $ret->scalarval() . " " - . $mname->scalarval() . "("; - if($x->arraysize()>1) - { - for($k=1; $k<$x->arraysize(); $k++) - { - $y = $x->arraymem($k); - print $y->scalarval(); - if($k < $x->arraysize()-1) - { - print ", "; - } - } - } - print ")
\n"; - } - } - else - { - print "Signature unknown\n"; - } - print "

\n"; - } - } - } -?> -
-$Id$ - - + xmlrpc

Introspect demo

Query server for available methods and their description

The code demonstrates usage of multicall and introspection methods

faultCode() . " Reason: '" .$r->faultString()."'
"; } // 'new style' client constuctor $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); print "

methods available at http://" . $c->server . $c->path . "

\n"; $m = new xmlrpcmsg('system.listMethods'); $r =& $c->send($m); if($r->faultCode()) { display_error($r); } else { $v=$r->value(); for($i=0; $i<$v->arraysize(); $i++) { $mname=$v->arraymem($i); print "

" . $mname->scalarval() . "

\n"; // build messages first, add params later $m1 = new xmlrpcmsg('system.methodHelp'); $m2 = new xmlrpcmsg('system.methodSignature'); $val = new xmlrpcval($mname->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); // send multiple messages in one pass. // If server does not support multicall, client will fall back to 2 separate calls $ms = array($m1, $m2); $rs =& $c->send($ms); if($rs[0]->faultCode()) { display_error($rs[0]); } else { $val=$rs[0]->value(); $txt=$val->scalarval(); if($txt != "") { print "

Documentation

${txt}

\n"; } else { print "

No documentation available.

\n"; } } if($rs[1]->faultCode()) { display_error($rs[1]); } else { print "

Signature

\n"; $val = $rs[1]->value(); if($val->kindOf()=="array") { for($j=0; $j<$val->arraysize(); $j++) { $x = $val->arraymem($j); $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " . $mname->scalarval() . "("; if($x->arraysize()>1) { for($k=1; $k<$x->arraysize(); $k++) { $y = $x->arraymem($k); print $y->scalarval(); if($k < $x->arraysize()-1) { print ", "; } } } print ")
\n"; } } else { print "Signature unknown\n"; } print "

\n"; } } } ?>
$Id$ \ No newline at end of file diff --git a/demo/client/mail.php b/demo/client/mail.php index f73ed377..f0fd82ee 100644 --- a/demo/client/mail.php +++ b/demo/client/mail.php @@ -1,8 +1,8 @@ xmlrpc @@ -18,36 +18,36 @@ // Play nice to PHP 5 installations with REGISTER_LONG_ARRAYS off if (!isset($HTTP_POST_VARS) && isset($_POST)) - $HTTP_POST_VARS = $_POST; + $HTTP_POST_VARS = $_POST; if (isset($HTTP_POST_VARS["server"]) && $HTTP_POST_VARS["server"]) { - if ($HTTP_POST_VARS["server"]=="Userland") { - $XP="/RPC2"; $XS="206.204.24.2"; - } else { - $XP="/xmlrpc/server.php"; $XS="pingu.heddley.com"; - } - $f=new xmlrpcmsg('mail.send'); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailto"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailsub"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailmsg"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailfrom"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailcc"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailbcc"])); - $f->addParam(new xmlrpcval("text/plain")); + if ($HTTP_POST_VARS["server"]=="Userland") { + $XP="/RPC2"; $XS="206.204.24.2"; + } else { + $XP="/xmlrpc/server.php"; $XS="pingu.heddley.com"; + } + $f=new xmlrpcmsg('mail.send'); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailto"])); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailsub"])); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailmsg"])); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailfrom"])); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailcc"])); + $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailbcc"])); + $f->addParam(new xmlrpcval("text/plain")); - $c=new xmlrpc_client($XP, $XS, 80); - $c->setDebug(2); - $r=&$c->send($f); - if (!$r->faultCode()) { - print "Mail sent OK
\n"; - } else { - print ""; - print "Mail send failed
\n"; - print "Fault: "; - print "Code: " . htmlspecialchars($r->faultCode()) . - " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; - print "
"; - } + $c=new xmlrpc_client($XP, $XS, 80); + $c->setDebug(2); + $r=&$c->send($f); + if (!$r->faultCode()) { + print "Mail sent OK
\n"; + } else { + print ""; + print "Mail send failed
\n"; + print "Fault: "; + print "Code: " . htmlspecialchars($r->faultCode()) . + " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; + print "
"; + } } ?>
diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php index 9d47dc8a..6f907d5c 100644 --- a/demo/client/simple_call.php +++ b/demo/client/simple_call.php @@ -6,53 +6,53 @@ * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt */ - /** - * Takes a client object, a remote method name, and a variable numbers of - * php values, and calls the method with the supplied parameters. The - * parameters are native php values and the result is an xmlrpcresp object. - * - * Notes: - * The function encodes the received parameters using php_xmlrpc_encode: - * the limitations of automatic encoding apply to this function too); - * - * the type of the value returned by the function can be changed setting - * beforehand the 'return_type' member of the client object to 'phpvals' - - * see the manual for more details about this capability). - * - * - * @author Toth Istvan - * - * @param xmlrpc_client client object, properly set up to connect to server - * @param string remote function name - * @param mixed $parameter1 - * @param mixed $parameter2 - * @param mixed $parameter3 ... - * @return xmlrpcresp or false on error - */ - function xmlrpccall_simple() - { - if(func_num_args() < 2) - { - // Incorrect - return false; - } - else - { - $varargs = func_get_args(); - $client = array_shift($varargs); - $remote_function_name = array_shift($varargs); - if (!is_a($client, 'xmlrpc_client') || !is_string($remote_function_name)) - { - return false; - } + /** + * Takes a client object, a remote method name, and a variable numbers of + * php values, and calls the method with the supplied parameters. The + * parameters are native php values and the result is an xmlrpcresp object. + * + * Notes: + * The function encodes the received parameters using php_xmlrpc_encode: + * the limitations of automatic encoding apply to this function too); + * + * the type of the value returned by the function can be changed setting + * beforehand the 'return_type' member of the client object to 'phpvals' - + * see the manual for more details about this capability). + * + * + * @author Toth Istvan + * + * @param xmlrpc_client client object, properly set up to connect to server + * @param string remote function name + * @param mixed $parameter1 + * @param mixed $parameter2 + * @param mixed $parameter3 ... + * @return xmlrpcresp or false on error + */ + function xmlrpccall_simple() + { + if(func_num_args() < 2) + { + // Incorrect + return false; + } + else + { + $varargs = func_get_args(); + $client = array_shift($varargs); + $remote_function_name = array_shift($varargs); + if (!is_a($client, 'xmlrpc_client') || !is_string($remote_function_name)) + { + return false; + } - $xmlrpcval_array = array(); - foreach($varargs as $parameter) - { - $xmlrpcval_array[] = php_xmlrpc_encode($parameter); - } + $xmlrpcval_array = array(); + foreach($varargs as $parameter) + { + $xmlrpcval_array[] = php_xmlrpc_encode($parameter); + } - return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); - } - } + return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); + } + } ?> diff --git a/demo/client/which.php b/demo/client/which.php index 0699c8bb..bea011bd 100644 --- a/demo/client/which.php +++ b/demo/client/which.php @@ -1,32 +1 @@ - -xmlrpc - -

Which toolkit demo

-

Query server for toolkit information

-

The code demonstrates usage of the php_xmlrpc_decode function

-send($f); - if(!$r->faultCode()) - { - $v = php_xmlrpc_decode($r->value()); - print "
";

-		print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

-		print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

-		print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

-		print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

-		print "
"; - } - else - { - print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; - } -?> -
-$Id$ - - + xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if(!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";

        print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

        print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

        print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

        print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

        print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?>
$Id$ \ No newline at end of file diff --git a/demo/client/wrap.php b/demo/client/wrap.php index 6b4e005d..d91454eb 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -8,49 +8,49 @@ 2) wrapping of remote methods into php functions return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals - $r =& $c->send(new xmlrpcmsg('system.listMethods')); - if($r->faultCode()) - { - echo "

Server methods list could not be retrieved: error '".htmlspecialchars($r->faultString())."'

\n"; - } - else - { - $testcase = ''; - echo "

Server methods list retrieved, now wrapping it up...

\n
    \n"; - foreach($r->value() as $methodname) // $r->value is an array of strings - { - // do not wrap remote server system methods - if (strpos($methodname, 'system.') !== 0) - { - $funcname = wrap_xmlrpc_method($c, $methodname); - if($funcname) - { - echo "
  • Remote server method ".htmlspecialchars($methodname)." wrapped into php function ".$funcname."
  • \n"; - } - else - { - echo "
  • Remote server method ".htmlspecialchars($methodname)." could not be wrapped!
  • \n"; - } - if($methodname == 'examples.getStateName') - { - $testcase = $funcname; - } - } - } - echo "
\n"; - if($testcase) - { - echo "Now testing function $testcase: remote method to convert U.S. state number into state name"; - $statenum = 25; - $statename = $testcase($statenum, 2); - echo "State number $statenum is ".htmlspecialchars($statename); - } - } + $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); + $c->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals + $r =& $c->send(new xmlrpcmsg('system.listMethods')); + if($r->faultCode()) + { + echo "

Server methods list could not be retrieved: error '".htmlspecialchars($r->faultString())."'

\n"; + } + else + { + $testcase = ''; + echo "

Server methods list retrieved, now wrapping it up...

\n
    \n"; + foreach($r->value() as $methodname) // $r->value is an array of strings + { + // do not wrap remote server system methods + if (strpos($methodname, 'system.') !== 0) + { + $funcname = wrap_xmlrpc_method($c, $methodname); + if($funcname) + { + echo "
  • Remote server method ".htmlspecialchars($methodname)." wrapped into php function ".$funcname."
  • \n"; + } + else + { + echo "
  • Remote server method ".htmlspecialchars($methodname)." could not be wrapped!
  • \n"; + } + if($methodname == 'examples.getStateName') + { + $testcase = $funcname; + } + } + } + echo "
\n"; + if($testcase) + { + echo "Now testing function $testcase: remote method to convert U.S. state number into state name"; + $statenum = 25; + $statename = $testcase($statenum, 2); + echo "State number $statenum is ".htmlspecialchars($statename); + } + } ?>
$Id$ diff --git a/demo/client/zopetest.php b/demo/client/zopetest.php index 1029e01c..3ea4ee3a 100644 --- a/demo/client/zopetest.php +++ b/demo/client/zopetest.php @@ -4,26 +4,26 @@

Zope test demo

The code demonstrates usage of basic authentication to connect to the server

setCredentials("username", "password"); - $c->setDebug(2); - $r = $c->send($f); - if(!$r->faultCode()) - { - $v = $r->value(); - print "I received:" . htmlspecialchars($v->scalarval()) . "
"; - print "
I got this value back
pre>" . - htmlentities($r->serialize()). "\n"; - } - else - { - print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) - . " Reason: '" . ($r->faultString()) . "'
"; - } + $f = new xmlrpcmsg('document_src', array()); + $c = new xmlrpc_client("/index_html", "pingu.heddley.com", 9080); + $c->setCredentials("username", "password"); + $c->setDebug(2); + $r = $c->send($f); + if(!$r->faultCode()) + { + $v = $r->value(); + print "I received:" . htmlspecialchars($v->scalarval()) . "
"; + print "
I got this value back
pre>" . + htmlentities($r->serialize()). "\n"; + } + else + { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) + . " Reason: '" . ($r->faultString()) . "'
"; + } ?>
$Id$ diff --git a/demo/server/discuss.php b/demo/server/discuss.php index 70723059..078b0877 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -1,124 +1,123 @@ getParam(0)); - } - else - { - $msgID=php_xmlrpc_decode($m->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 xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - // otherwise, we create the right response - // with the state name - return new xmlrpcresp(php_xmlrpc_encode($ra)); - } - } + function getcomments($m) + { + global $xmlrpcerruser; + $err=""; + $ra=array(); + // get the first param + if(XMLRPC_EPI_ENABLED == '1') + { + $msgID=xmlrpc_decode($m->getParam(0)); + } + else + { + $msgID=php_xmlrpc_decode($m->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 xmlrpcresp(0, $xmlrpcerruser, $err); + } + else + { + // otherwise, we create the right response + // with the state name + return new xmlrpcresp(php_xmlrpc_encode($ra)); + } + } - $s = new xmlrpc_server(array( - "discuss.addComment" => array( - "function" => "addcomment", - "signature" => $addcomment_sig, - "docstring" => $addcomment_doc - ), - "discuss.getComments" => array( - "function" => "getcomments", - "signature" => $getcomments_sig, - "docstring" => $getcomments_doc - ) - )); -?> + $s = new xmlrpc_server(array( + "discuss.addComment" => array( + "function" => "addcomment", + "signature" => $addcomment_sig, + "docstring" => $addcomment_doc + ), + "discuss.getComments" => array( + "function" => "getcomments", + "signature" => $getcomments_sig, + "docstring" => $getcomments_doc + ) + )); diff --git a/demo/server/proxy.php b/demo/server/proxy.php index 684be959..e9ecde54 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -9,77 +9,76 @@ * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt */ - include("xmlrpc.inc"); - include("xmlrpcs.inc"); + include("xmlrpc.inc"); + include("xmlrpcs.inc"); - /** - * Forward an xmlrpc request to another server, and return to client the response received. - * @param xmlrpcmsg $m (see method docs below for a description of the expected parameters) - * @return xmlrpcresp - */ - function forward_request($m) - { - // create client - $timeout = 0; - $url = php_xmlrpc_decode($m->getParam(0)); - $c = new xmlrpc_client($url); - if ($m->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 = php_xmlrpc_decode($m->getParam(3)); - foreach($options as $key => $val) - { - switch($key) - { - case 'Cookie': - break; - case 'Credentials': - break; - case 'RequestCompression': - $c->setRequestCompression($val); - break; - case 'SSLVerifyHost': - $c->setSSLVerifyHost($val); - break; - case 'SSLVerifyPeer': - $c->setSSLVerifyPeer($val); - break; - case 'Timeout': - $timeout = (integer) $val; - break; - } // switch - } - } + /** + * Forward an xmlrpc request to another server, and return to client the response received. + * @param xmlrpcmsg $m (see method docs below for a description of the expected parameters) + * @return xmlrpcresp + */ + function forward_request($m) + { + // create client + $timeout = 0; + $url = php_xmlrpc_decode($m->getParam(0)); + $c = new xmlrpc_client($url); + if ($m->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 = php_xmlrpc_decode($m->getParam(3)); + foreach($options as $key => $val) + { + switch($key) + { + case 'Cookie': + break; + case 'Credentials': + break; + case 'RequestCompression': + $c->setRequestCompression($val); + break; + case 'SSLVerifyHost': + $c->setSSLVerifyHost($val); + break; + case 'SSLVerifyPeer': + $c->setSSLVerifyPeer($val); + break; + case 'Timeout': + $timeout = (integer) $val; + break; + } // switch + } + } - // build call for remote server - /// @todo find a weay 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... - $method = php_xmlrpc_decode($m->getParam(1)); - $pars = $m->getParam(2); - $m = new xmlrpcmsg($method); - for ($i = 0; $i < $pars->arraySize(); $i++) - { - $m->addParam($pars->arraymem($i)); - } + // build call for remote server + /// @todo find a weay 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... + $method = php_xmlrpc_decode($m->getParam(1)); + $pars = $m->getParam(2); + $m = new xmlrpcmsg($method); + for ($i = 0; $i < $pars->arraySize(); $i++) + { + $m->addParam($pars->arraymem($i)); + } - // add debug info into response we give back to caller - xmlrpc_debugmsg("Sending to server $url the payload: ".$m->serialize()); - return $c->send($m, $timeout); - } + // add debug info into response we give back to caller + xmlrpc_debugmsg("Sending to server $url the payload: ".$m->serialize()); + return $c->send($m, $timeout); + } - // run the server - $server = new xmlrpc_server( - array( - 'xmlrpcproxy.call' => array( - 'function' => 'forward_request', - 'signature' => array( - array('mixed', 'string', 'string', 'array'), - array('mixed', 'string', 'string', 'array', 'stuct'), - ), - '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' - ) - ) - ); -?> + // run the server + $server = new xmlrpc_server( + array( + 'xmlrpcproxy.call' => array( + 'function' => 'forward_request', + 'signature' => array( + array('mixed', 'string', 'string', 'array'), + array('mixed', 'string', 'string', 'array', 'stuct'), + ), + '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' + ) + ) + ); diff --git a/demo/server/server.php b/demo/server/server.php index 45caf649..f44c2c79 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -13,322 +13,323 @@ // 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(); + highlight_file(__FILE__); + die(); } - include("xmlrpc.inc"); - include("xmlrpcs.inc"); - include("xmlrpc_wrappers.inc"); - - /** - * Used to test usage of object methods in dispatch maps and in wrapper code - */ - class xmlrpc_server_methods_container - { - /** - * Method used to test logging of php warnings generated by user functions. - */ - function phpwarninggenerator($m) - { - $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined - return new xmlrpcresp(new xmlrpcval(1, 'boolean')); - } - - /** - * Method used to testcatching of exceptions in the server. - */ - function exceptiongenerator($m) - { - throw new Exception("it's just a test", 1); - } - - /** - * a PHP version of the state-number server. Send me an integer and i'll sell you a state - * @param integer $s - * @return string - */ - static function findstate($s) - { - return inner_findstate($s); - } - } - - - // 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($xmlrpcString, $xmlrpcInt)); - $findstate_doc='When passed an integer between 1 and 51 returns the + include("xmlrpc.inc"); + include("xmlrpcs.inc"); + include("xmlrpc_wrappers.inc"); + + /** + * Used to test usage of object methods in dispatch maps and in wrapper code + */ + class xmlrpc_server_methods_container + { + /** + * Method used to test logging of php warnings generated by user functions. + */ + function phpwarninggenerator($m) + { + $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined + return new xmlrpcresp(new xmlrpcval(1, 'boolean')); + } + + /** + * Method used to testcatching of exceptions in the server. + */ + function exceptiongenerator($m) + { + throw new Exception("it's just a test", 1); + } + + /** + * a PHP version of the state-number server. Send me an integer and i'll sell you a state + * @param integer $s + * @return string + */ + static function findstate($s) + { + return inner_findstate($s); + } + } + + + // 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($xmlrpcString, $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($m) - { - global $xmlrpcerruser, $stateNames; - $err=""; - // get the first param - $sno=$m->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])) - { - $sname=$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 xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - // otherwise, we create the right response - // with the state name - return new xmlrpcresp(new xmlrpcval($sname)); - } - } - - /** - * Inner code of the state-number server. - * Used to test auto-registration of PHP funcions as xmlrpc methods. - * @param integer $stateno the state number - * @return string the name of the state (or error descrption) - */ - function inner_findstate($stateno) - { - global $stateNames; - if (isset($stateNames[$stateno-1])) - { - return $stateNames[$stateno-1]; - } - else - { - // not, there so complain - return "I don't have a state for the index '" . $stateno . "'"; - } - } - $findstate2_sig = wrap_php_function('inner_findstate'); - - $findstate3_sig = wrap_php_function(array('xmlrpc_server_methods_container', 'findstate')); - - $findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); - - $obj = new xmlrpc_server_methods_container(); - $findstate4_sig = wrap_php_function(array($obj, 'findstate')); - - $addtwo_sig=array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); - $addtwo_doc='Add two integers together and return the result'; - function addtwo($m) - { - $s=$m->getParam(0); - $t=$m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"int")); - } - - $addtwodouble_sig=array(array($xmlrpcDouble, $xmlrpcDouble, $xmlrpcDouble)); - $addtwodouble_doc='Add two doubles together and return the result'; - function addtwodouble($m) - { - $s=$m->getParam(0); - $t=$m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"double")); - } - - $stringecho_sig=array(array($xmlrpcString, $xmlrpcString)); - $stringecho_doc='Accepts a string parameter, returns the string.'; - function stringecho($m) - { - // just sends back a string - $s=$m->getParam(0); - $v = $s->scalarval(); - return new xmlrpcresp(new xmlrpcval($s->scalarval())); - } - - $echoback_sig=array(array($xmlrpcString, $xmlrpcString)); - $echoback_doc='Accepts a string parameter, returns the entire incoming payload'; - function echoback($m) - { - // just sends back a string with what i got - // sent to me, just escaped, that's all - // - // $m is an incoming message - $s="I got the following message:\n" . $m->serialize(); - return new xmlrpcresp(new xmlrpcval($s)); - } - - $echosixtyfour_sig=array(array($xmlrpcString, $xmlrpcBase64)); - $echosixtyfour_doc='Accepts a base64 parameter and returns it decoded as a string'; - function echosixtyfour($m) - { - // accepts an encoded value, but sends it back - // as a normal string. this is to test base64 encoding - // is working as expected - $incoming=$m->getParam(0); - return new xmlrpcresp(new xmlrpcval($incoming->scalarval(), "string")); - } - - $bitflipper_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $bitflipper_doc='Accepts an array of booleans, and returns them inverted'; - function bitflipper($m) - { - global $xmlrpcArray; - - $v=$m->getParam(0); - $sz=$v->arraysize(); - $rv=new xmlrpcval(array(), $xmlrpcArray); - - for($j=0; $j<$sz; $j++) - { - $b=$v->arraymem($j); - if ($b->scalarval()) - { - $rv->addScalar(false, "boolean"); - } - else - { - $rv->addScalar(true, "boolean"); - } - } - - return new xmlrpcresp($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[$b]) - { - return 0; - } - return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1; - } - - $agesorter_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $agesorter_doc='Send this method an array of [string, int] structs, eg: + function findstate($m) + { + global $xmlrpcerruser, $stateNames; + $err=""; + // get the first param + $sno=$m->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])) + { + $sname=$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 xmlrpcresp(0, $xmlrpcerruser, $err); + } + else + { + // otherwise, we create the right response + // with the state name + return new xmlrpcresp(new xmlrpcval($sname)); + } + } + + /** + * Inner code of the state-number server. + * Used to test auto-registration of PHP funcions as xmlrpc methods. + * @param integer $stateno the state number + * @return string the name of the state (or error descrption) + */ + function inner_findstate($stateno) + { + global $stateNames; + if (isset($stateNames[$stateno-1])) + { + return $stateNames[$stateno-1]; + } + else + { + // not, there so complain + return "I don't have a state for the index '" . $stateno . "'"; + } + } + $findstate2_sig = wrap_php_function('inner_findstate'); + + $findstate3_sig = wrap_php_function(array('xmlrpc_server_methods_container', 'findstate')); + + $findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); + + $obj = new xmlrpc_server_methods_container(); + $findstate4_sig = wrap_php_function(array($obj, 'findstate')); + + $addtwo_sig=array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); + $addtwo_doc='Add two integers together and return the result'; + function addtwo($m) + { + $s=$m->getParam(0); + $t=$m->getParam(1); + return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"int")); + } + + $addtwodouble_sig=array(array($xmlrpcDouble, $xmlrpcDouble, $xmlrpcDouble)); + $addtwodouble_doc='Add two doubles together and return the result'; + function addtwodouble($m) + { + $s=$m->getParam(0); + $t=$m->getParam(1); + return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"double")); + } + + $stringecho_sig=array(array($xmlrpcString, $xmlrpcString)); + $stringecho_doc='Accepts a string parameter, returns the string.'; + function stringecho($m) + { + // just sends back a string + $s=$m->getParam(0); + $v = $s->scalarval(); +file_put_contents('D:/temp/zozzo.log', $v, FILE_APPEND); + return new xmlrpcresp(new xmlrpcval($s->scalarval())); + } + + $echoback_sig=array(array($xmlrpcString, $xmlrpcString)); + $echoback_doc='Accepts a string parameter, returns the entire incoming payload'; + function echoback($m) + { + // just sends back a string with what i got + // sent to me, just escaped, that's all + // + // $m is an incoming message + $s="I got the following message:\n" . $m->serialize(); + return new xmlrpcresp(new xmlrpcval($s)); + } + + $echosixtyfour_sig=array(array($xmlrpcString, $xmlrpcBase64)); + $echosixtyfour_doc='Accepts a base64 parameter and returns it decoded as a string'; + function echosixtyfour($m) + { + // accepts an encoded value, but sends it back + // as a normal string. this is to test base64 encoding + // is working as expected + $incoming=$m->getParam(0); + return new xmlrpcresp(new xmlrpcval($incoming->scalarval(), "string")); + } + + $bitflipper_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $bitflipper_doc='Accepts an array of booleans, and returns them inverted'; + function bitflipper($m) + { + global $xmlrpcArray; + + $v=$m->getParam(0); + $sz=$v->arraysize(); + $rv=new xmlrpcval(array(), $xmlrpcArray); + + for($j=0; $j<$sz; $j++) + { + $b=$v->arraymem($j); + if ($b->scalarval()) + { + $rv->addScalar(false, "boolean"); + } + else + { + $rv->addScalar(true, "boolean"); + } + } + + return new xmlrpcresp($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[$b]) + { + return 0; + } + return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1; + } + + $agesorter_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $agesorter_doc='Send this method an array of [string, int] structs, eg:
  Dave   35
- Edd	45
+ Edd    45
  Fred   23
  Barney 37
 
And the array will be returned with the entries sorted by their numbers. '; - function agesorter($m) - { - global $agesorter_arr, $xmlrpcerruser, $s; - - xmlrpc_debugmsg("Entering 'agesorter'"); - // get the parameter - $sno=$m->getParam(0); - // error string for [if|when] things go wrong - $err=""; - // create the output value - $v=new xmlrpcval(); - $agar=array(); - - if (isset($sno) && $sno->kindOf()=="array") - { - $max=$sno->arraysize(); - // TODO: create debug method to print can work once more - // print "\n"; - for($i=0; $i<$max; $i++) - { - $rec=$sno->arraymem($i); - if ($rec->kindOf()!="struct") - { - $err="Found non-struct in array at element $i"; - break; - } - // extract name and age from struct - $n=$rec->structmem("name"); - $a=$rec->structmem("age"); - // $n and $a are xmlrpcvals, - // so get the scalarval from them - $agar[$n->scalarval()]=$a->scalarval(); - } - - $agesorter_arr=$agar; - // hack, must make global as uksort() won't - // allow us to pass any other auxilliary information - uksort($agesorter_arr, agesorter_compare); - $outAr=array(); - while (list( $key, $val ) = each( $agesorter_arr ) ) - { - // recreate each struct element - $outAr[]=new xmlrpcval(array("name" => - new xmlrpcval($key), - "age" => - new xmlrpcval($val, "int")), "struct"); - } - // add this array to the output value - $v->addArray($outAr); - } - else - { - $err="Must be one parameter, an array of structs"; - } - - if ($err) - { - return new xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - return new xmlrpcresp($v); - } - } - - // signature and instructions, place these in the dispatch - // map - $mail_send_sig=array(array( - $xmlrpcBoolean, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString - )); - - $mail_send_doc='mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
+ function agesorter($m) + { + global $agesorter_arr, $xmlrpcerruser, $s; + + xmlrpc_debugmsg("Entering 'agesorter'"); + // get the parameter + $sno=$m->getParam(0); + // error string for [if|when] things go wrong + $err=""; + // create the output value + $v=new xmlrpcval(); + $agar=array(); + + if (isset($sno) && $sno->kindOf()=="array") + { + $max=$sno->arraysize(); + // TODO: create debug method to print can work once more + // print "\n"; + for($i=0; $i<$max; $i++) + { + $rec=$sno->arraymem($i); + if ($rec->kindOf()!="struct") + { + $err="Found non-struct in array at element $i"; + break; + } + // extract name and age from struct + $n=$rec->structmem("name"); + $a=$rec->structmem("age"); + // $n and $a are xmlrpcvals, + // so get the scalarval from them + $agar[$n->scalarval()]=$a->scalarval(); + } + + $agesorter_arr=$agar; + // hack, must make global as uksort() won't + // allow us to pass any other auxilliary information + uksort($agesorter_arr, agesorter_compare); + $outAr=array(); + while (list( $key, $val ) = each( $agesorter_arr ) ) + { + // recreate each struct element + $outAr[]=new xmlrpcval(array("name" => + new xmlrpcval($key), + "age" => + new xmlrpcval($val, "int")), "struct"); + } + // add this array to the output value + $v->addArray($outAr); + } + else + { + $err="Must be one parameter, an array of structs"; + } + + if ($err) + { + return new xmlrpcresp(0, $xmlrpcerruser, $err); + } + else + { + return new xmlrpcresp($v); + } + } + + // signature and instructions, place these in the dispatch + // map + $mail_send_sig=array(array( + $xmlrpcBoolean, $xmlrpcString, $xmlrpcString, + $xmlrpcString, $xmlrpcString, $xmlrpcString, + $xmlrpcString, $xmlrpcString + )); + + $mail_send_doc='mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.
subject is a string, the subject of the message.
sender is a string, it\'s the email address of the person sending the message. This string can not be @@ -336,517 +337,516 @@ function agesorter($m) text is a string, it contains the body of the message.
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 mail_send($m) - { - global $xmlrpcerruser, $xmlrpcBoolean; - $err=""; - - $mTo=$m->getParam(0); - $mSub=$m->getParam(1); - $mBody=$m->getParam(2); - $mFrom=$m->getParam(3); - $mCc=$m->getParam(4); - $mBcc=$m->getParam(5); - $mMime=$m->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 xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - return new xmlrpcresp(new xmlrpcval("true", $xmlrpcBoolean)); - } - } - - $getallheaders_sig=array(array($xmlrpcStruct)); - $getallheaders_doc='Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS'; - function getallheaders_xmlrpc($m) - { - global $xmlrpcerruser; - if (function_exists('getallheaders')) - { - return new xmlrpcresp(php_xmlrpc_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 xmlrpcresp(php_xmlrpc_encode($headers)); - } - } - - $setcookies_sig=array(array($xmlrpcInt, $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($m) - { - $m = $m->getParam(0); - while(list($name,$value) = $m->structeach()) - { - $cookiedesc = php_xmlrpc_decode($value); - setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); - } - return new xmlrpcresp(new xmlrpcval(1, 'int')); - } - - $getcookies_sig=array(array($xmlrpcStruct)); - $getcookies_doc='Sends to client a response containing all http cookies as received in the request (as struct)'; - function getcookies($m) - { - return new xmlrpcresp(php_xmlrpc_encode($_COOKIE)); - } - - $v1_arrayOfStructs_sig=array(array($xmlrpcInt, $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 s. Your handler must add all the struct elements named curly and return the result.'; - function v1_arrayOfStructs($m) - { - $sno=$m->getParam(0); - $numcurly=0; - for($i=0; $i<$sno->arraysize(); $i++) - { - $str=$sno->arraymem($i); - $str->structreset(); - while(list($key,$val)=$str->structeach()) - { - if ($key=="curly") - { - $numcurly+=$val->scalarval(); - } - } - } - return new xmlrpcresp(new xmlrpcval($numcurly, "int")); - } - - $v1_easyStruct_sig=array(array($xmlrpcInt, $xmlrpcStruct)); - $v1_easyStruct_doc='This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; - function v1_easyStruct($m) - { - $sno=$m->getParam(0); - $moe=$sno->structmem("moe"); - $larry=$sno->structmem("larry"); - $curly=$sno->structmem("curly"); - $num=$moe->scalarval() + $larry->scalarval() + $curly->scalarval(); - return new xmlrpcresp(new xmlrpcval($num, "int")); - } - - $v1_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); - $v1_echoStruct_doc='This handler takes a single parameter, a struct. Your handler must return the struct.'; - function v1_echoStruct($m) - { - $sno=$m->getParam(0); - return new xmlrpcresp($sno); - } - - $v1_manyTypes_sig=array(array( - $xmlrpcArray, $xmlrpcInt, $xmlrpcBoolean, - $xmlrpcString, $xmlrpcDouble, $xmlrpcDateTime, - $xmlrpcBase64 - )); - $v1_manyTypes_doc='This handler takes six parameters, and returns an array containing all the parameters.'; - function v1_manyTypes($m) - { - return new xmlrpcresp(new xmlrpcval(array( - $m->getParam(0), - $m->getParam(1), - $m->getParam(2), - $m->getParam(3), - $m->getParam(4), - $m->getParam(5)), - "array" - )); - } - - $v1_moderateSizeArrayCheck_sig=array(array($xmlrpcString, $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($m) - { - $ar=$m->getParam(0); - $sz=$ar->arraysize(); - $first=$ar->arraymem(0); - $last=$ar->arraymem($sz-1); - return new xmlrpcresp(new xmlrpcval($first->scalarval() . - $last->scalarval(), "string")); - } - - $v1_simpleStructReturn_sig=array(array($xmlrpcStruct, $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($m) - { - $sno=$m->getParam(0); - $v=$sno->scalarval(); - return new xmlrpcresp(new xmlrpcval(array( - "times10" => new xmlrpcval($v*10, "int"), - "times100" => new xmlrpcval($v*100, "int"), - "times1000" => new xmlrpcval($v*1000, "int")), - "struct" - )); - } - - $v1_nestedStruct_sig=array(array($xmlrpcInt, $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 <i4>s. Your handler must add the three numbers and return the result.'; - function v1_nestedStruct($m) - { - $sno=$m->getParam(0); - - $twoK=$sno->structmem("2000"); - $april=$twoK->structmem("04"); - $fools=$april->structmem("01"); - $curly=$fools->structmem("curly"); - $larry=$fools->structmem("larry"); - $moe=$fools->structmem("moe"); - return new xmlrpcresp(new xmlrpcval($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); - } - - $v1_countTheEntities_sig=array(array($xmlrpcStruct, $xmlrpcString)); - $v1_countTheEntities_doc='This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, >, & \' and ".
Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; - function v1_countTheEntities($m) - { - $sno=$m->getParam(0); - $str=$sno->scalarval(); - $gt=0; $lt=0; $ap=0; $qu=0; $amp=0; - for($i=0; $i": - $gt++; - break; - case "<": - $lt++; - break; - case "\"": - $qu++; - break; - case "'": - $ap++; - break; - case "&": - $amp++; - break; - default: - break; - } - } - return new xmlrpcresp(new xmlrpcval(array( - "ctLeftAngleBrackets" => new xmlrpcval($lt, "int"), - "ctRightAngleBrackets" => new xmlrpcval($gt, "int"), - "ctAmpersands" => new xmlrpcval($amp, "int"), - "ctApostrophes" => new xmlrpcval($ap, "int"), - "ctQuotes" => new xmlrpcval($qu, "int")), - "struct" - )); - } - - // trivial interop tests - // http://www.xmlrpc.com/stories/storyReader$1636 - - $i_echoString_sig=array(array($xmlrpcString, $xmlrpcString)); - $i_echoString_doc="Echoes string."; - - $i_echoStringArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoStringArray_doc="Echoes string array."; - - $i_echoInteger_sig=array(array($xmlrpcInt, $xmlrpcInt)); - $i_echoInteger_doc="Echoes integer."; - - $i_echoIntegerArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoIntegerArray_doc="Echoes integer array."; - - $i_echoFloat_sig=array(array($xmlrpcDouble, $xmlrpcDouble)); - $i_echoFloat_doc="Echoes float."; - - $i_echoFloatArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoFloatArray_doc="Echoes float array."; - - $i_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); - $i_echoStruct_doc="Echoes struct."; - - $i_echoStructArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoStructArray_doc="Echoes struct array."; - - $i_echoValue_doc="Echoes any value back."; - $i_echoValue_sig=array(array($xmlrpcValue, $xmlrpcValue)); - - $i_echoBase64_sig=array(array($xmlrpcBase64, $xmlrpcBase64)); - $i_echoBase64_doc="Echoes base64."; - - $i_echoDate_sig=array(array($xmlrpcDateTime, $xmlrpcDateTime)); - $i_echoDate_doc="Echoes dateTime."; - - function i_echoParam($m) - { - $s=$m->getParam(0); - return new xmlrpcresp($s); - } - - function i_echoString($m) { return i_echoParam($m); } - function i_echoInteger($m) { return i_echoParam($m); } - function i_echoFloat($m) { return i_echoParam($m); } - function i_echoStruct($m) { return i_echoParam($m); } - function i_echoStringArray($m) { return i_echoParam($m); } - function i_echoIntegerArray($m) { return i_echoParam($m); } - function i_echoFloatArray($m) { return i_echoParam($m); } - function i_echoStructArray($m) { return i_echoParam($m); } - function i_echoValue($m) { return i_echoParam($m); } - function i_echoBase64($m) { return i_echoParam($m); } - function i_echoDate($m) { return i_echoParam($m); } - - $i_whichToolkit_sig=array(array($xmlrpcStruct)); - $i_whichToolkit_doc="Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; - - function i_whichToolkit($m) - { - global $xmlrpcName, $xmlrpcVersion,$SERVER_SOFTWARE; - $ret=array( - "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", - "toolkitName" => $xmlrpcName, - "toolkitVersion" => $xmlrpcVersion, - "toolkitOperatingSystem" => isset ($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'] - ); - return new xmlrpcresp ( php_xmlrpc_encode($ret)); - } - - $o=new xmlrpc_server_methods_container; - $a=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 - ), - "examples.generatePHPWarning" => array( - "function" => array($o, "phpwarninggenerator") - //'function' => 'xmlrpc_server_methods_container::phpwarninggenerator' - ), - "examples.raiseException" => array( - "function" => array($o, "exceptiongenerator") - ), - "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" => "mail_send", - "signature" => $mail_send_sig, - "docstring" => $mail_send_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 - ) - ); - - if ($findstate2_sig) - $a['examples.php.getStateName'] = $findstate2_sig; - - if ($findstate3_sig) - $a['examples.php2.getStateName'] = $findstate3_sig; - - if ($findstate4_sig) - $a['examples.php3.getStateName'] = $findstate4_sig; + // 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 mail_send($m) + { + global $xmlrpcerruser, $xmlrpcBoolean; + $err=""; + + $mTo=$m->getParam(0); + $mSub=$m->getParam(1); + $mBody=$m->getParam(2); + $mFrom=$m->getParam(3); + $mCc=$m->getParam(4); + $mBcc=$m->getParam(5); + $mMime=$m->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 xmlrpcresp(0, $xmlrpcerruser, $err); + } + else + { + return new xmlrpcresp(new xmlrpcval("true", $xmlrpcBoolean)); + } + } + + $getallheaders_sig=array(array($xmlrpcStruct)); + $getallheaders_doc='Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS'; + function getallheaders_xmlrpc($m) + { + global $xmlrpcerruser; + if (function_exists('getallheaders')) + { + return new xmlrpcresp(php_xmlrpc_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 xmlrpcresp(php_xmlrpc_encode($headers)); + } + } + + $setcookies_sig=array(array($xmlrpcInt, $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($m) + { + $m = $m->getParam(0); + while(list($name,$value) = $m->structeach()) + { + $cookiedesc = php_xmlrpc_decode($value); + setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); + } + return new xmlrpcresp(new xmlrpcval(1, 'int')); + } + + $getcookies_sig=array(array($xmlrpcStruct)); + $getcookies_doc='Sends to client a response containing all http cookies as received in the request (as struct)'; + function getcookies($m) + { + return new xmlrpcresp(php_xmlrpc_encode($_COOKIE)); + } + + $v1_arrayOfStructs_sig=array(array($xmlrpcInt, $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 s. Your handler must add all the struct elements named curly and return the result.'; + function v1_arrayOfStructs($m) + { + $sno=$m->getParam(0); + $numcurly=0; + for($i=0; $i<$sno->arraysize(); $i++) + { + $str=$sno->arraymem($i); + $str->structreset(); + while(list($key,$val)=$str->structeach()) + { + if ($key=="curly") + { + $numcurly+=$val->scalarval(); + } + } + } + return new xmlrpcresp(new xmlrpcval($numcurly, "int")); + } + + $v1_easyStruct_sig=array(array($xmlrpcInt, $xmlrpcStruct)); + $v1_easyStruct_doc='This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; + function v1_easyStruct($m) + { + $sno=$m->getParam(0); + $moe=$sno->structmem("moe"); + $larry=$sno->structmem("larry"); + $curly=$sno->structmem("curly"); + $num=$moe->scalarval() + $larry->scalarval() + $curly->scalarval(); + return new xmlrpcresp(new xmlrpcval($num, "int")); + } + + $v1_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); + $v1_echoStruct_doc='This handler takes a single parameter, a struct. Your handler must return the struct.'; + function v1_echoStruct($m) + { + $sno=$m->getParam(0); + return new xmlrpcresp($sno); + } + + $v1_manyTypes_sig=array(array( + $xmlrpcArray, $xmlrpcInt, $xmlrpcBoolean, + $xmlrpcString, $xmlrpcDouble, $xmlrpcDateTime, + $xmlrpcBase64 + )); + $v1_manyTypes_doc='This handler takes six parameters, and returns an array containing all the parameters.'; + function v1_manyTypes($m) + { + return new xmlrpcresp(new xmlrpcval(array( + $m->getParam(0), + $m->getParam(1), + $m->getParam(2), + $m->getParam(3), + $m->getParam(4), + $m->getParam(5)), + "array" + )); + } + + $v1_moderateSizeArrayCheck_sig=array(array($xmlrpcString, $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($m) + { + $ar=$m->getParam(0); + $sz=$ar->arraysize(); + $first=$ar->arraymem(0); + $last=$ar->arraymem($sz-1); + return new xmlrpcresp(new xmlrpcval($first->scalarval() . + $last->scalarval(), "string")); + } + + $v1_simpleStructReturn_sig=array(array($xmlrpcStruct, $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($m) + { + $sno=$m->getParam(0); + $v=$sno->scalarval(); + return new xmlrpcresp(new xmlrpcval(array( + "times10" => new xmlrpcval($v*10, "int"), + "times100" => new xmlrpcval($v*100, "int"), + "times1000" => new xmlrpcval($v*1000, "int")), + "struct" + )); + } + + $v1_nestedStruct_sig=array(array($xmlrpcInt, $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 <i4>s. Your handler must add the three numbers and return the result.'; + function v1_nestedStruct($m) + { + $sno=$m->getParam(0); + + $twoK=$sno->structmem("2000"); + $april=$twoK->structmem("04"); + $fools=$april->structmem("01"); + $curly=$fools->structmem("curly"); + $larry=$fools->structmem("larry"); + $moe=$fools->structmem("moe"); + return new xmlrpcresp(new xmlrpcval($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); + } + + $v1_countTheEntities_sig=array(array($xmlrpcStruct, $xmlrpcString)); + $v1_countTheEntities_doc='This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, >, & \' and ".
Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; + function v1_countTheEntities($m) + { + $sno=$m->getParam(0); + $str=$sno->scalarval(); + $gt=0; $lt=0; $ap=0; $qu=0; $amp=0; + for($i=0; $i": + $gt++; + break; + case "<": + $lt++; + break; + case "\"": + $qu++; + break; + case "'": + $ap++; + break; + case "&": + $amp++; + break; + default: + break; + } + } + return new xmlrpcresp(new xmlrpcval(array( + "ctLeftAngleBrackets" => new xmlrpcval($lt, "int"), + "ctRightAngleBrackets" => new xmlrpcval($gt, "int"), + "ctAmpersands" => new xmlrpcval($amp, "int"), + "ctApostrophes" => new xmlrpcval($ap, "int"), + "ctQuotes" => new xmlrpcval($qu, "int")), + "struct" + )); + } + + // trivial interop tests + // http://www.xmlrpc.com/stories/storyReader$1636 + + $i_echoString_sig=array(array($xmlrpcString, $xmlrpcString)); + $i_echoString_doc="Echoes string."; + + $i_echoStringArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $i_echoStringArray_doc="Echoes string array."; + + $i_echoInteger_sig=array(array($xmlrpcInt, $xmlrpcInt)); + $i_echoInteger_doc="Echoes integer."; + + $i_echoIntegerArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $i_echoIntegerArray_doc="Echoes integer array."; + + $i_echoFloat_sig=array(array($xmlrpcDouble, $xmlrpcDouble)); + $i_echoFloat_doc="Echoes float."; + + $i_echoFloatArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $i_echoFloatArray_doc="Echoes float array."; + + $i_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); + $i_echoStruct_doc="Echoes struct."; + + $i_echoStructArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); + $i_echoStructArray_doc="Echoes struct array."; + + $i_echoValue_doc="Echoes any value back."; + $i_echoValue_sig=array(array($xmlrpcValue, $xmlrpcValue)); + + $i_echoBase64_sig=array(array($xmlrpcBase64, $xmlrpcBase64)); + $i_echoBase64_doc="Echoes base64."; + + $i_echoDate_sig=array(array($xmlrpcDateTime, $xmlrpcDateTime)); + $i_echoDate_doc="Echoes dateTime."; + + function i_echoParam($m) + { + $s=$m->getParam(0); + return new xmlrpcresp($s); + } + + function i_echoString($m) { return i_echoParam($m); } + function i_echoInteger($m) { return i_echoParam($m); } + function i_echoFloat($m) { return i_echoParam($m); } + function i_echoStruct($m) { return i_echoParam($m); } + function i_echoStringArray($m) { return i_echoParam($m); } + function i_echoIntegerArray($m) { return i_echoParam($m); } + function i_echoFloatArray($m) { return i_echoParam($m); } + function i_echoStructArray($m) { return i_echoParam($m); } + function i_echoValue($m) { return i_echoParam($m); } + function i_echoBase64($m) { return i_echoParam($m); } + function i_echoDate($m) { return i_echoParam($m); } + + $i_whichToolkit_sig=array(array($xmlrpcStruct)); + $i_whichToolkit_doc="Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; + + function i_whichToolkit($m) + { + global $xmlrpcName, $xmlrpcVersion,$SERVER_SOFTWARE; + $ret=array( + "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", + "toolkitName" => $xmlrpcName, + "toolkitVersion" => $xmlrpcVersion, + "toolkitOperatingSystem" => isset ($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'] + ); + return new xmlrpcresp ( php_xmlrpc_encode($ret)); + } + + $o=new xmlrpc_server_methods_container; + $a=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 + ), + "examples.generatePHPWarning" => array( + "function" => array($o, "phpwarninggenerator") + //'function' => 'xmlrpc_server_methods_container::phpwarninggenerator' + ), + "examples.raiseException" => array( + "function" => array($o, "exceptiongenerator") + ), + "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" => "mail_send", + "signature" => $mail_send_sig, + "docstring" => $mail_send_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 + ) + ); + + if ($findstate2_sig) + $a['examples.php.getStateName'] = $findstate2_sig; + + if ($findstate3_sig) + $a['examples.php2.getStateName'] = $findstate3_sig; + + if ($findstate4_sig) + $a['examples.php3.getStateName'] = $findstate4_sig; if ($findstate5_sig) $a['examples.php4.getStateName'] = $findstate5_sig; - $s=new xmlrpc_server($a, 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['EXCEPTION_HANDLING'])) - $s->exception_handling = $_GET['EXCEPTION_HANDLING']; - $s->service(); - // that should do all we need! -?> \ No newline at end of file + $s=new xmlrpc_server($a, 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['EXCEPTION_HANDLING'])) + $s->exception_handling = $_GET['EXCEPTION_HANDLING']; + $s->service(); + // that should do all we need! diff --git a/demo/vardemo.php b/demo/vardemo.php index 3e7a4018..05846b45 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -2,59 +2,59 @@ xmlrpc Testing value serialization\n"; - - $v = new xmlrpcval(23, "int"); - print "
" . htmlentities($v->serialize()) . "
"; - $v = new xmlrpcval("What are you saying? >> << &&"); - print "
" . htmlentities($v->serialize()) . "
"; - - $v = new xmlrpcval(array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean')), - "array" - ); - - print "
" . htmlentities($v->serialize()) . "
"; - - $v = new xmlrpcval( - array( - "thearray" => new xmlrpcval( - array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean'), - new xmlrpcval(0, 'boolean'), - new xmlrpcval(true, 'boolean'), - new xmlrpcval(false, 'boolean') - ), - "array" - ), - "theint" => new xmlrpcval(23, 'int'), - "thestring" => new xmlrpcval("foobarwhizz"), - "thestruct" => new xmlrpcval( - array( - "one" => new xmlrpcval(1, 'int'), - "two" => new xmlrpcval(2, 'int') - ), - "struct" - ) - ), - "struct" - ); - - print "
" . htmlentities($v->serialize()) . "
"; - - $w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array"); - - print "
" . htmlentities($w->serialize()) . "
"; - - $w = new xmlrpcval("Mary had a little lamb, + include("xmlrpc.inc"); + + $f = new xmlrpcmsg('examples.getStateName'); + + print "

Testing value serialization

\n"; + + $v = new xmlrpcval(23, "int"); + print "
" . htmlentities($v->serialize()) . "
"; + $v = new xmlrpcval("What are you saying? >> << &&"); + print "
" . htmlentities($v->serialize()) . "
"; + + $v = new xmlrpcval(array( + new xmlrpcval("ABCDEFHIJ"), + new xmlrpcval(1234, 'int'), + new xmlrpcval(1, 'boolean')), + "array" + ); + + print "
" . htmlentities($v->serialize()) . "
"; + + $v = new xmlrpcval( + array( + "thearray" => new xmlrpcval( + array( + new xmlrpcval("ABCDEFHIJ"), + new xmlrpcval(1234, 'int'), + new xmlrpcval(1, 'boolean'), + new xmlrpcval(0, 'boolean'), + new xmlrpcval(true, 'boolean'), + new xmlrpcval(false, 'boolean') + ), + "array" + ), + "theint" => new xmlrpcval(23, 'int'), + "thestring" => new xmlrpcval("foobarwhizz"), + "thestruct" => new xmlrpcval( + array( + "one" => new xmlrpcval(1, 'int'), + "two" => new xmlrpcval(2, 'int') + ), + "struct" + ) + ), + "struct" + ); + + print "
" . htmlentities($v->serialize()) . "
"; + + $w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array"); + + print "
" . htmlentities($w->serialize()) . "
"; + + $w = new xmlrpcval("Mary had a little lamb, Whose fleece was white as snow, And everywhere that Mary went the lamb was sure to go. @@ -63,29 +63,29 @@ She tied it to a pylon Ten thousand volts went down its back And turned it into nylon", "base64" - ); - print "
" . htmlentities($w->serialize()) . "
"; - print "
Value of base64 string is: '" . $w->scalarval() . "'
"; + ); + print "
" . htmlentities($w->serialize()) . "
"; + print "
Value of base64 string is: '" . $w->scalarval() . "'
"; - $f->method(''); - $f->addParam(new xmlrpcval("41", "int")); + $f->method(''); + $f->addParam(new xmlrpcval("41", "int")); - print "

Testing request serialization

\n"; - $op = $f->serialize(); - print "
" . htmlentities($op) . "
"; + print "

Testing request serialization

\n"; + $op = $f->serialize(); + print "
" . htmlentities($op) . "
"; - print "

Testing ISO date format

\n";
+    print "

Testing ISO date format

\n";
 
-	$t = time();
-	$date = iso8601_encode($t);
-	print "Now is $t --> $date\n";
-	print "Or in UTC, that is " . iso8601_encode($t, 1) . "\n";
-	$tb = iso8601_decode($date);
-	print "That is to say $date --> $tb\n";
-	print "Which comes out at " . iso8601_encode($tb) . "\n";
-	print "Which was the time in UTC at " . iso8601_decode($date, 1) . "\n";
+    $t = time();
+    $date = iso8601_encode($t);
+    print "Now is $t --> $date\n";
+    print "Or in UTC, that is " . iso8601_encode($t, 1) . "\n";
+    $tb = iso8601_decode($date);
+    print "That is to say $date --> $tb\n";
+    print "Which comes out at " . iso8601_encode($tb) . "\n";
+    print "Which was the time in UTC at " . iso8601_decode($date, 1) . "\n";
 
-	print "
\n"; + print "
\n"; ?> diff --git a/doc/convert.php b/doc/convert.php index 8e7f7f0c..4de3b444 100644 --- a/doc/convert.php +++ b/doc/convert.php @@ -55,4 +55,3 @@ file_put_contents($_SERVER['argv'][3], $out); echo "OK\n"; -?> \ No newline at end of file diff --git a/doc/highlight.php b/doc/highlight.php index eb8eacb9..b8afda17 100644 --- a/doc/highlight.php +++ b/doc/highlight.php @@ -17,12 +17,12 @@ function highlight($file) 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 = substr($content, $start+strlen($starttag), $end-$start-strlen($starttag)); + if ($code[strlen($code)-1] == "\n") { + $code = substr($code, 0, -1); + } //var_dump($code); - $code = str_replace(array('>', '<'), array('>', '<'), $code); + $code = str_replace(array('>', '<'), array('>', '<'), $code); $code = highlight_string('<?php 
', '', $code); //echo($code); @@ -38,11 +38,9 @@ function highlight($file) $files = scandir($dir); foreach($files as $file) { - if (substr($file, -5, 5) == '.html') - { - $out = highlight($dir.'/'.$file); - file_put_contents($dir.'/'.$file, $out); - } + if (substr($file, -5, 5) == '.html') + { + $out = highlight($dir.'/'.$file); + file_put_contents($dir.'/'.$file, $out); + } } - -?> \ No newline at end of file diff --git a/doc/xmlrpc_php.xml b/doc/xmlrpc_php.xml index 9262814f..91b1c46c 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/xmlrpc_php.xml @@ -8,10 +8,10 @@ PHP-XMLRPC User manual XML-RPC for PHP - version 3.0.0 beta + version 3.0.0 - Sep 5, 2009 + Feb 2, 2014 @@ -212,6 +212,15 @@ PHP-XMLRPC User manual functions and methods please take a look at the source code of the library, which is quite thoroughly commented in javadoc-like form. + + 3.0.0 + + + ... + + + + 3.0.0 beta @@ -806,9 +815,6 @@ PHP-XMLRPC User manual wrap_php_function and wrap_xmlrpc_method, and has many caveats, with php being a typeless language and all... - - With PHP versions lesser than 5.0.3 wrapping of php functions - into xmlrpc methods is not supported yet. @@ -855,11 +861,7 @@ PHP-XMLRPC User manual configuration. The minimum supported PHP version is - 5.0. - - Automatic generation of xml-rpc methods from php functions is only - supported with PHP version 5.0.3 and later (note that the lib will - generate some warnings with PHP 5 in strict error reporting mode). + 5.1.0 If you wish to use SSL or HTTP 1.1 to communicate with remote servers, you need the "curl" extension compiled into your PHP @@ -3642,7 +3644,7 @@ else { transparently carried out by the lib, while datetime vals are passed around as strings). - Known limitations: requires PHP 5.0.3 +; only works for + Known limitations: only works for user-defined functions, not for PHP internal functions (reflection does not support retrieving number/type of params for those); the wrapped php function will not be able to programmatically return an diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php index 5edc2eec..8c3d34cb 100644 --- a/lib/phpxmlrpc.php +++ b/lib/phpxmlrpc.php @@ -193,5 +193,3 @@ public static function instance() { return Phpxmlrpc::$instance; } } - -?> \ No newline at end of file diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index efc56228..111e6b24 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -579,7 +579,7 @@ function xmlrpc_cd($parser, $data) // we always initialize the accumulator before starting parsing, anyway... //if(!@isset($xmlrpc->_xh['ac'])) //{ - // $xmlrpc->_xh['ac'] = ''; + // $xmlrpc->_xh['ac'] = ''; //} $xmlrpc->_xh['ac'].=$data; } @@ -599,7 +599,7 @@ function xmlrpc_dh($parser, $data) // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 //if($xmlrpc->_xh['lv']==1) //{ - // $xmlrpc->_xh['lv']=2; + // $xmlrpc->_xh['lv']=2; //} $xmlrpc->_xh['ac'].=$data; } @@ -808,7 +808,7 @@ function php_xmlrpc_decode($xmlrpc_val, $options=array()) * @author Dan Libby (dan@libby.com) * * @param mixed $php_val the value to be converted into an xmlrpcval object - * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' * @return xmlrpcval */ function php_xmlrpc_encode($php_val, $options=array()) @@ -1187,5 +1187,3 @@ function is_valid_charset($encoding, $validlist) return false; } } - -?> \ No newline at end of file diff --git a/lib/xmlrpc_client.php b/lib/xmlrpc_client.php index 7e58aeee..0a75f4c9 100644 --- a/lib/xmlrpc_client.php +++ b/lib/xmlrpc_client.php @@ -1,4 +1,5 @@ \ No newline at end of file +} diff --git a/lib/xmlrpc_wrappers.php b/lib/xmlrpc_wrappers.php index 01dfbcaa..e96be5e5 100644 --- a/lib/xmlrpc_wrappers.php +++ b/lib/xmlrpc_wrappers.php @@ -443,7 +443,7 @@ function wrap_php_function($funcname, $newfuncname='', $extra_options=array()) } // shall we exclude functions returning by ref? // if($func->returnsReference()) - // return false; + // return false; $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}"; //print_r($code); if ($buildit) @@ -930,4 +930,3 @@ function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlr //$code .= "\$client->setDebug(\$debug);\n"; return $code; } -?> \ No newline at end of file diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php index 05e627d7..569a5490 100644 --- a/lib/xmlrpcmsg.php +++ b/lib/xmlrpcmsg.php @@ -609,4 +609,3 @@ public function &parseResponse($data='', $headers_processed=false, $return_type= return $r; } } -?> \ No newline at end of file diff --git a/lib/xmlrpcresp.php b/lib/xmlrpcresp.php index 98981739..527b4639 100644 --- a/lib/xmlrpcresp.php +++ b/lib/xmlrpcresp.php @@ -161,5 +161,3 @@ public function serialize($charset_encoding='') return $result; } } - -?> \ No newline at end of file diff --git a/lib/xmlrpcs.php b/lib/xmlrpcs.php index 27efd630..3236a85c 100644 --- a/lib/xmlrpcs.php +++ b/lib/xmlrpcs.php @@ -259,7 +259,7 @@ function _xmlrpcs_multicall_do_call($server, $call) if($result->faultCode() != 0) { - return _xmlrpcs_multicall_error($result); // Method returned fault. + return _xmlrpcs_multicall_error($result); // Method returned fault. } return new xmlrpcval(array($result->value()), 'array'); @@ -303,7 +303,7 @@ function _xmlrpcs_multicall_do_call_phpvals($server, $call) if($result->faultCode() != 0) { - return _xmlrpcs_multicall_error($result); // Method returned fault. + return _xmlrpcs_multicall_error($result); // Method returned fault. } return new xmlrpcval(array($result->value()), 'array'); @@ -695,7 +695,7 @@ function service($data=null, $return_payload=false) function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false) { $this->dmap[$methodname] = array( - 'function' => $function, + 'function' => $function, 'docstring' => $doc ); if ($sig) @@ -910,7 +910,7 @@ function parseRequest($data, $req_encoding='') // 2005/05/07 commented and moved into caller function code //if($data=='') //{ - // $data=$GLOBALS['HTTP_RAW_POST_DATA']; + // $data=$GLOBALS['HTTP_RAW_POST_DATA']; //} // G. Giunta 2005/02/13: we do NOT expect to receive html entities @@ -1236,4 +1236,3 @@ function echoInput() print $r->serialize(); } } -?> \ No newline at end of file diff --git a/lib/xmlrpcval.php b/lib/xmlrpcval.php index 59ef28b7..56c7af3e 100644 --- a/lib/xmlrpcval.php +++ b/lib/xmlrpcval.php @@ -477,5 +477,3 @@ public function structsize() return count($this->me['struct']); } } - -?> \ No newline at end of file diff --git a/test/benchmark.php b/test/benchmark.php index 700e487c..4e408381 100644 --- a/test/benchmark.php +++ b/test/benchmark.php @@ -8,225 +8,225 @@ * @todo add a test for response ok in call testing? **/ - include(getcwd().'/parse_args.php'); - - require_once('xmlrpc.inc'); - - // 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'); - - $test_results=array(); - $xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable'); - if ($xd) - $num_tests = 1; - else - $num_tests = 10; - - $title = 'XML-RPC Benchmark Tests'; - - if(isset($_SERVER['REQUEST_METHOD'])) - { - echo "\n\n\n$title\n\n\n

$title

\n
\n";
-	}
-	else
-	{
-		echo "$title\n\n";
-	}
-
-	if(isset($_SERVER['REQUEST_METHOD']))
-	{
-		echo "

Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."

\n"; - if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; - flush(); - ob_flush(); - } - else - { - echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; - if ($xd) echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: ".xdebug_get_profiler_filename()."\n"; - } - - // test 'old 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 xmlrpcval($val[0], 'int'); - $values[] = new xmlrpcval($val[1], 'double'); - $values[] = new xmlrpcval($val[2], 'string'); - $values[] = new xmlrpcval($val[3], 'boolean'); - $values[] = new xmlrpcval($val[4], 'dateTime.iso8601'); - $values[] = new xmlrpcval($val[5], 'int'); - $values[] = new xmlrpcval($val[6], 'double'); - $values[] = new xmlrpcval($val[7], 'string'); - $values[] = new xmlrpcval($val[8], 'boolean'); - $values[] = new xmlrpcval($val[9], 'dateTime.iso8601'); - $valarray[$key] = new xmlrpcval($values, 'array'); - } - $vals[] = new xmlrpcval($valarray, 'struct'); - } - $value = new xmlrpcval($vals, 'array'); - $out = $value->serialize(); - } - end_test('Data encoding (large array)', 'manual encoding', $out); - - begin_test('Data encoding (large array)', 'automatic encoding'); - for ($i = 0; $i < $num_tests; $i++) - { - $value = php_xmlrpc_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 xmlrpcmsg(''); - $out = new xmlrpcresp($value); - $in = ''."\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(); - for ($k = 0; $k < $value->arraysize(); $k++) - { - $val1 = $value->arraymem($k); - $out = array(); - while (list($name, $val) = $val1->structeach()) - { - $out[$name] = array(); - for ($j = 0; $j < $val->arraysize(); $j++) - { - $data = $val->arraymem($j); - $out[$name][] = $data->scalarval(); - } - } // while - $result[] = $out; - } - } - end_test('Data decoding (large array)', 'manual decoding', $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 - $value = php_xmlrpc_encode($data1, array('auto_dates')); - $msg = new xmlrpcmsg('interopEchoTests.echoValue', array($value)); - $msgs=array(); - for ($i = 0; $i < 25; $i++) - $msgs[] = $msg; - $server = explode(':', $LOCALSERVER); - if(count($server) > 1) - { - $c = new xmlrpc_client($URI, $server[0], $server[1]); - } - else - { - $c = new xmlrpc_client($URI, $LOCALSERVER); - } - // do not interfere with http compression - $c->accepted_compression = array(); - //$c->debug=true; - - if (function_exists('gzinflate')) { - $c->accepted_compression = null; - } - begin_test('Repeated send (small array)', 'http 10'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 10', $response); - - if (function_exists('curl_init')) - { - begin_test('Repeated send (small array)', 'http 11 w. keep-alive'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11 w. keep-alive', $response); - - $c->keepalive = false; - begin_test('Repeated send (small array)', 'http 11'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11', $response); - } - - begin_test('Repeated send (small array)', 'multicall'); - $response =& $c->send($msgs); - foreach ($response as $key =>& $val) - { - $val = $val->value(); - } - end_test('Repeated send (small array)', 'multicall', $response); - - if (function_exists('gzinflate')) - { - $c->accepted_compression = array('gzip'); - $c->request_compression = 'gzip'; - - begin_test('Repeated send (small array)', 'http 10 w. compression'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 10 w. compression', $response); + include(getcwd().'/parse_args.php'); + + require_once('xmlrpc.inc'); + + // 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'); + + $test_results=array(); + $xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable'); + if ($xd) + $num_tests = 1; + else + $num_tests = 10; + + $title = 'XML-RPC Benchmark Tests'; + + if(isset($_SERVER['REQUEST_METHOD'])) + { + echo "\n\n\n$title\n\n\n

$title

\n
\n";
+    }
+    else
+    {
+        echo "$title\n\n";
+    }
+
+    if(isset($_SERVER['REQUEST_METHOD']))
+    {
+        echo "

Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."

\n"; + if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; + flush(); + ob_flush(); + } + else + { + echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; + if ($xd) echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: ".xdebug_get_profiler_filename()."\n"; + } + + // test 'old 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 xmlrpcval($val[0], 'int'); + $values[] = new xmlrpcval($val[1], 'double'); + $values[] = new xmlrpcval($val[2], 'string'); + $values[] = new xmlrpcval($val[3], 'boolean'); + $values[] = new xmlrpcval($val[4], 'dateTime.iso8601'); + $values[] = new xmlrpcval($val[5], 'int'); + $values[] = new xmlrpcval($val[6], 'double'); + $values[] = new xmlrpcval($val[7], 'string'); + $values[] = new xmlrpcval($val[8], 'boolean'); + $values[] = new xmlrpcval($val[9], 'dateTime.iso8601'); + $valarray[$key] = new xmlrpcval($values, 'array'); + } + $vals[] = new xmlrpcval($valarray, 'struct'); + } + $value = new xmlrpcval($vals, 'array'); + $out = $value->serialize(); + } + end_test('Data encoding (large array)', 'manual encoding', $out); + + begin_test('Data encoding (large array)', 'automatic encoding'); + for ($i = 0; $i < $num_tests; $i++) + { + $value = php_xmlrpc_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 xmlrpcmsg(''); + $out = new xmlrpcresp($value); + $in = ''."\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(); + for ($k = 0; $k < $value->arraysize(); $k++) + { + $val1 = $value->arraymem($k); + $out = array(); + while (list($name, $val) = $val1->structeach()) + { + $out[$name] = array(); + for ($j = 0; $j < $val->arraysize(); $j++) + { + $data = $val->arraymem($j); + $out[$name][] = $data->scalarval(); + } + } // while + $result[] = $out; + } + } + end_test('Data decoding (large array)', 'manual decoding', $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 + $value = php_xmlrpc_encode($data1, array('auto_dates')); + $msg = new xmlrpcmsg('interopEchoTests.echoValue', array($value)); + $msgs=array(); + for ($i = 0; $i < 25; $i++) + $msgs[] = $msg; + $server = explode(':', $LOCALSERVER); + if(count($server) > 1) + { + $c = new xmlrpc_client($URI, $server[0], $server[1]); + } + else + { + $c = new xmlrpc_client($URI, $LOCALSERVER); + } + // do not interfere with http compression + $c->accepted_compression = array(); + //$c->debug=true; + + if (function_exists('gzinflate')) { + $c->accepted_compression = null; + } + begin_test('Repeated send (small array)', 'http 10'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp =& $c->send($msg); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 10', $response); + + if (function_exists('curl_init')) + { + begin_test('Repeated send (small array)', 'http 11 w. keep-alive'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp =& $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11 w. keep-alive', $response); + + $c->keepalive = false; + begin_test('Repeated send (small array)', 'http 11'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp =& $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11', $response); + } + + begin_test('Repeated send (small array)', 'multicall'); + $response =& $c->send($msgs); + foreach ($response as $key =>& $val) + { + $val = $val->value(); + } + end_test('Repeated send (small array)', 'multicall', $response); + + if (function_exists('gzinflate')) + { + $c->accepted_compression = array('gzip'); + $c->request_compression = 'gzip'; + + begin_test('Repeated send (small array)', 'http 10 w. compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp =& $c->send($msg); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 10 w. compression', $response); if (function_exists('curl_init')) { @@ -257,44 +257,43 @@ $val = $val->value(); } end_test('Repeated send (small array)', 'multicall w. compression', $response); - } - - } // end of 'if no xdebug profiling' - - 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 sterted'); - $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(); - } - - - 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(isset($_SERVER['REQUEST_METHOD'])) - { - echo "\n
\n\n\n"; - } -?> \ No newline at end of file + } + + } // end of 'if no xdebug profiling' + + 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 sterted'); + $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(); + } + + + 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(isset($_SERVER['REQUEST_METHOD'])) + { + echo "\n
\n\n\n"; + } diff --git a/test/parse_args.php b/test/parse_args.php index 81f5bd06..60e777fc 100644 --- a/test/parse_args.php +++ b/test/parse_args.php @@ -13,123 +13,122 @@ * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt **/ - require_once('xmlrpc.inc'); - require_once('xmlrpcs.inc'); + require_once('xmlrpc.inc'); + require_once('xmlrpcs.inc'); - // play nice to older PHP versions that miss superglobals - if(!isset($_SERVER)) - { - $_SERVER = $HTTP_SERVER_VARS; - $_GET = isset($HTTP_GET_VARS) ? $HTTP_GET_VARS : array(); - $_POST = isset($HTTP_POST_VARS) ? $HTTP_POST_VARS : array(); - } + // play nice to older PHP versions that miss superglobals + if(!isset($_SERVER)) + { + $_SERVER = $HTTP_SERVER_VARS; + $_GET = isset($HTTP_GET_VARS) ? $HTTP_GET_VARS : array(); + $_POST = isset($HTTP_POST_VARS) ? $HTTP_POST_VARS : array(); + } - // 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) - { - $$param[0]=$param[1]; - } - } - } - } - elseif(!ini_get('register_globals')) - { - // play nice to 'safe' PHP installations with register globals OFF - // NB: we might as well consider using $_GET stuff later on... - extract($_GET); - extract($_POST); - } + // 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) + { + $$param[0]=$param[1]; + } + } + } + } + elseif(!ini_get('register_globals')) + { + // play nice to 'safe' PHP installations with register globals OFF + // NB: we might as well consider using $_GET stuff later on... + extract($_GET); + extract($_POST); + } - if(!isset($DEBUG)) - { - $DEBUG = 0; - } - else - { - $DEBUG = intval($DEBUG); - } + if(!isset($DEBUG)) + { + $DEBUG = 0; + } + else + { + $DEBUG = intval($DEBUG); + } - if(!isset($LOCALSERVER)) - { - if(isset($HTTP_HOST)) - { - $LOCALSERVER = $HTTP_HOST; - } - elseif(isset($_SERVER['HTTP_HOST'])) - { - $LOCALSERVER = $_SERVER['HTTP_HOST']; - } - else - { - $LOCALSERVER = 'localhost'; - } - } - if(!isset($HTTPSSERVER)) - { - $HTTPSSERVER = 'xmlrpc.usefulinc.com'; - } - if(!isset($HTTPSURI)) - { - $HTTPSURI = '/server.php'; - } - if(!isset($HTTPSIGNOREPEER)) - { - $HTTPSIGNOREPEER = false; - } - if(!isset($PROXY)) - { - $PROXYSERVER = null; - } - else - { - $arr = explode(':',$PROXY); - $PROXYSERVER = $arr[0]; - if(count($arr) > 1) - { - $PROXYPORT = $arr[1]; - } - else - { - $PROXYPORT = 8080; - } - } - 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('/test/testsuite.php', '/demo/server/server.php', $REQUEST_URI); - $URI = str_replace('/testsuite.php', '/server.php', $URI); - $URI = str_replace('/test/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('/test/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']); - $URI = str_replace('/testsuite.php', '/server.php', $URI); - $URI = str_replace('/test/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; - } - if(!isset($LOCALPATH)) - { - $LOCALPATH = dirname(__FILE__); - } -?> \ No newline at end of file + if(!isset($LOCALSERVER)) + { + if(isset($HTTP_HOST)) + { + $LOCALSERVER = $HTTP_HOST; + } + elseif(isset($_SERVER['HTTP_HOST'])) + { + $LOCALSERVER = $_SERVER['HTTP_HOST']; + } + else + { + $LOCALSERVER = 'localhost'; + } + } + if(!isset($HTTPSSERVER)) + { + $HTTPSSERVER = 'xmlrpc.usefulinc.com'; + } + if(!isset($HTTPSURI)) + { + $HTTPSURI = '/server.php'; + } + if(!isset($HTTPSIGNOREPEER)) + { + $HTTPSIGNOREPEER = false; + } + if(!isset($PROXY)) + { + $PROXYSERVER = null; + } + else + { + $arr = explode(':',$PROXY); + $PROXYSERVER = $arr[0]; + if(count($arr) > 1) + { + $PROXYPORT = $arr[1]; + } + else + { + $PROXYPORT = 8080; + } + } + 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('/test/testsuite.php', '/demo/server/server.php', $REQUEST_URI); + $URI = str_replace('/testsuite.php', '/server.php', $URI); + $URI = str_replace('/test/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('/test/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']); + $URI = str_replace('/testsuite.php', '/server.php', $URI); + $URI = str_replace('/test/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; + } + if(!isset($LOCALPATH)) + { + $LOCALPATH = dirname(__FILE__); + } diff --git a/test/testsuite.php b/test/testsuite.php index dbbfa0b1..202bbc3c 100644 --- a/test/testsuite.php +++ b/test/testsuite.php @@ -1521,4 +1521,3 @@ function testCurlKAErr() toHTML()."\n\n\n"; } -?> \ No newline at end of file From 449de1d9e63fd5d7f7466bda8f8ebe80aceb2476 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 26 May 2014 22:44:07 +0100 Subject: [PATCH 014/228] Rename php file containing server class, remove phpunit --- ChangeLog | 6 + lib/xmlrpc.php | 2 +- lib/{xmlrpcs.php => xmlrpc_server.php} | 0 test/PHPUnit/Assert.php | 400 ------------------------- test/PHPUnit/TestCase.php | 267 ----------------- test/PHPUnit/TestDecorator.php | 130 -------- test/PHPUnit/TestFailure.php | 104 ------- test/PHPUnit/TestListener.php | 136 --------- test/PHPUnit/TestResult.php | 321 -------------------- test/PHPUnit/TestSuite.php | 239 --------------- test/PHPUnit/license.txt | 68 ----- test/phpunit.php | 106 ------- 12 files changed, 7 insertions(+), 1772 deletions(-) rename lib/{xmlrpcs.php => xmlrpc_server.php} (100%) delete mode 100644 test/PHPUnit/Assert.php delete mode 100644 test/PHPUnit/TestCase.php delete mode 100644 test/PHPUnit/TestDecorator.php delete mode 100644 test/PHPUnit/TestFailure.php delete mode 100644 test/PHPUnit/TestListener.php delete mode 100644 test/PHPUnit/TestResult.php delete mode 100644 test/PHPUnit/TestSuite.php delete mode 100644 test/PHPUnit/license.txt delete mode 100644 test/phpunit.php diff --git a/ChangeLog b/ChangeLog index fa261c51..de81b16a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +2014-05-26 - G. Giunta (giunta.gaetano@gmail.com) + + * removed bundled php unit + * converted all tabs to spaces in php files and removed closing tags + 2014-05-12 - Samu Voutilainen (smar@smar.fi) * removed obsolete xml.so open; dl() is deprecated and removed from 5.3.0 @@ -5,6 +10,7 @@ * removed deprecated xmlrpc_backslash * converted $GLOBALS to internal class. This makes testing much easier and should be more flexible regarding other projects * changed verifyhost from 1 to 2. This makes modern php versions work properly. + * split off each class in its own file 2014-02-03 - G. Giunta (giunta.gaetano@gmail.com) diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php index 111e6b24..ca3cb26e 100644 --- a/lib/xmlrpc.php +++ b/lib/xmlrpc.php @@ -52,7 +52,7 @@ * 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 + * @todo make usage of iconv() or recode_string() or mb_string() where available */ function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') { diff --git a/lib/xmlrpcs.php b/lib/xmlrpc_server.php similarity index 100% rename from lib/xmlrpcs.php rename to lib/xmlrpc_server.php diff --git a/test/PHPUnit/Assert.php b/test/PHPUnit/Assert.php deleted file mode 100644 index 04513d79..00000000 --- a/test/PHPUnit/Assert.php +++ /dev/null @@ -1,400 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -/** - * A set of assert methods. - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_Assert { - /** - * @var boolean - * @access private - */ - var $_looselyTyped = FALSE; - - /** - * Asserts that a haystack contains a needle. - * - * @param mixed - * @param mixed - * @param string - * @access public - * @since Method available since Release 1.1.0 - */ - function assertContains($needle, $haystack, $message = '') { - if (is_string($needle) && is_string($haystack)) { - $this->assertTrue(strpos($haystack, $needle) !== FALSE, $message); - } - - else if (is_array($haystack) && !is_object($needle)) { - $this->assertTrue(in_array($needle, $haystack), $message); - } - - else { - $this->fail('Unsupported parameter passed to assertContains().'); - } - } - - /** - * Asserts that a haystack does not contain a needle. - * - * @param mixed - * @param mixed - * @param string - * @access public - * @since Method available since Release 1.1.0 - */ - function assertNotContains($needle, $haystack, $message = '') { - if (is_string($needle) && is_string($haystack)) { - $this->assertFalse(strpos($haystack, $needle) !== FALSE, $message); - } - - else if (is_array($haystack) && !is_object($needle)) { - $this->assertFalse(in_array($needle, $haystack), $message); - } - - else { - $this->fail('Unsupported parameter passed to assertNotContains().'); - } - } - - /** - * Asserts that two variables are equal. - * - * @param mixed - * @param mixed - * @param string - * @param mixed - * @access public - */ - function assertEquals($expected, $actual, $message = '', $delta = 0) { - if ((is_array($actual) && is_array($expected)) || - (is_object($actual) && is_object($expected))) { - if (is_array($actual) && is_array($expected)) { - ksort($actual); - ksort($expected); - } - - if ($this->_looselyTyped) { - $actual = $this->_convertToString($actual); - $expected = $this->_convertToString($expected); - } - - $actual = serialize($actual); - $expected = serialize($expected); - - $message = sprintf( - '%sexpected %s, actual %s', - - !empty($message) ? $message . ' ' : '', - $expected, - $actual - ); - - if ($actual !== $expected) { - return $this->fail($message); - } - } - - elseif (is_numeric($actual) && is_numeric($expected)) { - $message = sprintf( - '%sexpected %s%s, actual %s', - - !empty($message) ? $message . ' ' : '', - $expected, - ($delta != 0) ? ('+/- ' . $delta) : '', - $actual - ); - - if (!($actual >= ($expected - $delta) && $actual <= ($expected + $delta))) { - return $this->fail($message); - } - } - - else { - $message = sprintf( - '%sexpected %s, actual %s', - - !empty($message) ? $message . ' ' : '', - $expected, - $actual - ); - - if ($actual !== $expected) { - return $this->fail($message); - } - } - } - - /** - * Asserts that two variables reference the same object. - * This requires the Zend Engine 2 to work. - * - * @param object - * @param object - * @param string - * @access public - * @deprecated - */ - function assertSame($expected, $actual, $message = '') { - if (!version_compare(phpversion(), '5.0.0', '>=')) { - $this->fail('assertSame() only works with PHP >= 5.0.0.'); - } - - if ((is_object($expected) || is_null($expected)) && - (is_object($actual) || is_null($actual))) { - $message = sprintf( - '%sexpected two variables to reference the same object', - - !empty($message) ? $message . ' ' : '' - ); - - if ($expected !== $actual) { - return $this->fail($message); - } - } else { - $this->fail('Unsupported parameter passed to assertSame().'); - } - } - - /** - * Asserts that two variables do not reference the same object. - * This requires the Zend Engine 2 to work. - * - * @param object - * @param object - * @param string - * @access public - * @deprecated - */ - function assertNotSame($expected, $actual, $message = '') { - if (!version_compare(phpversion(), '5.0.0', '>=')) { - $this->fail('assertNotSame() only works with PHP >= 5.0.0.'); - } - - if ((is_object($expected) || is_null($expected)) && - (is_object($actual) || is_null($actual))) { - $message = sprintf( - '%sexpected two variables to reference different objects', - - !empty($message) ? $message . ' ' : '' - ); - - if ($expected === $actual) { - return $this->fail($message); - } - } else { - $this->fail('Unsupported parameter passed to assertNotSame().'); - } - } - - /** - * Asserts that a variable is not NULL. - * - * @param mixed - * @param string - * @access public - */ - function assertNotNull($actual, $message = '') { - $message = sprintf( - '%sexpected NOT NULL, actual NULL', - - !empty($message) ? $message . ' ' : '' - ); - - if (is_null($actual)) { - return $this->fail($message); - } - } - - /** - * Asserts that a variable is NULL. - * - * @param mixed - * @param string - * @access public - */ - function assertNull($actual, $message = '') { - $message = sprintf( - '%sexpected NULL, actual NOT NULL', - - !empty($message) ? $message . ' ' : '' - ); - - if (!is_null($actual)) { - return $this->fail($message); - } - } - - /** - * Asserts that a condition is true. - * - * @param boolean - * @param string - * @access public - */ - function assertTrue($condition, $message = '') { - $message = sprintf( - '%sexpected TRUE, actual FALSE', - - !empty($message) ? $message . ' ' : '' - ); - - if (!$condition) { - return $this->fail($message); - } - } - - /** - * Asserts that a condition is false. - * - * @param boolean - * @param string - * @access public - */ - function assertFalse($condition, $message = '') { - $message = sprintf( - '%sexpected FALSE, actual TRUE', - - !empty($message) ? $message . ' ' : '' - ); - - if ($condition) { - return $this->fail($message); - } - } - - /** - * Asserts that a string matches a given regular expression. - * - * @param string - * @param string - * @param string - * @access public - */ - function assertRegExp($pattern, $string, $message = '') { - $message = sprintf( - '%s"%s" does not match pattern "%s"', - - !empty($message) ? $message . ' ' : '', - $string, - $pattern - ); - - if (!preg_match($pattern, $string)) { - return $this->fail($message); - } - } - - /** - * Asserts that a string does not match a given regular expression. - * - * @param string - * @param string - * @param string - * @access public - * @since Method available since Release 1.1.0 - */ - function assertNotRegExp($pattern, $string, $message = '') { - $message = sprintf( - '%s"%s" matches pattern "%s"', - - !empty($message) ? $message . ' ' : '', - $string, - $pattern - ); - - if (preg_match($pattern, $string)) { - return $this->fail($message); - } - } - - /** - * Asserts that a variable is of a given type. - * - * @param string $expected - * @param mixed $actual - * @param optional string $message - * @access public - */ - function assertType($expected, $actual, $message = '') { - return $this->assertEquals( - $expected, - gettype($actual), - $message - ); - } - - /** - * Converts a value to a string. - * - * @param mixed $value - * @access private - */ - function _convertToString($value) { - foreach ($value as $k => $v) { - if (is_array($v)) { - $value[$k] = $this->_convertToString($value[$k]); - } else { - settype($value[$k], 'string'); - } - } - - return $value; - } - - /** - * @param boolean $looselyTyped - * @access public - */ - function setLooselyTyped($looselyTyped) { - if (is_bool($looselyTyped)) { - $this->_looselyTyped = $looselyTyped; - } - } - - /** - * Fails a test with the given message. - * - * @param string - * @access protected - * @abstract - */ - function fail($message = '') { /* abstract */ } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestCase.php b/test/PHPUnit/TestCase.php deleted file mode 100644 index be46b884..00000000 --- a/test/PHPUnit/TestCase.php +++ /dev/null @@ -1,267 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -require_once 'PHPUnit/Assert.php'; -require_once 'PHPUnit/TestResult.php'; - -/** - * A TestCase defines the fixture to run multiple tests. - * - * To define a TestCase - * - * 1) Implement a subclass of PHPUnit_TestCase. - * 2) Define instance variables that store the state of the fixture. - * 3) Initialize the fixture state by overriding setUp(). - * 4) Clean-up after a test by overriding tearDown(). - * - * Each test runs in its own fixture so there can be no side effects - * among test runs. - * - * Here is an example: - * - * - * PHPUnit_TestCase($name); - * } - * - * function setUp() { - * $this->fValue1 = 2; - * $this->fValue2 = 3; - * } - * } - * ?> - * - * - * For each test implement a method which interacts with the fixture. - * Verify the expected results with assertions specified by calling - * assert with a boolean. - * - * - * assertTrue($this->fValue1 + $this->fValue2 == 5); - * } - * ?> - * - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestCase extends PHPUnit_Assert { - /** - * @var boolean - * @access private - */ - var $_failed = FALSE; - - /** - * The name of the test case. - * - * @var string - * @access private - */ - var $_name = ''; - - /** - * PHPUnit_TestResult object - * - * @var object - * @access private - */ - var $_result; - - /** - * Constructs a test case with the given name. - * - * @param string - * @access public - */ - function PHPUnit_TestCase($name = FALSE) { - if ($name !== FALSE) { - $this->setName($name); - } - } - - /** - * Counts the number of test cases executed by run(TestResult result). - * - * @return integer - * @access public - */ - function countTestCases() { - return 1; - } - - /** - * Gets the name of a TestCase. - * - * @return string - * @access public - */ - function getName() { - return $this->_name; - } - - /** - * Runs the test case and collects the results in a given TestResult object. - * - * @param object - * @return object - * @access public - */ - function run(&$result) { - $this->_result = &$result; - $this->_result->run($this); - - return $this->_result; - } - - /** - * Runs the bare test sequence. - * - * @access public - */ - function runBare() { - $this->setUp(); - $this->runTest(); - $this->tearDown(); - $this->pass(); - } - - /** - * Override to run the test and assert its state. - * - * @access protected - */ - function runTest() { - call_user_func( - array( - &$this, - $this->_name - ) - ); - } - - /** - * Sets the name of a TestCase. - * - * @param string - * @access public - */ - function setName($name) { - $this->_name = $name; - } - - /** - * Returns a string representation of the test case. - * - * @return string - * @access public - */ - function toString() { - return ''; - } - - /** - * Creates a default TestResult object. - * - * @return object - * @access protected - */ - function &createResult() { - return new PHPUnit_TestResult; - } - - /** - * Fails a test with the given message. - * - * @param string - * @access protected - */ - function fail($message = '') { - if (function_exists('debug_backtrace')) { - $trace = debug_backtrace(); - - if (isset($trace['1']['file'])) { - $message = sprintf( - "%s in %s:%s", - - $message, - $trace['1']['file'], - $trace['1']['line'] - ); - } - } - - $this->_result->addFailure($this, $message); - $this->_failed = TRUE; - } - - /** - * Passes a test. - * - * @access protected - */ - function pass() { - if (!$this->_failed) { - $this->_result->addPassedTest($this); - } - } - - /** - * Sets up the fixture, for example, open a network connection. - * This method is called before a test is executed. - * - * @access protected - * @abstract - */ - function setUp() { /* abstract */ } - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * - * @access protected - * @abstract - */ - function tearDown() { /* abstract */ } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestDecorator.php b/test/PHPUnit/TestDecorator.php deleted file mode 100644 index bf9afe0a..00000000 --- a/test/PHPUnit/TestDecorator.php +++ /dev/null @@ -1,130 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -require_once 'PHPUnit/TestCase.php'; -require_once 'PHPUnit/TestSuite.php'; - -if (!function_exists('is_a')) { - require_once 'PHP/Compat/Function/is_a.php'; -} - -/** - * A Decorator for Tests. - * - * Use TestDecorator as the base class for defining new - * test decorators. Test decorator subclasses can be introduced - * to add behaviour before or after a test is run. - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestDecorator { - /** - * The Test to be decorated. - * - * @var object - * @access protected - */ - var $_test = NULL; - - /** - * Constructor. - * - * @param object - * @access public - */ - function PHPUnit_TestDecorator(&$test) { - if (is_object($test) && - (is_a($test, 'PHPUnit_TestCase') || - is_a($test, 'PHPUnit_TestSuite'))) { - - $this->_test = &$test; - } - } - - /** - * Runs the test and collects the - * result in a TestResult. - * - * @param object - * @access public - */ - function basicRun(&$result) { - $this->_test->run($result); - } - - /** - * Counts the number of test cases that - * will be run by this test. - * - * @return integer - * @access public - */ - function countTestCases() { - return $this->_test->countTestCases(); - } - - /** - * Returns the test to be run. - * - * @return object - * @access public - */ - function &getTest() { - return $this->_test; - } - - /** - * Runs the decorated test and collects the - * result in a TestResult. - * - * @param object - * @access public - * @abstract - */ - function run(&$result) { /* abstract */ } - - /** - * Returns a string representation of the test. - * - * @return string - * @access public - */ - function toString() { - return $this->_test->toString(); - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestFailure.php b/test/PHPUnit/TestFailure.php deleted file mode 100644 index f30d4511..00000000 --- a/test/PHPUnit/TestFailure.php +++ /dev/null @@ -1,104 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -/** - * A TestFailure collects a failed test together with the caught exception. - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestFailure { - /** - * @var object - * @access private - */ - var $_failedTest; - - /** - * @var string - * @access private - */ - var $_thrownException; - - /** - * Constructs a TestFailure with the given test and exception. - * - * @param object - * @param string - * @access public - */ - function PHPUnit_TestFailure(&$failedTest, &$thrownException) { - $this->_failedTest = &$failedTest; - $this->_thrownException = &$thrownException; - } - - /** - * Gets the failed test. - * - * @return object - * @access public - */ - function &failedTest() { - return $this->_failedTest; - } - - /** - * Gets the thrown exception. - * - * @return object - * @access public - */ - function &thrownException() { - return $this->_thrownException; - } - - /** - * Returns a short description of the failure. - * - * @return string - * @access public - */ - function toString() { - return sprintf( - "TestCase %s->%s() failed: %s\n", - - get_class($this->_failedTest), - $this->_failedTest->getName(), - $this->_thrownException - ); - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestListener.php b/test/PHPUnit/TestListener.php deleted file mode 100644 index b74f8379..00000000 --- a/test/PHPUnit/TestListener.php +++ /dev/null @@ -1,136 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -/** - * A Listener for test progress. - * - * Here is an example: - * - * - * PHPUnit_TestCase($name); - * } - * - * function setUp() { - * $this->fValue1 = 2; - * $this->fValue2 = 3; - * } - * - * function testAdd() { - * $this->assertTrue($this->fValue1 + $this->fValue2 == 4); - * } - * } - * - * class MyListener extends PHPUnit_TestListener { - * function addError(&$test, &$t) { - * print "MyListener::addError() called.\n"; - * } - * - * function addFailure(&$test, &$t) { - * print "MyListener::addFailure() called.\n"; - * } - * - * function endTest(&$test) { - * print "MyListener::endTest() called.\n"; - * } - * - * function startTest(&$test) { - * print "MyListener::startTest() called.\n"; - * } - * } - * - * $suite = new PHPUnit_TestSuite; - * $suite->addTest(new MathTest('testAdd')); - * - * $result = new PHPUnit_TestResult; - * $result->addListener(new MyListener); - * - * $suite->run($result); - * print $result->toString(); - * ?> - * - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestListener { - /** - * An error occurred. - * - * @param object - * @param object - * @access public - * @abstract - */ - function addError(&$test, &$t) { /*abstract */ } - - /** - * A failure occurred. - * - * @param object - * @param object - * @access public - * @abstract - */ - function addFailure(&$test, &$t) { /*abstract */ } - - /** - * A test ended. - * - * @param object - * @access public - * @abstract - */ - function endTest(&$test) { /*abstract */ } - - /** - * A test started. - * - * @param object - * @access public - * @abstract - */ - function startTest(&$test) { /*abstract */ } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestResult.php b/test/PHPUnit/TestResult.php deleted file mode 100644 index 6d1c37a4..00000000 --- a/test/PHPUnit/TestResult.php +++ /dev/null @@ -1,321 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -require_once 'PHPUnit/TestFailure.php'; -require_once 'PHPUnit/TestListener.php'; - -if (!function_exists('is_a')) { - require_once 'PHP/Compat/Function/is_a.php'; -} - -/** - * A TestResult collects the results of executing a test case. - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestResult { - /** - * @var array - * @access protected - */ - var $_errors = array(); - - /** - * @var array - * @access protected - */ - var $_failures = array(); - - /** - * @var array - * @access protected - */ - var $_listeners = array(); - - /** - * @var array - * @access protected - */ - var $_passedTests = array(); - - /** - * @var integer - * @access protected - */ - var $_runTests = 0; - - /** - * @var boolean - * @access private - */ - var $_stop = FALSE; - - /** - * Adds an error to the list of errors. - * The passed in exception caused the error. - * - * @param object - * @param object - * @access public - */ - function addError(&$test, &$t) { - $this->_errors[] = new PHPUnit_TestFailure($test, $t); - - for ($i = 0; $i < sizeof($this->_listeners); $i++) { - $this->_listeners[$i]->addError($test, $t); - } - } - - /** - * Adds a failure to the list of failures. - * The passed in exception caused the failure. - * - * @param object - * @param object - * @access public - */ - function addFailure(&$test, &$t) { - $this->_failures[] = new PHPUnit_TestFailure($test, $t); - - for ($i = 0; $i < sizeof($this->_listeners); $i++) { - $this->_listeners[$i]->addFailure($test, $t); - } - } - - /** - * Registers a TestListener. - * - * @param object - * @access public - */ - function addListener(&$listener) { - if (is_object($listener) && - is_a($listener, 'PHPUnit_TestListener')) { - $this->_listeners[] = &$listener; - } - } - - /** - * Adds a passed test to the list of passed tests. - * - * @param object - * @access public - */ - function addPassedTest(&$test) { - $this->_passedTests[] = &$test; - } - - /** - * Informs the result that a test was completed. - * - * @param object - * @access public - */ - function endTest(&$test) { - for ($i = 0; $i < sizeof($this->_listeners); $i++) { - $this->_listeners[$i]->endTest($test); - } - } - - /** - * Gets the number of detected errors. - * - * @return integer - * @access public - */ - function errorCount() { - return sizeof($this->_errors); - } - - /** - * Returns an Enumeration for the errors. - * - * @return array - * @access public - */ - function &errors() { - return $this->_errors; - } - - /** - * Gets the number of detected failures. - * - * @return integer - * @access public - */ - function failureCount() { - return sizeof($this->_failures); - } - - /** - * Returns an Enumeration for the failures. - * - * @return array - * @access public - */ - function &failures() { - return $this->_failures; - } - - /** - * Returns an Enumeration for the passed tests. - * - * @return array - * @access public - */ - function &passedTests() { - return $this->_passedTests; - } - - /** - * Unregisters a TestListener. - * This requires the Zend Engine 2 (to work properly). - * - * @param object - * @access public - */ - function removeListener(&$listener) { - for ($i = 0; $i < sizeof($this->_listeners); $i++) { - if ($this->_listeners[$i] === $listener) { - unset($this->_listeners[$i]); - } - } - } - - /** - * Runs a TestCase. - * - * @param object - * @access public - */ - function run(&$test) { - $this->startTest($test); - $this->_runTests++; - $test->runBare(); - $this->endTest($test); - } - - /** - * Gets the number of run tests. - * - * @return integer - * @access public - */ - function runCount() { - return $this->_runTests; - } - - /** - * Checks whether the test run should stop. - * - * @access public - */ - function shouldStop() { - return $this->_stop; - } - - /** - * Informs the result that a test will be started. - * - * @param object - * @access public - */ - function startTest(&$test) { - for ($i = 0; $i < sizeof($this->_listeners); $i++) { - $this->_listeners[$i]->startTest($test); - } - } - - /** - * Marks that the test run should stop. - * - * @access public - */ - function stop() { - $this->_stop = TRUE; - } - - /** - * Returns a HTML representation of the test result. - * - * @return string - * @access public - */ - function toHTML() { - return '
' . htmlspecialchars($this->toString()) . '
'; - } - - /** - * Returns a text representation of the test result. - * - * @return string - * @access public - */ - function toString() { - $result = ''; - - foreach ($this->_passedTests as $passedTest) { - $result .= sprintf( - "TestCase %s->%s() passed\n", - - get_class($passedTest), - $passedTest->getName() - ); - } - - foreach ($this->_failures as $failedTest) { - $result .= $failedTest->toString(); - } - - return $result; - } - - /** - * Returns whether the entire test was successful or not. - * - * @return boolean - * @access public - */ - function wasSuccessful() { - if (empty($this->_errors) && empty($this->_failures)) { - return TRUE; - } else { - return FALSE; - } - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> diff --git a/test/PHPUnit/TestSuite.php b/test/PHPUnit/TestSuite.php deleted file mode 100644 index 55220b74..00000000 --- a/test/PHPUnit/TestSuite.php +++ /dev/null @@ -1,239 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -require_once 'PHPUnit/TestCase.php'; - -/** - * A TestSuite is a Composite of Tests. It runs a collection of test cases. - * - * Here is an example using the dynamic test definition. - * - * - * addTest(new MathTest('testPass')); - * ?> - * - * - * Alternatively, a TestSuite can extract the tests to be run automatically. - * To do so you pass the classname of your TestCase class to the TestSuite - * constructor. - * - * - * - * - * - * This constructor creates a suite with all the methods starting with - * "test" that take no arguments. - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit_TestSuite { - /** - * The name of the test suite. - * - * @var string - * @access private - */ - var $_name = ''; - - /** - * The tests in the test suite. - * - * @var array - * @access private - */ - var $_tests = array(); - - /** - * Constructs a TestSuite. - * - * @param mixed - * @access public - */ - function PHPUnit_TestSuite($test = FALSE) { - if ($test !== FALSE) { - $this->setName($test); - $this->addTestSuite($test); - } - } - - /** - * Adds a test to the suite. - * - * @param object - * @access public - */ - function addTest(&$test) { - $this->_tests[] = &$test; - } - - /** - * Adds the tests from the given class to the suite. - * - * @param string - * @access public - */ - function addTestSuite($testClass) { - if (class_exists($testClass)) { - $methods = get_class_methods($testClass); - $parentClasses = array(strtolower($testClass)); - $parentClass = $testClass; - - while(is_string($parentClass = get_parent_class($parentClass))) { - $parentClasses[] = $parentClass; - } - - foreach ($methods as $method) { - if (substr($method, 0, 4) == 'test' && - !in_array($method, $parentClasses)) { - $this->addTest(new $testClass($method)); - } - } - } - } - - /** - * Counts the number of test cases that will be run by this test. - * - * @return integer - * @access public - */ - function countTestCases() { - $count = 0; - - foreach ($this->_tests as $test) { - $count += $test->countTestCases(); - } - - return $count; - } - - /** - * Returns the name of the suite. - * - * @return string - * @access public - */ - function getName() { - return $this->_name; - } - - /** - * Runs the tests and collects their result in a TestResult. - * - * @param object - * @access public - */ - function run(&$result, $show_progress='') { - for ($i = 0; $i < sizeof($this->_tests) && !$result->shouldStop(); $i++) { - $this->_tests[$i]->run($result); - if ($show_progress != '') { - echo $show_progress; flush(); @ob_flush(); - } - } - } - - /** - * Runs a test. - * - * @param object - * @param object - * @access public - */ - function runTest(&$test, &$result) { - $test->run($result); - } - - /** - * Sets the name of the suite. - * - * @param string - * @access public - */ - function setName($name) { - $this->_name = $name; - } - - /** - * Returns the test at the given index. - * - * @param integer - * @return object - * @access public - */ - function &testAt($index) { - if (isset($this->_tests[$index])) { - return $this->_tests[$index]; - } else { - return FALSE; - } - } - - /** - * Returns the number of tests in this suite. - * - * @return integer - * @access public - */ - function testCount() { - return sizeof($this->_tests); - } - - /** - * Returns the tests as an enumeration. - * - * @return array - * @access public - */ - function &tests() { - return $this->_tests; - } - - /** - * Returns a string representation of the test suite. - * - * @return string - * @access public - */ - function toString() { - return ''; - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> \ No newline at end of file diff --git a/test/PHPUnit/license.txt b/test/PHPUnit/license.txt deleted file mode 100644 index 6c1c1708..00000000 --- a/test/PHPUnit/license.txt +++ /dev/null @@ -1,68 +0,0 @@ --------------------------------------------------------------------- - The PHP License, version 3.0 -Copyright (c) 1999 - 2006 The PHP Group. All rights reserved. --------------------------------------------------------------------- - -Redistribution and use in source and binary forms, with or without -modification, is permitted provided that the following conditions -are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. 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. - - 3. The name "PHP" must not be used to endorse or promote products - derived from this software without prior written permission. For - written permission, please contact group@php.net. - - 4. Products derived from this software may not be called "PHP", nor - may "PHP" appear in their name, without prior written permission - from group@php.net. You may indicate that your software works in - conjunction with PHP by saying "Foo for PHP" instead of calling - it "PHP Foo" or "phpfoo" - - 5. The PHP Group may publish revised and/or new versions of the - license from time to time. Each version will be given a - distinguishing version number. - Once covered code has been published under a particular version - of the license, you may always continue to use it under the terms - of that version. You may also choose to use such covered code - under the terms of any subsequent version of the license - published by the PHP Group. No one other than the PHP Group has - the right to modify the terms applicable to covered code created - under this License. - - 6. Redistributions of any form whatsoever must retain the following - acknowledgment: - "This product includes PHP, freely available from - ". - -THIS SOFTWARE IS PROVIDED BY THE PHP DEVELOPMENT TEAM ``AS IS'' AND -ANY EXPRESSED 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 PHP -DEVELOPMENT TEAM OR ITS 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. - --------------------------------------------------------------------- - -This software consists of voluntary contributions made by many -individuals on behalf of the PHP Group. - -The PHP Group can be contacted via Email at group@php.net. - -For more information on the PHP Group and the PHP project, -please see . - -This product includes the Zend Engine, freely available at -. diff --git a/test/phpunit.php b/test/phpunit.php deleted file mode 100644 index 8b822023..00000000 --- a/test/phpunit.php +++ /dev/null @@ -1,106 +0,0 @@ - - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/PHPUnit - * @since File available since Release 1.0.0 - */ - -require_once 'PHPUnit/TestCase.php'; -require_once 'PHPUnit/TestResult.php'; -require_once 'PHPUnit/TestSuite.php'; - -/** - * PHPUnit runs a TestSuite and returns a TestResult object. - * - * Here is an example: - * - * - * PHPUnit_TestCase($name); - * } - * - * function setUp() { - * $this->fValue1 = 2; - * $this->fValue2 = 3; - * } - * - * function testAdd() { - * $this->assertTrue($this->fValue1 + $this->fValue2 == 5); - * } - * } - * - * $suite = new PHPUnit_TestSuite(); - * $suite->addTest(new MathTest('testAdd')); - * - * $result = PHPUnit::run($suite); - * print $result->toHTML(); - * ?> - * - * - * Alternatively, you can pass a class name to the PHPUnit_TestSuite() - * constructor and let it automatically add all methods of that class - * that start with 'test' to the suite: - * - * - * toHTML(); - * ?> - * - * - * @category Testing - * @package PHPUnit - * @author Sebastian Bergmann - * @copyright 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHPUnit - * @since Class available since Release 1.0.0 - */ -class PHPUnit { - /** - * Runs a test(suite). - * - * @param mixed - * @return PHPUnit_TestResult - * @access public - */ - function &run(&$suite, $show_progress=false) { - $result = new PHPUnit_TestResult(); - $suite->run($result, $show_progress); - - return $result; - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ -?> From 29797b74a1b1eaf40844c37888c0a01bf34c107a Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 26 May 2014 23:12:35 +0100 Subject: [PATCH 015/228] Nitpicks: formatting, commented-out code --- lib/phpxmlrpc.php | 7 ++++--- lib/xmlrpc_client.php | 2 +- lib/xmlrpcmsg.php | 6 ++++-- lib/xmlrpcresp.php | 6 ++++-- lib/xmlrpcval.php | 3 ++- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php index 8c3d34cb..fa04f70d 100644 --- a/lib/phpxmlrpc.php +++ b/lib/phpxmlrpc.php @@ -1,6 +1,7 @@ Date: Mon, 26 May 2014 23:16:38 +0100 Subject: [PATCH 016/228] One more nitpick --- lib/phpxmlrpc.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php index fa04f70d..8fa6684a 100644 --- a/lib/phpxmlrpc.php +++ b/lib/phpxmlrpc.php @@ -46,12 +46,7 @@ class Phpxmlrpc /// These will NOT be present in true ISO-8859-1, but will save the unwary /// windows user from sending junk (though no luck when reciving them...) /* - public $xml_cp1252_Entities'=array(); - for ($i = 128; $i < 160; $i++) - { - $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i); - } - public $xml_cp1252_Entities['out'] = array( + public $xml_cp1252_Entities = array('in' => array(), out' => array( '€', '?', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', @@ -60,7 +55,7 @@ class Phpxmlrpc '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '?', 'ž', 'Ÿ' - ); + )); */ public $xmlrpcerr = array( @@ -181,6 +176,11 @@ private function __construct() { $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); + }*/ } /** From fc11f8b24caff6db782867a0061f70a1e35ef5ca Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:01:55 +0000 Subject: [PATCH 017/228] Fix leftovers from branch merging; remove more php closing tags; bump up requirements to 5.3; fix composer autoloading; do not test on 5.2 on travis --- .travis.yml | 4 +--- ChangeLog | 2 +- Makefile | 3 +-- NEWS | 18 +++++++++++++++--- composer.json | 7 +++++-- demo/client/simple_call.php | 1 - demo/client/which.php | 6 +----- demo/server/server.php | 1 - doc/xmlrpc_php.xml | 4 +++- lib/phpxmlrpc.php | 2 +- lib/xmlrpc_wrappers.php | 9 +++++---- test/parse_args.php | 5 +++++ 12 files changed, 38 insertions(+), 24 deletions(-) diff --git a/.travis.yml b/.travis.yml index ca59cd00..a40322be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.2 - 5.3 - 5.4 - 5.5 @@ -9,8 +8,7 @@ php: - hhvm install: - # NB: the lib does not declare dependencies for now. Also, composer will not run on php 5.2 - - if [ $TRAVIS_PHP_VERSION != "5.2" ]; then composer self-update && composer install; fi + - composer self-update && composer install before_script: # Disable xdebug. NB: this should NOT be done for hhvm... diff --git a/ChangeLog b/ChangeLog index 4306b5e4..e032f791 100644 --- a/ChangeLog +++ b/ChangeLog @@ -4,7 +4,7 @@ See https://github.com/gggeek/phpxmlrpc/commits/master 2014-05-26 - G. Giunta (giunta.gaetano@gmail.com) - * removed bundled php unit + * removed bundled phpunit * converted all tabs to spaces in php files and removed closing tags 2014-05-12 - Samu Voutilainen (smar@smar.fi) diff --git a/Makefile b/Makefile index 28a83b0e..4b4e4efa 100644 --- a/Makefile +++ b/Makefile @@ -21,8 +21,7 @@ DOS2UNIX=dos2unix # recover version number from code # thanks to Firman Pribadi for unix command line help # on unix shells lasts char should be \\2/g ) -###export VERSION=$(shell grep -E "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) -export VERSION=3.0.0 +export VERSION=$(shell grep -E "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc diff --git a/NEWS b/NEWS index 5d36f479..62b43ee0 100644 --- a/NEWS +++ b/NEWS @@ -1,8 +1,20 @@ -XML-RPC for PHP version 3.0.1 - 201X/Y/Z +XML-RPC for PHP version 4.0.0 - 201X/Y/Z -Taking baby steps to modern-world php, this release is now tested using Travis ( https://travis-ci.org/ ). +This release does away with the past and starts a transition to modern-world php. -Improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds +Code has been heavily refactored, taking care to preserve backwards compatibility as much as possible, +but some breackage is to be expected. + +PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. + +The minimum requied php version has been increase to 5.3, +even though we stronly urge you to use more recent versions. + +* improved: this release is now tested using Travis ( https://travis-ci.org/ ). + +* improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds + +* improved: phpunit is now installed via composer, not bundled anymore XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/composer.json b/composer.json index 20c31ec6..294d5c67 100644 --- a/composer.json +++ b/composer.json @@ -5,9 +5,12 @@ "homepage": "http://gggeek.github.io/phpxmlrpc/", "keywords": [ "xmlrpc", "webservices" ], "require": { - "php": ">=5.1.0" + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "4.3.*" }, "autoload": { - "classmap": [ "lib/xmlrpc.inc", "lib/xmlrpcs.inc" ] + "classmap": [ "lib/" ] } } \ No newline at end of file diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php index 6f907d5c..9764b7fa 100644 --- a/demo/client/simple_call.php +++ b/demo/client/simple_call.php @@ -55,4 +55,3 @@ function xmlrpccall_simple() return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); } } -?> diff --git a/demo/client/which.php b/demo/client/which.php index 49337dcc..8b1ba488 100644 --- a/demo/client/which.php +++ b/demo/client/which.php @@ -1,5 +1 @@ -<<<<<<< HEAD - xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if(!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";

		print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

		print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

		print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

		print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

		print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?> -======= - xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if(!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";

        print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

        print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

        print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

        print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

        print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?>
$Id$ ->>>>>>> php53 + xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if(!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";

		print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

		print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

		print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

		print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

		print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?> \ No newline at end of file diff --git a/demo/server/server.php b/demo/server/server.php index f44c2c79..853dc4b6 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -166,7 +166,6 @@ function stringecho($m) // just sends back a string $s=$m->getParam(0); $v = $s->scalarval(); -file_put_contents('D:/temp/zozzo.log', $v, FILE_APPEND); return new xmlrpcresp(new xmlrpcval($s->scalarval())); } diff --git a/doc/xmlrpc_php.xml b/doc/xmlrpc_php.xml index d395f5f4..e6c927fa 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/xmlrpc_php.xml @@ -12,6 +12,7 @@ PHP-XMLRPC User manual June 15, 2014 + Edd @@ -238,7 +239,8 @@ PHP-XMLRPC User manual
- 3.0.0 beta + + 3.0.0 beta 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 diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php index 8fa6684a..01133914 100644 --- a/lib/phpxmlrpc.php +++ b/lib/phpxmlrpc.php @@ -123,7 +123,7 @@ class Phpxmlrpc public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? public $xmlrpcName = "XML-RPC for PHP"; - public $xmlrpcVersion = "3.0.0.beta"; + public $xmlrpcVersion = "4.0.0.beta"; // let user errors start at 800 public $xmlrpcerruser = 800; diff --git a/lib/xmlrpc_wrappers.php b/lib/xmlrpc_wrappers.php index e96be5e5..6db92f06 100644 --- a/lib/xmlrpc_wrappers.php +++ b/lib/xmlrpc_wrappers.php @@ -515,12 +515,12 @@ function wrap_php_class($classname, $extra_options=array()) * 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 +* object 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 +* could in principle 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 @@ -536,11 +536,11 @@ function wrap_php_class($classname, $extra_options=array()) * * @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 +* @param array $extra_options array of options that specify conversion details. valid options 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 new_function_name the name of php function to create. If unspecified, 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 --- @@ -570,6 +570,7 @@ function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=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; + // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... $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'; diff --git a/test/parse_args.php b/test/parse_args.php index 60e777fc..418b18c7 100644 --- a/test/parse_args.php +++ b/test/parse_args.php @@ -100,6 +100,11 @@ $PROXYPORT = 8080; } } + // used to silence testsuite warnings about proxy code not being tested + if(!isset($NOPROXY)) + { + $NOPROXY = false; + } if(!isset($URI)) { // GUESTIMATE the url of local demo server From 07b9bffa475640552524aa250b5789caa177503d Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:46:33 +0000 Subject: [PATCH 018/228] Fix gitignore for installation of the library itself via composer --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 8d880eab..a441d051 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /.idea composer.phar +/vendor/* From 40b3de7a7de2900c1ae0ecf28f4492b65b3b18c6 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:48:36 +0000 Subject: [PATCH 019/228] Introduce __DIR__; some CRLF -> LF; wrappers file has been renamed --- debugger/action.php | 6 +++--- debugger/controller.php | 2 +- demo/client/wrap.php | 2 +- demo/server/server.php | 2 +- doc/xmlrpc_php.xml | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index f79aba05..f56946cf 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -36,7 +36,7 @@ return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals diff --git a/demo/server/server.php b/demo/server/server.php index 853dc4b6..d17f73c1 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -19,7 +19,7 @@ include("xmlrpc.inc"); include("xmlrpcs.inc"); - include("xmlrpc_wrappers.inc"); + include("xmlrpc_wrappers.php"); /** * Used to test usage of object methods in dispatch maps and in wrapper code diff --git a/doc/xmlrpc_php.xml b/doc/xmlrpc_php.xml index e6c927fa..d9fff5f6 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/xmlrpc_php.xml @@ -486,7 +486,7 @@ PHP-XMLRPC User manual 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 + a file of their own: xmlrpc_wrappers.php. 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 @@ -913,7 +913,7 @@ PHP-XMLRPC User manual - lib/xmlrpc_wrappers.inc + lib/xmlrpc_wrappers.php helper functions to "automagically" convert plain php From a4e3e30d1f3ff8b9e2b9e08aff180bae7d8dc288 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:49:53 +0000 Subject: [PATCH 020/228] nitpick: private => protected singleton member in base library --- lib/phpxmlrpc.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php index 01133914..23dc001c 100644 --- a/lib/phpxmlrpc.php +++ b/lib/phpxmlrpc.php @@ -151,7 +151,7 @@ class Phpxmlrpc // used to validate nesting of xmlrpc elements public $_xh = null; - private static $instance = null; + protected static $instance = null; private function __construct() { $this->xmlrpcTypes = array( @@ -187,10 +187,10 @@ private function __construct() { * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. */ public static function instance() { - if(Phpxmlrpc::$instance === null) { - Phpxmlrpc::$instance = new Phpxmlrpc(); + if(self::$instance === null) { + self::$instance = new self(); } - return Phpxmlrpc::$instance; + return self::$instance; } } From 4c69746bd560bc4cc2ad7e968d90e4a52955af61 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:50:14 +0000 Subject: [PATCH 021/228] CRLF -> LF --- lib/xmlrpc_wrappers.php | 1866 +++++++++++++++++++-------------------- 1 file changed, 933 insertions(+), 933 deletions(-) diff --git a/lib/xmlrpc_wrappers.php b/lib/xmlrpc_wrappers.php index 6db92f06..52798f4c 100644 --- a/lib/xmlrpc_wrappers.php +++ b/lib/xmlrpc_wrappers.php @@ -1,933 +1,933 @@ -' . $funcname[1]; - } - $exists = method_exists($funcname[0], $funcname[1]); - } - else - { - $plainfuncname = $funcname; - $exists = function_exists($funcname); - } - - if(!$exists) - { - error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); - return false; - } - else - { - // determine name of new php function - if($newfuncname == '') - { - if(is_array($funcname)) - { - if(is_string($funcname[0])) - $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); - else - $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; - } - else - { - $xmlrpcfuncname = "{$prefix}_$funcname"; - } - } - else - { - $xmlrpcfuncname = $newfuncname; - } - while($buildit && function_exists($xmlrpcfuncname)) - { - $xmlrpcfuncname .= 'x'; - } - - // start to introspect PHP code - if(is_array($funcname)) - { - $func = new ReflectionMethod($funcname[0], $funcname[1]); - if($func->isPrivate()) - { - error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); - return false; - } - if($func->isProtected()) - { - error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); - return false; - } - if($func->isConstructor()) - { - error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); - return false; - } - if($func->isDestructor()) - { - error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); - return false; - } - if($func->isAbstract()) - { - error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); - return false; - } - /// @todo add more checks for static vs. nonstatic? - } - else - { - $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: '.$plainfuncname); - 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"; - // since there are no closures in php, if we are given an object instance, - // we store a pointer to it in a global var... - if ( is_array($funcname) && is_object($funcname[0]) ) - { - $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; - $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; - $realfuncname = '$obj->'.$funcname[1]; - } - else - { - $realfuncname = $plainfuncname; - } - foreach($parsvariations as $pars) - { - $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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 '.$plainfuncname); - 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 a user-defined PHP class or php object, map its methods onto a list of -* PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server -* object and called from remote clients (as well as their corresponding signature info). -* -* @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class -* @param array $extra_options see the docs for wrap_php_method for more options -* string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance -* @return array or false on failure -* -* @todo get_class_methods will return both static and non-static methods. -* we have to differentiate the action, depending on wheter we recived a class name or object -*/ -function wrap_php_class($classname, $extra_options=array()) -{ - $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; - $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; - - $result = array(); - $mlist = get_class_methods($classname); - foreach($mlist as $mname) - { - if ($methodfilter == '' || preg_match($methodfilter, $mname)) - { - // echo $mlist."\n"; - $func = new ReflectionMethod($classname, $mname); - if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) - { - if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || - (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) - { - $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); - if ( $methodwrap ) - { - $result[$methodwrap['function']] = $methodwrap['function']; - } - } - } - } - } - return $result; -} - -/** -* 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 -* object 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 principle 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 options 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 unspecified, 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 options) - 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; - // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... - $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; -} +' . $funcname[1]; + } + $exists = method_exists($funcname[0], $funcname[1]); + } + else + { + $plainfuncname = $funcname; + $exists = function_exists($funcname); + } + + if(!$exists) + { + error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); + return false; + } + else + { + // determine name of new php function + if($newfuncname == '') + { + if(is_array($funcname)) + { + if(is_string($funcname[0])) + $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); + else + $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; + } + else + { + $xmlrpcfuncname = "{$prefix}_$funcname"; + } + } + else + { + $xmlrpcfuncname = $newfuncname; + } + while($buildit && function_exists($xmlrpcfuncname)) + { + $xmlrpcfuncname .= 'x'; + } + + // start to introspect PHP code + if(is_array($funcname)) + { + $func = new ReflectionMethod($funcname[0], $funcname[1]); + if($func->isPrivate()) + { + error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); + return false; + } + if($func->isProtected()) + { + error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); + return false; + } + if($func->isConstructor()) + { + error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); + return false; + } + if($func->isDestructor()) + { + error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); + return false; + } + if($func->isAbstract()) + { + error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); + return false; + } + /// @todo add more checks for static vs. nonstatic? + } + else + { + $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: '.$plainfuncname); + 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"; + // since there are no closures in php, if we are given an object instance, + // we store a pointer to it in a global var... + if ( is_array($funcname) && is_object($funcname[0]) ) + { + $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; + $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; + $realfuncname = '$obj->'.$funcname[1]; + } + else + { + $realfuncname = $plainfuncname; + } + foreach($parsvariations as $pars) + { + $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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 '.$plainfuncname); + 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 a user-defined PHP class or php object, map its methods onto a list of +* PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server +* object and called from remote clients (as well as their corresponding signature info). +* +* @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class +* @param array $extra_options see the docs for wrap_php_method for more options +* string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance +* @return array or false on failure +* +* @todo get_class_methods will return both static and non-static methods. +* we have to differentiate the action, depending on wheter we recived a class name or object +*/ +function wrap_php_class($classname, $extra_options=array()) +{ + $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; + $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; + + $result = array(); + $mlist = get_class_methods($classname); + foreach($mlist as $mname) + { + if ($methodfilter == '' || preg_match($methodfilter, $mname)) + { + // echo $mlist."\n"; + $func = new ReflectionMethod($classname, $mname); + if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) + { + if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || + (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) + { + $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); + if ( $methodwrap ) + { + $result[$methodwrap['function']] = $methodwrap['function']; + } + } + } + } + } + return $result; +} + +/** +* 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 +* object 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 principle 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 options 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 unspecified, 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 options) - 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; + // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... + $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; +} From 2570a908dfc18d3b612c506e24446e6b10a21fdb Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:51:17 +0000 Subject: [PATCH 022/228] git ignore composer.lock --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index a441d051..a344dca6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /.idea composer.phar +composer.lock /vendor/* From 33b92a395f2d2bbcc3522b7ef984df2b02d1ddf7 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 10 Dec 2014 00:53:05 +0000 Subject: [PATCH 023/228] WIP testsuite refactoring --- test/benchmark.php | 4 ++-- test/parse_args.php | 13 +------------ test/testsuite.php | 32 ++++++++++++++++---------------- 3 files changed, 19 insertions(+), 30 deletions(-) diff --git a/test/benchmark.php b/test/benchmark.php index 0c183d5b..8c0f6941 100644 --- a/test/benchmark.php +++ b/test/benchmark.php @@ -8,9 +8,9 @@ * @todo add a test for response ok in call testing? **/ - include(dirname(__FILE__).'/parse_args.php'); + include_once(__DIR__.'/../vendor/autoload.php'); - require_once('xmlrpc.inc'); + include(__DIR__.'/parse_args.php'); // 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'); diff --git a/test/parse_args.php b/test/parse_args.php index 418b18c7..f8e2f558 100644 --- a/test/parse_args.php +++ b/test/parse_args.php @@ -13,17 +13,6 @@ * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt **/ - require_once('xmlrpc.inc'); - require_once('xmlrpcs.inc'); - - // play nice to older PHP versions that miss superglobals - if(!isset($_SERVER)) - { - $_SERVER = $HTTP_SERVER_VARS; - $_GET = isset($HTTP_GET_VARS) ? $HTTP_GET_VARS : array(); - $_POST = isset($HTTP_POST_VARS) ? $HTTP_POST_VARS : array(); - } - // check for command line vs web page input params if(!isset($_SERVER['REQUEST_METHOD'])) { @@ -135,5 +124,5 @@ } if(!isset($LOCALPATH)) { - $LOCALPATH = dirname(__FILE__); + $LOCALPATH = __DIR__; } diff --git a/test/testsuite.php b/test/testsuite.php index a5fe24b8..c1a111b5 100644 --- a/test/testsuite.php +++ b/test/testsuite.php @@ -1,24 +1,23 @@ Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; - echo '

Running '.$suite->testCount().' tests (some of which are multiple) against servers: http://'.htmlspecialchars($LOCALSERVER.$URI).' and https://'.htmlspecialchars($HTTPSSERVER.$HTTPSURI)."\n ...

\n"; + echo '

Running '.$suite->count().' tests (some of which are multiple) against servers: http://'.htmlspecialchars($LOCALSERVER.$URI).' and https://'.htmlspecialchars($HTTPSSERVER.$HTTPSURI)."\n ...

\n"; flush(); @ob_flush(); } else { echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; - echo 'Running '.$suite->testCount().' tests (some of which are multiple) against servers: http://'.$LOCALSERVER.$URI.' and https://'.$HTTPSSERVER.$HTTPSURI."\n\n"; + echo 'Running '.$suite->count().' tests (some of which are multiple) against servers: http://'.$LOCALSERVER.$URI.' and https://'.$HTTPSSERVER.$HTTPSURI."\n\n"; } // do some basic timing measurement list($micro, $sec) = explode(' ', microtime()); $start_time = $sec + $micro; -$PHPUnit = new PHPUnit; -$result = $PHPUnit->run($suite, ($DEBUG == 0 ? '.' : '
')); +//$PHPUnit = new PHPUnit; +//$result = $PHPUnit->run($suite, ($DEBUG == 0 ? '.' : '
')); +$result = $suite->run(); list($micro, $sec) = explode(' ', microtime()); $end_time = $sec + $micro; From e6cabdb3e199688162612e667ae35e32c7023249 Mon Sep 17 00:00:00 2001 From: Hugo Zonderland Date: Wed, 10 Dec 2014 11:01:46 +0100 Subject: [PATCH 024/228] Update and rename README to README.md Added Travis build status. Made the file more readable. --- README => README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) rename README => README.md (51%) diff --git a/README b/README.md similarity index 51% rename from README rename to README.md index 80048133..27d81e38 100644 --- a/README +++ b/README.md @@ -1,15 +1,19 @@ -NAME: XMLRPC for PHP - -DESCRIPTION: A php library for building xmlrpc clients and servers - +[![Build Status](https://travis-ci.org/gggeek/phpxmlrpc.svg?branch=php53)](https://travis-ci.org/gggeek/phpxmlrpc) +XMLRPC for PHP +============== +A php library for building xmlrpc clients and servers. +Installation +------------ Installation instructions are in the INSTALL file. +Docs +---- The manual, in HTML and pdf versions, can be found in the doc/ directory. - Recent changes in the ChangeLog file. - Use of this software is subject to the terms in doc/index.html +SSL-certificate +--------------- The passphrase for the rsakey.pem certificate is 'test'. From 64b37dfbd32a7858e729e03eb276a2eaa0f19ccd Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 14 Dec 2014 02:20:46 +0000 Subject: [PATCH 025/228] WIP introduce namespaces; move all global functions and variables to classes --- README.md | 3 +- composer.json | 9 +- demo/server/discuss.php | 10 +- lib/phpxmlrpc.php | 196 -- lib/xmlrpc.inc | 117 ++ lib/xmlrpc.php | 1189 ----------- lib/xmlrpc_wrappers.inc | 49 + lib/xmlrpc_wrappers.php | 933 --------- lib/xmlrpcmsg.php | 613 ------ lib/xmlrpcs.inc | 56 + lib/xmlrpc_client.php => src/Client.php | 76 +- src/Encoder.php | 420 ++++ src/Helper/Charset.php | 246 +++ src/Helper/Date.php | 68 + src/Helper/Http.php | 62 + src/Helper/XMLParser.php | 488 +++++ src/PhpXmlRpc.php | 86 + src/Request.php | 608 ++++++ lib/xmlrpcresp.php => src/Response.php | 20 +- lib/xmlrpc_server.php => src/Server.php | 2416 +++++++++++------------ lib/xmlrpcval.php => src/Value.php | 93 +- src/Wrapper.php | 937 +++++++++ test/testsuite.php | 6 +- test/verify_compat.php | 6 +- 24 files changed, 4434 insertions(+), 4273 deletions(-) delete mode 100644 lib/phpxmlrpc.php create mode 100644 lib/xmlrpc.inc delete mode 100644 lib/xmlrpc.php create mode 100644 lib/xmlrpc_wrappers.inc delete mode 100644 lib/xmlrpc_wrappers.php delete mode 100644 lib/xmlrpcmsg.php create mode 100644 lib/xmlrpcs.inc rename lib/xmlrpc_client.php => src/Client.php (93%) create mode 100644 src/Encoder.php create mode 100644 src/Helper/Charset.php create mode 100644 src/Helper/Date.php create mode 100644 src/Helper/Http.php create mode 100644 src/Helper/XMLParser.php create mode 100644 src/PhpXmlRpc.php create mode 100644 src/Request.php rename lib/xmlrpcresp.php => src/Response.php (91%) rename lib/xmlrpc_server.php => src/Server.php (62%) rename lib/xmlrpcval.php => src/Value.php (84%) create mode 100644 src/Wrapper.php diff --git a/README.md b/README.md index 27d81e38..037b73f6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ XMLRPC for PHP ============== -A php library for building xmlrpc clients and servers. +A php library for building xml-rpc clients and servers. Installation ------------ @@ -11,7 +11,6 @@ Installation instructions are in the INSTALL file. Docs ---- The manual, in HTML and pdf versions, can be found in the doc/ directory. -Recent changes in the ChangeLog file. Use of this software is subject to the terms in doc/index.html SSL-certificate diff --git a/composer.json b/composer.json index 294d5c67..db3c1498 100644 --- a/composer.json +++ b/composer.json @@ -5,12 +5,17 @@ "homepage": "http://gggeek.github.io/phpxmlrpc/", "keywords": [ "xmlrpc", "webservices" ], "require": { - "php": ">=5.3.0" + "php": ">=5.3.0", + "ext-xml": "*" }, "require-dev": { "phpunit/phpunit": "4.3.*" }, + "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" + }, "autoload": { - "classmap": [ "lib/" ] + "psr-4": {"PhpXmlRpc\\": "src/"} } } \ No newline at end of file diff --git a/demo/server/discuss.php b/demo/server/discuss.php index 078b0877..dcba75d6 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -68,15 +68,7 @@ function getcomments($m) global $xmlrpcerruser; $err=""; $ra=array(); - // get the first param - if(XMLRPC_EPI_ENABLED == '1') - { - $msgID=xmlrpc_decode($m->getParam(0)); - } - else - { - $msgID=php_xmlrpc_decode($m->getParam(0)); - } + $msgID=php_xmlrpc_decode($m->getParam(0)); $dbh=dba_open("/tmp/comments.db", "r", "db2"); if($dbh) { diff --git a/lib/phpxmlrpc.php b/lib/phpxmlrpc.php deleted file mode 100644 index 23dc001c..00000000 --- a/lib/phpxmlrpc.php +++ /dev/null @@ -1,196 +0,0 @@ - array('MEMBER', 'DATA', 'PARAM', 'FAULT'), - 'BOOLEAN' => array('VALUE'), - 'I4' => 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 - ); - - // tables used for transcoding different charsets into us-ascii xml - public $xml_iso88591_Entities = 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 reciving them...) - /* - public $xml_cp1252_Entities = array('in' => array(), out' => array( - '€', '?', '‚', 'ƒ', - '„', '…', '†', '‡', - 'ˆ', '‰', 'Š', '‹', - 'Œ', '?', 'Ž', '?', - '?', '‘', '’', '“', - '”', '•', '–', '—', - '˜', '™', 'š', '›', - 'œ', '?', 'ž', 'Ÿ' - )); - */ - - 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 - ); - - 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 messages and - // by the client for received responses when received charset cannot be determined - // or is not supported - public $xmlrpc_defencoding = "UTF-8"; - - // 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 - public $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? - - public $xmlrpcName = "XML-RPC for PHP"; - public $xmlrpcVersion = "4.0.0.beta"; - - // let user errors start at 800 - public $xmlrpcerruser = 800; - // let XML parse errors start at 100 - public $xmlrpcerrxml = 100; - - // set to TRUE to enable correct decoding of and values - public $xmlrpc_null_extension = false; - - // set to TRUE to enable encoding of php NULL values to instead of - public $xmlrpc_null_apache_encoding = false; - - public $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; - - // used to store state during parsing - // quick explanation of components: - // ac - used to accumulate values - // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1) - // isf_reason - used for storing xmlrpcresp fault string - // lv - used to indicate "looking for a value": implements - // the logic to allow values with no types to be strings - // params - used to store parameters in method calls - // method - used to store method name - // stack - array with genealogy of xml elements names: - // used to validate nesting of xmlrpc elements - public $_xh = null; - - protected static $instance = null; - - private function __construct() { - $this->xmlrpcTypes = array( - $this->xmlrpcI4 => 1, - $this->xmlrpcInt => 1, - $this->xmlrpcBoolean => 1, - $this->xmlrpcDouble => 1, - $this->xmlrpcString => 1, - $this->xmlrpcDateTime => 1, - $this->xmlrpcBase64 => 1, - $this->xmlrpcArray => 2, - $this->xmlrpcStruct => 3, - $this->xmlrpcNull => 1 - ); - - 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); - }*/ - } - - /** - * This class is singleton for performance reasons: this way the ASCII array needs to be done only once. - */ - public static function instance() { - if(self::$instance === null) { - self::$instance = new self(); - } - - return self::$instance; - } -} diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc new file mode 100644 index 00000000..c706758a --- /dev/null +++ b/lib/xmlrpc.inc @@ -0,0 +1,117 @@ + + +// 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/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'); + +/* Expose with the old names the classes which have been namespaced */ + +class xmlrpcval extends PhpXmlRpc\Value +{ +} + +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 */ + +function xmlrpc_encode_entitites($data, $srcEncoding='', $destEncoding='') +{ + return PhpXmlRpc\Helper\Charset::instance()->encode_entitites($data, $srcEncoding, $destEncoding); +} + +function iso8601_encode($timeT, $utc=0) +{ + return PhpXmlRpc\Helper\Date::iso8601_encode($timeT, $utc); +} + +function iso8601_decode($iDate, $utc=0) +{ + return PhpXmlRpc\Helper\Date::iso8601_decode($iDate, $utc); +} + +function decode_chunked($buffer) +{ + return PhpXmlRpc\Helper\Http::decode_chunked($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->decode_xml($xmlVal, $options); +} + +function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null) +{ +} + +function is_valid_charset($encoding, $validList) +{ + return PhpXmlRpc\Helper\Charset::instance()->is_valid_charset($encoding, $validList); +} \ No newline at end of file diff --git a/lib/xmlrpc.php b/lib/xmlrpc.php deleted file mode 100644 index ca3cb26e..00000000 --- a/lib/xmlrpc.php +++ /dev/null @@ -1,1189 +0,0 @@ - - -// 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. - -require_once __DIR__ . "/phpxmlrpc.php"; -require_once __DIR__ . "/xmlrpc_client.php"; -require_once __DIR__ . "/xmlrpcresp.php"; -require_once __DIR__ . "/xmlrpcmsg.php"; -require_once __DIR__ . "/xmlrpcval.php"; - -/** - * 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 - */ -function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='') -{ - $xmlrpc = Phpxmlrpc::instance(); - if ($src_encoding == '') - { - // lame, but we know no better... - $src_encoding = $xmlrpc->xmlrpc_internalencoding; - } - - switch(strtoupper($src_encoding.'_'.$dest_encoding)) - { - case 'ISO-8859-1_': - case 'ISO-8859-1_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($xmlrpc->xml_iso88591_Entities['in'], $xmlrpc->xml_iso88591_Entities['out'], $escaped_data); - break; - case 'ISO-8859-1_UTF-8': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = utf8_encode($escaped_data); - 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': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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 -$escaped_data = ''; -// be kind to users creating string xmlrpcvals out of different php types -$data = (string) $data; -$ns = strlen ($data); -for ($nn = 0; $nn < $ns; $nn++) -{ - $ch = $data[$nn]; - $ii = ord($ch); - //1 7 0bbbbbbb (127) - if ($ii < 128) - { - /// @todo shall we replace this with a (supposedly) faster str_replace? - switch($ii){ - case 34: - $escaped_data .= '"'; - break; - case 38: - $escaped_data .= '&'; - break; - case 39: - $escaped_data .= '''; - break; - case 60: - $escaped_data .= '<'; - break; - case 62: - $escaped_data .= '>'; - break; - default: - $escaped_data .= $ch; - } // switch - } - //2 11 110bbbbb 10bbbbbb (2047) - else if ($ii>>5 == 6) - { - $b1 = ($ii & 31); - $ii = ord($data[$nn+1]); - $b2 = ($ii & 63); - $ii = ($b1 * 64) + $b2; - $ent = sprintf ('&#%d;', $ii); - $escaped_data .= $ent; - $nn += 1; - } - //3 16 1110bbbb 10bbbbbb 10bbbbbb - else if ($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); - $escaped_data .= $ent; - $nn += 2; - } - //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - else if ($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); - $escaped_data .= $ent; - $nn += 3; - } -} - break; -/* - case 'CP1252_': - case 'CP1252_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data); - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - break; - case 'CP1252_UTF-8': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - $escaped_data = utf8_encode($escaped_data); - break; - case 'CP1252_ISO-8859-1': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - // we might as well replave 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... - $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data); - break; -*/ - default: - $escaped_data = ''; - error_log("Converting from $src_encoding to $dest_encoding: not supported..."); - } - return $escaped_data; -} - -/// xml parser handler function for opening element tags -function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) -{ - $xmlrpc = Phpxmlrpc::instance(); - // if invalid xmlrpc already detected, skip all processing - if ($xmlrpc->_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($xmlrpc->_xh['stack']) == 0) - { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( - $name != 'VALUE' && !$accept_single_vals)) - { - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = 'missing top level xmlrpc element'; - return; - } - else - { - $xmlrpc->_xh['rt'] = strtolower($name); - $xmlrpc->_xh['rt'] = strtolower($name); - } - } - else - { - // not top level element: see if parent is OK - $parent = end($xmlrpc->_xh['stack']); - if (!array_key_exists($name, $xmlrpc->xmlrpc_valid_parents) || !in_array($parent, $xmlrpc->xmlrpc_valid_parents[$name])) - { - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_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 - $xmlrpc->_xh['vt']='value'; // indicator: no value found yet - $xmlrpc->_xh['ac']=''; - $xmlrpc->_xh['lv']=1; - $xmlrpc->_xh['php_class']=null; - break; - case 'I4': - case 'INT': - case 'STRING': - case 'BOOLEAN': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - $xmlrpc->_xh['ac']=''; // reset the accumulator - break; - case 'STRUCT': - case 'ARRAY': - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - // create an empty array to hold child values, and push it onto appropriate stack - $cur_val = array(); - $cur_val['values'] = array(); - $cur_val['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'])) - { - $cur_val['php_class'] = $attrs['PHP_CLASS']; - } - $xmlrpc->_xh['valuestack'][] = $cur_val; - $xmlrpc->_xh['vt']='data'; // be prepared for a data element next - break; - case 'DATA': - if ($xmlrpc->_xh['vt']!='data') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_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 - $xmlrpc->_xh['ac']=''; - break; - case 'FAULT': - $xmlrpc->_xh['isf']=1; - break; - case 'MEMBER': - $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on - //$xmlrpc->_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 - $xmlrpc->_xh['vt']=null; - break; - case 'NIL': - case 'EX:NIL': - if ($xmlrpc->xmlrpc_null_extension) - { - if ($xmlrpc->_xh['vt']!='value') - { - //two data elements inside a value: an error occurred! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "$name element following a {$xmlrpc->_xh['vt']} element inside a single value"; - return; - } - $xmlrpc->_xh['ac']=''; // reset the accumulator - break; - } - // we do not support the extension, so - // drop through intentionally - default: - /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!! - $xmlrpc->_xh['isf'] = 2; - $xmlrpc->_xh['isf_reason'] = "found not-xmlrpc xml element $name"; - break; - } - - // Save current element name to stack, to validate nesting - $xmlrpc->_xh['stack'][] = $name; - - /// @todo optimization creep: move this inside the big switch() above - if($name!='VALUE') - { - $xmlrpc->_xh['lv']=0; - } - } -} - -/// Used in decoding xml chunks that might represent single xmlrpc values -function xmlrpc_se_any($parser, $name, $attrs) -{ - xmlrpc_se($parser, $name, $attrs, true); -} - -/// xml parser handler function for close element tags -function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) -{ - $xmlrpc = Phpxmlrpc::instance(); - - if ($xmlrpc->_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 == $curr_elem. - // we also checked for proper nesting at start of elements... - $curr_elem = array_pop($xmlrpc->_xh['stack']); - - switch($name) - { - case 'VALUE': - // This if() detects if no scalar was inside - if ($xmlrpc->_xh['vt']=='value') - { - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcString; - } - - if ($rebuild_xmlrpcvals) - { - // build the xmlrpc val out of the data received, and substitute it - $temp = new xmlrpcval($xmlrpc->_xh['value'], $xmlrpc->_xh['vt']); - // in case we got info about underlying php class, save it - // in the object we're rebuilding - if (isset($xmlrpc->_xh['php_class'])) - $temp->_php_class = $xmlrpc->_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($xmlrpc->_xh['valuestack']); - if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') - { - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $temp; - } - else - { - $xmlrpc->_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($xmlrpc->_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($xmlrpc->_xh['valuestack']); - if ($vscount && $xmlrpc->_xh['valuestack'][$vscount-1]['type']=='ARRAY') - { - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][] = $xmlrpc->_xh['value']; - } - } - break; - case 'BOOLEAN': - case 'I4': - case 'INT': - case 'STRING': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - $xmlrpc->_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') - { - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - } - elseif ($name=='DATETIME.ISO8601') - { - if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $xmlrpc->_xh['ac'])) - { - error_log('XML-RPC: invalid value received in DATETIME: '.$xmlrpc->_xh['ac']); - } - $xmlrpc->_xh['vt']=$xmlrpc->xmlrpcDateTime; - $xmlrpc->_xh['value']=$xmlrpc->_xh['ac']; - } - elseif ($name=='BASE64') - { - /// @todo check for failure of base64 decoding / catch warnings - $xmlrpc->_xh['value']=base64_decode($xmlrpc->_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 ($xmlrpc->_xh['ac']=='1' || strcasecmp($xmlrpc->_xh['ac'], 'true') == 0) - { - $xmlrpc->_xh['value']=true; - } - else - { - // log if receiveing something strange, even though we set the value to false anyway - if ($xmlrpc->_xh['ac']!='0' && strcasecmp($xmlrpc->_xh['ac'], 'false') != 0) - error_log('XML-RPC: invalid value received in BOOLEAN: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']=false; - } - } - elseif ($name=='DOUBLE') - { - // we have a DOUBLE - // we must check that only 0123456789-. are characters here - // NOTE: regexp could be much stricter than this... - if (!preg_match('/^[+-eE0123456789 \t.]+$/', $xmlrpc->_xh['ac'])) - { - /// @todo: find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in DOUBLE: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { - // it's ok, add it on - $xmlrpc->_xh['value']=(double)$xmlrpc->_xh['ac']; - } - } - else - { - // we have an I4/INT - // we must check that only 0123456789- are characters here - if (!preg_match('/^[+-]?[0123456789 \t]+$/', $xmlrpc->_xh['ac'])) - { - /// @todo find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in INT: '.$xmlrpc->_xh['ac']); - $xmlrpc->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { - // it's ok, add it on - $xmlrpc->_xh['value']=(int)$xmlrpc->_xh['ac']; - } - } - //$xmlrpc->_xh['ac']=''; // is this necessary? - $xmlrpc->_xh['lv']=3; // indicate we've found a value - break; - case 'NAME': - $xmlrpc->_xh['valuestack'][count($xmlrpc->_xh['valuestack'])-1]['name'] = $xmlrpc->_xh['ac']; - break; - case 'MEMBER': - //$xmlrpc->_xh['ac']=''; // is this necessary? - // add to array in the stack the last element built, - // unless no VALUE was found - if ($xmlrpc->_xh['vt']) - { - $vscount = count($xmlrpc->_xh['valuestack']); - $xmlrpc->_xh['valuestack'][$vscount-1]['values'][$xmlrpc->_xh['valuestack'][$vscount-1]['name']] = $xmlrpc->_xh['value']; - } else - error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); - break; - case 'DATA': - //$xmlrpc->_xh['ac']=''; // is this necessary? - $xmlrpc->_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 - $curr_val = array_pop($xmlrpc->_xh['valuestack']); - $xmlrpc->_xh['value'] = $curr_val['values']; - $xmlrpc->_xh['vt']=strtolower($name); - if (isset($curr_val['php_class'])) - { - $xmlrpc->_xh['php_class'] = $curr_val['php_class']; - } - break; - case 'PARAM': - // add to array of params the current value, - // unless no VALUE was found - if ($xmlrpc->_xh['vt']) - { - $xmlrpc->_xh['params'][]=$xmlrpc->_xh['value']; - $xmlrpc->_xh['pt'][]=$xmlrpc->_xh['vt']; - } - else - error_log('XML-RPC: missing VALUE inside PARAM in received xml'); - break; - case 'METHODNAME': - $xmlrpc->_xh['method']=preg_replace('/^[\n\r\t ]+/', '', $xmlrpc->_xh['ac']); - break; - case 'NIL': - case 'EX:NIL': - if ($xmlrpc->xmlrpc_null_extension) - { - $xmlrpc->_xh['vt']='null'; - $xmlrpc->_xh['value']=null; - $xmlrpc->_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 -function xmlrpc_ee_fast($parser, $name) -{ - xmlrpc_ee($parser, $name, false); -} - -/// xml parser handler function for character data -function xmlrpc_cd($parser, $data) -{ - $xmlrpc = Phpxmlrpc::instance(); - // skip processing if xml fault already detected - if ($xmlrpc->_xh['isf'] < 2) - { - // "lookforvalue==3" means that we've found an entire value - // and should discard any further character data - if($xmlrpc->_xh['lv']!=3) - { - // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 - //if($xmlrpc->_xh['lv']==1) - //{ - // if we've found text and we're just in a then - // say we've found a value - //$xmlrpc->_xh['lv']=2; - //} - // we always initialize the accumulator before starting parsing, anyway... - //if(!@isset($xmlrpc->_xh['ac'])) - //{ - // $xmlrpc->_xh['ac'] = ''; - //} - $xmlrpc->_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... -function xmlrpc_dh($parser, $data) -{ - $xmlrpc = Phpxmlrpc::instance(); - // skip processing if xml fault already detected - if ($xmlrpc->_xh['isf'] < 2) - { - if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') - { - // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 - //if($xmlrpc->_xh['lv']==1) - //{ - // $xmlrpc->_xh['lv']=2; - //} - $xmlrpc->_xh['ac'].=$data; - } - } - return true; -} - -// date helpers - -/** - * 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 - */ -function iso8601_encode($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) - */ -function iso8601_decode($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; -} - -/** - * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types. - * - * Works with xmlrpc message 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 xmlrpcval $xmlrpc_val - * @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 - */ -function php_xmlrpc_decode($xmlrpc_val, $options=array()) -{ - switch($xmlrpc_val->kindOf()) - { - case 'scalar': - if (in_array('extension_api', $options)) - { - reset($xmlrpc_val->me); - list($typ,$val) = each($xmlrpc_val->me); - switch ($typ) - { - case 'dateTime.iso8601': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->xmlrpc_type = 'datetime'; - $xmlrpc_val->timestamp = iso8601_decode($val); - return $xmlrpc_val; - case 'base64': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->type = $typ; - return $xmlrpc_val; - default: - return $xmlrpc_val->scalarval(); - } - } - if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') - { - // we return a Datetime object instead of a string - // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, - // we cater to all 3 cases here - $out = $xmlrpc_val->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 $xmlrpc_val->scalarval(); - case 'array': - $size = $xmlrpc_val->arraysize(); - $arr = array(); - for($i = 0; $i < $size; $i++) - { - $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options); - } - return $arr; - case 'struct': - $xmlrpc_val->structreset(); - // 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 xmlrpcval instead of - // presence of _php_class to detect what we can do? - if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' - && class_exists($xmlrpc_val->_php_class)) - { - $obj = @new $xmlrpc_val->_php_class; - while(list($key,$value)=$xmlrpc_val->structeach()) - { - $obj->$key = php_xmlrpc_decode($value, $options); - } - return $obj; - } - else - { - $arr = array(); - while(list($key,$value)=$xmlrpc_val->structeach()) - { - $arr[$key] = php_xmlrpc_decode($value, $options); - } - return $arr; - } - case 'msg': - $paramcount = $xmlrpc_val->getNumParams(); - $arr = array(); - for($i = 0; $i < $paramcount; $i++) - { - $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i)); - } - return $arr; - } -} - -// This constant left here only for historical reasons... -// it was used to decide if we have to define xmlrpc_encode on our own, but -// we do not do it anymore -if(function_exists('xmlrpc_decode')) -{ - define('XMLRPC_EPI_ENABLED','1'); -} -else -{ - define('XMLRPC_EPI_ENABLED','0'); -} - -/** - * Takes native php types and encodes them into xmlrpc PHP object format. - * It will not re-encode xmlrpcval 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 $php_val the value to be converted into an xmlrpcval object - * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' - * @return xmlrpcval - */ -function php_xmlrpc_encode($php_val, $options=array()) -{ - $xmlrpc = Phpxmlrpc::instance(); - $type = gettype($php_val); - 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}$/', $php_val)) - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDateTime); - else - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcString); - break; - case 'integer': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcInt); - break; - case 'double': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcDouble); - break; - // - // Add support for encoding/decoding of booleans, since they are supported in PHP - case 'boolean': - $xmlrpc_val = new xmlrpcval($php_val, $xmlrpc->xmlrpcBoolean); - break; - // - 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($php_val), range(0, count($php_val)-1)); - // but execution time skyrockets! - $j = 0; - $arr = array(); - $ko = false; - foreach($php_val as $key => $val) - { - $arr[$key] = php_xmlrpc_encode($val, $options); - if(!$ko && $key !== $j) - { - $ko = true; - } - $j++; - } - if($ko) - { - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); - } - else - { - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcArray); - } - break; - case 'object': - if(is_a($php_val, 'xmlrpcval')) - { - $xmlrpc_val = $php_val; - } - else if(is_a($php_val, 'DateTime')) - { - $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $xmlrpc->xmlrpcStruct); - } - else - { - $arr = array(); - reset($php_val); - while(list($k,$v) = each($php_val)) - { - $arr[$k] = php_xmlrpc_encode($v, $options); - } - $xmlrpc_val = new xmlrpcval($arr, $xmlrpc->xmlrpcStruct); - if (in_array('encode_php_objs', $options)) - { - // let's save original class name into xmlrpcval: - // might be useful later on... - $xmlrpc_val->_php_class = get_class($php_val); - } - } - break; - case 'NULL': - if (in_array('extension_api', $options)) - { - $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcString); - } - else if (in_array('null_extension', $options)) - { - $xmlrpc_val = new xmlrpcval('', $xmlrpc->xmlrpcNull); - } - else - { - $xmlrpc_val = new xmlrpcval(); - } - break; - case 'resource': - if (in_array('extension_api', $options)) - { - $xmlrpc_val = new xmlrpcval((int)$php_val, $xmlrpc->xmlrpcInt); - } - else - { - $xmlrpc_val = new xmlrpcval(); - } - // catch "user function", "unknown type" - default: - // giancarlo pinerolo - // it has to return - // an empty object in case, not a boolean. - $xmlrpc_val = new xmlrpcval(); - break; - } - return $xmlrpc_val; -} - -/** - * Convert the xml representation of a method response, method request or single - * xmlrpc value into the appropriate object (a.k.a. deserialize) - * @param string $xml_val - * @param array $options - * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp - */ -function php_xmlrpc_decode_xml($xml_val, $options=array()) -{ - $xmlrpc = Phpxmlrpc::instance(); - - $xmlrpc->_xh = array(); - $xmlrpc->_xh['ac'] = ''; - $xmlrpc->_xh['stack'] = array(); - $xmlrpc->_xh['valuestack'] = array(); - $xmlrpc->_xh['params'] = array(); - $xmlrpc->_xh['pt'] = array(); - $xmlrpc->_xh['isf'] = 0; - $xmlrpc->_xh['isf_reason'] = ''; - $xmlrpc->_xh['method'] = false; - $xmlrpc->_xh['rt'] = ''; - /// @todo 'guestimate' encoding - $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($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); - } - 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, $xml_val, 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 ($xmlrpc->_xh['isf'] > 1) // test that $xmlrpc->_xh['value'] is an obj, too??? - { - error_log($xmlrpc->_xh['isf_reason']); - return false; - } - switch ($xmlrpc->_xh['rt']) - { - case 'methodresponse': - $v =& $xmlrpc->_xh['value']; - if ($xmlrpc->_xh['isf'] == 1) - { - $vc = $v->structmem('faultCode'); - $vs = $v->structmem('faultString'); - $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval()); - } - else - { - $r = new xmlrpcresp($v); - } - return $r; - case 'methodcall': - $m = new xmlrpcmsg($xmlrpc->_xh['method']); - for($i=0; $i < count($xmlrpc->_xh['params']); $i++) - { - $m->addParam($xmlrpc->_xh['params'][$i]); - } - return $m; - case 'value': - return $xmlrpc->_xh['value']; - default: - return false; - } -} - -/** - * decode a string that is encoded w/ "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 - */ -function decode_chunked($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); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - while($chunk_size > 0) - { - $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); - - // 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); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; -} - -/** - * 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 unconforming (legacy?) clients/servers, - * which will be most probably using UTF-8 anyway... - * - * @param string $httpheader the http Content-type header - * @param string $xmlchunk xml content buffer - * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) - * @return string - * - * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! - */ -function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) -{ - $xmlrpc = Phpxmlrpc::instance(); - - // 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 cointrol 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 - // NB: we favour finding an encoding that is compatible with what we can process - if(extension_loaded('mbstring')) - { - if($encoding_prefs) - { - $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); - } - 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 $xmlrpc->xmlrpc_defencoding; - } -} - -/** - * 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 mixed $validlist comma separated list of valid charsets (or array of charsets) - * @return bool - */ -function is_valid_charset($encoding, $validlist) -{ - $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') - ); - if (is_string($validlist)) - $validlist = explode(',', $validlist); - if (@in_array(strtoupper($encoding), $validlist)) - return true; - else - { - if (array_key_exists($encoding, $charset_supersets)) - foreach ($validlist as $allowed) - if (in_array($allowed, $charset_supersets[$encoding])) - return true; - return false; - } -} diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc new file mode 100644 index 00000000..90949346 --- /dev/null +++ b/lib/xmlrpc_wrappers.inc @@ -0,0 +1,49 @@ +php_2_xmlrpc_type($phpType); +} + +function xmlrpc_2_php_type($xmlrpcType) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->xmlrpc_2_php_type($xmlrpcType); +} + +function wrap_php_function($funcName, $newFuncName='', $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->wrap_php_function($funcName, $newFuncName, $extraOptions); +} + +function wrap_php_class($className, $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->wrap_php_class($className, $extraOptions); +} + +function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $protocol='', $newFuncName='') +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->wrap_xmlrpc_method($client, $methodName, $extraOptions, $timeout, $protocol, $newFuncName); +} + +function wrap_xmlrpc_server($client, $extraOptions=array()) +{ + $wrapper = new PhpXmlRpc\Wrapper(); + return $wrapper->wrap_xmlrpc_server($client, $extraOptions); +} \ No newline at end of file diff --git a/lib/xmlrpc_wrappers.php b/lib/xmlrpc_wrappers.php deleted file mode 100644 index 52798f4c..00000000 --- a/lib/xmlrpc_wrappers.php +++ /dev/null @@ -1,933 +0,0 @@ -' . $funcname[1]; - } - $exists = method_exists($funcname[0], $funcname[1]); - } - else - { - $plainfuncname = $funcname; - $exists = function_exists($funcname); - } - - if(!$exists) - { - error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); - return false; - } - else - { - // determine name of new php function - if($newfuncname == '') - { - if(is_array($funcname)) - { - if(is_string($funcname[0])) - $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); - else - $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; - } - else - { - $xmlrpcfuncname = "{$prefix}_$funcname"; - } - } - else - { - $xmlrpcfuncname = $newfuncname; - } - while($buildit && function_exists($xmlrpcfuncname)) - { - $xmlrpcfuncname .= 'x'; - } - - // start to introspect PHP code - if(is_array($funcname)) - { - $func = new ReflectionMethod($funcname[0], $funcname[1]); - if($func->isPrivate()) - { - error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); - return false; - } - if($func->isProtected()) - { - error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); - return false; - } - if($func->isConstructor()) - { - error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); - return false; - } - if($func->isDestructor()) - { - error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); - return false; - } - if($func->isAbstract()) - { - error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); - return false; - } - /// @todo add more checks for static vs. nonstatic? - } - else - { - $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: '.$plainfuncname); - 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"; - // since there are no closures in php, if we are given an object instance, - // we store a pointer to it in a global var... - if ( is_array($funcname) && is_object($funcname[0]) ) - { - $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; - $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; - $realfuncname = '$obj->'.$funcname[1]; - } - else - { - $realfuncname = $plainfuncname; - } - foreach($parsvariations as $pars) - { - $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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 '.$plainfuncname); - 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 a user-defined PHP class or php object, map its methods onto a list of -* PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server -* object and called from remote clients (as well as their corresponding signature info). -* -* @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class -* @param array $extra_options see the docs for wrap_php_method for more options -* string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance -* @return array or false on failure -* -* @todo get_class_methods will return both static and non-static methods. -* we have to differentiate the action, depending on wheter we recived a class name or object -*/ -function wrap_php_class($classname, $extra_options=array()) -{ - $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; - $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; - - $result = array(); - $mlist = get_class_methods($classname); - foreach($mlist as $mname) - { - if ($methodfilter == '' || preg_match($methodfilter, $mname)) - { - // echo $mlist."\n"; - $func = new ReflectionMethod($classname, $mname); - if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) - { - if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || - (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) - { - $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); - if ( $methodwrap ) - { - $result[$methodwrap['function']] = $methodwrap['function']; - } - } - } - } - } - return $result; -} - -/** -* 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 -* object 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 principle 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 options 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 unspecified, 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 options) - 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; - // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... - $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; -} diff --git a/lib/xmlrpcmsg.php b/lib/xmlrpcmsg.php deleted file mode 100644 index 1c26af08..00000000 --- a/lib/xmlrpcmsg.php +++ /dev/null @@ -1,613 +0,0 @@ -methodname=$meth; - if(is_array($pars) && count($pars)>0) - { - for($i=0; $iaddParam($pars[$i]); - } - } - } - - private function xml_header($charset_encoding='') - { - if ($charset_encoding != '') - { - return "\n\n"; - } - else - { - return "\n\n"; - } - } - - private function xml_footer() - { - return ''; - } - - private function kindOf() - { - return 'msg'; - } - - public function createPayload($charset_encoding='') - { - if ($charset_encoding != '') - $this->content_type = 'text/xml; charset=' . $charset_encoding; - else - $this->content_type = 'text/xml'; - $this->payload=$this->xml_header($charset_encoding); - $this->payload.='' . $this->methodname . "\n"; - $this->payload.="\n"; - for($i=0; $iparams); $i++) - { - $p=$this->params[$i]; - $this->payload.="\n" . $p->serialize($charset_encoding) . - "\n"; - } - $this->payload.="\n"; - $this->payload.=$this->xml_footer(); - } - - /** - * Gets/sets the xmlrpc method to be invoked - * @param string $meth the method to be set (leave empty not to set it) - * @return string the method that will be invoked - */ - public function method($meth='') - { - if($meth!='') - { - $this->methodname=$meth; - } - return $this->methodname; - } - - /** - * Returns xml representation of the message. XML prologue included - * @param string $charset_encoding - * @return string the xml representation of the message, xml prologue included - */ - public function serialize($charset_encoding='') - { - $this->createPayload($charset_encoding); - return $this->payload; - } - - /** - * Add a parameter to the list of parameters to be used upon method invocation - * @param xmlrpcval $par - * @return boolean false on failure - */ - public function addParam($par) - { - // add check: do not add to self params which are not xmlrpcvals - if(is_object($par) && is_a($par, 'xmlrpcval')) - { - $this->params[]=$par; - return true; - } - else - { - return false; - } - } - - /** - * Returns the nth parameter in the message. The index zero-based. - * @param integer $i the index of the parameter to fetch (zero based) - * @return xmlrpcval the i-th parameter - */ - public function getParam($i) { return $this->params[$i]; } - - /** - * Returns the number of parameters in the messge. - * @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 axmlrpc 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 xmlrpcresp - * @todo add 2nd & 3rd param to be passed to ParseResponse() ??? - */ - public function &parseResponseFile($fp) - { - $ipd=''; - while($data=fread($fp, 32768)) - { - $ipd.=$data; - } - //fclose($fp); - $r =& $this->parseResponse($ipd); - return $r; - } - - /** - * Parses HTTP headers and separates them from data. - */ - private function &parseResponseHeaders(&$data, $headers_processed=false) - { - $xmlrpc = Phpxmlrpc::instance(); - // 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'); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); - return $r; - } - } - - // 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); - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $xmlrpc->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; - } - - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - - // 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) - { - $header_name = 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'][$header_name] - /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') - { - if ($header_name == '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($xmlrpc->_xh['headers'][$header_name])) - $xmlrpc->_xh['headers'][$header_name] .= ', ' . trim($cookie); - else - $xmlrpc->_xh['headers'][$header_name] = 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; - $xmlrpc->_xh['cookies'][$tag] = array(); - $xmlrpc->_xh['cookies'][$cookiename]['value'] = urldecode($val); - } - else - { - if ($tag != 'value') - { - $xmlrpc->_xh['cookies'][$cookiename][$tag] = $val; - } - } - } - } - } - else - { - $xmlrpc->_xh['headers'][$header_name] = trim($arr[1]); - } - } - elseif(isset($header_name)) - { - /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $xmlrpc->_xh['headers'][$header_name] .= ' ' . trim($line); - } - } - - $data = substr($data, $bd); - - if($this->debug && count($xmlrpc->_xh['headers'])) - { - print '
';
-                foreach($xmlrpc->_xh['headers'] as $header => $value)
-                {
-                    print htmlentities("HEADER: $header: $value\n");
-                }
-                foreach($xmlrpc->_xh['cookies'] as $header => $value)
-                {
-                    print htmlentities("COOKIE: $header={$value['value']}\n");
-                }
-                print "
\n"; - } - - // if CURL was used for the call, http headers have been processed, - // and dechunking + reinflating have been carried out - if(!$headers_processed) - { - // Decode chunked encoding sent by http 1.1 servers - if(isset($xmlrpc->_xh['headers']['transfer-encoding']) && $xmlrpc->_xh['headers']['transfer-encoding'] == 'chunked') - { - if(!$data = decode_chunked($data)) - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['dechunk_fail'], $xmlrpc->xmlrpcstr['dechunk_fail']); - return $r; - } - } - - // Decode gzip-compressed stuff - // code shamelessly inspired from nusoap library by Dietrich Ayala - if(isset($xmlrpc->_xh['headers']['content-encoding'])) - { - $xmlrpc->_xh['headers']['content-encoding'] = str_replace('x-', '', $xmlrpc->_xh['headers']['content-encoding']); - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' || $xmlrpc->_xh['headers']['content-encoding'] == 'gzip') - { - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')) - { - if($xmlrpc->_xh['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - elseif($xmlrpc->_xh['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { - $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - else - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['decompress_fail'], $xmlrpc->xmlrpcstr['decompress_fail']); - return $r; - } - } - else - { - error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['cannot_decompress'], $xmlrpc->xmlrpcstr['cannot_decompress']); - return $r; - } - } - } - } // end of 'if needed, de-chunk, re-inflate response' - - // real stupid hack to avoid PHP complaining about returning NULL by ref - $r = null; - $r =& $r; - return $r; - } - - /** - * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object. - * @param string $data the xmlrpc response, eventually including http headers - * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding - * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' - * @return xmlrpcresp - */ - public function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') - { - $xmlrpc = Phpxmlrpc::instance(); - - if($this->debug) - { - //by maHo, replaced htmlspecialchars with htmlentities - print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; - } - - if($data == '') - { - error_log('XML-RPC: '.__METHOD__.': no response received from server.'); - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_data'], $xmlrpc->xmlrpcstr['no_data']); - return $r; - } - - $xmlrpc->_xh=array(); - - $raw_data = $data; - // parse the HTTP headers of the response, if present, and separate them from data - if(substr($data, 0, 4) == 'HTTP') - { - $r =& $this->parseResponseHeaders($data, $headers_processed); - if ($r) - { - // failed processing of HTTP response headers - // save into response obj the full payload received, for debugging - $r->raw_data = $data; - return $r; - } - } - else - { - $xmlrpc->_xh['headers'] = array(); - $xmlrpc->_xh['cookies'] = array(); - } - - if($this->debug) - { - $start = strpos($data, '', $start); - $comments = substr($data, $start, $end-$start); - print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; - } - } - - // 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 originally in PEARified version of the lib - $pos = strrpos($data, ''); - if($pos !== false) - { - $data = substr($data, 0, $pos+17); - } - - // if user wants back raw xml, give it to him - if ($return_type == 'xml') - { - $r = new xmlrpcresp($data, 0, '', 'xml'); - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - - // try to 'guestimate' the character encoding of the received response - $resp_encoding = guess_encoding(@$xmlrpc->_xh['headers']['content-type'], $data); - - $xmlrpc->_xh['ac']=''; - //$xmlrpc->_xh['qt']=''; //unused... - $xmlrpc->_xh['stack'] = array(); - $xmlrpc->_xh['valuestack'] = array(); - $xmlrpc->_xh['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc - $xmlrpc->_xh['isf_reason']=''; - $xmlrpc->_xh['rt']=''; // 'methodcall or 'methodresponse' - - // if response charset encoding is not known / supported, try to use - // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); - $resp_encoding = $xmlrpc->xmlrpc_defencoding; - } - $parser = xml_parser_create($resp_encoding); - 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_entitites() and setting xmlrpc_internalencoding - if (!in_array($xmlrpc->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, $xmlrpc->xmlrpc_internalencoding); - } - - if ($return_type == '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 - 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 xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], $xmlrpc->xmlrpcstr['invalid_return'].' ('.$errstr.')'); - xml_parser_free($parser); - if($this->debug) - { - print $errstr; - } - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } - xml_parser_free($parser); - // second error check: xml well formed but not xml-rpc compliant - if ($xmlrpc->_xh['isf'] > 1) - { - if ($this->debug) - { - /// @todo echo something for user? - } - - $r = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return'] . ' ' . $xmlrpc->_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 ($return_type == 'xmlrpcvals' && !is_object($xmlrpc->_xh['value'])) - { - // something odd has happened - // and it's time to generate a client side error - // indicating something odd went on - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['invalid_return'], - $xmlrpc->xmlrpcstr['invalid_return']); - } - else - { - if ($this->debug) - { - print "
---PARSED---\n";
-                // somehow htmlentities chokes on var_export, and some full html string...
-                //print htmlentitites(var_export($xmlrpc->_xh['value'], true));
-                print htmlspecialchars(var_export($xmlrpc->_xh['value'], true));
-                print "\n---END---
"; - } - - // note that using =& will raise an error if $xmlrpc->_xh['st'] does not generate an object. - $v =& $xmlrpc->_xh['value']; - - if($xmlrpc->_xh['isf']) - { - /// @todo we should test here if server sent an int and a string, - /// and/or coerce them into such... - if ($return_type == 'xmlrpcvals') - { - $errno_v = $v->structmem('faultCode'); - $errstr_v = $v->structmem('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 xmlrpcresp(0, $errno, $errstr); - } - else - { - $r=new xmlrpcresp($v, 0, '', $return_type); - } - } - - $r->hdrs = $xmlrpc->_xh['headers']; - $r->_cookies = $xmlrpc->_xh['cookies']; - $r->raw_data = $raw_data; - return $r; - } -} diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.inc new file mode 100644 index 00000000..7daf1c44 --- /dev/null +++ b/lib/xmlrpcs.inc @@ -0,0 +1,56 @@ + + +// 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 +{ +} + +/* Expose as global functions the ones which are now class methods */ + +function xmlrpc_debugmsg($m) +{ + PhpXmlRpc\Server::xmlrpc_debugmsg($m); +} \ No newline at end of file diff --git a/lib/xmlrpc_client.php b/src/Client.php similarity index 93% rename from lib/xmlrpc_client.php rename to src/Client.php index 88853883..a31c7327 100644 --- a/lib/xmlrpc_client.php +++ b/src/Client.php @@ -1,6 +1,8 @@ accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); // initialize user_agent string - $this->user_agent = $xmlrpc->xmlrpcName . ' ' . $xmlrpc->xmlrpcVersion; + $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion; } /** @@ -321,7 +321,7 @@ function SetUserAgent( $agentstring ) /** * Send an xmlrpc request - * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request + * @param mixed $msg The request object, or an array of requests for using multicall, or the complete xml representation of a request * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used * @return xmlrpcresp @@ -343,7 +343,7 @@ public function& send($msg, $timeout=0, $method='') } elseif(is_string($msg)) { - $n = new xmlrpcmsg(''); + $n = new Message(''); $n->payload = $msg; $msg = $n; } @@ -353,7 +353,7 @@ public function& send($msg, $timeout=0, $method='') if($method == 'https') { - $r =& $this->sendPayloadHTTPS( + $r = $this->sendPayloadHTTPS( $msg, $this->server, $this->port, @@ -377,7 +377,7 @@ public function& send($msg, $timeout=0, $method='') } elseif($method == 'http11') { - $r =& $this->sendPayloadCURL( + $r = $this->sendPayloadCURL( $msg, $this->server, $this->port, @@ -400,7 +400,7 @@ public function& send($msg, $timeout=0, $method='') } else { - $r =& $this->sendPayloadHTTP10( + $r = $this->sendPayloadHTTP10( $msg, $this->server, $this->port, @@ -419,12 +419,10 @@ public function& send($msg, $timeout=0, $method='') return $r; } - private function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, + private function sendPayloadHTTP10($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) { - $xmlrpc = Phpxmlrpc::instance(); - if($port==0) { $port=80; @@ -575,7 +573,7 @@ private function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, else { $this->errstr='Connect error: '.$this->errstr; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); return $r; } @@ -583,7 +581,7 @@ private function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, { fclose($fp); $this->errstr='Write error'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['http_error'], $this->errstr); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr); return $r; } else @@ -601,17 +599,17 @@ private function &sendPayloadHTTP10($msg, $server, $port, $timeout=0, $ipd.=fread($fp, 32768); } while(!feof($fp)); fclose($fp); - $r =& $msg->parseResponse($ipd, false, $this->return_type); + $r = $msg->parseResponse($ipd, false, $this->return_type); return $r; } - private function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', + private function sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $keepalive=false, $key='', $keypass='') { - $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, + $r = $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); return $r; @@ -622,17 +620,15 @@ private function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username=' * Requires curl to be built into PHP * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! */ - private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', + private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', $keepalive=false, $key='', $keypass='') { - $xmlrpc = Phpxmlrpc::instance(); - if(!function_exists('curl_init')) { $this->errstr='CURL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_curl'], $xmlrpc->xmlrpcstr['no_curl']); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); return $r; } if($method == 'https') @@ -641,7 +637,7 @@ private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='' ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) { $this->errstr='SSL unavailable on this install'; - $r=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['no_ssl'], $xmlrpc->xmlrpcstr['no_ssl']); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); return $r; } } @@ -873,7 +869,7 @@ private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='' if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? { $this->errstr='no response'; - $resp=new xmlrpcresp(0, $xmlrpc->xmlrpcerr['curl_fail'], $xmlrpc->xmlrpcstr['curl_fail']. ': '. curl_error($curl)); + $resp=new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail']. ': '. curl_error($curl)); curl_close($curl); if($keepalive) { @@ -886,9 +882,9 @@ private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='' { curl_close($curl); } - $resp =& $msg->parseResponse($result, true, $this->return_type); + $resp = $msg->parseResponse($result, true, $this->return_type); // if we got back a 302, we can not reuse the curl handle for later calls - if($resp->faultCode() == $xmlrpc->xmlrpcerr['http_error'] && $keepalive) + if($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepalive) { curl_close($curl); $this->xmlrpc_curl_handle = null; @@ -898,7 +894,7 @@ private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='' } /** - * Send an array of request messages and return an array of responses. + * Send an array of requests and return an array of responses. * Unless $this->no_multicall has been set to true, it will try first * to use one single xmlrpc call to server method system.multicall, and * revert to sending many successive calls in case of failure. @@ -920,8 +916,6 @@ private function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='' */ public function multicall($msgs, $timeout=0, $method='', $fallback=true) { - $xmlrpc = Phpxmlrpc::instance(); - if ($method == '') { $method = $this->method; @@ -951,7 +945,7 @@ public function multicall($msgs, $timeout=0, $method='', $fallback=true) } else { - $result = new xmlrpcresp(0, $xmlrpc->xmlrpcerr['multicall_error'], $xmlrpc->xmlrpcstr['multicall_error']); + $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']); } } } @@ -970,7 +964,7 @@ public function multicall($msgs, $timeout=0, $method='', $fallback=true) // emulate multicall via multiple requests foreach($msgs as $msg) { - $results[] =& $this->send($msg, $timeout, $method); + $results[] = $this->send($msg, $timeout, $method); } } else @@ -993,25 +987,25 @@ public function multicall($msgs, $timeout=0, $method='', $fallback=true) */ private function _try_multicall($msgs, $timeout, $method) { - // Construct multicall message + // Construct multicall request $calls = array(); foreach($msgs as $msg) { - $call['methodName'] = new xmlrpcval($msg->method(),'string'); + $call['methodName'] = new Value($msg->method(),'string'); $numParams = $msg->getNumParams(); $params = array(); for($i = 0; $i < $numParams; $i++) { $params[$i] = $msg->getParam($i); } - $call['params'] = new xmlrpcval($params, 'array'); - $calls[] = new xmlrpcval($call, 'struct'); + $call['params'] = new Value($params, 'array'); + $calls[] = new Value($call, 'struct'); } - $multicall = new xmlrpcmsg('system.multicall'); - $multicall->addParam(new xmlrpcval($calls, 'array')); + $multicall = new Request('system.multicall'); + $multicall->addParam(new Value($calls, 'array')); // Attempt RPC call - $result =& $this->send($multicall, $timeout, $method); + $result = $this->send($multicall, $timeout, $method); if($result->faultCode() != 0) { @@ -1055,7 +1049,7 @@ private function _try_multicall($msgs, $timeout, $method) return false; // Bad value } // Normal return value - $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals'); + $response[$i] = new Response($val[0], 0, '', 'phpvals'); break; case 2: /// @todo remove usage of @: it is apparently quite slow @@ -1069,7 +1063,7 @@ private function _try_multicall($msgs, $timeout, $method) { return false; } - $response[$i] = new xmlrpcresp(0, $code, $str); + $response[$i] = new Response(0, $code, $str); break; default: return false; @@ -1102,7 +1096,7 @@ private function _try_multicall($msgs, $timeout, $method) return false; // Bad value } // Normal return value - $response[$i] = new xmlrpcresp($val->arraymem(0)); + $response[$i] = new Response($val->arraymem(0)); break; case 'struct': $code = $val->structmem('faultCode'); @@ -1115,7 +1109,7 @@ private function _try_multicall($msgs, $timeout, $method) { return false; } - $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval()); + $response[$i] = new Response(0, $code->scalarval(), $str->scalarval()); break; default: return false; diff --git a/src/Encoder.php b/src/Encoder.php new file mode 100644 index 00000000..f464f822 --- /dev/null +++ b/src/Encoder.php @@ -0,0 +1,420 @@ +kindOf()) + { + case 'scalar': + if (in_array('extension_api', $options)) + { + reset($xmlrpc_val->me); + list($typ,$val) = each($xmlrpc_val->me); + switch ($typ) + { + case 'dateTime.iso8601': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->type = 'datetime'; + $xmlrpc_val->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val); + return $xmlrpc_val; + case 'base64': + $xmlrpc_val->scalar = $val; + $xmlrpc_val->type = $typ; + return $xmlrpc_val; + default: + return $xmlrpc_val->scalarval(); + } + } + if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') + { + // we return a Datetime object instead of a string + // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, + // we cater to all 3 cases here + $out = $xmlrpc_val->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 $xmlrpc_val->scalarval(); + case 'array': + $size = $xmlrpc_val->arraysize(); + $arr = array(); + for($i = 0; $i < $size; $i++) + { + $arr[] = $this->decode($xmlrpc_val->arraymem($i), $options); + } + return $arr; + case 'struct': + $xmlrpc_val->structreset(); + // 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 xmlrpcval instead of + // presence of _php_class to detect what we can do? + if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' + && class_exists($xmlrpc_val->_php_class)) + { + $obj = @new $xmlrpc_val->_php_class; + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $obj->$key = $this->decode($value, $options); + } + return $obj; + } + else + { + $arr = array(); + while(list($key,$value)=$xmlrpc_val->structeach()) + { + $arr[$key] = $this->decode($value, $options); + } + return $arr; + } + case 'msg': + $paramcount = $xmlrpc_val->getNumParams(); + $arr = array(); + for($i = 0; $i < $paramcount; $i++) + { + $arr[] = $this->decode($xmlrpc_val->getParam($i)); + } + return $arr; + } + } + + /** + * Takes native php types and encodes them into xmlrpc PHP object format. + * It will not re-encode xmlrpcval 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 $php_val the value to be converted into an xmlrpcval object + * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * @return xmlrpcval + */ + function encode($php_val, $options=array()) + { + $type = gettype($php_val); + 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}$/', $php_val)) + $xmlrpc_val = new Value($php_val, Value::$xmlrpcDateTime); + else + $xmlrpc_val = new Value($php_val, Value::$xmlrpcString); + break; + case 'integer': + $xmlrpc_val = new Value($php_val, Value::$xmlrpcInt); + break; + case 'double': + $xmlrpc_val = new Value($php_val, Value::$xmlrpcDouble); + break; + // + // Add support for encoding/decoding of booleans, since they are supported in PHP + case 'boolean': + $xmlrpc_val = new Value($php_val, Value::$xmlrpcBoolean); + break; + // + 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($php_val), range(0, count($php_val)-1)); + // but execution time skyrockets! + $j = 0; + $arr = array(); + $ko = false; + foreach($php_val as $key => $val) + { + $arr[$key] = $this->encode($val, $options); + if(!$ko && $key !== $j) + { + $ko = true; + } + $j++; + } + if($ko) + { + $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); + } + else + { + $xmlrpc_val = new Value($arr, Value::$xmlrpcArray); + } + break; + case 'object': + if(is_a($php_val, 'xmlrpcval')) + { + $xmlrpc_val = $php_val; + } + else if(is_a($php_val, 'DateTime')) + { + $xmlrpc_val = new Value($php_val->format('Ymd\TH:i:s'), Value::$xmlrpcStruct); + } + else + { + $arr = array(); + reset($php_val); + while(list($k,$v) = each($php_val)) + { + $arr[$k] = $this->encode($v, $options); + } + $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); + if (in_array('encode_php_objs', $options)) + { + // let's save original class name into xmlrpcval: + // might be useful later on... + $xmlrpc_val->_php_class = get_class($php_val); + } + } + break; + case 'NULL': + if (in_array('extension_api', $options)) + { + $xmlrpc_val = new Value('', Value::$xmlrpcString); + } + else if (in_array('null_extension', $options)) + { + $xmlrpc_val = new Value('', Value::$xmlrpcNull); + } + else + { + $xmlrpc_val = new Value(); + } + break; + case 'resource': + if (in_array('extension_api', $options)) + { + $xmlrpc_val = new Value((int)$php_val, Value::$xmlrpcInt); + } + else + { + $xmlrpc_val = new Value(); + } + // catch "user function", "unknown type" + default: + // giancarlo pinerolo + // it has to return + // an empty object in case, not a boolean. + $xmlrpc_val = new Value(); + break; + } + return $xmlrpc_val; + } + + /** + * Convert the xml representation of a method response, method request or single + * xmlrpc value into the appropriate object (a.k.a. deserialize) + * @param string $xml_val + * @param array $options + * @return mixed false on error, or an instance of either Value, Request or Response + */ + function decode_xml($xml_val, $options=array()) + { + + /// @todo 'guestimate' encoding + $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, $xml_val, 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->structmem('faultCode'); + $vs = $v->structmem('faultString'); + $r = new Response(0, $vc->scalarval(), $vs->scalarval()); + } + else + { + $r = new Response($v); + } + return $r; + case 'methodcall': + $m = new Request($xmlRpcParser->_xh['method']); + for($i=0; $i < count($xmlRpcParser->_xh['params']); $i++) + { + $m->addParam($xmlRpcParser->_xh['params'][$i]); + } + return $m; + case 'value': + return $xmlRpcParser->_xh['value']; + default: + return false; + } + } + + +/** + * 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 unconforming (legacy?) clients/servers, + * which will be most probably using UTF-8 anyway... + * + * @param string $httpheader the http Content-type header + * @param string $xmlchunk xml content buffer + * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) + * @return string + * + * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! + */ +function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=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 cointrol 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 + // NB: we favour finding an encoding that is compatible with what we can process + if(extension_loaded('mbstring')) + { + if($encoding_prefs) + { + $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + } + 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; + } +} + +} \ No newline at end of file diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php new file mode 100644 index 00000000..db301cc7 --- /dev/null +++ b/src/Helper/Charset.php @@ -0,0 +1,246 @@ + 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( + '€', '?', '‚', 'ƒ', + '„', '…', '†', '‡', + 'ˆ', '‰', 'Š', '‹', + 'Œ', '?', 'Ž', '?', + '?', '‘', '’', '“', + '”', '•', '–', '—', + '˜', '™', 'š', '›', + 'œ', '?', 'ž', 'Ÿ' + )); + */ + + 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 $src_encoding + * @param string $dest_encoding + * @return string + */ + public function encode_entities($data, $src_encoding='', $dest_encoding='') + { + if ($src_encoding == '') + { + // lame, but we know no better... + $src_encoding = PhpXmlRpc::$xmlrpc_internalencoding; + } + + switch(strtoupper($src_encoding.'_'.$dest_encoding)) + { + case 'ISO-8859-1_': + case 'ISO-8859-1_US-ASCII': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escaped_data); + break; + case 'ISO-8859-1_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = utf8_encode($escaped_data); + 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': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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 + $escaped_data = ''; + // be kind to users creating string xmlrpcvals out of different php types + $data = (string) $data; + $ns = strlen ($data); + for ($nn = 0; $nn < $ns; $nn++) + { + $ch = $data[$nn]; + $ii = ord($ch); + //1 7 0bbbbbbb (127) + if ($ii < 128) + { + /// @todo shall we replace this with a (supposedly) faster str_replace? + switch($ii){ + case 34: + $escaped_data .= '"'; + break; + case 38: + $escaped_data .= '&'; + break; + case 39: + $escaped_data .= '''; + break; + case 60: + $escaped_data .= '<'; + break; + case 62: + $escaped_data .= '>'; + break; + default: + $escaped_data .= $ch; + } // switch + } + //2 11 110bbbbb 10bbbbbb (2047) + else if ($ii>>5 == 6) + { + $b1 = ($ii & 31); + $ii = ord($data[$nn+1]); + $b2 = ($ii & 63); + $ii = ($b1 * 64) + $b2; + $ent = sprintf ('&#%d;', $ii); + $escaped_data .= $ent; + $nn += 1; + } + //3 16 1110bbbb 10bbbbbb 10bbbbbb + else if ($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); + $escaped_data .= $ent; + $nn += 2; + } + //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + else if ($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); + $escaped_data .= $ent; + $nn += 3; + } + } + break; + /* + case 'CP1252_': + case 'CP1252_US-ASCII': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escaped_data = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escaped_data); + $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); + break; + case 'CP1252_UTF-8': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) + $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); + $escaped_data = utf8_encode($escaped_data); + break; + case 'CP1252_ISO-8859-1': + $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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... + $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); + break; + */ + default: + $escaped_data = ''; + error_log("Converting from $src_encoding to $dest_encoding: not supported..."); + } + return $escaped_data; + } + + /** + * 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 is_valid_charset($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; + } + } + +} \ No newline at end of file diff --git a/src/Helper/Date.php b/src/Helper/Date.php new file mode 100644 index 00000000..9501a9b9 --- /dev/null +++ b/src/Helper/Date.php @@ -0,0 +1,68 @@ + 0) + { + $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); + + // 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); + $chunk_size = hexdec( trim($temp) ); + $chunkstart = $chunkend; + } + return $new; + } + +} \ No newline at end of file diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php new file mode 100644 index 00000000..6803ebf4 --- /dev/null +++ b/src/Helper/XMLParser.php @@ -0,0 +1,488 @@ + '', + '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'), + '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 + */ + function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=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' && !$accept_single_vals)) + { + $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 '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 + $cur_val = array(); + $cur_val['values'] = array(); + $cur_val['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'])) + { + $cur_val['php_class'] = $attrs['PHP_CLASS']; + } + $this->_xh['valuestack'][] = $cur_val; + $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 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 + */ + function xmlrpc_se_any($parser, $name, $attrs) + { + $this->xmlrpc_se($parser, $name, $attrs, true); + } + + /** + * xml parser handler function for close element tags + */ + function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = 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 == $curr_elem. + // we also checked for proper nesting at start of elements... + $curr_elem = array_pop($this->_xh['stack']); + + switch($name) + { + case 'VALUE': + // This if() detects if no scalar was inside + if ($this->_xh['vt']=='value') + { + $this->_xh['value']=$this->_xh['ac']; + $this->_xh['vt']=Value::$xmlrpcString; + } + + if ($rebuild_xmlrpcvals) + { + // 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 '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: 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: 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-. 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: 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/INT + // we must check that only 0123456789- 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: 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['ac']=''; // is this necessary? + $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': + //$this->_xh['ac']=''; // is this necessary? + // 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: missing VALUE inside STRUCT in received xml'); + break; + case 'DATA': + //$this->_xh['ac']=''; // is this necessary? + $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 + $curr_val = array_pop($this->_xh['valuestack']); + $this->_xh['value'] = $curr_val['values']; + $this->_xh['vt']=strtolower($name); + if (isset($curr_val['php_class'])) + { + $this->_xh['php_class'] = $curr_val['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: 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 + */ + function xmlrpc_ee_fast($parser, $name) + { + $this->xmlrpc_ee($parser, $name, false); + } + + /** + * xml parser handler function for character data + */ + 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) + { + // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 + //if($this->_xh['lv']==1) + //{ + // if we've found text and we're just in a then + // say we've found a value + //$this->_xh['lv']=2; + //} + // we always initialize the accumulator before starting parsing, anyway... + //if(!@isset($this->_xh['ac'])) + //{ + // $this->_xh['ac'] = ''; + //} + $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... + */ + 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) == ';') + { + // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 + //if($this->_xh['lv']==1) + //{ + // $this->_xh['lv']=2; + //} + $this->_xh['ac'].=$data; + } + } + return true; + } + +} \ No newline at end of file diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php new file mode 100644 index 00000000..201ba635 --- /dev/null +++ b/src/PhpXmlRpc.php @@ -0,0 +1,86 @@ +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 + // or is not supported + public static $xmlrpc_defencoding = "UTF-8"; + + // 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 + public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? + + public static $xmlrpcName = "XML-RPC for PHP"; + public static $xmlrpcVersion = "4.0.0.beta"; + + // 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 and values + public static $xmlrpc_null_extension = false; + + // set to TRUE to enable encoding of php NULL values to instead of + public static $xmlrpc_null_apache_encoding = false; + + public static $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions"; +} diff --git a/src/Request.php b/src/Request.php new file mode 100644 index 00000000..c341407f --- /dev/null +++ b/src/Request.php @@ -0,0 +1,608 @@ +methodname = $methodName; + foreach($params as $param) + { + $this->addParam($param); + } + } + + private function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n\n"; + } + else + { + return "\n\n"; + } + } + + private function xml_footer() + { + return ''; + } + + /** + * Kept the old name even if class was renamed, for compatibility + * @return string + */ + private function kindOf() + { + return 'msg'; + } + + public function createPayload($charset_encoding='') + { + if ($charset_encoding != '') + $this->content_type = 'text/xml; charset=' . $charset_encoding; + else + $this->content_type = 'text/xml'; + $this->payload=$this->xml_header($charset_encoding); + $this->payload.='' . $this->methodname . "\n"; + $this->payload.="\n"; + foreach($this->params as $p) + { + $this->payload.="\n" . $p->serialize($charset_encoding) . + "\n"; + } + $this->payload.="\n"; + $this->payload.=$this->xml_footer(); + } + + /** + * Gets/sets the xmlrpc method to be invoked + * @param string $meth 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 $charset_encoding + * @return string the xml representation of the message, xml prologue included + */ + public function serialize($charset_encoding='') + { + $this->createPayload($charset_encoding); + return $this->payload; + } + + /** + * Add a parameter to the list of parameters to be used upon method invocation + * @param Value $par + * @return boolean false on failure + */ + public function addParam($param) + { + // add check: do not add to self params which are not xmlrpcvals + 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 messge. + * @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 axmlrpc 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; + } + //fclose($fp); + return $this->parseResponse($ipd); + } + + /** + * Parses HTTP headers and separates them from data. + * @return null|Response null on success, or a Response on error + */ + private function parseResponseHeaders(&$data, $headers_processed=false) + { + $this->httpResponse['headers'] = array(); + $this->httpResponse['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'); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + return $r; + } + } + + // 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); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (' . $errstr . ')'); + return $r; + } + + // 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) + { + $header_name = 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'][$header_name] + /// instead of replacing it for those... + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') + { + if ($header_name == '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($this->httpResponse['headers'][$header_name])) + $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie); + else + $this->httpResponse['headers'][$header_name] = 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; + $this->httpResponse['cookies'][$tag] = array(); + $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val); + } + else + { + if ($tag != 'value') + { + $this->httpResponse['cookies'][$cookiename][$tag] = $val; + } + } + } + } + } + else + { + $this->httpResponse['headers'][$header_name] = trim($arr[1]); + } + } + elseif(isset($header_name)) + { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $this->httpResponse['headers'][$header_name] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + /// @todo when in CLI mode, do not html-encode the output + if($this->debug && count($this->httpResponse['headers'])) + { + print "\n"; + foreach($this->httpResponse['headers'] as $header => $value) + { + print htmlentities("HEADER: $header: $value\n"); + } + foreach($this->httpResponse['cookies'] as $header => $value) + { + print htmlentities("COOKIE: $header={$value['value']}\n"); + } + print "\n"; + } + + // if CURL was used for the call, http headers have been processed, + // and dechunking + reinflating have been carried out + if(!$headers_processed) + { + // Decode chunked encoding sent by http 1.1 servers + if(isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') + { + if(!$data = Http::decode_chunked($data)) + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']); + return $r; + } + } + + // Decode gzip-compressed stuff + // code shamelessly inspired from nusoap library by Dietrich Ayala + if(isset($this->httpResponse['headers']['content-encoding'])) + { + $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']); + if($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate')) + { + if($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + elseif($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug) + print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; + } + else + { + error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']); + return $r; + } + } + else + { + error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']); + return $r; + } + } + } + } // end of 'if needed, de-chunk, re-inflate response' + + return null; + } + + /** + * Parse the xmlrpc response contained in the string $data and return a Response object. + * @param string $data the xmlrpc response, eventually including http headers + * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding + * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @return Response + */ + public function parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + { + if($this->debug) + { + // by maHo, replaced htmlspecialchars with htmlentities + print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; + } + + $this->httpResponse = array(); + $this->httpResponse['raw_data'] = $data; + $this->httpResponse['headers'] = array(); + $this->httpResponse['cookies'] = array(); + + if($data == '') + { + error_log('XML-RPC: '.__METHOD__.': no response received from server.'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']); + return $r; + } + + // parse the HTTP headers of the response, if present, and separate them from data + if(substr($data, 0, 4) == 'HTTP') + { + $r = $this->parseResponseHeaders($data, $headers_processed); + if ($r) + { + // failed processing of HTTP response headers + // save into response obj the full payload received, for debugging + $r->raw_data = $data; + return $r; + } + } + + if($this->debug) + { + $start = strpos($data, '', $start); + $comments = substr($data, $start, $end-$start); + print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; + } + } + + // 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 originally in PEARified version of the lib + $pos = strrpos($data, ''); + if($pos !== false) + { + $data = substr($data, 0, $pos+17); + } + + // if user wants back raw xml, give it to him + if ($return_type == '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; + } + + // try to 'guestimate' the character encoding of the received response + $resp_encoding = guess_encoding(@$this->httpResponse['headers']['content-type'], $data); + + // if response charset encoding is not known / supported, try to use + // the default encoding and parse the xml anyway, but log a warning... + if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); + $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding; + } + $parser = xml_parser_create($resp_encoding); + 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_entitites() 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 ($return_type == '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 + 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 ($return_type == '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) + { + print "
---PARSED---\n";
+                // somehow htmlentities chokes on var_export, and some full html string...
+                //print htmlentitites(var_export($xmlRpcParser->_xh['value'], true));
+                print htmlspecialchars(var_export($xmlRpcParser->_xh['value'], true));
+                print "\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 ($return_type == 'xmlrpcvals') + { + $errno_v = $v->structmem('faultCode'); + $errstr_v = $v->structmem('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, '', $return_type); + } + } + + $r->hdrs = $this->httpResponse['headers']; + $r->_cookies = $this->httpResponse['cookies']; + $r->raw_data = $this->httpResponse['raw_data'];; + return $r; + } +} diff --git a/lib/xmlrpcresp.php b/src/Response.php similarity index 91% rename from lib/xmlrpcresp.php rename to src/Response.php index 22c99097..5f0f6ec7 100644 --- a/lib/xmlrpcresp.php +++ b/src/Response.php @@ -1,6 +1,10 @@ val) && is_a($this->val, 'xmlrpcval')) + if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) { $this->valtyp = 'xmlrpcvals'; } else if (is_string($this->val)) { $this->valtyp = 'xml'; - } else { @@ -111,28 +114,27 @@ public function cookies() */ public function serialize($charset_encoding='') { - $xmlrpc = Phpxmlrpc::instance(); - if ($charset_encoding != '') $this->content_type = 'text/xml; charset=' . $charset_encoding; else $this->content_type = 'text/xml'; - if ($xmlrpc->xmlrpc_null_apache_encoding) + if (PhpXmlRpc::$xmlrpc_null_apache_encoding) { - $result = "xmlrpc_null_apache_encoding_ns."\">\n"; + $result = "\n"; } else { - $result = "\n"; + $result = "\n"; } if($this->errno) { // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients // by xml-encoding non ascii chars + $charsetEncoder = $result .= "\n" . "\nfaultCode\n" . $this->errno . "\n\n\nfaultString\n" . -xmlrpc_encode_entitites($this->errstr, $xmlrpc->xmlrpc_internalencoding, $charset_encoding) . "\n\n" . +Charset::instance()->encode_entitites($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" . "\n
\n"; } else diff --git a/lib/xmlrpc_server.php b/src/Server.php similarity index 62% rename from lib/xmlrpc_server.php rename to src/Server.php index 3236a85c..a3cde97e 100644 --- a/lib/xmlrpc_server.php +++ b/src/Server.php @@ -1,1238 +1,1178 @@ - - -// 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. - - -// XML RPC Server class -// requires: xmlrpc.inc - -$GLOBALS['xmlrpcs_capabilities'] = array( - // xmlrpc spec: always supported - 'xmlrpc' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'), - // if we support system.xxx functions, we always support multicall, too... - // Note that, as of 2006/09/17, the following URL does not respond anymore - 'system.multicall' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'), - // introspection: version 2! we support 'mixed', too - 'introspection' => new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), - 'specVersion' => new xmlrpcval(2, 'int') - ), 'struct') -); - -/* Functions that implement system.XXX methods of xmlrpc servers */ -$_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct'])); -$_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to'; -$_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec')); -function _xmlrpcs_getCapabilities($server, $m=null) -{ - $outAr = $GLOBALS['xmlrpcs_capabilities']; - // NIL extension - if ($GLOBALS['xmlrpc_null_extension']) { - $outAr['nil'] = new xmlrpcval(array( - 'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), - 'specVersion' => new xmlrpcval(1, 'int') - ), 'struct'); - } - return new xmlrpcresp(new xmlrpcval($outAr, 'struct')); -} - -// listMethods: signature was either a string, or nothing. -// The useless string variant has been removed -$_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 -{ - - $outAr=array(); - foreach($server->dmap as $key => $val) - { - $outAr[]=new xmlrpcval($key, 'string'); - } - if($server->allow_system_funcs) - { - foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) - { - $outAr[]=new xmlrpcval($key, 'string'); - } - } - return new xmlrpcresp(new xmlrpcval($outAr, 'array')); -} - -$_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) -{ - // let accept as parameter both an xmlrpcval or string - if (is_object($m)) - { - $methName=$m->getParam(0); - $methName=$methName->scalarval(); - } - else - { - $methName=$m; - } - if(strpos($methName, "system.") === 0) - { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; - } - else - { - $dmap=$server->dmap; $sysCall=0; - } - if(isset($dmap[$methName])) - { - if(isset($dmap[$methName]['signature'])) - { - $sigs=array(); - foreach($dmap[$methName]['signature'] as $inSig) - { - $cursig=array(); - foreach($inSig as $sig) - { - $cursig[]=new xmlrpcval($sig, 'string'); - } - $sigs[]=new xmlrpcval($cursig, 'array'); - } - $r=new xmlrpcresp(new xmlrpcval($sigs, 'array')); - } - else - { - // NB: according to the official docs, we should be returning a - // "none-array" here, which means not-an-array - $r=new xmlrpcresp(new xmlrpcval('undef', 'string')); - } - } - else - { - $r=new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); - } - return $r; -} - -$_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) -{ - // let accept as parameter both an xmlrpcval or string - if (is_object($m)) - { - $methName=$m->getParam(0); - $methName=$methName->scalarval(); - } - else - { - $methName=$m; - } - if(strpos($methName, "system.") === 0) - { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; - } - else - { - $dmap=$server->dmap; $sysCall=0; - } - if(isset($dmap[$methName])) - { - if(isset($dmap[$methName]['docstring'])) - { - $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string'); - } - else - { - $r=new xmlrpcresp(new xmlrpcval('', 'string')); - } - } - else - { - $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); - } - return $r; -} - -$_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_error($err) -{ - if(is_string($err)) - { - $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; - $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; - } - else - { - $code = $err->faultCode(); - $str = $err->faultString(); - } - $struct = array(); - $struct['faultCode'] = new xmlrpcval($code, 'int'); - $struct['faultString'] = new xmlrpcval($str, 'string'); - return new xmlrpcval($struct, 'struct'); -} - -function _xmlrpcs_multicall_do_call($server, $call) -{ - if($call->kindOf() != 'struct') - { - return _xmlrpcs_multicall_error('notstruct'); - } - $methName = @$call->structmem('methodName'); - if(!$methName) - { - return _xmlrpcs_multicall_error('nomethod'); - } - if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') - { - return _xmlrpcs_multicall_error('notstring'); - } - if($methName->scalarval() == 'system.multicall') - { - return _xmlrpcs_multicall_error('recursion'); - } - - $params = @$call->structmem('params'); - if(!$params) - { - return _xmlrpcs_multicall_error('noparams'); - } - if($params->kindOf() != 'array') - { - return _xmlrpcs_multicall_error('notarray'); - } - $numParams = $params->arraysize(); - - $msg = new xmlrpcmsg($methName->scalarval()); - for($i = 0; $i < $numParams; $i++) - { - if(!$msg->addParam($params->arraymem($i))) - { - $i++; - return _xmlrpcs_multicall_error(new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); - } - } - - $result = $server->execute($msg); - - if($result->faultCode() != 0) - { - return _xmlrpcs_multicall_error($result); // Method returned fault. - } - - return new xmlrpcval(array($result->value()), 'array'); -} - -function _xmlrpcs_multicall_do_call_phpvals($server, $call) -{ - if(!is_array($call)) - { - return _xmlrpcs_multicall_error('notstruct'); - } - if(!array_key_exists('methodName', $call)) - { - return _xmlrpcs_multicall_error('nomethod'); - } - if (!is_string($call['methodName'])) - { - return _xmlrpcs_multicall_error('notstring'); - } - if($call['methodName'] == 'system.multicall') - { - return _xmlrpcs_multicall_error('recursion'); - } - if(!array_key_exists('params', $call)) - { - return _xmlrpcs_multicall_error('noparams'); - } - if(!is_array($call['params'])) - { - return _xmlrpcs_multicall_error('notarray'); - } - - // this is a real dirty and simplistic hack, since we might have received a - // base64 or datetime values, but they will be listed as strings here... - $numParams = count($call['params']); - $pt = array(); - foreach($call['params'] as $val) - $pt[] = php_2_xmlrpc_type(gettype($val)); - - $result = $server->execute($call['methodName'], $call['params'], $pt); - - if($result->faultCode() != 0) - { - return _xmlrpcs_multicall_error($result); // Method returned fault. - } - - return new xmlrpcval(array($result->value()), 'array'); -} - -function _xmlrpcs_multicall($server, $m) -{ - $result = array(); - // let accept a plain list of php parameters, beside a single xmlrpc msg object - if (is_object($m)) - { - $calls = $m->getParam(0); - $numCalls = $calls->arraysize(); - for($i = 0; $i < $numCalls; $i++) - { - $call = $calls->arraymem($i); - $result[$i] = _xmlrpcs_multicall_do_call($server, $call); - } - } - else - { - $numCalls=count($m); - for($i = 0; $i < $numCalls; $i++) - { - $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); - } - } - - return new xmlrpcresp(new xmlrpcval($result, 'array')); -} - -$GLOBALS['_xmlrpcs_dmap']=array( - 'system.listMethods' => array( - 'function' => '_xmlrpcs_listMethods', - 'signature' => $_xmlrpcs_listMethods_sig, - 'docstring' => $_xmlrpcs_listMethods_doc, - 'signature_docs' => $_xmlrpcs_listMethods_sdoc), - 'system.methodHelp' => array( - 'function' => '_xmlrpcs_methodHelp', - 'signature' => $_xmlrpcs_methodHelp_sig, - 'docstring' => $_xmlrpcs_methodHelp_doc, - 'signature_docs' => $_xmlrpcs_methodHelp_sdoc), - 'system.methodSignature' => array( - 'function' => '_xmlrpcs_methodSignature', - 'signature' => $_xmlrpcs_methodSignature_sig, - 'docstring' => $_xmlrpcs_methodSignature_doc, - 'signature_docs' => $_xmlrpcs_methodSignature_sdoc), - 'system.multicall' => array( - 'function' => '_xmlrpcs_multicall', - 'signature' => $_xmlrpcs_multicall_sig, - 'docstring' => $_xmlrpcs_multicall_doc, - 'signature_docs' => $_xmlrpcs_multicall_sdoc), - 'system.getCapabilities' => array( - 'function' => '_xmlrpcs_getCapabilities', - 'signature' => $_xmlrpcs_getCapabilities_sig, - 'docstring' => $_xmlrpcs_getCapabilities_doc, - 'signature_docs' => $_xmlrpcs_getCapabilities_sdoc) -); - -$GLOBALS['_xmlrpcs_occurred_errors'] = ''; -$GLOBALS['_xmlrpcs_prev_ehandler'] = ''; - -/** -* Error handler used to track errors that occur during server-side execution of PHP code. -* This allows to report back to the client whether an internal error has occurred or not -* using an xmlrpc response object, instead of letting the client deal with the html junk -* that a PHP execution error on the server generally entails. -* -* NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. -* -*/ -function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) -{ - // obey the @ protocol - if (error_reporting() == 0) - return; - - //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) - if($errcode != E_STRICT) - { - $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n"; - } - // Try to avoid as much as possible disruption to the previous error handling - // mechanism in place - if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') - { - // The previous error handler was the default: all we should do is log error - // to the default error log (if level high enough) - if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) - { - error_log($errstring); - } - } - else - { - // Pass control on to previous error handler, trying to avoid loops... - if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler') - { - // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers - if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) - { - // the following works both with static class methods and plain object methods as error handler - call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); - } - else - { - $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); - } - } - } -} - -$GLOBALS['_xmlrpc_debuginfo']=''; - -/** -* Add a string to the debug info that can be later seralized by the server -* as part of the response message. -* Note that for best compatibility, the debug string should be encoded using -* the $GLOBALS['xmlrpc_internalencoding'] character set. -* @param string $m -* @access public -*/ -function xmlrpc_debugmsg($m) -{ - $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n"; -} - -class xmlrpc_server -{ - /** - * Array defining php functions exposed as xmlrpc methods by this server - * @access private - */ - var $dmap=array(); - /** - * Defines how functions in dmap will be invoked: either using an xmlrpc msg object - * or plain php values. - * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' - */ - var $functions_parameters_type='xmlrpcvals'; - /** - * Option used for fine-tuning the encoding the php values returned from - * functions registered in the dispatch map when the functions_parameters_types - * member is set to 'phpvals' - * @see php_xmlrpc_encode for a list of values - */ - var $phpvals_encoding_options = array( 'auto_dates' ); - /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3 - var $debug = 1; - /** - * Controls behaviour of server when invoked user function throws an exception: - * 0 = catch it and return an 'internal error' xmlrpc response (default) - * 1 = catch it and return an xmlrpc response with the error corresponding to the exception - * 2 = allow the exception to float to the upper layers - */ - var $exception_handling = 0; - /** - * When set to true, it will enable HTTP compression of the response, in case - * the client has declared its support for compression in the request. - */ - var $compress_response = false; - /** - * List of http compression methods accepted by the server for requests. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib - */ - var $accepted_compression = array(); - /// shall we serve calls to system.* methods? - var $allow_system_funcs = true; - /// list of charset encodings natively accepted for requests - var $accepted_charset_encodings = array(); - /** - * charset encoding to be used for response. - * NB: if we can, we will convert the generated response from internal_encoding to the intended one. - * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), - * null (leave unspecified in response, convert output stream to US_ASCII), - * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), - * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). - * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) - */ - var $response_charset_encoding = ''; - /** - * Storage for internal debug info - * @access private - */ - var $debug_info = ''; - /** - * Extra data passed at runtime to method handling functions. Used only by EPI layer - */ - var $user_data = null; - - /** - * @param array $dispmap the dispatch map with definition of exposed services - * @param boolean $servicenow set to false to prevent the server from running upon construction - */ - function xmlrpc_server($dispMap=null, $serviceNow=true) - { - // if ZLIB is enabled, let the server by default accept compressed requests, - // and compress responses sent to clients that support them - if(function_exists('gzinflate')) - { - $this->accepted_compression = array('gzip', 'deflate'); - $this->compress_response = true; - } - - // by default the xml parser can support these 3 charset encodings - $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); - - // dispMap is a dispatch array of methods - // mapped to function names and signatures - // if a method - // doesn't appear in the map then an unknown - // method error is generated - /* milosch - changed to make passing dispMap optional. - * instead, you can use the class add_to_map() function - * to add functions manually (borrowed from SOAPX4) - */ - if($dispMap) - { - $this->dmap = $dispMap; - if($serviceNow) - { - $this->service(); - } - } - } - - /** - * Set debug level of server. - * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) - * 0 = no debug info, - * 1 = msgs set from user with debugmsg(), - * 2 = add complete xmlrpc request (headers and body), - * 3 = add also all processing warnings happened during method processing - * (NB: this involves setting a custom error handler, and might interfere - * with the standard processing of the php function exposed as method. In - * particular, triggering an USER_ERROR level error will not halt script - * execution anymore, but just end up logged in the xmlrpc response) - * Note that info added at level 2 and 3 will be base64 encoded - * @access public - */ - function setDebug($in) - { - $this->debug=$in; - } - - /** - * Return a string with the serialized representation of all debug info - * @param string $charset_encoding the target charset encoding for the serialization - * @return string an XML comment (or two) - */ - function serializeDebug($charset_encoding='') - { - // Tough encoding problem: which internal charset should we assume for debug info? - // It might contain a copy of raw data received from client, ie with unknown encoding, - // intermixed with php generated data and user generated data... - // so we split it: system debug is base 64 encoded, - // user debug info should be encoded by the end user using the INTERNAL_ENCODING - $out = ''; - if ($this->debug_info != '') - { - $out .= "\n"; - } - if($GLOBALS['_xmlrpc_debuginfo']!='') - { - - $out .= "\n"; - // NB: a better solution MIGHT be to use CDATA, but we need to insert it - // into return payload AFTER the beginning tag - //$out .= "', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n"; - } - return $out; - } - - /** - * Execute the xmlrpc request, printing the response - * @param string $data the request body. If null, the http POST request will be examined - * @return xmlrpcresp the response object (usually not used by caller...) - * @access public - */ - function service($data=null, $return_payload=false) - { - if ($data === null) - { - // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA - $data = file_get_contents('php://input'); - } - $raw_data = $data; - - // reset internal debug info - $this->debug_info = ''; - - // Echo back what we received, before parsing it - if($this->debug > 1) - { - $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); - } - - $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); - if (!$r) - { - $r=$this->parseRequest($data, $req_charset); - } - - // save full body of request into response, for more debugging usages - $r->raw_data = $raw_data; - - if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) - { - $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . - $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); - } - - $payload=$this->xml_header($resp_charset); - if($this->debug > 0) - { - $payload = $payload . $this->serializeDebug($resp_charset); - } - - // G. Giunta 2006-01-27: do not create response serialization if it has - // already happened. Helps building json magic - if (empty($r->payload)) - { - $r->serialize($resp_charset); - } - $payload = $payload . $r->payload; - - if ($return_payload) - { - return $payload; - } - - // if we get a warning/error that has output some text before here, then we cannot - // add a new header. We cannot say we are sending xml, either... - if(!headers_sent()) - { - header('Content-Type: '.$r->content_type); - // we do not know if client actually told us an accepted charset, but if he did - // we have to tell him what we did - header("Vary: Accept-Charset"); - - // http compression of output: only - // if we can do it, and we want to do it, and client asked us to, - // and php ini settings do not force it already - $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); - if($this->compress_response && function_exists('gzencode') && $resp_encoding != '' - && $php_no_self_compress) - { - if(strpos($resp_encoding, 'gzip') !== false) - { - $payload = gzencode($payload); - header("Content-Encoding: gzip"); - header("Vary: Accept-Encoding"); - } - elseif (strpos($resp_encoding, 'deflate') !== false) - { - $payload = gzcompress($payload); - header("Content-Encoding: deflate"); - header("Vary: Accept-Encoding"); - } - } - - // do not ouput content-length header if php is compressing output for us: - // it will mess up measurements - if($php_no_self_compress) - { - header('Content-Length: ' . (int)strlen($payload)); - } - } - else - { - error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages'); - } - - print $payload; - - // return request, in case subclasses want it - return $r; - } - - /** - * Add a method to the dispatch map - * @param string $methodname the name with which the method will be made available - * @param string $function the php function that will get invoked - * @param array $sig the array of valid method signatures - * @param string $doc method documentation - * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type) - * @access public - */ - function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false) - { - $this->dmap[$methodname] = array( - 'function' => $function, - 'docstring' => $doc - ); - if ($sig) - { - $this->dmap[$methodname]['signature'] = $sig; - } - if ($sigdoc) - { - $this->dmap[$methodname]['signature_docs'] = $sigdoc; - } - } - - /** - * Verify type and number of parameters received against a list of known signatures - * @param array $in array of either xmlrpcval objects or xmlrpc type definitions - * @param array $sig array of known signatures to match against - * @return array - * @access private - */ - function verifySignature($in, $sig) - { - // check each possible signature in turn - if (is_object($in)) - { - $numParams = $in->getNumParams(); - } - else - { - $numParams = count($in); - } - foreach($sig as $cursig) - { - if(count($cursig)==$numParams+1) - { - $itsOK=1; - for($n=0; $n<$numParams; $n++) - { - if (is_object($in)) - { - $p=$in->getParam($n); - if($p->kindOf() == 'scalar') - { - $pt=$p->scalartyp(); - } - else - { - $pt=$p->kindOf(); - } - } - else - { - $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4... - } - - // param index is $n+1, as first member of sig is return type - if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) - { - $itsOK=0; - $pno=$n+1; - $wanted=$cursig[$n+1]; - $got=$pt; - break; - } - } - if($itsOK) - { - return array(1,''); - } - } - } - if(isset($wanted)) - { - return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); - } - else - { - return array(0, "No method signature matches number of parameters"); - } - } - - /** - * Parse http headers received along with xmlrpc request. If needed, inflate request - * @return mixed null on success or an xmlrpcresp - * @access private - */ - function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) - { - // check if $_SERVER is populated: it might have been disabled via ini file - // (this is true even when in CLI mode) - if (count($_SERVER) == 0) - { - error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated'); - } - - if($this->debug > 1) - { - if(function_exists('getallheaders')) - { - $this->debugmsg(''); // empty line - foreach(getallheaders() as $name => $val) - { - $this->debugmsg("HEADER: $name: $val"); - } - } - - } - - if(isset($_SERVER['HTTP_CONTENT_ENCODING'])) - { - $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); - } - else - { - $content_encoding = ''; - } - - // check if request body has been compressed and decompress it - if($content_encoding != '' && strlen($data)) - { - if($content_encoding == 'deflate' || $content_encoding == 'gzip') - { - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) - { - if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) - { - $data = $degzdata; - if($this->debug > 1) - { - $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); - } - } - elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { - $data = $degzdata; - if($this->debug > 1) - $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); - } - else - { - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); - return $r; - } - } - else - { - //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); - return $r; - } - } - } - - // check if client specified accepted charsets, and if we know how to fulfill - // the request - if ($this->response_charset_encoding == 'auto') - { - $resp_encoding = ''; - if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) - { - // here we should check if we can match the client-requested encoding - // with the encodings we know we can generate. - /// @todo we should parse q=0.x preferences instead of getting first charset specified... - $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); - // Give preference to internal encoding - $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII'); - foreach ($known_charsets as $charset) - { - foreach ($client_accepted_charsets as $accepted) - if (strpos($accepted, $charset) === 0) - { - $resp_encoding = $charset; - break; - } - if ($resp_encoding) - break; - } - } - } - else - { - $resp_encoding = $this->response_charset_encoding; - } - - if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) - { - $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; - } - else - { - $resp_compression = ''; - } - - // 'guestimate' request encoding - /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? - $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', - $data); - - return null; - } - - /** - * Parse an xml chunk containing an xmlrpc request and execute the corresponding - * php function registered with the server - * @param string $data the xml request - * @param string $req_encoding (optional) the charset encoding of the xml request - * @return xmlrpcresp - * @access private - */ - function parseRequest($data, $req_encoding='') - { - // 2005/05/07 commented and moved into caller function code - //if($data=='') - //{ - // $data=$GLOBALS['HTTP_RAW_POST_DATA']; - //} - - // G. Giunta 2005/02/13: we do NOT expect to receive html entities - // so we do not try to convert them into xml character entities - //$data = xmlrpc_html_entity_xlate($data); - - $GLOBALS['_xh']=array(); - $GLOBALS['_xh']['ac']=''; - $GLOBALS['_xh']['stack']=array(); - $GLOBALS['_xh']['valuestack'] = array(); - $GLOBALS['_xh']['params']=array(); - $GLOBALS['_xh']['pt']=array(); - $GLOBALS['_xh']['isf']=0; - $GLOBALS['_xh']['isf_reason']=''; - $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not - $GLOBALS['_xh']['rt']=''; - - // decompose incoming XML into request structure - if ($req_encoding != '') - { - if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding); - $req_encoding = $GLOBALS['xmlrpc_defencoding']; - } - /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, - // the encoding is not UTF8 and there are non-ascii chars in the text... - /// @todo use an empty string for php 5 ??? - $parser = xml_parser_create($req_encoding); - } - else - { - $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_entitites() and setting xmlrpc_internalencoding - if (!in_array($GLOBALS['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, $GLOBALS['xmlrpc_internalencoding']); - } - - if ($this->functions_parameters_type != 'xmlrpcvals') - 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'); - if(!xml_parse($parser, $data, 1)) - { - // return XML error as a faultCode - $r=new xmlrpcresp(0, - $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser), - 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))); - xml_parser_free($parser); - } - elseif ($GLOBALS['_xh']['isf']) - { - xml_parser_free($parser); - $r=new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['invalid_request'], - $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']); - } - else - { - xml_parser_free($parser); - // small layering violation in favor of speed and memory usage: - // we should allow the 'execute' method handle this, but in the - // most common scenario (xmlrpcvals type server with some methods - // registered as phpvals) that would mean a useless encode+decode pass - if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals'))) - { - if($this->debug > 1) - { - $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++"); - } - $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']); - } - else - { - // build an xmlrpcmsg object with data parsed from xml - $m=new xmlrpcmsg($GLOBALS['_xh']['method']); - // now add parameters in - for($i=0; $iaddParam($GLOBALS['_xh']['params'][$i]); - } - - if($this->debug > 1) - { - $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++"); - } - $r = $this->execute($m); - } - } - return $r; - } - - /** - * Execute a method invoked by the client, checking parameters used - * @param mixed $m either an xmlrpcmsg obj or a method name - * @param array $params array with method parameters as php types (if m is method name only) - * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) - * @return xmlrpcresp - * @access private - */ - function execute($m, $params=null, $paramtypes=null) - { - if (is_object($m)) - { - $methName = $m->method(); - } - else - { - $methName = $m; - } - $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); - $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; - - if(!isset($dmap[$methName]['function'])) - { - // No such method - return new xmlrpcresp(0, - $GLOBALS['xmlrpcerr']['unknown_method'], - $GLOBALS['xmlrpcstr']['unknown_method']); - } - - // Check signature - if(isset($dmap[$methName]['signature'])) - { - $sig = $dmap[$methName]['signature']; - if (is_object($m)) - { - list($ok, $errstr) = $this->verifySignature($m, $sig); - } - else - { - list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); - } - if(!$ok) - { - // Didn't match. - return new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" - ); - } - } - - $func = $dmap[$methName]['function']; - // let the 'class::function' syntax be accepted in dispatch maps - if(is_string($func) && strpos($func, '::')) - { - $func = explode('::', $func); - } - // verify that function to be invoked is in fact callable - if(!is_callable($func)) - { - error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable"); - return new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" - ); - } - - // If debug level is 3, we should catch all errors generated during - // processing of user function, and log them as part of response - if($this->debug > 2) - { - $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); - } - try - { - // Allow mixed-convention servers - if (is_object($m)) - { - if($sysCall) - { - $r = call_user_func($func, $this, $m); - } - else - { - $r = call_user_func($func, $m); - } - if (!is_a($r, 'xmlrpcresp')) - { - error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); - if (is_a($r, 'xmlrpcval')) - { - $r = new xmlrpcresp($r); - } - else - { - $r = new xmlrpcresp( - 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" - ); - } - } - } - else - { - // call a 'plain php' function - if($sysCall) - { - array_unshift($params, $this); - $r = call_user_func_array($func, $params); - } - else - { - // 3rd API convention for method-handling functions: EPI-style - if ($this->functions_parameters_type == 'epivals') - { - $r = call_user_func_array($func, array($methName, $params, $this->user_data)); - // mimic EPI behaviour: if we get an array that looks like an error, make it - // an eror response - if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) - { - $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']); - } - else - { - // functions using EPI api should NOT return resp objects, - // so make sure we encode the return type correctly - $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api'))); - } - } - else - { - $r = call_user_func_array($func, $params); - } - } - // the return type can be either an xmlrpcresp object or a plain php value... - if (!is_a($r, 'xmlrpcresp')) - { - // what should we assume here about automatic encoding of datetimes - // and php classes instances??? - $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options)); - } - } - } - catch(Exception $e) - { - // (barring errors in the lib) an uncatched exception happened - // in the called function, we wrap it in a proper error-response - switch($this->exception_handling) - { - case 2: - throw $e; - break; - case 1: - $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage()); - break; - default: - $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']); - } - } - if($this->debug > 2) - { - // note: restore the error handler we found before calling the - // user func, even if it has been changed inside the func itself - if($GLOBALS['_xmlrpcs_prev_ehandler']) - { - set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); - } - else - { - restore_error_handler(); - } - } - return $r; - } - - /** - * add a string to the 'internal debug message' (separate from 'user debug message') - * @param string $string - * @access private - */ - function debugmsg($string) - { - $this->debug_info .= $string."\n"; - } - - /** - * @access private - */ - function xml_header($charset_encoding='') - { - if ($charset_encoding != '') - { - return "\n"; - } - else - { - return "\n"; - } - } - - /** - * A debugging routine: just echoes back the input packet as a string value - * DEPRECATED! - */ - function echoInput() - { - $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); - print $r->serialize(); - } -} +accepted_compression = array('gzip', 'deflate'); + $this->compress_response = true; + } + + // by default the xml parser can support these 3 charset encodings + $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); + + // dispMap is a dispatch array of methods + // mapped to function names and signatures + // if a method + // doesn't appear in the map then an unknown + // method error is generated + /* milosch - changed to make passing dispMap optional. + * instead, you can use the class add_to_map() function + * to add functions manually (borrowed from SOAPX4) + */ + if($dispMap) + { + $this->dmap = $dispMap; + if($serviceNow) + { + $this->service(); + } + } + } + + /** + * Set debug level of server. + * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) + * 0 = no debug info, + * 1 = msgs set from user with debugmsg(), + * 2 = add complete xmlrpc request (headers and body), + * 3 = add also all processing warnings happened during method processing + * (NB: this involves setting a custom error handler, and might interfere + * with the standard processing of the php function exposed as method. In + * particular, triggering an USER_ERROR level error will not halt script + * execution anymore, but just end up logged in the xmlrpc response) + * Note that info added at level 2 and 3 will be base64 encoded + */ + function setDebug($in) + { + $this->debug=$in; + } + + /** + * Add a string to the debug info that can be later serialized by the server + * as part of the response message. + * Note that for best compatibility, the debug string should be encoded using + * the PhpXmlRpc::$xmlrpc_internalencoding character set. + * @param string $m + * @access public + */ + public static function xmlrpc_debugmsg($m) + { + static::$_xmlrpc_debuginfo .= $m . "\n"; + } + + /** + * Return a string with the serialized representation of all debug info + * @param string $charset_encoding the target charset encoding for the serialization + * @return string an XML comment (or two) + */ + function serializeDebug($charset_encoding='') + { + // Tough encoding problem: which internal charset should we assume for debug info? + // It might contain a copy of raw data received from client, ie with unknown encoding, + // intermixed with php generated data and user generated data... + // so we split it: system debug is base 64 encoded, + // user debug info should be encoded by the end user using the INTERNAL_ENCODING + $out = ''; + if ($this->debug_info != '') + { + $out .= "\n"; + } + if($GLOBALS['_xmlrpc_debuginfo']!='') + { + + $out .= "\n"; + // NB: a better solution MIGHT be to use CDATA, but we need to insert it + // into return payload AFTER the beginning tag + //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n"; + } + return $out; + } + + /** + * Execute the xmlrpc request, printing the response + * @param string $data the request body. If null, the http POST request will be examined + * @param bool $return_payload When true, return the response but do not echo it or any http header + * @return xmlrpcresp the response object (usually not used by caller...) + */ + function service($data=null, $return_payload=false) + { + if ($data === null) + { + // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA + $data = file_get_contents('php://input'); + } + $raw_data = $data; + + // reset internal debug info + $this->debug_info = ''; + + // Echo back what we received, before parsing it + if($this->debug > 1) + { + $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); + } + + $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); + if (!$r) + { + $r=$this->parseRequest($data, $req_charset); + } + + // save full body of request into response, for more debugging usages + $r->raw_data = $raw_data; + + if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) + { + $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . + $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); + } + + $payload=$this->xml_header($resp_charset); + if($this->debug > 0) + { + $payload = $payload . $this->serializeDebug($resp_charset); + } + + // G. Giunta 2006-01-27: do not create response serialization if it has + // already happened. Helps building json magic + if (empty($r->payload)) + { + $r->serialize($resp_charset); + } + $payload = $payload . $r->payload; + + if ($return_payload) + { + return $payload; + } + + // if we get a warning/error that has output some text before here, then we cannot + // add a new header. We cannot say we are sending xml, either... + if(!headers_sent()) + { + header('Content-Type: '.$r->content_type); + // we do not know if client actually told us an accepted charset, but if he did + // we have to tell him what we did + header("Vary: Accept-Charset"); + + // http compression of output: only + // if we can do it, and we want to do it, and client asked us to, + // and php ini settings do not force it already + $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); + if($this->compress_response && function_exists('gzencode') && $resp_encoding != '' + && $php_no_self_compress) + { + if(strpos($resp_encoding, 'gzip') !== false) + { + $payload = gzencode($payload); + header("Content-Encoding: gzip"); + header("Vary: Accept-Encoding"); + } + elseif (strpos($resp_encoding, 'deflate') !== false) + { + $payload = gzcompress($payload); + header("Content-Encoding: deflate"); + header("Vary: Accept-Encoding"); + } + } + + // do not output content-length header if php is compressing output for us: + // it will mess up measurements + if($php_no_self_compress) + { + header('Content-Length: ' . (int)strlen($payload)); + } + } + else + { + error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages'); + } + + print $payload; + + // return request, in case subclasses want it + return $r; + } + + /** + * Add a method to the dispatch map + * @param string $methodname the name with which the method will be made available + * @param string $function the php function that will get invoked + * @param array $sig the array of valid method signatures + * @param string $doc method documentation + * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type) + */ + function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false) + { + $this->dmap[$methodname] = array( + 'function' => $function, + 'docstring' => $doc + ); + if ($sig) + { + $this->dmap[$methodname]['signature'] = $sig; + } + if ($sigdoc) + { + $this->dmap[$methodname]['signature_docs'] = $sigdoc; + } + } + + /** + * Verify type and number of parameters received against a list of known signatures + * @param array $in array of either xmlrpcval objects or xmlrpc type definitions + * @param array $sig array of known signatures to match against + * @return array + */ + protected function verifySignature($in, $sig) + { + // check each possible signature in turn + if (is_object($in)) + { + $numParams = $in->getNumParams(); + } + else + { + $numParams = count($in); + } + foreach($sig as $cursig) + { + if(count($cursig)==$numParams+1) + { + $itsOK=1; + for($n=0; $n<$numParams; $n++) + { + if (is_object($in)) + { + $p=$in->getParam($n); + if($p->kindOf() == 'scalar') + { + $pt=$p->scalartyp(); + } + else + { + $pt=$p->kindOf(); + } + } + else + { + $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4... + } + + // param index is $n+1, as first member of sig is return type + if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) + { + $itsOK=0; + $pno=$n+1; + $wanted=$cursig[$n+1]; + $got=$pt; + break; + } + } + if($itsOK) + { + return array(1,''); + } + } + } + if(isset($wanted)) + { + return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); + } + else + { + return array(0, "No method signature matches number of parameters"); + } + } + + /** + * Parse http headers received along with xmlrpc request. If needed, inflate request + * @return mixed null on success or an xmlrpcresp + */ + protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) + { + // check if $_SERVER is populated: it might have been disabled via ini file + // (this is true even when in CLI mode) + if (count($_SERVER) == 0) + { + error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated'); + } + + if($this->debug > 1) + { + if(function_exists('getallheaders')) + { + $this->debugmsg(''); // empty line + foreach(getallheaders() as $name => $val) + { + $this->debugmsg("HEADER: $name: $val"); + } + } + + } + + if(isset($_SERVER['HTTP_CONTENT_ENCODING'])) + { + $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); + } + else + { + $content_encoding = ''; + } + + // check if request body has been compressed and decompress it + if($content_encoding != '' && strlen($data)) + { + if($content_encoding == 'deflate' || $content_encoding == 'gzip') + { + // if decoding works, use it. else assume data wasn't gzencoded + if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) + { + if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) + { + $data = $degzdata; + if($this->debug > 1) + { + $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + } + elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) + { + $data = $degzdata; + if($this->debug > 1) + $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++"); + } + else + { + $r = new Response(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); + return $r; + } + } + else + { + //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + $r = new Response(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); + return $r; + } + } + } + + // check if client specified accepted charsets, and if we know how to fulfill + // the request + if ($this->response_charset_encoding == 'auto') + { + $resp_encoding = ''; + if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) + { + // here we should check if we can match the client-requested encoding + // with the encodings we know we can generate. + /// @todo we should parse q=0.x preferences instead of getting first charset specified... + $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); + // Give preference to internal encoding + $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + foreach ($known_charsets as $charset) + { + foreach ($client_accepted_charsets as $accepted) + if (strpos($accepted, $charset) === 0) + { + $resp_encoding = $charset; + break; + } + if ($resp_encoding) + break; + } + } + } + else + { + $resp_encoding = $this->response_charset_encoding; + } + + if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) + { + $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; + } + else + { + $resp_compression = ''; + } + + // 'guestimate' request encoding + /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? + $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $data); + + return null; + } + + /** + * Parse an xml chunk containing an xmlrpc request and execute the corresponding + * php function registered with the server + * @param string $data the xml request + * @param string $req_encoding (optional) the charset encoding of the xml request + * @return xmlrpcresp + */ + public function parseRequest($data, $req_encoding='') + { + // 2005/05/07 commented and moved into caller function code + //if($data=='') + //{ + // $data=$GLOBALS['HTTP_RAW_POST_DATA']; + //} + + // G. Giunta 2005/02/13: we do NOT expect to receive html entities + // so we do not try to convert them into xml character entities + //$data = xmlrpc_html_entity_xlate($data); + + // decompose incoming XML into request structure + if ($req_encoding != '') + { + if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + { + error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding); + $req_encoding = $GLOBALS['xmlrpc_defencoding']; + } + /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, + // the encoding is not UTF8 and there are non-ascii chars in the text... + /// @todo use an empty string for php 5 ??? + $parser = xml_parser_create($req_encoding); + } + else + { + $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_entitites() and setting xmlrpc_internalencoding + if (!in_array($GLOBALS['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, $GLOBALS['xmlrpc_internalencoding']); + } + + $xmlRpcParser = new XMLParser(); + xml_set_object($parser, $xmlRpcParser); + + if ($this->functions_parameters_type != 'xmlrpcvals') + 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'); + if(!xml_parse($parser, $data, 1)) + { + // return XML error as a faultCode + $r=new Response(0, + PhpXmlRpc::$xmlrpcerrxml+xml_get_error_code($parser), + 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))); + xml_parser_free($parser); + } + elseif ($xmlRpcParser->_xh['isf']) + { + xml_parser_free($parser); + $r=new Response(0, + PhpXmlRpc::$xmlrpcerr['invalid_request'], + PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']); + } + else + { + xml_parser_free($parser); + // small layering violation in favor of speed and memory usage: + // we should allow the 'execute' method handle this, but in the + // most common scenario (xmlrpcvals type server with some methods + // registered as phpvals) that would mean a useless encode+decode pass + if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) + { + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($xmlRpcParser->_xh['params'], true)."\n+++END+++"); + } + $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']); + } + else + { + // build a Request object with data parsed from xml + $m=new Request($xmlRpcParser->_xh['method']); + // now add parameters in + for($i=0; $i_xh['params']); $i++) + { + $m->addParam($xmlRpcParser->_xh['params'][$i]); + } + + if($this->debug > 1) + { + $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++"); + } + $r = $this->execute($m); + } + } + return $r; + } + + /** + * Execute a method invoked by the client, checking parameters used + * @param mixed $m either an xmlrpcmsg obj or a method name + * @param array $params array with method parameters as php types (if m is method name only) + * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) + * @return xmlrpcresp + */ + protected function execute($m, $params=null, $paramtypes=null) + { + if (is_object($m)) + { + $methName = $m->method(); + } + else + { + $methName = $m; + } + $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); + $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; + + if(!isset($dmap[$methName]['function'])) + { + // No such method + return new Response(0, + $GLOBALS['xmlrpcerr']['unknown_method'], + $GLOBALS['xmlrpcstr']['unknown_method']); + } + + // Check signature + if(isset($dmap[$methName]['signature'])) + { + $sig = $dmap[$methName]['signature']; + if (is_object($m)) + { + list($ok, $errstr) = $this->verifySignature($m, $sig); + } + else + { + list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); + } + if(!$ok) + { + // Didn't match. + return new Response( + 0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" + ); + } + } + + $func = $dmap[$methName]['function']; + // let the 'class::function' syntax be accepted in dispatch maps + if(is_string($func) && strpos($func, '::')) + { + $func = explode('::', $func); + } + // verify that function to be invoked is in fact callable + if(!is_callable($func)) + { + error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable"); + return new Response( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" + ); + } + + // If debug level is 3, we should catch all errors generated during + // processing of user function, and log them as part of response + if($this->debug > 2) + { + $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); + } + try + { + // Allow mixed-convention servers + if (is_object($m)) + { + if($sysCall) + { + $r = call_user_func($func, $this, $m); + } + else + { + $r = call_user_func($func, $m); + } + if (!is_a($r, 'xmlrpcresp')) + { + error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); + if (is_a($r, 'xmlrpcval')) + { + $r = new Response($r); + } + else + { + $r = new Response( + 0, + $GLOBALS['xmlrpcerr']['server_error'], + $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" + ); + } + } + } + else + { + // call a 'plain php' function + if($sysCall) + { + array_unshift($params, $this); + $r = call_user_func_array($func, $params); + } + else + { + // 3rd API convention for method-handling functions: EPI-style + if ($this->functions_parameters_type == 'epivals') + { + $r = call_user_func_array($func, array($methName, $params, $this->user_data)); + // mimic EPI behaviour: if we get an array that looks like an error, make it + // an eror response + if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) + { + $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']); + } + else + { + // functions using EPI api should NOT return resp objects, + // so make sure we encode the return type correctly + $r = new Response(php_xmlrpc_encode($r, array('extension_api'))); + } + } + else + { + $r = call_user_func_array($func, $params); + } + } + // the return type can be either an xmlrpcresp object or a plain php value... + if (!is_a($r, 'xmlrpcresp')) + { + // what should we assume here about automatic encoding of datetimes + // and php classes instances??? + $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options)); + } + } + } + catch(Exception $e) + { + // (barring errors in the lib) an uncatched exception happened + // in the called function, we wrap it in a proper error-response + switch($this->exception_handling) + { + case 2: + throw $e; + break; + case 1: + $r = new Response(0, $e->getCode(), $e->getMessage()); + break; + default: + $r = new Response(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']); + } + } + if($this->debug > 2) + { + // note: restore the error handler we found before calling the + // user func, even if it has been changed inside the func itself + if($GLOBALS['_xmlrpcs_prev_ehandler']) + { + set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); + } + else + { + restore_error_handler(); + } + } + return $r; + } + + /** + * add a string to the 'internal debug message' (separate from 'user debug message') + * @param string $string + */ + protected function debugmsg($string) + { + $this->debug_info .= $string."\n"; + } + + protected function xml_header($charset_encoding='') + { + if ($charset_encoding != '') + { + return "\n"; + } + else + { + return "\n"; + } + } + + /** + * A debugging routine: just echoes back the input packet as a string value + * DEPRECATED! + */ + function echoInput() + { + $r=new Response(new Value( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); + print $r->serialize(); + } + + /* Functions that implement system.XXX methods of xmlrpc servers */ + + protected function getSystemDispatchMap() + { + return array( + 'system.listMethods' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_listMethods', + // listMethods: signature was either a string, or nothing. + // The useless string variant has been removed + 'signature' => array(array(Value::$xmlrpcArray)), + 'docstring' => 'This method lists all the methods that the XML-RPC server knows how to dispatch', + 'signature_docs' => array(array('list of method names')), + ), + 'system.methodHelp' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodHelp', + 'signature' => array(array(Value::$xmlrpcString, Value::$xmlrpcString)), + 'docstring' => 'Returns help text if defined for the method passed, otherwise returns an empty string', + 'signature_docs' => array(array('method description', 'name of the method to be described')), + ), + 'system.methodSignature' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_methodSignature', + 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcString)), + 'docstring' => '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)', + 'signature_docs' => array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described')), + ), + 'system.multicall' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_multicall', + 'signature' => array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)), + 'docstring' => 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details', + 'signature_docs' => 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"')), + ), + 'system.getCapabilities' => array( + 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities', + 'signature' => array(array($GLOBALS['xmlrpcStruct'])), + 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to', + 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')) + ) + ); + } + + public static function _xmlrpcs_getCapabilities($server, $m=null) + { + $outAr = array( + // xmlrpc spec: always supported + 'xmlrpc' => new Value(array( + 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'), + 'specVersion' => new Value(1, 'int') + ), 'struct'), + // if we support system.xxx functions, we always support multicall, too... + // Note that, as of 2006/09/17, the following URL does not respond anymore + 'system.multicall' => new Value(array( + 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), + 'specVersion' => new Value(1, 'int') + ), 'struct'), + // introspection: version 2! we support 'mixed', too + 'introspection' => new Value(array( + 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), + 'specVersion' => new Value(2, 'int') + ), 'struct') + ); + + // NIL extension + if ($GLOBALS['xmlrpc_null_extension']) { + $outAr['nil'] = new Value(array( + 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), + 'specVersion' => new Value(1, 'int') + ), 'struct'); + } + return new Response(new Value($outAr, 'struct')); + } + + public static function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing + { + + $outAr=array(); + foreach($server->dmap as $key => $val) + { + $outAr[]=new Value($key, 'string'); + } + if($server->allow_system_funcs) + { + foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) + { + $outAr[]=new Value($key, 'string'); + } + } + return new Response(new Value($outAr, 'array')); + } + + public static function _xmlrpcs_methodSignature($server, $m) + { + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['signature'])) + { + $sigs=array(); + foreach($dmap[$methName]['signature'] as $inSig) + { + $cursig=array(); + foreach($inSig as $sig) + { + $cursig[]=new Value($sig, 'string'); + } + $sigs[]=new Value($cursig, 'array'); + } + $r=new Response(new Value($sigs, 'array')); + } + else + { + // NB: according to the official docs, we should be returning a + // "none-array" here, which means not-an-array + $r=new Response(new Value('undef', 'string')); + } + } + else + { + $r=new Response(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; + } + + public static function _xmlrpcs_methodHelp($server, $m) + { + // let accept as parameter both an xmlrpcval or string + if (is_object($m)) + { + $methName=$m->getParam(0); + $methName=$methName->scalarval(); + } + else + { + $methName=$m; + } + if(strpos($methName, "system.") === 0) + { + $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + } + else + { + $dmap=$server->dmap; $sysCall=0; + } + if(isset($dmap[$methName])) + { + if(isset($dmap[$methName]['docstring'])) + { + $r=new Response(new Value($dmap[$methName]['docstring']), 'string'); + } + else + { + $r=new Response(new Value('', 'string')); + } + } + else + { + $r=new Response(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + } + return $r; + } + + public static function _xmlrpcs_multicall_error($err) + { + if(is_string($err)) + { + $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; + $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; + } + else + { + $code = $err->faultCode(); + $str = $err->faultString(); + } + $struct = array(); + $struct['faultCode'] = new Value($code, 'int'); + $struct['faultString'] = new Value($str, 'string'); + return new Value($struct, 'struct'); + } + + public static function _xmlrpcs_multicall_do_call($server, $call) + { + if($call->kindOf() != 'struct') + { + return _xmlrpcs_multicall_error('notstruct'); + } + $methName = @$call->structmem('methodName'); + if(!$methName) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') + { + return _xmlrpcs_multicall_error('notstring'); + } + if($methName->scalarval() == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + + $params = @$call->structmem('params'); + if(!$params) + { + return _xmlrpcs_multicall_error('noparams'); + } + if($params->kindOf() != 'array') + { + return _xmlrpcs_multicall_error('notarray'); + } + $numParams = $params->arraysize(); + + $msg = new Request($methName->scalarval()); + for($i = 0; $i < $numParams; $i++) + { + if(!$msg->addParam($params->arraymem($i))) + { + $i++; + return _xmlrpcs_multicall_error(new Response(0, + $GLOBALS['xmlrpcerr']['incorrect_params'], + $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); + } + } + + $result = $server->execute($msg); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new Value(array($result->value()), 'array'); + } + + public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) + { + if(!is_array($call)) + { + return _xmlrpcs_multicall_error('notstruct'); + } + if(!array_key_exists('methodName', $call)) + { + return _xmlrpcs_multicall_error('nomethod'); + } + if (!is_string($call['methodName'])) + { + return _xmlrpcs_multicall_error('notstring'); + } + if($call['methodName'] == 'system.multicall') + { + return _xmlrpcs_multicall_error('recursion'); + } + if(!array_key_exists('params', $call)) + { + return _xmlrpcs_multicall_error('noparams'); + } + if(!is_array($call['params'])) + { + return _xmlrpcs_multicall_error('notarray'); + } + + // this is a real dirty and simplistic hack, since we might have received a + // base64 or datetime values, but they will be listed as strings here... + $numParams = count($call['params']); + $pt = array(); + foreach($call['params'] as $val) + $pt[] = php_2_xmlrpc_type(gettype($val)); + + $result = $server->execute($call['methodName'], $call['params'], $pt); + + if($result->faultCode() != 0) + { + return _xmlrpcs_multicall_error($result); // Method returned fault. + } + + return new Value(array($result->value()), 'array'); + } + + public static function _xmlrpcs_multicall($server, $m) + { + $result = array(); + // let accept a plain list of php parameters, beside a single xmlrpc msg object + if (is_object($m)) + { + $calls = $m->getParam(0); + $numCalls = $calls->arraysize(); + for($i = 0; $i < $numCalls; $i++) + { + $call = $calls->arraymem($i); + $result[$i] = _xmlrpcs_multicall_do_call($server, $call); + } + } + else + { + $numCalls=count($m); + for($i = 0; $i < $numCalls; $i++) + { + $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); + } + } + + return new Response(new Value($result, 'array')); + } +} diff --git a/lib/xmlrpcval.php b/src/Value.php similarity index 84% rename from lib/xmlrpcval.php rename to src/Value.php index 7cfca961..fd4a840c 100644 --- a/lib/xmlrpcval.php +++ b/src/Value.php @@ -1,7 +1,35 @@ 1, + "int" => 1, + "boolean" => 1, + "double" => 1, + "string" => 1, + "dateTime.iso8601" => 1, + "base64" => 1, + "array" => 2, + "struct" => 3, + "null" => 1 + ); /// @todo: does these need to be public? public $me=array(); @@ -50,15 +78,15 @@ function __construct($val=-1, $type='') { { $type='string'; } - if($GLOBALS['xmlrpcTypes'][$type]==1) + if(static::$xmlrpcTypes[$type]==1) { $this->addScalar($val,$type); } - elseif($GLOBALS['xmlrpcTypes'][$type]==2) + elseif(static::$xmlrpcTypes[$type]==2) { $this->addArray($val); } - elseif($GLOBALS['xmlrpcTypes'][$type]==3) + elseif(static::$xmlrpcTypes[$type]==3) { $this->addStruct($val); }*/ @@ -73,11 +101,9 @@ function __construct($val=-1, $type='') { */ function addScalar($val, $type='string') { - $xmlrpc = Phpxmlrpc::instance(); - $typeof = null; - if(isset($xmlrpc->xmlrpcTypes[$type])) { - $typeof = $xmlrpc->xmlrpcTypes[$type]; + if(isset(static::$xmlrpcTypes[$type])) { + $typeof = static::$xmlrpcTypes[$type]; } if($typeof!=1) @@ -89,7 +115,7 @@ function addScalar($val, $type='string') // coerce booleans into correct values // NB: we should either do it for datetimes, integers and doubles, too, // or just plain remove this check, implemented on booleans only... - if($type==$xmlrpc->xmlrpcBoolean) + if($type==static::$xmlrpcBoolean) { if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false'))) { @@ -112,10 +138,10 @@ function addScalar($val, $type='string') case 2: // we're adding a scalar value to an array here //$ar=$this->me['array']; - //$ar[]=new xmlrpcval($val, $type); + //$ar[]=new Value($val, $type); //$this->me['array']=$ar; // Faster (?) avoid all the costly array-copy-by-val done here... - $this->me['array'][]=new xmlrpcval($val, $type); + $this->me['array'][]=new Value($val, $type); return 1; default: // a scalar, so set the value and remember we're scalar @@ -134,10 +160,9 @@ function addScalar($val, $type='string') */ public function addArray($vals) { - $xmlrpc = Phpxmlrpc::instance(); if($this->mytype==0) { - $this->mytype=$xmlrpc->xmlrpcTypes['array']; + $this->mytype=static::$xmlrpcTypes['array']; $this->me['array']=$vals; return 1; } @@ -163,11 +188,9 @@ public function addArray($vals) */ public function addStruct($vals) { - $xmlrpc = Phpxmlrpc::instance(); - if($this->mytype==0) { - $this->mytype=$xmlrpc->xmlrpcTypes['struct']; + $this->mytype=static::$xmlrpcTypes['struct']; $this->me['struct']=$vals; return 1; } @@ -208,34 +231,33 @@ public function kindOf() private function serializedata($typ, $val, $charset_encoding='') { - $xmlrpc = Phpxmlrpc::instance(); $rs=''; - if(!isset($xmlrpc->xmlrpcTypes[$typ])) { + if(!isset(static::$xmlrpcTypes[$typ])) { return $rs; } - switch($xmlrpc->xmlrpcTypes[$typ]) + switch(static::$xmlrpcTypes[$typ]) { case 1: switch($typ) { - case $xmlrpc->xmlrpcBase64: + case static::$xmlrpcBase64: $rs.="<${typ}>" . base64_encode($val) . ""; break; - case $xmlrpc->xmlrpcBoolean: + case static::$xmlrpcBoolean: $rs.="<${typ}>" . ($val ? '1' : '0') . ""; break; - case $xmlrpc->xmlrpcString: + 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}>" . xmlrpc_encode_entitites($val, $xmlrpc->xmlrpc_internalencoding, $charset_encoding). ""; + $rs.="<${typ}>" . Charset::instance()->encode_entities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding). ""; break; - case $xmlrpc->xmlrpcInt: - case $xmlrpc->xmlrpcI4: + case static::$xmlrpcInt: + case static::$xmlrpcI4: $rs.="<${typ}>".(int)$val.""; break; - case $xmlrpc->xmlrpcDouble: + 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. @@ -243,7 +265,7 @@ private function serializedata($typ, $val, $charset_encoding='') // 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, '.', '')).""; break; - case $xmlrpc->xmlrpcDateTime: + case static::$xmlrpcDateTime: if (is_string($val)) { $rs.="<${typ}>${val}"; @@ -262,8 +284,8 @@ private function serializedata($typ, $val, $charset_encoding='') $rs.="<${typ}>${val}"; } break; - case $xmlrpc->xmlrpcNull: - if ($xmlrpc->xmlrpc_null_apache_encoding) + case static::$xmlrpcNull: + if (PhpXmlRpc::$xmlrpc_null_apache_encoding) { $rs.=""; } @@ -288,9 +310,10 @@ private function serializedata($typ, $val, $charset_encoding='') { $rs.="\n"; } + $charsetEncoder = Charset::instance(); foreach($val as $key2 => $val2) { - $rs.=''.xmlrpc_encode_entitites($key2, $xmlrpc->xmlrpc_internalencoding, $charset_encoding)."\n"; + $rs.=''.$charsetEncoder->encode_entities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding)."\n"; //$rs.=$this->serializeval($val2); $rs.=$val2->serialize($charset_encoding); $rs.="\n"; @@ -300,10 +323,10 @@ private function serializedata($typ, $val, $charset_encoding='') case 2: // array $rs.="\n\n"; - for($i=0; $iserializeval($val[$i]); - $rs.=$val[$i]->serialize($charset_encoding); + $rs.=$element->serialize($charset_encoding); } $rs.="\n"; break; @@ -439,13 +462,11 @@ public function scalarval() */ public function scalartyp() { - $xmlrpc = Phpxmlrpc::instance(); - reset($this->me); list($a,)=each($this->me); - if($a==$xmlrpc->xmlrpcI4) + if($a==static::xmlrpcI4) { - $a=$xmlrpc->xmlrpcInt; + $a=static::xmlrpcInt; } return $a; } diff --git a/src/Wrapper.php b/src/Wrapper.php new file mode 100644 index 00000000..138d186e --- /dev/null +++ b/src/Wrapper.php @@ -0,0 +1,937 @@ +' . $funcname[1]; + } + $exists = method_exists($funcname[0], $funcname[1]); + } + else + { + $plainfuncname = $funcname; + $exists = function_exists($funcname); + } + + if(!$exists) + { + error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname); + return false; + } + else + { + // determine name of new php function + if($newfuncname == '') + { + if(is_array($funcname)) + { + if(is_string($funcname[0])) + $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname); + else + $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1]; + } + else + { + $xmlrpcfuncname = "{$prefix}_$funcname"; + } + } + else + { + $xmlrpcfuncname = $newfuncname; + } + while($buildit && function_exists($xmlrpcfuncname)) + { + $xmlrpcfuncname .= 'x'; + } + + // start to introspect PHP code + if(is_array($funcname)) + { + $func = new ReflectionMethod($funcname[0], $funcname[1]); + if($func->isPrivate()) + { + error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); + return false; + } + if($func->isProtected()) + { + error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname); + return false; + } + if($func->isConstructor()) + { + error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname); + return false; + } + if($func->isDestructor()) + { + error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname); + return false; + } + if($func->isAbstract()) + { + error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname); + return false; + } + /// @todo add more checks for static vs. nonstatic? + } + else + { + $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: '.$plainfuncname); + return false; + } + + // retrieve parameter names, types and description from javadoc comments + + // function description + $desc = ''; + // type of return val: by default 'any' + $returns = Value::$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, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."');\n" . $innercode; + } + else + { + $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode; + } + + $innercode .= "\$np = false;\n"; + // since there are no closures in php, if we are given an object instance, + // we store a pointer to it in a global var... + if ( is_array($funcname) && is_object($funcname[0]) ) + { + $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0]; + $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; + $realfuncname = '$obj->'.$funcname[1]; + } + else + { + $realfuncname = $plainfuncname; + } + foreach($parsvariations as $pars) + { + $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']); + } + else + { + $sig[] = Value::$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, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."'); else {\n"; + //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; + $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n"; + if($returns == Value::$xmlrpcDateTime || $returns == Value::$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 '.$plainfuncname); + 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 a user-defined PHP class or php object, map its methods onto a list of + * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server + * object and called from remote clients (as well as their corresponding signature info). + * + * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class + * @param array $extra_options see the docs for wrap_php_method for more options + * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance + * @return array or false on failure + * + * @todo get_class_methods will return both static and non-static methods. + * we have to differentiate the action, depending on wheter we recived a class name or object + */ + public function wrap_php_class($classname, $extra_options=array()) + { + $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; + $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; + + $result = array(); + $mlist = get_class_methods($classname); + foreach($mlist as $mname) + { + if ($methodfilter == '' || preg_match($methodfilter, $mname)) + { + // echo $mlist."\n"; + $func = new ReflectionMethod($classname, $mname); + if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) + { + if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || + (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))) + { + $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); + if ( $methodwrap ) + { + $result[$methodwrap['function']] = $methodwrap['function']; + } + } + } + } + } + return $result; + } + + /** + * 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 + * object 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 principle 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 options 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 unspecified, 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... + */ + public 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 options) - 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; + // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... + $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 = $this->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) + */ + public 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 .= $this->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... + */ + protected 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 = $this->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 '.$this->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 '.$this->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. + */ + protected 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; + } + +} \ No newline at end of file diff --git a/test/testsuite.php b/test/testsuite.php index c1a111b5..34069e20 100644 --- a/test/testsuite.php +++ b/test/testsuite.php @@ -2,9 +2,11 @@ include_once(__DIR__.'/../vendor/autoload.php'); -include(__DIR__.'/parse_args.php'); +include_once(__DIR__.'/../lib/xmlrpc.inc'); +include_once(__DIR__.'/../lib/xmlrpcs.inc'); +include_once(__DIR__.'/../lib/xmlrpc_wrappers.inc'); -require_once(__DIR__.'/../lib/xmlrpc_wrappers.php'); +include(__DIR__.'/parse_args.php'); //require_once 'PHPUnit/TestDecorator.php'; diff --git a/test/verify_compat.php b/test/verify_compat.php index a9862c4d..c9c4ad24 100644 --- a/test/verify_compat.php +++ b/test/verify_compat.php @@ -19,7 +19,7 @@ function phpxmlrpc_verify_compat($mode='client') $ver = phpversion(); $tests['php_version'] = array(); $tests['php_version']['description'] = 'PHP version found: '.$ver.".\n\n"; - if (version_compare($ver, '5.1.0') < 0) + 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'; @@ -66,7 +66,7 @@ function phpxmlrpc_verify_compat($mode='client') $ver = phpversion(); $tests['php_version'] = array(); $tests['php_version']['description'] = 'PHP version found: '.$ver.".\n\n"; - if (version_compare($ver, '5.1.0') < 0) + 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'; @@ -142,7 +142,7 @@ function phpxmlrpc_verify_compat($mode='client')

PHPXMLRPC compatibility assessment with the current PHP install

-

For phpxmlrpc version 3.0 or later

+

For phpxmlrpc version 4.0 or later

Server usage

From e2ef0823a57f66ef5260006a2d08528428457c84 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 14 Dec 2014 23:23:23 +0000 Subject: [PATCH 026/228] WIP fix bugs after introduction of namespaces, found trying to run the testsuite --- debugger/action.php | 4 ++-- demo/client/wrap.php | 2 +- demo/server/server.php | 2 +- lib/xmlrpc.inc | 4 ++++ src/Encoder.php | 2 +- src/PhpXmlRpc.php | 35 +++++++++++++++++++++++++++++++++++ src/Response.php | 2 +- src/Server.php | 2 +- src/Value.php | 8 ++++---- 9 files changed, 50 insertions(+), 11 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index f56946cf..fae20652 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -149,10 +149,10 @@ switch ($action) { case 'wrap': - @include('xmlrpc_wrappers.php'); + @include('xmlrpc_wrappers.inc'); if (!function_exists('build_remote_method_wrapper_code')) { - die('Error: to enable creation of method stubs the xmlrpc_wrappers.php file is needed'); + die('Error: to enable creation of method stubs the xmlrpc_wrappers.inc file is needed'); } // fall thru intentionally case 'describe': diff --git a/demo/client/wrap.php b/demo/client/wrap.php index faae4bf4..8ec452cd 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -9,7 +9,7 @@ return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals diff --git a/demo/server/server.php b/demo/server/server.php index d17f73c1..853dc4b6 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -19,7 +19,7 @@ include("xmlrpc.inc"); include("xmlrpcs.inc"); - include("xmlrpc_wrappers.php"); + include("xmlrpc_wrappers.inc"); /** * Used to test usage of object methods in dispatch maps and in wrapper code diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index c706758a..57a0adc4 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -49,6 +49,10 @@ include_once(__DIR__.'/../src/Response.php'); include_once(__DIR__.'/../src/Client.php'); include_once(__DIR__.'/../src/Encoder.php'); + +/* Expose the global variables which used to be defined */ +PhpXmlRpc\PhpXmlRpc::exportGlobals(); + /* Expose with the old names the classes which have been namespaced */ class xmlrpcval extends PhpXmlRpc\Value diff --git a/src/Encoder.php b/src/Encoder.php index f464f822..d687467d 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -185,7 +185,7 @@ function encode($php_val, $options=array()) } break; case 'object': - if(is_a($php_val, 'xmlrpcval')) + if(is_a($php_val, 'PhpXmlRpc\Value')) { $xmlrpc_val = $php_val; } diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 201ba635..dc0c4ab7 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -83,4 +83,39 @@ class PhpXmlRpc 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'); + $staticProperties = $reflection->getStaticProperties(); + foreach ($staticProperties as $name => $value) + { + $GLOBALS[$name] = $value; + } + } + + /** + * 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]; + } + } } diff --git a/src/Response.php b/src/Response.php index 5f0f6ec7..bd205a8f 100644 --- a/src/Response.php +++ b/src/Response.php @@ -139,7 +139,7 @@ public function serialize($charset_encoding='') } else { - if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval')) + if(!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) { if (is_string($this->val) && $this->valtyp == 'xml') { diff --git a/src/Server.php b/src/Server.php index a3cde97e..74acb069 100644 --- a/src/Server.php +++ b/src/Server.php @@ -740,7 +740,7 @@ protected function execute($m, $params=null, $paramtypes=null) if (!is_a($r, 'xmlrpcresp')) { error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); - if (is_a($r, 'xmlrpcval')) + if (is_a($r, 'PhpXmlRpc\Value')) { $r = new Response($r); } diff --git a/src/Value.php b/src/Value.php index fd4a840c..04df2ebf 100644 --- a/src/Value.php +++ b/src/Value.php @@ -130,10 +130,10 @@ function addScalar($val, $type='string') switch($this->mytype) { case 1: - error_log('XML-RPC: '.__METHOD__.': scalar xmlrpcval can have only one value'); + 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 xmlrpcval'); + 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 @@ -464,9 +464,9 @@ public function scalartyp() { reset($this->me); list($a,)=each($this->me); - if($a==static::xmlrpcI4) + if($a==static::$xmlrpcI4) { - $a=static::xmlrpcInt; + $a=static::$xmlrpcInt; } return $a; } From eba8c60be4ad9d6799591719e96f2a2170d849c0 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 14 Dec 2014 23:37:26 +0000 Subject: [PATCH 027/228] Rename and reformat demo xml files --- demo/demo1.txt | 36 ---------------------------- demo/demo1.xml | 60 ++++++++++++++++++++++++++++++++++++++++++++++ demo/demo2.txt | 8 ------- demo/demo2.xml | 10 ++++++++ demo/demo3.txt | 17 ------------- demo/demo3.xml | 21 ++++++++++++++++ doc/xmlrpc_php.xml | 4 ++-- 7 files changed, 93 insertions(+), 63 deletions(-) delete mode 100644 demo/demo1.txt create mode 100644 demo/demo1.xml delete mode 100644 demo/demo2.txt create mode 100644 demo/demo2.xml delete mode 100644 demo/demo3.txt create mode 100644 demo/demo3.xml diff --git a/demo/demo1.txt b/demo/demo1.txt deleted file mode 100644 index 2543c90a..00000000 --- a/demo/demo1.txt +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - -thearray - - -ABCDEFHIJ -1234 -1 - - - -theint -23 - -thestring -foobarwhizz - -thestruct - -one -1 - -two -2 - - - - - - - - diff --git a/demo/demo1.xml b/demo/demo1.xml new file mode 100644 index 00000000..eeb6a69b --- /dev/null +++ b/demo/demo1.xml @@ -0,0 +1,60 @@ + + + + + + + + thearray + + + + + ABCDEFHIJ + + + 1234 + + + 1 + + + + + + + theint + + 23 + + + + thestring + + foobarwhizz + + + + thestruct + + + + one + + 1 + + + + two + + 2 + + + + + + + + + + diff --git a/demo/demo2.txt b/demo/demo2.txt deleted file mode 100644 index 28914225..00000000 --- a/demo/demo2.txt +++ /dev/null @@ -1,8 +0,0 @@ - - - - - South Dakota's own - - - diff --git a/demo/demo2.xml b/demo/demo2.xml new file mode 100644 index 00000000..3289caf5 --- /dev/null +++ b/demo/demo2.xml @@ -0,0 +1,10 @@ + + + + + + South Dakota's own + + + + diff --git a/demo/demo3.txt b/demo/demo3.txt deleted file mode 100644 index 9247fca3..00000000 --- a/demo/demo3.txt +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - faultCode - 4 - - - faultString - Too many parameters. - - - - - diff --git a/demo/demo3.xml b/demo/demo3.xml new file mode 100644 index 00000000..e77a4af3 --- /dev/null +++ b/demo/demo3.xml @@ -0,0 +1,21 @@ + + + + + + + faultCode + + 4 + + + + faultString + + Too many parameters. + + + + + + diff --git a/doc/xmlrpc_php.xml b/doc/xmlrpc_php.xml index d9fff5f6..139ef6c7 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/xmlrpc_php.xml @@ -997,7 +997,7 @@ PHP-XMLRPC User manual - demo/demo1.txt, demo/demo2.txt, demo/demo3.txt + demo/demo1.xml, demo/demo2.xml, demo/demo3.xml XML-RPC responses captured in a file for testing purposes (you @@ -1801,7 +1801,7 @@ $msg = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int"))); parseResponse. This method is useful to construct responses from pre-prepared - files (see files demo1.txt, demo2.txt, demo3.txt + files (see files demo1.xml, demo2.xml, demo3.xml in this distribution). It processes any HTTP headers it finds, and does not close the file handle. From 9e9427b378d6be8e12413145f9aeaf6cfe324e62 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 15 Dec 2014 00:07:10 +0000 Subject: [PATCH 028/228] WIP - more fixes --- demo/server/discuss.php | 4 +-- demo/server/proxy.php | 4 +-- demo/server/server.php | 10 +++++--- demo/vardemo.php | 4 ++- src/PhpXmlRpc.php | 9 +++++-- src/Request.php | 2 +- src/Response.php | 2 +- src/Server.php | 54 ++++++++++++++++++++--------------------- src/Wrapper.php | 4 +-- 9 files changed, 51 insertions(+), 42 deletions(-) diff --git a/demo/server/discuss.php b/demo/server/discuss.php index dcba75d6..d1dc0a4e 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -1,7 +1,7 @@ xmlrpc getStaticProperties(); - foreach ($staticProperties as $name => $value) + foreach ($reflection->getStaticProperties() as $name => $value) + { + $GLOBALS[$name] = $value; + } + + $reflection = new \ReflectionClass('PhpXmlRpc\Value'); + foreach ($reflection->getStaticProperties() as $name => $value) { $GLOBALS[$name] = $value; } diff --git a/src/Request.php b/src/Request.php index c341407f..8b4a1139 100644 --- a/src/Request.php +++ b/src/Request.php @@ -482,7 +482,7 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' // 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_entitites() and setting xmlrpc_internalencoding + // 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'); diff --git a/src/Response.php b/src/Response.php index bd205a8f..65325477 100644 --- a/src/Response.php +++ b/src/Response.php @@ -134,7 +134,7 @@ public function serialize($charset_encoding='') $result .= "\n" . "\nfaultCode\n" . $this->errno . "\n\n\nfaultString\n" . -Charset::instance()->encode_entitites($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" . +Charset::instance()->encode_entities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" . "\n\n"; } else diff --git a/src/Server.php b/src/Server.php index 74acb069..639095ad 100644 --- a/src/Server.php +++ b/src/Server.php @@ -205,10 +205,10 @@ function serializeDebug($charset_encoding='') { $out .= "\n"; } - if($GLOBALS['_xmlrpc_debuginfo']!='') + if( static::$_xmlrpc_debuginfo!='') { - $out .= "\n"; + $out .= "\n"; // NB: a better solution MIGHT be to use CDATA, but we need to insert it // into return payload AFTER the beginning tag //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n"; @@ -388,7 +388,7 @@ protected function verifySignature($in, $sig) } // param index is $n+1, as first member of sig is return type - if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue']) + if($pt != $cursig[$n+1] && $cursig[$n+1] != Value::$xmlrpcValue) { $itsOK=0; $pno=$n+1; @@ -472,14 +472,14 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, } else { - $r = new Response(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']); return $r; } } else { //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new Response(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']); return $r; } } @@ -497,7 +497,7 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, /// @todo we should parse q=0.x preferences instead of getting first charset specified... $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); // Give preference to internal encoding - $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + $known_charsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII'); foreach ($known_charsets as $charset) { foreach ($client_accepted_charsets as $accepted) @@ -561,7 +561,7 @@ public function parseRequest($data, $req_encoding='') //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding); - $req_encoding = $GLOBALS['xmlrpc_defencoding']; + $req_encoding = PhpXmlRpc::$xmlrpc_defencoding; } /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, // the encoding is not UTF8 and there are non-ascii chars in the text... @@ -579,14 +579,14 @@ public function parseRequest($data, $req_encoding='') // 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_entitites() and setting xmlrpc_internalencoding - if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + // 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, $GLOBALS['xmlrpc_internalencoding']); + xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); } $xmlRpcParser = new XMLParser(); @@ -674,8 +674,8 @@ protected function execute($m, $params=null, $paramtypes=null) { // No such method return new Response(0, - $GLOBALS['xmlrpcerr']['unknown_method'], - $GLOBALS['xmlrpcstr']['unknown_method']); + PhpXmlRpc::$xmlrpcerr['unknown_method'], + PhpXmlRpc::$xmlrpcstr['unknown_method']); } // Check signature @@ -695,8 +695,8 @@ protected function execute($m, $params=null, $paramtypes=null) // Didn't match. return new Response( 0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}" + PhpXmlRpc::$xmlrpcerr['incorrect_params'], + PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errstr}" ); } } @@ -713,8 +713,8 @@ protected function execute($m, $params=null, $paramtypes=null) error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable"); return new Response( 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method" + PhpXmlRpc::$xmlrpcerr['server_error'], + PhpXmlRpc::$xmlrpcstr['server_error'] . ": no function matches method" ); } @@ -748,8 +748,8 @@ protected function execute($m, $params=null, $paramtypes=null) { $r = new Response( 0, - $GLOBALS['xmlrpcerr']['server_error'], - $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object" + PhpXmlRpc::$xmlrpcerr['server_error'], + PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpcresp object" ); } } @@ -808,7 +808,7 @@ protected function execute($m, $params=null, $paramtypes=null) $r = new Response(0, $e->getCode(), $e->getMessage()); break; default: - $r = new Response(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']); } } if($this->debug > 2) @@ -891,7 +891,7 @@ protected function getSystemDispatchMap() ), 'system.getCapabilities' => array( 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities', - 'signature' => array(array($GLOBALS['xmlrpcStruct'])), + 'signature' => array(array(Value::$xmlrpcStruct)), 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to', 'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')) ) @@ -920,7 +920,7 @@ public static function _xmlrpcs_getCapabilities($server, $m=null) ); // NIL extension - if ($GLOBALS['xmlrpc_null_extension']) { + if (PhpXmlRpc::$xmlrpc_null_extension) { $outAr['nil'] = new Value(array( 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), 'specVersion' => new Value(1, 'int') @@ -992,7 +992,7 @@ public static function _xmlrpcs_methodSignature($server, $m) } else { - $r=new Response(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + $r=new Response(0,PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']); } return $r; } @@ -1030,7 +1030,7 @@ public static function _xmlrpcs_methodHelp($server, $m) } else { - $r=new Response(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']); + $r=new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']); } return $r; } @@ -1039,8 +1039,8 @@ public static function _xmlrpcs_multicall_error($err) { if(is_string($err)) { - $str = $GLOBALS['xmlrpcstr']["multicall_${err}"]; - $code = $GLOBALS['xmlrpcerr']["multicall_${err}"]; + $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"]; + $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"]; } else { @@ -1091,8 +1091,8 @@ public static function _xmlrpcs_multicall_do_call($server, $call) { $i++; return _xmlrpcs_multicall_error(new Response(0, - $GLOBALS['xmlrpcerr']['incorrect_params'], - $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i)); + PhpXmlRpc::$xmlrpcerr['incorrect_params'], + PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i)); } } diff --git a/src/Wrapper.php b/src/Wrapper.php index 138d186e..ff1bbba9 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -214,7 +214,7 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr // start to introspect PHP code if(is_array($funcname)) { - $func = new ReflectionMethod($funcname[0], $funcname[1]); + $func = new \ReflectionMethod($funcname[0], $funcname[1]); if($func->isPrivate()) { error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname); @@ -244,7 +244,7 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr } else { - $func = new ReflectionFunction($funcname); + $func = new \ReflectionFunction($funcname); } if($func->isInternal()) { From 62a0db8fc871a6c8667dcc101e38710cf9a89b4d Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 15 Dec 2014 00:16:09 +0000 Subject: [PATCH 029/228] WIP - more fixes --- demo/server/discuss.php | 2 ++ demo/server/proxy.php | 2 ++ src/Server.php | 13 +++++++++---- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/demo/server/discuss.php b/demo/server/discuss.php index d1dc0a4e..6996564f 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -1,5 +1,7 @@ raw_data = $raw_data; - if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors']) + if($this->debug > 2 && static::$_xmlrpcs_occurred_errors) { $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . - $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++"); + static::$_xmlrpcs_occurred_errors . "+++END+++"); } $payload=$this->xml_header($resp_charset); From 2c0f47e778a796891fc7190c31dc73a9ea7f8289 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 15 Dec 2014 00:33:41 +0000 Subject: [PATCH 030/228] WIP - more fixes: system methods in server, charset guessing --- src/Encoder.php | 174 ++++++++++++++++++++++++------------------------ src/Request.php | 3 +- src/Server.php | 19 +++--- 3 files changed, 99 insertions(+), 97 deletions(-) diff --git a/src/Encoder.php b/src/Encoder.php index d687467d..371237ba 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -132,7 +132,7 @@ function decode($xmlrpc_val, $options=array()) * * @param mixed $php_val the value to be converted into an xmlrpcval object * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' - * @return xmlrpcval + * @return \PhpXmlrpc\Value */ function encode($php_val, $options=array()) { @@ -319,102 +319,102 @@ function decode_xml($xml_val, $options=array()) } -/** - * 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 unconforming (legacy?) clients/servers, - * which will be most probably using UTF-8 anyway... - * - * @param string $httpheader the http Content-type header - * @param string $xmlchunk xml content buffer - * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) - * @return string - * - * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! - */ -function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=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 cointrol 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)) + /** + * 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 unconforming (legacy?) clients/servers, + * which will be most probably using UTF-8 anyway... + * + * @param string $httpheader the http Content-type header + * @param string $xmlchunk xml content buffer + * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) + * @return string + * + * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! + */ + static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) { - return strtoupper(trim($matches[1], " \t\"")); - } + // discussion: see http://www.yale.edu/pclt/encoding/ + // 1 - test if encoding is specified in HTTP HEADERS - // 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'; - } + //Details: + // LWS: (\13\10)?( |\t)+ + // token: (any char but excluded stuff)+ + // quoted string: " (any char but double quotes and cointrol 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... - // 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)); - } + /// @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\"")); + } - // 4 - if mbstring is available, let it do the guesswork - // NB: we favour finding an encoding that is compatible with what we can process - if(extension_loaded('mbstring')) - { - if($encoding_prefs) + // 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)) { - $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + return 'UCS-4'; } - else + elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk)) { - $enc = mb_detect_encoding($xmlchunk); + return 'UTF-16'; } - // 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') + elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk)) { - $enc = 'US-'.$enc; + 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 + // NB: we favour finding an encoding that is compatible with what we can process + if(extension_loaded('mbstring')) + { + if($encoding_prefs) + { + $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + } + 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; } - 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; } -} } \ No newline at end of file diff --git a/src/Request.php b/src/Request.php index 8b4a1139..00db29cb 100644 --- a/src/Request.php +++ b/src/Request.php @@ -4,6 +4,7 @@ use PhpXmlRpc\Helper\Http; use PhpXmlRpc\Helper\XMLParser; +use PhpXmlRpc\Helper\Encoder; class Request { @@ -463,7 +464,7 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' } // try to 'guestimate' the character encoding of the received response - $resp_encoding = guess_encoding(@$this->httpResponse['headers']['content-type'], $data); + $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data); // if response charset encoding is not known / supported, try to use // the default encoding and parse the xml anyway, but log a warning... diff --git a/src/Server.php b/src/Server.php index c4d16a86..56fd6e80 100644 --- a/src/Server.php +++ b/src/Server.php @@ -4,6 +4,7 @@ use PhpXmlRpc\Helper\XMLParser; use PhpXmlRpc\Helper\Charset; +use PhpXmlRpc\Helper\Encoder; /** * Error handler used to track errors that occur during server-side execution of PHP code. @@ -225,7 +226,7 @@ function serializeDebug($charset_encoding='') * Execute the xmlrpc request, printing the response * @param string $data the request body. If null, the http POST request will be examined * @param bool $return_payload When true, return the response but do not echo it or any http header - * @return xmlrpcresp the response object (usually not used by caller...) + * @return Response the response object (usually not used by caller...) */ function service($data=null, $return_payload=false) { @@ -532,7 +533,7 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, // 'guestimate' request encoding /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? - $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $req_encoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', $data); return null; @@ -673,7 +674,7 @@ protected function execute($m, $params=null, $paramtypes=null) $methName = $m; } $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); - $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; + $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap; if(!isset($dmap[$methName]['function'])) { @@ -865,7 +866,7 @@ function echoInput() /* Functions that implement system.XXX methods of xmlrpc servers */ - protected function getSystemDispatchMap() + public function getSystemDispatchMap() { return array( 'system.listMethods' => array( @@ -944,7 +945,7 @@ public static function _xmlrpcs_listMethods($server, $m=null) // if called in pl } if($server->allow_system_funcs) { - foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val) + foreach($server->getSystemDispatchMap() as $key => $val) { $outAr[]=new Value($key, 'string'); } @@ -966,11 +967,11 @@ public static function _xmlrpcs_methodSignature($server, $m) } if(strpos($methName, "system.") === 0) { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + $dmap=$server->getSystemDispatchMap(); } else { - $dmap=$server->dmap; $sysCall=0; + $dmap=$server->dmap; } if(isset($dmap[$methName])) { @@ -1016,11 +1017,11 @@ public static function _xmlrpcs_methodHelp($server, $m) } if(strpos($methName, "system.") === 0) { - $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1; + $dmap=$server->getSystemDispatchMap(); } else { - $dmap=$server->dmap; $sysCall=0; + $dmap=$server->dmap; } if(isset($dmap[$methName])) { From c79e320a2d513194a0e7b65d26407a45ae4cbdd3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 16 Dec 2014 01:01:58 +0000 Subject: [PATCH 031/228] WIP - more bugfixes and start of testsuite reimplementation --- composer.json | 2 +- src/Client.php | 12 +- src/Request.php | 1 - src/Response.php | 8 +- src/Server.php | 122 ++- src/Wrapper.php | 10 +- test/benchmark.php | 299 ------ test/parse_args.php | 128 --- test/testsuite.php | 1550 ----------------------------- tests/InvalidHostTest.php | 82 ++ tests/LocalhostTest.php | 627 ++++++++++++ tests/ParsingBugsTest.php | 502 ++++++++++ tests/benchmark.php | 307 ++++++ tests/parse_args.php | 143 +++ {test => tests}/verify_compat.php | 0 15 files changed, 1737 insertions(+), 2056 deletions(-) delete mode 100644 test/benchmark.php delete mode 100644 test/parse_args.php delete mode 100644 test/testsuite.php create mode 100644 tests/InvalidHostTest.php create mode 100644 tests/LocalhostTest.php create mode 100644 tests/ParsingBugsTest.php create mode 100644 tests/benchmark.php create mode 100644 tests/parse_args.php rename {test => tests}/verify_compat.php (100%) diff --git a/composer.json b/composer.json index db3c1498..30644908 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ "ext-xml": "*" }, "require-dev": { - "phpunit/phpunit": "4.3.*" + "phpunit/phpunit": ">=4.0.0" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", diff --git a/src/Client.php b/src/Client.php index a31c7327..c12d4070 100644 --- a/src/Client.php +++ b/src/Client.php @@ -59,7 +59,7 @@ class Client /// Charset encoding to be used in serializing request. NULL = use ASCII public $request_charset_encoding = ''; /** - * Decides the content of xmlrpcresp objects returned by calls to send() + * Decides the content of Response objects returned by calls to send() * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' */ public $return_type = 'xmlrpcvals'; @@ -324,7 +324,7 @@ function SetUserAgent( $agentstring ) * @param mixed $msg The request object, or an array of requests for using multicall, or the complete xml representation of a request * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used - * @return xmlrpcresp + * @return Response */ public function& send($msg, $timeout=0, $method='') { @@ -337,7 +337,7 @@ public function& send($msg, $timeout=0, $method='') if(is_array($msg)) { - // $msg is an array of xmlrpcmsg's + // $msg is an array of Requests $r = $this->multicall($msg, $timeout, $method); return $r; } @@ -348,7 +348,7 @@ public function& send($msg, $timeout=0, $method='') $msg = $n; } - // where msg is an xmlrpcmsg + // where msg is a Request $msg->debug=$this->debug; if($method == 'https') @@ -908,7 +908,7 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', * NB: trying to shoehorn extra functionality into existing syntax has resulted * in pretty much convoluted code... * - * @param array $msgs an array of xmlrpcmsg objects + * @param Request[] $msgs an array of Request objects * @param integer $timeout connection timeout (in seconds) * @param string $method the http protocol variant to be used * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted @@ -939,7 +939,7 @@ public function multicall($msgs, $timeout=0, $method='', $fallback=true) } else { - if (is_a($results, 'xmlrpcresp')) + if (is_a($results, '\PhpXmlRpc\Response')) { $result = $results; } diff --git a/src/Request.php b/src/Request.php index 00db29cb..70519319 100644 --- a/src/Request.php +++ b/src/Request.php @@ -4,7 +4,6 @@ use PhpXmlRpc\Helper\Http; use PhpXmlRpc\Helper\XMLParser; -use PhpXmlRpc\Helper\Encoder; class Request { diff --git a/src/Response.php b/src/Response.php index 65325477..fe945c13 100644 --- a/src/Response.php +++ b/src/Response.php @@ -26,7 +26,7 @@ class Response * * @todo add check that $val / $fcode / $fstr is of correct type??? * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain - * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called... + * php val, or a complete xml chunk, depending on usage of Client::send() inside which creator is called... */ function __construct($val, $fcode = 0, $fstr = '', $valtyp='') { @@ -85,7 +85,7 @@ public function faultString() /** * Returns the value received by the server. - * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects + * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects */ public function value() { @@ -99,7 +99,7 @@ public function value() * 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 xmlrpc_client::setCookie) or not + * request to the server (using Client::setCookie) or not * @return array array of cookies received from the server */ public function cookies() @@ -150,7 +150,7 @@ public function serialize($charset_encoding='') else { /// @todo try to build something serializable? - die('cannot serialize xmlrpcresp objects whose content is native php values'); + die('cannot serialize xmlrpc response objects whose content is native php values'); } } else diff --git a/src/Server.php b/src/Server.php index 56fd6e80..7f42b164 100644 --- a/src/Server.php +++ b/src/Server.php @@ -4,58 +4,6 @@ use PhpXmlRpc\Helper\XMLParser; use PhpXmlRpc\Helper\Charset; -use PhpXmlRpc\Helper\Encoder; - -/** -* Error handler used to track errors that occur during server-side execution of PHP code. -* This allows to report back to the client whether an internal error has occurred or not -* using an xmlrpc response object, instead of letting the client deal with the html junk -* that a PHP execution error on the server generally entails. -* -* NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. -* -*/ -function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) -{ - // obey the @ protocol - if (error_reporting() == 0) - return; - - //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) - if($errcode != E_STRICT) - { - \PhpXmlRpc\Server::error_occurred($errstring); - } - // Try to avoid as much as possible disruption to the previous error handling - // mechanism in place - if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') - { - // The previous error handler was the default: all we should do is log error - // to the default error log (if level high enough) - if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) - { - error_log($errstring); - } - } - else - { - // Pass control on to previous error handler, trying to avoid loops... - if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler') - { - // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers - if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) - { - // the following works both with static class methods and plain object methods as error handler - call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); - } - else - { - $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); - } - } - } -} - class Server { @@ -421,7 +369,7 @@ protected function verifySignature($in, $sig) /** * Parse http headers received along with xmlrpc request. If needed, inflate request - * @return mixed null on success or an xmlrpcresp + * @return mixed null on success or a Response */ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) { @@ -544,7 +492,7 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, * php function registered with the server * @param string $data the xml request * @param string $req_encoding (optional) the charset encoding of the xml request - * @return xmlrpcresp + * @return Response */ public function parseRequest($data, $req_encoding='') { @@ -658,10 +606,10 @@ public function parseRequest($data, $req_encoding='') /** * Execute a method invoked by the client, checking parameters used - * @param mixed $m either an xmlrpcmsg obj or a method name + * @param mixed $m either a Request obj or a method name * @param array $params array with method parameters as php types (if m is method name only) * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) - * @return xmlrpcresp + * @return Response */ protected function execute($m, $params=null, $paramtypes=null) { @@ -728,7 +676,7 @@ protected function execute($m, $params=null, $paramtypes=null) // processing of user function, and log them as part of response if($this->debug > 2) { - $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); + $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')); } try { @@ -743,9 +691,9 @@ protected function execute($m, $params=null, $paramtypes=null) { $r = call_user_func($func, $m); } - if (!is_a($r, 'xmlrpcresp')) + if (!is_a($r, 'PhpXmlRpc\Response')) { - error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object"); + error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpc response object"); if (is_a($r, 'PhpXmlRpc\Value')) { $r = new Response($r); @@ -755,7 +703,7 @@ protected function execute($m, $params=null, $paramtypes=null) $r = new Response( 0, PhpXmlRpc::$xmlrpcerr['server_error'], - PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpcresp object" + PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response object" ); } } @@ -792,8 +740,8 @@ protected function execute($m, $params=null, $paramtypes=null) $r = call_user_func_array($func, $params); } } - // the return type can be either an xmlrpcresp object or a plain php value... - if (!is_a($r, 'xmlrpcresp')) + // the return type can be either a Response object or a plain php value... + if (!is_a($r, '\PhpXmlRpc\Response')) { // what should we assume here about automatic encoding of datetimes // and php classes instances??? @@ -1181,4 +1129,54 @@ public static function _xmlrpcs_multicall($server, $m) return new Response(new Value($result, 'array')); } + + /** + * Error handler used to track errors that occur during server-side execution of PHP code. + * This allows to report back to the client whether an internal error has occurred or not + * using an xmlrpc response object, instead of letting the client deal with the html junk + * that a PHP execution error on the server generally entails. + * + * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. + * + */ + public static function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null) + { + // obey the @ protocol + if (error_reporting() == 0) + return; + + //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) + if($errcode != E_STRICT) + { + \PhpXmlRpc\Server::error_occurred($errstring); + } + // Try to avoid as much as possible disruption to the previous error handling + // mechanism in place + if($GLOBALS['_xmlrpcs_prev_ehandler'] == '') + { + // The previous error handler was the default: all we should do is log error + // to the default error log (if level high enough) + if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) + { + error_log($errstring); + } + } + else + { + // Pass control on to previous error handler, trying to avoid loops... + if($GLOBALS['_xmlrpcs_prev_ehandler'] != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) + { + if(is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) + { + // the following works both with static class methods and plain object methods as error handler + call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); + } + else + { + $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); + } + } + } + } + } diff --git a/src/Wrapper.php b/src/Wrapper.php index ff1bbba9..3b7addd2 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -122,7 +122,7 @@ public function xmlrpc_2_php_type($xmlrpctype) * 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) + * php functions (ie. functions not expecting a single Request 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') and array('class', 'methodname') are ok too @@ -518,7 +518,7 @@ public function wrap_php_class($classname, $extra_options=array()) /** * 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 + * params and results. The generated php function will return a Response * object for failed xmlrpc calls * * Known limitations: @@ -538,7 +538,7 @@ public function wrap_php_class($classname, $extra_options=array()) * 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 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 options include * integer signum the index of the method signature to use in mapping (if method exposes many sigs) @@ -548,7 +548,7 @@ public function wrap_php_class($classname, $extra_options=array()) * 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 + * mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the Response 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... */ @@ -688,7 +688,7 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $time * 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 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) */ diff --git a/test/benchmark.php b/test/benchmark.php deleted file mode 100644 index 8c0f6941..00000000 --- a/test/benchmark.php +++ /dev/null @@ -1,299 +0,0 @@ - $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'); - - $test_results=array(); - $xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable'); - if ($xd) - $num_tests = 1; - else - $num_tests = 10; - - $title = 'XML-RPC Benchmark Tests'; - - if(isset($_SERVER['REQUEST_METHOD'])) - { - echo "\n\n\n$title\n\n\n

$title

\n
\n";
-    }
-    else
-    {
-        echo "$title\n\n";
-    }
-
-    if(isset($_SERVER['REQUEST_METHOD']))
-    {
-        echo "

Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."

\n"; - if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; - flush(); - ob_flush(); - } - else - { - echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; - if ($xd) echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: ".xdebug_get_profiler_filename()."\n"; - } - - // test 'old 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 xmlrpcval($val[0], 'int'); - $values[] = new xmlrpcval($val[1], 'double'); - $values[] = new xmlrpcval($val[2], 'string'); - $values[] = new xmlrpcval($val[3], 'boolean'); - $values[] = new xmlrpcval($val[4], 'dateTime.iso8601'); - $values[] = new xmlrpcval($val[5], 'int'); - $values[] = new xmlrpcval($val[6], 'double'); - $values[] = new xmlrpcval($val[7], 'string'); - $values[] = new xmlrpcval($val[8], 'boolean'); - $values[] = new xmlrpcval($val[9], 'dateTime.iso8601'); - $valarray[$key] = new xmlrpcval($values, 'array'); - } - $vals[] = new xmlrpcval($valarray, 'struct'); - } - $value = new xmlrpcval($vals, 'array'); - $out = $value->serialize(); - } - end_test('Data encoding (large array)', 'manual encoding', $out); - - begin_test('Data encoding (large array)', 'automatic encoding'); - for ($i = 0; $i < $num_tests; $i++) - { - $value = php_xmlrpc_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 xmlrpcmsg(''); - $out = new xmlrpcresp($value); - $in = ''."\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(); - for ($k = 0; $k < $value->arraysize(); $k++) - { - $val1 = $value->arraymem($k); - $out = array(); - while (list($name, $val) = $val1->structeach()) - { - $out[$name] = array(); - for ($j = 0; $j < $val->arraysize(); $j++) - { - $data = $val->arraymem($j); - $out[$name][] = $data->scalarval(); - } - } // while - $result[] = $out; - } - } - end_test('Data decoding (large array)', 'manual decoding', $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 - $value = php_xmlrpc_encode($data1, array('auto_dates')); - $msg = new xmlrpcmsg('interopEchoTests.echoValue', array($value)); - $msgs=array(); - for ($i = 0; $i < 25; $i++) - $msgs[] = $msg; - $server = explode(':', $LOCALSERVER); - if(count($server) > 1) - { - $c = new xmlrpc_client($URI, $server[0], $server[1]); - } - else - { - $c = new xmlrpc_client($URI, $LOCALSERVER); - } - // do not interfere with http compression - $c->accepted_compression = array(); - //$c->debug=true; - - if (function_exists('gzinflate')) { - $c->accepted_compression = null; - } - begin_test('Repeated send (small array)', 'http 10'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 10', $response); - - if (function_exists('curl_init')) - { - begin_test('Repeated send (small array)', 'http 11 w. keep-alive'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11 w. keep-alive', $response); - - $c->keepalive = false; - begin_test('Repeated send (small array)', 'http 11'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11', $response); - } - - begin_test('Repeated send (small array)', 'multicall'); - $response =& $c->send($msgs); - foreach ($response as $key =>& $val) - { - $val = $val->value(); - } - end_test('Repeated send (small array)', 'multicall', $response); - - if (function_exists('gzinflate')) - { - $c->accepted_compression = array('gzip'); - $c->request_compression = 'gzip'; - - begin_test('Repeated send (small array)', 'http 10 w. compression'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 10 w. compression', $response); - - if (function_exists('curl_init')) - { - begin_test('Repeated send (small array)', 'http 11 w. keep-alive and compression'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11 w. keep-alive and compression', $response); - - $c->keepalive = false; - begin_test('Repeated send (small array)', 'http 11 w. compression'); - $response = array(); - for ($i = 0; $i < 25; $i++) - { - $resp =& $c->send($msg, 10, 'http11'); - $response[] = $resp->value(); - } - end_test('Repeated send (small array)', 'http 11 w. compression', $response); - } - - begin_test('Repeated send (small array)', 'multicall w. compression'); - $response =& $c->send($msgs); - foreach ($response as $key =>& $val) - { - $val = $val->value(); - } - end_test('Repeated send (small array)', 'multicall w. compression', $response); - } - - } // end of 'if no xdebug profiling' - - 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 sterted'); - $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(); - } - - - 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(isset($_SERVER['REQUEST_METHOD'])) - { - echo "\n
\n\n\n"; - } diff --git a/test/parse_args.php b/test/parse_args.php deleted file mode 100644 index f8e2f558..00000000 --- a/test/parse_args.php +++ /dev/null @@ -1,128 +0,0 @@ - 1) - { - $$param[0]=$param[1]; - } - } - } - } - elseif(!ini_get('register_globals')) - { - // play nice to 'safe' PHP installations with register globals OFF - // NB: we might as well consider using $_GET stuff later on... - extract($_GET); - extract($_POST); - } - - if(!isset($DEBUG)) - { - $DEBUG = 0; - } - else - { - $DEBUG = intval($DEBUG); - } - - if(!isset($LOCALSERVER)) - { - if(isset($HTTP_HOST)) - { - $LOCALSERVER = $HTTP_HOST; - } - elseif(isset($_SERVER['HTTP_HOST'])) - { - $LOCALSERVER = $_SERVER['HTTP_HOST']; - } - else - { - $LOCALSERVER = 'localhost'; - } - } - if(!isset($HTTPSSERVER)) - { - $HTTPSSERVER = 'xmlrpc.usefulinc.com'; - } - if(!isset($HTTPSURI)) - { - $HTTPSURI = '/server.php'; - } - if(!isset($HTTPSIGNOREPEER)) - { - $HTTPSIGNOREPEER = false; - } - if(!isset($PROXY)) - { - $PROXYSERVER = null; - } - else - { - $arr = explode(':',$PROXY); - $PROXYSERVER = $arr[0]; - if(count($arr) > 1) - { - $PROXYPORT = $arr[1]; - } - else - { - $PROXYPORT = 8080; - } - } - // used to silence testsuite warnings about proxy code not being tested - if(!isset($NOPROXY)) - { - $NOPROXY = false; - } - 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('/test/testsuite.php', '/demo/server/server.php', $REQUEST_URI); - $URI = str_replace('/testsuite.php', '/server.php', $URI); - $URI = str_replace('/test/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('/test/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']); - $URI = str_replace('/testsuite.php', '/server.php', $URI); - $URI = str_replace('/test/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; - } - if(!isset($LOCALPATH)) - { - $LOCALPATH = __DIR__; - } diff --git a/test/testsuite.php b/test/testsuite.php deleted file mode 100644 index 34069e20..00000000 --- a/test/testsuite.php +++ /dev/null @@ -1,1550 +0,0 @@ - 1) - { - $this->client=new xmlrpc_client($URI, $server[0], $server[1]); - } - else - { - $this->client=new xmlrpc_client($URI, $LOCALSERVER); - } - if($DEBUG) - { - $this->client->setDebug($DEBUG); - } - $this->client->request_compression = $this->request_compression; - $this->client->accepted_compression = $this->accepted_compression; - } - - function send($msg, $errrorcode=0, $return_response=false) - { - $r = $this->client->send($msg, $this->timeout, $this->method); - // for multicall, return directly array of responses - if(is_array($r)) - { - return $r; - } - $this->assertEquals($r->faultCode(), $errrorcode, 'Error '.$r->faultCode().' connecting to server: '.$r->faultString()); - if(!$r->faultCode()) - { - if($return_response) - return $r; - else - return $r->value(); - } - else - { - return null; - } - } - - 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: -->"; - $f=new xmlrpcmsg('examples.stringecho', array( - new xmlrpcval($sendstring, 'string') - )); - $v=$this->send($f); - 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()); - } - } - - function testAddingDoubles() - { - // note that rounding errors mean we - // keep precision to sensible levels here ;-) - $a=12.13; $b=-23.98; - $f=new xmlrpcmsg('examples.addtwodouble',array( - new xmlrpcval($a, 'double'), - new xmlrpcval($b, 'double') - )); - $v=$this->send($f); - if($v) - { - $this->assertEquals($a+$b,$v->scalarval()); - } - } - - function testAdding() - { - $f=new xmlrpcmsg('examples.addtwo',array( - new xmlrpcval(12, 'int'), - new xmlrpcval(-23, 'int') - )); - $v=$this->send($f); - if($v) - { - $this->assertEquals(12-23, $v->scalarval()); - } - } - - function testInvalidNumber() - { - $f=new xmlrpcmsg('examples.addtwo',array( - new xmlrpcval('fred', 'int'), - new xmlrpcval("\"; exec('ls')", 'int') - )); - $v=$this->send($f); - /// @todo a fault condition should be generated here - /// by the server, which we pick up on - if($v) - { - $this->assertEquals(0, $v->scalarval()); - } - } - - function testBoolean() - { - $f=new xmlrpcmsg('examples.invertBooleans', array( - new xmlrpcval(array( - new xmlrpcval(true, 'boolean'), - new xmlrpcval(false, 'boolean'), - new xmlrpcval(1, 'boolean'), - new xmlrpcval(0, 'boolean'), - //new xmlrpcval('true', 'boolean'), - //new xmlrpcval('false', 'boolean') - ), - 'array' - ))); - $answer='0101'; - $v=$this->send($f); - 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); - } - } - - 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'; - $f=new xmlrpcmsg('examples.decode64',array( - new xmlrpcval($sendstring, 'base64') - )); - $v=$this->send($f); - 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()); - } - } - - 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()); - } - } - } - - function testCountEntities() - { - $sendstring = "h'fd>onc>>l>>rw&bpu>q>esend($f); - 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); - } - } - - function _multicall_msg($method, $params) - { - $struct['methodName'] = new xmlrpcval($method, 'string'); - $struct['params'] = new xmlrpcval($params, 'array'); - return new xmlrpcval($struct, 'struct'); - } - - 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' - ); - - $f = new xmlrpcmsg('system.multicall', array($arg)); - $v = $this->send($f); - 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" - ); - } - } - - 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" - ); - } - - 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"); - } - } - - 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'; - } - - function testCatchWarnings() - { - $f = new xmlrpcmsg('examples.generatePHPWarning', array( - new xmlrpcval('whatever', 'string') - )); - $v = $this->send($f); - if($v) - { - $this->assertEquals($v->scalarval(), true); - } - } - - function testCatchExceptions() - { - global $URI; - $f = new xmlrpcmsg('examples.raiseException', array( - new xmlrpcval('whatever', 'string') - )); - $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); - $this->client->path = $URI.'?EXCEPTION_HANDLING=1'; - $v = $this->send($f, 1); - $this->client->path = $URI.'?EXCEPTION_HANDLING=2'; - $v = $this->send($f, $GLOBALS['xmlrpcerr']['invalid_return']); - } - - function testZeroParams() - { - $f = new xmlrpcmsg('system.listMethods'); - $v = $this->send($f); - } - - function testCodeInjectionServerSide() - { - $f = new xmlrpcmsg('system.MethodHelp'); - $f->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; - $v = $this->send($f); - //$v = $r->faultCode(); - if ($v) - { - $this->assertEquals(0, $v->structsize()); - } - } - - function testAutoRegisteredFunction() - { - $f=new xmlrpcmsg('examples.php.getStateName',array( - new xmlrpcval(23, 'int') - )); - $v=$this->send($f); - if($v) - { - $this->assertEquals('Michigan', $v->scalarval()); - } - else - { - $this->fail('Note: server can only auto register functions if running with PHP 5.0.3 and up'); - } - } - - function testAutoRegisteredClass() - { - $f=new xmlrpcmsg('examples.php2.getStateName',array( - new xmlrpcval(23, 'int') - )); - $v=$this->send($f); - if($v) - { - $this->assertEquals('Michigan', $v->scalarval()); - $f=new xmlrpcmsg('examples.php3.getStateName',array( - new xmlrpcval(23, 'int') - )); - $v=$this->send($f); - if($v) - { - $this->assertEquals('Michigan', $v->scalarval()); - } - } - else - { - $this->fail('Note: server can only auto register class methods if running with PHP 5.0.3 and up'); - } - } - - function testAutoRegisteredMethod() - { - // 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' => 1)); - if($func == '') - { - $this->fail('Registration of examples.getStateName failed'); - } - else - { - $v=$func(23); - // work around bug in current version of phpunit - if(is_object($v)) - { - $v = var_export($v, true); - } - $this->assertEquals('Michigan', $v); - } - } - - 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); - $f=new xmlrpcmsg('examples.setcookies',array($cookiesval)); - $r=$this->send($f, 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]); - 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); - } - } - - function testSetCookies() - { - // let server set to us some cookies we tell it - $cookies = array( - 'c0' => null, - 'c1' => 1, - 'c2' => '2 3', - 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-' - ); - $f=new xmlrpcmsg('examples.getcookies',array()); - foreach ($cookies as $cookie => $val) - { - $this->client->setCookie($cookie, $val); - $cookies[$cookie] = (string) $cookies[$cookie]; - } - $r = $this->client->send($f, $this->timeout, $this->method); - $this->assertEquals($r->faultCode(), 0, 'Error '.$r->faultCode().' connecting to server: '.$r->faultString()); - if(!$r->faultCode()) - { - $v = $r->value(); - $v = php_xmlrpc_decode($v); - // on IIS and Apache getallheaders returns something slightly different... - $this->assertEquals($v, $cookies); - } - } - - function testSendTwiceSameMsg() - { - $f=new xmlrpcmsg('examples.stringecho', array( - new xmlrpcval('hello world', 'string') - )); - $v1 = $this->send($f); - $v2 = $this->send($f); - //$v = $r->faultCode(); - if ($v1 && $v2) - { - $this->assertEquals($v2, $v1); - } - } -} - -class LocalHostMultiTests extends LocalhostTests -{ - function _runtests() - { - global $failed_tests; - foreach(get_class_methods('LocalhostTests') as $meth) - { - if(strpos($meth, 'test') === 0 && $meth != 'testHttps' && $meth != 'testCatchExceptions') - { - if (!isset($failed_tests[$meth])) - { - $this->$meth(); - } - } - if ($this->_failed) - { - break; - } - } - } - - function testDeflate() - { - if(!function_exists('gzdeflate')) - { - $this->fail('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->fail('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->fail('CURL missing: cannot test http 1.1'); - return; - } - $this->method = 'http11'; - $this->client->keepalive = true; - $this->_runtests(); - } - - function testProxy() - { - global $PROXYSERVER, $PROXYPORT, $NOPROXY; - if ($PROXYSERVER) - { - $this->client->setProxy($PROXYSERVER, $PROXYPORT); - $this->_runtests(); - } - else - if (!$NOPROXY) - $this->fail('PROXY definition missing: cannot test proxy'); - } - - function testHttp11() - { - if(!function_exists('curl_init')) - { - $this->fail('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->fail('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->fail('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() - { - global $PROXYSERVER, $PROXYPORT, $NOPROXY; - if(!function_exists('curl_init')) - { - $this->fail('CURL missing: cannot test http 1.1 w. proxy'); - return; - } - else if ($PROXYSERVER == '') - { - if (!$NOPROXY) - $this->fail('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($PROXYSERVER, $PROXYPORT); - //$this->client->verifyhost = 0; - //$this->client->verifypeer = 0; - $this->client->keepalive = false; - $this->_runtests(); - } - - function testHttps() - { - global $HTTPSSERVER, $HTTPSURI, $HTTPSIGNOREPEER; - if(!function_exists('curl_init')) - { - $this->fail('CURL missing: cannot test https functionality'); - return; - } - $this->client->server = $HTTPSSERVER; - $this->method = 'https'; - $this->client->method = 'https'; - $this->client->path = $HTTPSURI; - $this->client->setSSLVerifyPeer( !$HTTPSIGNOREPEER ); - // silence warning with newish php versions - $this->client->setSSLVerifyHost(2); - $this->_runtests(); - } - - function testHttpsProxy() - { - global $HTTPSSERVER, $HTTPSURI, $PROXYSERVER, $PROXYPORT, $NOPROXY; - if(!function_exists('curl_init')) - { - $this->fail('CURL missing: cannot test https functionality'); - return; - } - else if ($PROXYSERVER == '') - { - if (!$NOPROXY) - $this->fail('PROXY definition missing: cannot test proxy w. http 1.1'); - return; - } - $this->client->server = $HTTPSSERVER; - $this->method = 'https'; - $this->client->method = 'https'; - $this->client->setProxy($PROXYSERVER, $PROXYPORT); - $this->client->path = $HTTPSURI; - $this->_runtests(); - } - - function testUTF8Responses() - { - global $URI; - //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8'; - $this->client->path = $URI.'?RESPONSE_ENCODING=UTF-8'; - $this->_runtests(); - } - - function testUTF8Requests() - { - $this->client->request_charset_encoding = 'UTF-8'; - $this->_runtests(); - } - - function testISOResponses() - { - global $URI; - //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8'; - $this->client->path = $URI.'?RESPONSE_ENCODING=ISO-8859-1'; - $this->_runtests(); - } - - function testISORequests() - { - $this->client->request_charset_encoding = 'ISO-8859-1'; - $this->_runtests(); - } -} - -class ParsingBugsTests extends PHPUnit_Framework_TestCase -{ - function testMinusOneString() - { - $v=new xmlrpcval('-1'); - $u=new xmlrpcval('-1', 'string'); - $this->assertEquals($u->scalarval(), $v->scalarval()); - } - - 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 = new xmlrpcmsg('dummy'); - $r = $m->parseResponse($r); - $v = $r->value(); - $this->assertEquals($v->structmemexists($str), true); - } - - function testUnicodeInErrorString() - { - $response = utf8_encode( -' - - - - - - - - -faultCode -888 - - -faultString -���àüè - - - - -'); - $m=new xmlrpcmsg('dummy'); - $r=$m->parseResponse($response); - $v=$r->faultString(); - $this->assertEquals('���', $v); - } - - function testValidNumbers() - { - $m=new xmlrpcmsg('dummy'); - $fp= -' - - - - - - -integer1 -01 - - -float1 -01.10 - - -integer2 -+1 - - -float2 -+1.10 - - -float3 --1.10e2 - - - - - -'; - $r=$m->parseResponse($fp); - $v=$r->value(); - $s=$v->structmem('integer1'); - $t=$v->structmem('float1'); - $u=$v->structmem('integer2'); - $w=$v->structmem('float2'); - $x=$v->structmem('float3'); - $this->assertEquals(1, $s->scalarval()); - $this->assertEquals(1.1, $t->scalarval()); - $this->assertEquals(1, $u->scalarval()); - $this->assertEquals(1.1, $w->scalarval()); - $this->assertEquals(-110.0, $x->scalarval()); - } - - 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); - } - - 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()); - } - - 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); - } - - function testEncodeArray() - { - $r=range(1, 100); - $v = php_xmlrpc_encode($r); - $this->assertEquals('array', $v->kindof()); - } - - function testEncodeRecursive() - { - $v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string')); - $this->assertEquals('scalar', $v->kindof()); - } - - function testBrokenRequests() - { - $s = new xmlrpc_server(); - // omitting the 'params' tag: not tolerated by the lib anymore -$f = ' - -system.methodHelp - -system.methodHelp - -'; - $r = $s->parserequest($f); - $this->assertEquals(15, $r->faultCode()); - // omitting a 'param' tag -$f = ' - -system.methodHelp - -system.methodHelp - -'; - $r = $s->parserequest($f); - $this->assertEquals(15, $r->faultCode()); - // omitting a 'value' tag -$f = ' - -system.methodHelp - -system.methodHelp - -'; - $r = $s->parserequest($f); - $this->assertEquals(15, $r->faultCode()); - } - - function testBrokenResponses() - { - $m=new xmlrpcmsg('dummy'); - //$m->debug = 1; - // omitting the 'params' tag: no more tolerated by the lib... -$f = ' - - -system.methodHelp - -'; - $r = $m->parseResponse($f); - $this->assertEquals(2, $r->faultCode()); - // omitting the 'param' tag: no more tolerated by the lib... -$f = ' - - -system.methodHelp - -'; - $r = $m->parseResponse($f); - $this->assertEquals(2, $r->faultCode()); - // omitting a 'value' tag: KO -$f = ' - - -system.methodHelp - -'; - $r = $m->parseResponse($f); - $this->assertEquals(2, $r->faultCode()); - } - - function testBuggyHttp() - { - $s = new xmlrpcmsg('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? - - - - - -userid311127 -dateCreated20011126T09:17:52contenthello world. 2 newlines follow - - -and there they were.postid7414222 - - '; - $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()); - } - - function testStringBug() - { - $s = new xmlrpcmsg('dummy'); -$f = ' - - - - - - - - -success - -1 - - - -sessionID - -S300510007I - - - - - - - '; - $r = $s->parseResponse($f); - $v = $r->value(); - $s = $v->structmem('sessionID'); - $this->assertEquals('S300510007I', $s->scalarval()); - } - - function testWhiteSpace() - { - $s = new xmlrpcmsg('dummy'); -$f = 'userid311127 -dateCreated20011126T09:17:52contenthello world. 2 newlines follow - - -and there they were.postid7414222 -'; - $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()); - } - - function testDoubleDataInArrayTag() - { - $s = new xmlrpcmsg('dummy'); -$f = ' - - - -'; - $r = $s->parseResponse($f); - $v = $r->faultCode(); - $this->assertEquals(2, $v); -$f = ' -Hello world - - -'; - $r = $s->parseResponse($f); - $v = $r->faultCode(); - $this->assertEquals(2, $v); - } - - function testDoubleStuffInValueTag() - { - $s = new xmlrpcmsg('dummy'); -$f = ' -hello world - - -'; - $r = $s->parseResponse($f); - $v = $r->faultCode(); - $this->assertEquals(2, $v); -$f = ' -hello -world - -'; - $r = $s->parseResponse($f); - $v = $r->faultCode(); - $this->assertEquals(2, $v); -$f = ' -hello -hello>world - -'; - $r = $s->parseResponse($f); - $v = $r->faultCode(); - $this->assertEquals(2, $v); - } - - function testAutodecodeResponse() - { - $s = new xmlrpcmsg('dummy'); -$f = 'userid311127 -dateCreated20011126T09:17:52contenthello world. 2 newlines follow - - -and there they were.postid7414222 -'; - $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); - } - - function testNoDecodeResponse() - { - $s = new xmlrpcmsg('dummy'); -$f = 'userid311127 -dateCreated20011126T09:17:52contenthello world. 2 newlines follow - - -and there they were.postid7414222'; - $r = $s->parseResponse($f, true, 'xml'); - $v = $r->value(); - $this->assertEquals($f, $v); - } - - 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 xmlrpcresp($v1); - $r2 = php_xmlrpc_decode_xml($r1->serialize()); - $r2->serialize(); // needed to set internal member payload - $this->assertEquals($r1, $r2); - $m1 = new xmlrpcmsg('hello dolly', array($v1)); - $m2 = php_xmlrpc_decode_xml($m1->serialize()); - $m2->serialize(); // needed to set internal member payload - $this->assertEquals($m1, $m2); - } - - function testUTF8Request() - { - $sendstring='κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! - $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; - $f = new xmlrpcval($sendstring, 'string'); - $v=$f->serialize(); - $this->assertEquals("κόσμε\n", $v); - $GLOBALS['xmlrpc_internalencoding'] = 'ISO-8859-1'; - } - - function testUTF8Response() - { - $s = new xmlrpcmsg('dummy'); -$f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n".'userid311127 -dateCreated20011126T09:17:52content'.utf8_encode('������').'postid7414222 -'; - $r = $s->parseResponse($f, false, 'phpvals'); - $v = $r->value(); - $v = $v['content']; - $this->assertEquals("������", $v); -$f = 'userid311127 -dateCreated20011126T09:17:52content'.utf8_encode('������').'postid7414222 -'; - $r = $s->parseResponse($f, false, 'phpvals'); - $v = $r->value(); - $v = $v['content']; - $this->assertEquals("������", $v); - } - - function testUTF8IntString() - { - $v=new xmlrpcval(100, 'int'); - $s=$v->serialize('UTF-8'); - $this->assertequals("100\n", $s); - } - - function testStringInt() - { - $v=new xmlrpcval('hello world', 'int'); - $s=$v->serialize(); - $this->assertequals("0\n", $s); - } - - 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); - } - - function testNilvalue() - { - // default case: we do not accept nil values received - $v = new xmlrpcval('hello', 'null'); - $r = new xmlrpcresp($v); - $s = $r->serialize(); - $m = new xmlrpcmsg('dummy'); - $r = $m->parseresponse($s); - $this->assertequals(2, $r->faultCode()); - // enable reception of nil values - $GLOBALS['xmlrpc_null_extension'] = true; - $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; - // serialization - $v = new xmlrpcval('hello', 'null'); - $s = $v->serialize(); - $this->assertequals(1, preg_match( '##', $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; - $r = $m->parseresponse($s); - $this->assertequals(2, $r->faultCode()); - } - - 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); - } - } -} - -class InvalidHostTests extends PHPUnit_Framework_TestCase -{ - var $client = null; - - function setUp() - { - global $DEBUG,$LOCALSERVER; - $this->client=new xmlrpc_client('/NOTEXIST.php', $LOCALSERVER, 80); - if($DEBUG) - { - $this->client->setDebug($DEBUG); - } - } - - function test404() - { - $f = new xmlrpcmsg('examples.echo',array( - new xmlrpcval('hello', 'string') - )); - $r = $this->client->send($f, 5); - $this->assertEquals(5, $r->faultCode()); - } - - function testSrvNotFound() - { - $f = new xmlrpcmsg('examples.echo',array( - new xmlrpcval('hello', 'string') - )); - $this->client->server .= 'XXX'; - $r = $this->client->send($f, 5); - $this->assertEquals(5, $r->faultCode()); - } - - function testCurlKAErr() - { - global $LOCALSERVER, $URI; - if(!function_exists('curl_init')) - { - $this->fail('CURL missing: cannot test curl keepalive errors'); - return; - } - $f = 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($f, 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(':', $LOCALSERVER); - if(count($server) > 1) - { - $this->client->port = $server[1]; - } - $this->client->server = $server[0]; - $this->client->path = $URI; - - $r = $this->client->send($f, 5, 'http11'); - $this->assertEquals(0, $r->faultCode()); - $ro = $r->value(); - is_object( $ro ) && $this->assertEquals('hello', $ro->scalarVal()); - } -} - - -$suite->addTest(new LocalhostTests('testString')); -$suite->addTest(new LocalhostTests('testAdding')); -$suite->addTest(new LocalhostTests('testAddingDoubles')); -$suite->addTest(new LocalhostTests('testInvalidNumber')); -$suite->addTest(new LocalhostTests('testBoolean')); -$suite->addTest(new LocalhostTests('testCountEntities')); -$suite->addTest(new LocalhostTests('testBase64')); -$suite->addTest(new LocalhostTests('testDateTime')); -$suite->addTest(new LocalhostTests('testServerMulticall')); -$suite->addTest(new LocalhostTests('testClientMulticall1')); -$suite->addTest(new LocalhostTests('testClientMulticall2')); -$suite->addTest(new LocalhostTests('testClientMulticall3')); -$suite->addTest(new LocalhostTests('testCatchWarnings')); -$suite->addTest(new LocalhostTests('testCatchExceptions')); -$suite->addTest(new LocalhostTests('testZeroParams')); -$suite->addTest(new LocalhostTests('testCodeInjectionServerSide')); -$suite->addTest(new LocalhostTests('testAutoRegisteredFunction')); -$suite->addTest(new LocalhostTests('testAutoRegisteredMethod')); -$suite->addTest(new LocalhostTests('testSetCookies')); -$suite->addTest(new LocalhostTests('testGetCookies')); -$suite->addTest(new LocalhostTests('testSendTwiceSameMsg')); - -$suite->addTest(new LocalhostMultiTests('testUTF8Requests')); -$suite->addTest(new LocalhostMultiTests('testUTF8Responses')); -$suite->addTest(new LocalhostMultiTests('testISORequests')); -$suite->addTest(new LocalhostMultiTests('testISOResponses')); -$suite->addTest(new LocalhostMultiTests('testGzip')); -$suite->addTest(new LocalhostMultiTests('testDeflate')); -$suite->addTest(new LocalhostMultiTests('testProxy')); -$suite->addTest(new LocalhostMultiTests('testHttp11')); -$suite->addTest(new LocalhostMultiTests('testHttp11Gzip')); -$suite->addTest(new LocalhostMultiTests('testHttp11Deflate')); -$suite->addTest(new LocalhostMultiTests('testKeepAlives')); -$suite->addTest(new LocalhostMultiTests('testHttp11Proxy')); -$suite->addTest(new LocalhostMultiTests('testHttps')); -$suite->addTest(new LocalhostMultiTests('testHttpsProxy')); - -$suite->addTest(new InvalidHostTests('test404')); -//$suite->addTest(new InvalidHostTests('testSrvNotFound')); -$suite->addTest(new InvalidHostTests('testCurlKAErr')); - -$suite->addTest(new ParsingBugsTests('testMinusOneString')); -$suite->addTest(new ParsingBugsTests('testUnicodeInMemberName')); -$suite->addTest(new ParsingBugsTests('testUnicodeInErrorString')); -$suite->addTest(new ParsingBugsTests('testValidNumbers')); -$suite->addTest(new ParsingBugsTests('testAddScalarToStruct')); -$suite->addTest(new ParsingBugsTests('testAddStructToStruct')); -$suite->addTest(new ParsingBugsTests('testAddArrayToArray')); -$suite->addTest(new ParsingBugsTests('testEncodeArray')); -$suite->addTest(new ParsingBugsTests('testEncodeRecursive')); -$suite->addTest(new ParsingBugsTests('testBrokenrequests')); -$suite->addTest(new ParsingBugsTests('testBrokenresponses')); -$suite->addTest(new ParsingBugsTests('testBuggyHttp')); -$suite->addTest(new ParsingBugsTests('testStringBug')); -$suite->addTest(new ParsingBugsTests('testWhiteSpace')); -$suite->addTest(new ParsingBugsTests('testAutodecodeResponse')); -$suite->addTest(new ParsingBugsTests('testNoDecodeResponse')); -$suite->addTest(new ParsingBugsTests('testAutoCoDec')); -$suite->addTest(new ParsingBugsTests('testUTF8Response')); -$suite->addTest(new ParsingBugsTests('testUTF8Request')); -$suite->addTest(new ParsingBugsTests('testUTF8IntString')); -$suite->addTest(new ParsingBugsTests('testStringInt')); -$suite->addTest(new ParsingBugsTests('testStructMemExists')); -$suite->addTest(new ParsingBugsTests('testDoubleDataInArrayTag')); -$suite->addTest(new ParsingBugsTests('testDoubleStuffInValueTag')); -$suite->addTest(new ParsingBugsTests('testNilValue')); -$suite->addTest(new ParsingBugsTests('testLocale')); - -$title = 'XML-RPC Unit Tests'; - -if(isset($only)) -{ - $suite = new PHPUnit_TestSuite($only); -} - -if(isset($_SERVER['REQUEST_METHOD'])) -{ - echo "\n\n\n$title\n\n\n

$title

\n"; -} -else -{ - echo "$title\n\n"; -} - -if(isset($_SERVER['REQUEST_METHOD'])) -{ - echo "

Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."

\n"; - echo '

Running '.$suite->count().' tests (some of which are multiple) against servers: http://'.htmlspecialchars($LOCALSERVER.$URI).' and https://'.htmlspecialchars($HTTPSSERVER.$HTTPSURI)."\n ...

\n"; - flush(); - @ob_flush(); -} -else -{ - echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; - echo 'Running '.$suite->count().' tests (some of which are multiple) against servers: http://'.$LOCALSERVER.$URI.' and https://'.$HTTPSSERVER.$HTTPSURI."\n\n"; -} - -// do some basic timing measurement -list($micro, $sec) = explode(' ', microtime()); -$start_time = $sec + $micro; - -//$PHPUnit = new PHPUnit; -//$result = $PHPUnit->run($suite, ($DEBUG == 0 ? '.' : '
')); -$result = $suite->run(); - -list($micro, $sec) = explode(' ', microtime()); -$end_time = $sec + $micro; - -if(!isset($_SERVER['REQUEST_METHOD'])) -{ - echo $result->toString()."\n"; -} - -if(isset($_SERVER['REQUEST_METHOD'])) -{ - echo '

'.$result->failureCount()." test failures

\n"; - printf("Time spent: %.2f secs
\n", $end_time - $start_time); -} -else -{ - echo $result->failureCount()." test failures\n"; - printf("Time spent: %.2f secs\n", $end_time - $start_time); -} - -if($result->failureCount() && !$DEBUG) -{ - $target = strpos($_SERVER['PHP_SELF'], '?') ? $_SERVER['PHP_SELF'].'&DEBUG=1' : $_SERVER['PHP_SELF'].'?DEBUG=1'; - $t2 = strpos($_SERVER['PHP_SELF'], '?') ? $_SERVER['PHP_SELF'].'&DEBUG=2' : $_SERVER['PHP_SELF'].'?DEBUG=2'; - if(isset($_SERVER['REQUEST_METHOD'])) - { - echo '

Run testsuite with DEBUG=1 to have more detail about tests results. Or with DEBUG=2 for even more.

'."\n"; - } - else - { - echo "Run testsuite with DEBUG=1 (or 2) to have more detail about tests results\n"; - } -} - -if(isset($_SERVER['REQUEST_METHOD'])) -{ -?> -More options... - -toHTML()."\n\n\n"; -} -else -{ - exit($result->failureCount()); -} diff --git a/tests/InvalidHostTest.php b/tests/InvalidHostTest.php new file mode 100644 index 00000000..fb89b432 --- /dev/null +++ b/tests/InvalidHostTest.php @@ -0,0 +1,82 @@ +args = argParser::getArgs(); + + $this->client = new xmlrpc_client('/NOTEXIST.php', $this->args['LOCALSERVER'], 80); + if($this->args['DEBUG']) + { + $this->client->setDebug($this->args['DEBUG']); + } + } + + function test404() + { + $f = new xmlrpcmsg('examples.echo',array( + new xmlrpcval('hello', 'string') + )); + $r = $this->client->send($f, 5); + $this->assertEquals(5, $r->faultCode()); + } + + function testSrvNotFound() + { + $f = new xmlrpcmsg('examples.echo',array( + new xmlrpcval('hello', 'string') + )); + $this->client->server .= 'XXX'; + $r = $this->client->send($f, 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()); + } + } + + function testCurlKAErr() + { + if(!function_exists('curl_init')) + { + $this->markTestSkipped('CURL missing: cannot test curl keepalive errors'); + return; + } + $f = 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($f, 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($f, 5, 'http11'); + $this->assertEquals(0, $r->faultCode()); + $ro = $r->value(); + is_object( $ro ) && $this->assertEquals('hello', $ro->scalarVal()); + } +} diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php new file mode 100644 index 00000000..28025244 --- /dev/null +++ b/tests/LocalhostTest.php @@ -0,0 +1,627 @@ +args = argParser::getArgs(); + + $server = explode(':', $this->args['LOCALSERVER']); + if(count($server) > 1) + { + $this->client=new xmlrpc_client(['URI'], $server[0], $server[1]); + } + else + { + $this->client=new xmlrpc_client($this->args['URI'], $this->args['LOCALSERVER']); + } + if($this->args['DEBUG']) + { + $this->client->setDebug($this->args['DEBUG']); + } + $this->client->request_compression = $this->request_compression; + $this->client->accepted_compression = $this->accepted_compression; + } + + function send($msg, $errrorcode=0, $return_response=false) + { + $r = $this->client->send($msg, $this->timeout, $this->method); + // for multicall, return directly array of responses + if(is_array($r)) + { + return $r; + } + $this->assertEquals($r->faultCode(), $errrorcode, 'Error '.$r->faultCode().' connecting to server: '.$r->faultString()); + if(!$r->faultCode()) + { + if($return_response) + return $r; + else + return $r->value(); + } + else + { + return null; + } + } + + 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: -->"; + $f=new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval($sendstring, 'string') + )); + $v=$this->send($f); + 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()); + } + } + + function testAddingDoubles() + { + // note that rounding errors mean we + // keep precision to sensible levels here ;-) + $a=12.13; $b=-23.98; + $f=new xmlrpcmsg('examples.addtwodouble',array( + new xmlrpcval($a, 'double'), + new xmlrpcval($b, 'double') + )); + $v=$this->send($f); + if($v) + { + $this->assertEquals($a+$b,$v->scalarval()); + } + } + + function testAdding() + { + $f=new xmlrpcmsg('examples.addtwo',array( + new xmlrpcval(12, 'int'), + new xmlrpcval(-23, 'int') + )); + $v=$this->send($f); + if($v) + { + $this->assertEquals(12-23, $v->scalarval()); + } + } + + function testInvalidNumber() + { + $f=new xmlrpcmsg('examples.addtwo',array( + new xmlrpcval('fred', 'int'), + new xmlrpcval("\"; exec('ls')", 'int') + )); + $v=$this->send($f); + /// @todo a fault condition should be generated here + /// by the server, which we pick up on + if($v) + { + $this->assertEquals(0, $v->scalarval()); + } + } + + function testBoolean() + { + $f=new xmlrpcmsg('examples.invertBooleans', array( + new xmlrpcval(array( + new xmlrpcval(true, 'boolean'), + new xmlrpcval(false, 'boolean'), + new xmlrpcval(1, 'boolean'), + new xmlrpcval(0, 'boolean'), + //new xmlrpcval('true', 'boolean'), + //new xmlrpcval('false', 'boolean') + ), + 'array' + ))); + $answer='0101'; + $v=$this->send($f); + 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); + } + } + + 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'; + $f=new xmlrpcmsg('examples.decode64',array( + new xmlrpcval($sendstring, 'base64') + )); + $v=$this->send($f); + 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()); + } + } + + 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()); + } + } + } + + function testCountEntities() + { + $sendstring = "h'fd>onc>>l>>rw&bpu>q>esend($f); + 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); + } + } + + function _multicall_msg($method, $params) + { + $struct['methodName'] = new xmlrpcval($method, 'string'); + $struct['params'] = new xmlrpcval($params, 'array'); + return new xmlrpcval($struct, 'struct'); + } + + 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' + ); + + $f = new xmlrpcmsg('system.multicall', array($arg)); + $v = $this->send($f); + 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" + ); + } + } + + 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" + ); + } + + 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"); + } + } + + 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'; + } + + function testCatchWarnings() + { + $f = new xmlrpcmsg('examples.generatePHPWarning', array( + new xmlrpcval('whatever', 'string') + )); + $v = $this->send($f); + if($v) + { + $this->assertEquals($v->scalarval(), true); + } + } + + function testCatchExceptions() + { + $f = new xmlrpcmsg('examples.raiseException', array( + new xmlrpcval('whatever', 'string') + )); + $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); + $this->client->path = $this->args['URI'].'?EXCEPTION_HANDLING=1'; + $v = $this->send($f, 1); + $this->client->path = $this->args['URI'].'?EXCEPTION_HANDLING=2'; + $v = $this->send($f, $GLOBALS['xmlrpcerr']['invalid_return']); + } + + function testZeroParams() + { + $f = new xmlrpcmsg('system.listMethods'); + $v = $this->send($f); + } + + function testCodeInjectionServerSide() + { + $f = new xmlrpcmsg('system.MethodHelp'); + $f->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; + $v = $this->send($f); + //$v = $r->faultCode(); + if ($v) + { + $this->assertEquals(0, $v->structsize()); + } + } + + function testAutoRegisteredFunction() + { + $f=new xmlrpcmsg('examples.php.getStateName',array( + new xmlrpcval(23, 'int') + )); + $v=$this->send($f); + if($v) + { + $this->assertEquals('Michigan', $v->scalarval()); + } + else + { + $this->fail('Note: server can only auto register functions if running with PHP 5.0.3 and up'); + } + } + + function testAutoRegisteredClass() + { + $f=new xmlrpcmsg('examples.php2.getStateName',array( + new xmlrpcval(23, 'int') + )); + $v=$this->send($f); + if($v) + { + $this->assertEquals('Michigan', $v->scalarval()); + $f=new xmlrpcmsg('examples.php3.getStateName',array( + new xmlrpcval(23, 'int') + )); + $v=$this->send($f); + if($v) + { + $this->assertEquals('Michigan', $v->scalarval()); + } + } + else + { + $this->fail('Note: server can only auto register class methods if running with PHP 5.0.3 and up'); + } + } + + function testAutoRegisteredMethod() + { + // 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' => 1)); + if($func == '') + { + $this->fail('Registration of examples.getStateName failed'); + } + else + { + $v=$func(23); + // work around bug in current version of phpunit + if(is_object($v)) + { + $v = var_export($v, true); + } + $this->assertEquals('Michigan', $v); + } + } + + 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); + $f=new xmlrpcmsg('examples.setcookies',array($cookiesval)); + $r=$this->send($f, 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]); + 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); + } + } + + function testSetCookies() + { + // let server set to us some cookies we tell it + $cookies = array( + 'c0' => null, + 'c1' => 1, + 'c2' => '2 3', + 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-' + ); + $f=new xmlrpcmsg('examples.getcookies',array()); + foreach ($cookies as $cookie => $val) + { + $this->client->setCookie($cookie, $val); + $cookies[$cookie] = (string) $cookies[$cookie]; + } + $r = $this->client->send($f, $this->timeout, $this->method); + $this->assertEquals($r->faultCode(), 0, 'Error '.$r->faultCode().' connecting to server: '.$r->faultString()); + if(!$r->faultCode()) + { + $v = $r->value(); + $v = php_xmlrpc_decode($v); + // on IIS and Apache getallheaders returns something slightly different... + $this->assertEquals($v, $cookies); + } + } + + function testSendTwiceSameMsg() + { + $f=new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval('hello world', 'string') + )); + $v1 = $this->send($f); + $v2 = $this->send($f); + //$v = $r->faultCode(); + if ($v1 && $v2) + { + $this->assertEquals($v2, $v1); + } + } +} \ No newline at end of file diff --git a/tests/ParsingBugsTest.php b/tests/ParsingBugsTest.php new file mode 100644 index 00000000..93626c71 --- /dev/null +++ b/tests/ParsingBugsTest.php @@ -0,0 +1,502 @@ +assertEquals($u->scalarval(), $v->scalarval()); + } + + 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 = new xmlrpcmsg('dummy'); + $r = $m->parseResponse($r); + $v = $r->value(); + $this->assertEquals($v->structmemexists($str), true); + } + + function testUnicodeInErrorString() + { + $response = utf8_encode( + ' + + + + + + + + +faultCode +888 + + +faultString +'.chr(224).chr(252).chr(232).'àüè + + + + +'); + $m = new xmlrpcmsg('dummy'); + $r = $m->parseResponse($response); + $v = $r->faultString(); + $this->assertEquals(chr(224).chr(252).chr(232).chr(224).chr(252).chr(232), $v); + } + + function testValidNumbers() + { + $m = new xmlrpcmsg('dummy'); + $fp= + ' + + + + + + +integer1 +01 + + +float1 +01.10 + + +integer2 ++1 + + +float2 ++1.10 + + +float3 +-1.10e2 + + + + + +'; + $r=$m->parseResponse($fp); + $v=$r->value(); + $s=$v->structmem('integer1'); + $t=$v->structmem('float1'); + $u=$v->structmem('integer2'); + $w=$v->structmem('float2'); + $x=$v->structmem('float3'); + $this->assertEquals(1, $s->scalarval()); + $this->assertEquals(1.1, $t->scalarval()); + $this->assertEquals(1, $u->scalarval()); + $this->assertEquals(1.1, $w->scalarval()); + $this->assertEquals(-110.0, $x->scalarval()); + } + + 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); + } + + 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()); + } + + 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); + } + + function testEncodeArray() + { + $r = range(1, 100); + $v = php_xmlrpc_encode($r); + $this->assertEquals('array', $v->kindof()); + } + + function testEncodeRecursive() + { + $v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string')); + $this->assertEquals('scalar', $v->kindof()); + } + + function testBrokenRequests() + { + $s = new xmlrpc_server(); + // omitting the 'params' tag: not tolerated by the lib anymore + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + // omitting a 'param' tag + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + // omitting a 'value' tag + $f = ' + +system.methodHelp + +system.methodHelp + +'; + $r = $s->parserequest($f); + $this->assertEquals(15, $r->faultCode()); + } + + function testBrokenResponses() + { + $m = new xmlrpcmsg('dummy'); + //$m->debug = 1; + // omitting the 'params' tag: no more tolerated by the lib... + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + // omitting the 'param' tag: no more tolerated by the lib... + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + // omitting a 'value' tag: KO + $f = ' + + +system.methodHelp + +'; + $r = $m->parseResponse($f); + $this->assertEquals(2, $r->faultCode()); + } + + function testBuggyHttp() + { + $s = new xmlrpcmsg('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? + + + + + +userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 + + '; + $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()); + } + + function testStringBug() + { + $s = new xmlrpcmsg('dummy'); + $f = ' + + + + + + + + +success + +1 + + + +sessionID + +S300510007I + + + + + + + '; + $r = $s->parseResponse($f); + $v = $r->value(); + $s = $v->structmem('sessionID'); + $this->assertEquals('S300510007I', $s->scalarval()); + } + + function testWhiteSpace() + { + $s = new xmlrpcmsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 +'; + $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()); + } + + function testDoubleDataInArrayTag() + { + $s = new xmlrpcmsg('dummy'); + $f = ' + + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +Hello world + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + } + + function testDoubleStuffInValueTag() + { + $s = new xmlrpcmsg('dummy'); + $f = ' +hello world + + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +hello +world + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + $f = ' +hello +hello>world + +'; + $r = $s->parseResponse($f); + $v = $r->faultCode(); + $this->assertEquals(2, $v); + } + + function testAutodecodeResponse() + { + $s = new xmlrpcmsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222 +'; + $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); + } + + function testNoDecodeResponse() + { + $s = new xmlrpcmsg('dummy'); + $f = 'userid311127 +dateCreated20011126T09:17:52contenthello world. 2 newlines follow + + +and there they were.postid7414222'; + $r = $s->parseResponse($f, true, 'xml'); + $v = $r->value(); + $this->assertEquals($f, $v); + } + + 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); + } + + 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("κόσμε\n", $v); + $GLOBALS['xmlrpc_internalencoding'] = 'ISO-8859-1'; + \PhpXmlRpc\PhpXmlRpc::importGlobals(); + } + + function testUTF8Response() + { + $s = new xmlrpcmsg('dummy'); + $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n".'userid311127 +dateCreated20011126T09:17:52content'.utf8_encode('').'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals("", $v); + $f = 'userid311127 +dateCreated20011126T09:17:52content'.utf8_encode('').'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals("", $v); + } + + function testUTF8IntString() + { + $v = new xmlrpcval(100, 'int'); + $s = $v->serialize('UTF-8'); + $this->assertequals("100\n", $s); + } + + function testStringInt() + { + $v = new xmlrpcval('hello world', 'int'); + $s = $v->serialize(); + $this->assertequals("0\n", $s); + } + + 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); + } + + function testNilvalue() + { + // default case: we do not accept nil values received + $v = new xmlrpcval('hello', 'null'); + $r = new xmlrpcresp($v); + $s = $r->serialize(); + $m = new xmlrpcmsg('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( '##', $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()); + } + + 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'); + } + } +} diff --git a/tests/benchmark.php b/tests/benchmark.php new file mode 100644 index 00000000..a762e5f7 --- /dev/null +++ b/tests/benchmark.php @@ -0,0 +1,307 @@ + $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 "\n\n\n$title\n\n\n

$title

\n
\n";
+}
+else
+{
+    echo "$title\n\n";
+}
+
+if($is_web)
+{
+    echo "

Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."

\n"; + if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; + flush(); + ob_flush(); +} +else +{ + echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; + if ($xd) echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: ".xdebug_get_profiler_filename()."\n"; +} + +// test 'old 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 xmlrpcval($val[0], 'int'); + $values[] = new xmlrpcval($val[1], 'double'); + $values[] = new xmlrpcval($val[2], 'string'); + $values[] = new xmlrpcval($val[3], 'boolean'); + $values[] = new xmlrpcval($val[4], 'dateTime.iso8601'); + $values[] = new xmlrpcval($val[5], 'int'); + $values[] = new xmlrpcval($val[6], 'double'); + $values[] = new xmlrpcval($val[7], 'string'); + $values[] = new xmlrpcval($val[8], 'boolean'); + $values[] = new xmlrpcval($val[9], 'dateTime.iso8601'); + $valarray[$key] = new xmlrpcval($values, 'array'); + } + $vals[] = new xmlrpcval($valarray, 'struct'); + } + $value = new xmlrpcval($vals, 'array'); + $out = $value->serialize(); +} +end_test('Data encoding (large array)', 'manual encoding', $out); + +begin_test('Data encoding (large array)', 'automatic encoding'); +for ($i = 0; $i < $num_tests; $i++) +{ + $value = php_xmlrpc_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 xmlrpcmsg(''); +$out = new xmlrpcresp($value); +$in = ''."\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(); + for ($k = 0; $k < $value->arraysize(); $k++) + { + $val1 = $value->arraymem($k); + $out = array(); + while (list($name, $val) = $val1->structeach()) + { + $out[$name] = array(); + for ($j = 0; $j < $val->arraysize(); $j++) + { + $data = $val->arraymem($j); + $out[$name][] = $data->scalarval(); + } + } // while + $result[] = $out; + } +} +end_test('Data decoding (large array)', 'manual decoding', $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 + $value = php_xmlrpc_encode($data1, array('auto_dates')); + $msg = new xmlrpcmsg('interopEchoTests.echoValue', array($value)); + $msgs=array(); + for ($i = 0; $i < 25; $i++) + $msgs[] = $msg; + $server = explode(':', $args['LOCALSERVER']); + if(count($server) > 1) + { + $c = new xmlrpc_client($args['URI'], $server[0], $server[1]); + } + else + { + $c = new xmlrpc_client($args['URI'], $args['LOCALSERVER']); + } + // do not interfere with http compression + $c->accepted_compression = array(); + //$c->debug=true; + + if (function_exists('gzinflate')) { + $c->accepted_compression = null; + } + begin_test('Repeated send (small array)', 'http 10'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 10', $response); + + if (function_exists('curl_init')) + { + begin_test('Repeated send (small array)', 'http 11 w. keep-alive'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11 w. keep-alive', $response); + + $c->keepalive = false; + begin_test('Repeated send (small array)', 'http 11'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11', $response); + } + + begin_test('Repeated send (small array)', 'multicall'); + $response = $c->send($msgs); + foreach ($response as $key =>& $val) + { + $val = $val->value(); + } + end_test('Repeated send (small array)', 'multicall', $response); + + if (function_exists('gzinflate')) + { + $c->accepted_compression = array('gzip'); + $c->request_compression = 'gzip'; + + begin_test('Repeated send (small array)', 'http 10 w. compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 10 w. compression', $response); + + if (function_exists('curl_init')) + { + begin_test('Repeated send (small array)', 'http 11 w. keep-alive and compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11 w. keep-alive and compression', $response); + + $c->keepalive = false; + begin_test('Repeated send (small array)', 'http 11 w. compression'); + $response = array(); + for ($i = 0; $i < 25; $i++) + { + $resp = $c->send($msg, 10, 'http11'); + $response[] = $resp->value(); + } + end_test('Repeated send (small array)', 'http 11 w. compression', $response); + } + + begin_test('Repeated send (small array)', 'multicall w. compression'); + $response = $c->send($msgs); + foreach ($response as $key =>& $val) + { + $val = $val->value(); + } + end_test('Repeated send (small array)', '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
\n\n\n"; +} diff --git a/tests/parse_args.php b/tests/parse_args.php new file mode 100644 index 00000000..18b6bc37 --- /dev/null +++ b/tests/parse_args.php @@ -0,0 +1,143 @@ + 0, + 'LOCALSERVER' => 'localhost', + 'HTTPSSERVER' => 'gggeek.ssl.altervista.org', + 'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php', + 'HTTPSIGNOREPEER' => false, + '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($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; + } + +} \ No newline at end of file diff --git a/test/verify_compat.php b/tests/verify_compat.php similarity index 100% rename from test/verify_compat.php rename to tests/verify_compat.php From befde0da202ea003aac701bb4a9a05df5374b3c1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 16 Dec 2014 01:04:30 +0000 Subject: [PATCH 032/228] Make Travis start using new testsuite --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a40322be..58ff96da 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,4 +21,4 @@ before_script: # See: http://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP script: - php -d "include_path=.:./lib:./test" test/testsuite.php LOCALSERVER=gggeek.altervista.org URI=/sw/xmlrpc/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 + phpunit tests LOCALSERVER=gggeek.altervista.org URI=/sw/xmlrpc/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 From a68b8ee4a72d20ad75377cacb7098054249f91ca Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 16 Dec 2014 01:14:44 +0000 Subject: [PATCH 033/228] bypass completely autoloading for old-style api --- lib/xmlrpc.inc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 57a0adc4..8f081279 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -40,6 +40,8 @@ * * 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'); @@ -48,7 +50,10 @@ 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/Date.php'); +include_once(__DIR__.'/../src/Helper/Charset.php'); +include_once(__DIR__.'/../src/Helper/Http.php'); +include_once(__DIR__.'/../src/Helper/XMLParser.php'); /* Expose the global variables which used to be defined */ PhpXmlRpc\PhpXmlRpc::exportGlobals(); From 18bc16094c3a59102cb21ec9a4d013a40f175560 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 11 Jan 2015 16:37:51 +0000 Subject: [PATCH 034/228] Fixes to make the debugger work --- debugger/action.php | 8 ++++---- src/Request.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index fae20652..00af2a03 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -157,20 +157,20 @@ // fall thru intentionally case 'describe': case 'wrap': - $msg[0] = new $msgclass('system.methodHelp', null, $id); + $msg[0] = new $msgclass('system.methodHelp', array(), $id); $msg[0]->addparam(new xmlrpcval($method)); - $msg[1] = new $msgclass('system.methodSignature', null, $id+1); + $msg[1] = new $msgclass('system.methodSignature', array(), $id+1); $msg[1]->addparam(new xmlrpcval($method)); $actionname = 'Description of method "'.$method.'"'; break; case 'list': - $msg[0] = new $msgclass('system.listMethods', null, $id); + $msg[0] = new $msgclass('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 $msgclass($method, null, $id); + $msg[0] = new $msgclass($method, array(), $id); // hack! build xml payload by hand if ($wstype == 1) { diff --git a/src/Request.php b/src/Request.php index 70519319..7c93a220 100644 --- a/src/Request.php +++ b/src/Request.php @@ -31,7 +31,7 @@ function __construct($methodName, $params=array()) } } - private function xml_header($charset_encoding='') + public function xml_header($charset_encoding='') { if ($charset_encoding != '') { @@ -43,7 +43,7 @@ private function xml_header($charset_encoding='') } } - private function xml_footer() + public function xml_footer() { return ''; } From 94e56278400ac8dac93b424b4bc17ba8449b6f75 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 11 Jan 2015 20:07:25 +0000 Subject: [PATCH 035/228] Move benchmark script to the new API --- tests/benchmark.php | 118 ++++++++++++++++++++++++-------------------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/tests/benchmark.php b/tests/benchmark.php index a762e5f7..59a9cb8c 100644 --- a/tests/benchmark.php +++ b/tests/benchmark.php @@ -1,16 +1,22 @@ Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; + echo "

Using lib version: ".PhpXmlRpc::$xmlrpcVersion." on PHP version: ".phpversion()."

\n"; if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; flush(); ob_flush(); } else { - echo "Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."\n"; + 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"; } @@ -89,29 +95,30 @@ function end_test($test_name, $test_case, $test_result) foreach ($data[$j] as $key => $val) { $values = array(); - $values[] = new xmlrpcval($val[0], 'int'); - $values[] = new xmlrpcval($val[1], 'double'); - $values[] = new xmlrpcval($val[2], 'string'); - $values[] = new xmlrpcval($val[3], 'boolean'); - $values[] = new xmlrpcval($val[4], 'dateTime.iso8601'); - $values[] = new xmlrpcval($val[5], 'int'); - $values[] = new xmlrpcval($val[6], 'double'); - $values[] = new xmlrpcval($val[7], 'string'); - $values[] = new xmlrpcval($val[8], 'boolean'); - $values[] = new xmlrpcval($val[9], 'dateTime.iso8601'); - $valarray[$key] = new xmlrpcval($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 xmlrpcval($valarray, 'struct'); + $vals[] = new Value($valarray, 'struct'); } - $value = new xmlrpcval($vals, 'array'); + $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 = php_xmlrpc_encode($data, array('auto_dates')); + $value = $encoder->encode($data, array('auto_dates')); $out = $value->serialize(); } end_test('Data encoding (large array)', 'automatic encoding', $out); @@ -133,8 +140,8 @@ function end_test($test_name, $test_case, $test_result) } // test 'old style' data decoding vs. 'automatic style' decoding -$dummy = new xmlrpcmsg(''); -$out = new xmlrpcresp($value); +$dummy = new Request(''); +$out = new Response($value); $in = ''."\n".$out->serialize(); begin_test('Data decoding (large array)', 'manual decoding'); @@ -184,109 +191,114 @@ function end_test($test_name, $test_case, $test_result) { /// test multicall vs. many calls vs. keep-alives - $value = php_xmlrpc_encode($data1, array('auto_dates')); - $msg = new xmlrpcmsg('interopEchoTests.echoValue', array($value)); - $msgs=array(); + $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++) - $msgs[] = $msg; + $reqs[] = $req; $server = explode(':', $args['LOCALSERVER']); if(count($server) > 1) { - $c = new xmlrpc_client($args['URI'], $server[0], $server[1]); + $srv = $server[1] . '://' . $server[0] . $args['URI']; + $c = new Client($args['URI'], $server[0], $server[1]); } else { - $c = new xmlrpc_client($args['URI'], $args['LOCALSERVER']); + $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('Repeated send (small array)', 'http 10'); + begin_test($testName, 'http 10'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg); + $resp = $c->send($req); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 10', $response); + end_test($testName, 'http 10', $response); if (function_exists('curl_init')) { - begin_test('Repeated send (small array)', 'http 11 w. keep-alive'); + begin_test($testName, 'http 11 w. keep-alive'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg, 10, 'http11'); + $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 11 w. keep-alive', $response); + end_test($testName, 'http 11 w. keep-alive', $response); $c->keepalive = false; - begin_test('Repeated send (small array)', 'http 11'); + begin_test($testName, 'http 11'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg, 10, 'http11'); + $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 11', $response); + end_test($testName, 'http 11', $response); } - begin_test('Repeated send (small array)', 'multicall'); - $response = $c->send($msgs); + begin_test($testName, 'multicall'); + $response = $c->send($reqs); foreach ($response as $key =>& $val) { $val = $val->value(); } - end_test('Repeated send (small array)', 'multicall', $response); + end_test($testName, 'multicall', $response); if (function_exists('gzinflate')) { $c->accepted_compression = array('gzip'); $c->request_compression = 'gzip'; - begin_test('Repeated send (small array)', 'http 10 w. compression'); + begin_test($testName, 'http 10 w. compression'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg); + $resp = $c->send($req); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 10 w. compression', $response); + end_test($testName, 'http 10 w. compression', $response); if (function_exists('curl_init')) { - begin_test('Repeated send (small array)', 'http 11 w. keep-alive and compression'); + begin_test($testName, 'http 11 w. keep-alive and compression'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg, 10, 'http11'); + $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 11 w. keep-alive and compression', $response); + end_test($testName, 'http 11 w. keep-alive and compression', $response); $c->keepalive = false; - begin_test('Repeated send (small array)', 'http 11 w. compression'); + begin_test($testName, 'http 11 w. compression'); $response = array(); for ($i = 0; $i < 25; $i++) { - $resp = $c->send($msg, 10, 'http11'); + $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } - end_test('Repeated send (small array)', 'http 11 w. compression', $response); + end_test($testName, 'http 11 w. compression', $response); } - begin_test('Repeated send (small array)', 'multicall w. compression'); - $response = $c->send($msgs); + begin_test($testName, 'multicall w. compression'); + $response = $c->send($reqs); foreach ($response as $key =>& $val) { $val = $val->value(); } - end_test('Repeated send (small array)', 'multicall w. compression', $response); + end_test($testName, 'multicall w. compression', $response); } } // end of 'if no xdebug profiling' From 2fbd84ece9a7f167192d389b81a20bd3aeeee7a2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 11 Jan 2015 20:15:49 +0000 Subject: [PATCH 036/228] Fix localhostTest --- tests/LocalhostTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php index 28025244..3078960c 100644 --- a/tests/LocalhostTest.php +++ b/tests/LocalhostTest.php @@ -45,7 +45,7 @@ function setUp() $server = explode(':', $this->args['LOCALSERVER']); if(count($server) > 1) { - $this->client=new xmlrpc_client(['URI'], $server[0], $server[1]); + $this->client=new xmlrpc_client($this->args['URI'], $server[0], $server[1]); } else { From df6a966781af900b11587a408665936e91132c4c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 11 Jan 2015 20:34:40 +0000 Subject: [PATCH 037/228] Fix server: multicalls and exception catching --- src/Server.php | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Server.php b/src/Server.php index 7f42b164..81da9ee8 100644 --- a/src/Server.php +++ b/src/Server.php @@ -749,7 +749,7 @@ protected function execute($m, $params=null, $paramtypes=null) } } } - catch(Exception $e) + catch(\Exception $e) { // (barring errors in the lib) an uncatched exception happened // in the called function, we wrap it in a proper error-response @@ -1011,30 +1011,30 @@ public static function _xmlrpcs_multicall_do_call($server, $call) { if($call->kindOf() != 'struct') { - return _xmlrpcs_multicall_error('notstruct'); + return static::_xmlrpcs_multicall_error('notstruct'); } $methName = @$call->structmem('methodName'); if(!$methName) { - return _xmlrpcs_multicall_error('nomethod'); + return static::_xmlrpcs_multicall_error('nomethod'); } if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') { - return _xmlrpcs_multicall_error('notstring'); + return static::_xmlrpcs_multicall_error('notstring'); } if($methName->scalarval() == 'system.multicall') { - return _xmlrpcs_multicall_error('recursion'); + return static::_xmlrpcs_multicall_error('recursion'); } $params = @$call->structmem('params'); if(!$params) { - return _xmlrpcs_multicall_error('noparams'); + return static::_xmlrpcs_multicall_error('noparams'); } if($params->kindOf() != 'array') { - return _xmlrpcs_multicall_error('notarray'); + return static::_xmlrpcs_multicall_error('notarray'); } $numParams = $params->arraysize(); @@ -1044,7 +1044,7 @@ public static function _xmlrpcs_multicall_do_call($server, $call) if(!$msg->addParam($params->arraymem($i))) { $i++; - return _xmlrpcs_multicall_error(new Response(0, + return static::_xmlrpcs_multicall_error(new Response(0, PhpXmlRpc::$xmlrpcerr['incorrect_params'], PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i)); } @@ -1054,7 +1054,7 @@ public static function _xmlrpcs_multicall_do_call($server, $call) if($result->faultCode() != 0) { - return _xmlrpcs_multicall_error($result); // Method returned fault. + return static::_xmlrpcs_multicall_error($result); // Method returned fault. } return new Value(array($result->value()), 'array'); @@ -1064,27 +1064,27 @@ public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) { if(!is_array($call)) { - return _xmlrpcs_multicall_error('notstruct'); + return static::_xmlrpcs_multicall_error('notstruct'); } if(!array_key_exists('methodName', $call)) { - return _xmlrpcs_multicall_error('nomethod'); + return static::_xmlrpcs_multicall_error('nomethod'); } if (!is_string($call['methodName'])) { - return _xmlrpcs_multicall_error('notstring'); + return static::_xmlrpcs_multicall_error('notstring'); } if($call['methodName'] == 'system.multicall') { - return _xmlrpcs_multicall_error('recursion'); + return static::_xmlrpcs_multicall_error('recursion'); } if(!array_key_exists('params', $call)) { - return _xmlrpcs_multicall_error('noparams'); + return static::_xmlrpcs_multicall_error('noparams'); } if(!is_array($call['params'])) { - return _xmlrpcs_multicall_error('notarray'); + return static::_xmlrpcs_multicall_error('notarray'); } // this is a real dirty and simplistic hack, since we might have received a @@ -1098,7 +1098,7 @@ public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) if($result->faultCode() != 0) { - return _xmlrpcs_multicall_error($result); // Method returned fault. + return static::_xmlrpcs_multicall_error($result); // Method returned fault. } return new Value(array($result->value()), 'array'); @@ -1115,7 +1115,7 @@ public static function _xmlrpcs_multicall($server, $m) for($i = 0; $i < $numCalls; $i++) { $call = $calls->arraymem($i); - $result[$i] = _xmlrpcs_multicall_do_call($server, $call); + $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call); } } else @@ -1123,7 +1123,7 @@ public static function _xmlrpcs_multicall($server, $m) $numCalls=count($m); for($i = 0; $i < $numCalls; $i++) { - $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); + $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); } } From b825566f55fd1aa4dab6b09145848e7d6e957fe5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 18:31:37 +0000 Subject: [PATCH 038/228] Reformat source code: debugger --- debugger/action.php | 934 +++++++++++++++++++++------------------- debugger/common.php | 130 +++--- debugger/controller.php | 672 +++++++++++++++++------------ debugger/index.php | 21 +- 4 files changed, 948 insertions(+), 809 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index 00af2a03..b12da804 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -8,519 +8,545 @@ * @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 **/ - ?> - XMLRPC Debugger - - + XMLRPC Debugger + + 1) - $pport = $pproxy[1]; - else - $pport = 8080; - $client->setProxy($pproxy[0], $pport, $proxyuser, $proxypwd); + $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'; + if ($protocol == 2) { + $client->setSSLVerifyPeer($verifypeer); + $client->setSSLVerifyHost($verifyhost); + if ($cainfo) { + $client->setCaCertificate($cainfo); + } + $httpprotocol = 'https'; + } elseif ($protocol == 1) { + $httpprotocol = 'http11'; + } else { + $httpprotocol = 'http'; } - else if ($protocol == 1) - $httpprotocol = 'http11'; - else - $httpprotocol = 'http'; - if ($username) - $client->setCredentials($username, $password, $authtype); + 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; + 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; + 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])); - } + foreach ($cookies as $cookie) { + if (strpos($cookie, '=')) { + $cookie = explode('=', $cookie); + $client->setCookie(trim($cookie[0]), trim(@$cookie[1])); + } } $msg = array(); switch ($action) { - case 'wrap': - @include('xmlrpc_wrappers.inc'); - if (!function_exists('build_remote_method_wrapper_code')) - { - die('Error: to enable creation of method stubs the xmlrpc_wrappers.inc file is needed'); - } + case 'wrap': + @include 'xmlrpc_wrappers.inc'; + if (!function_exists('build_remote_method_wrapper_code')) { + die('Error: to enable creation of method stubs the xmlrpc_wrappers.inc file is needed'); + } // fall thru intentionally - case 'describe': - case 'wrap': - $msg[0] = new $msgclass('system.methodHelp', array(), $id); - $msg[0]->addparam(new xmlrpcval($method)); - $msg[1] = new $msgclass('system.methodSignature', array(), $id+1); - $msg[1]->addparam(new xmlrpcval($method)); - $actionname = 'Description of method "'.$method.'"'; - break; - case 'list': - $msg[0] = new $msgclass('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 $msgclass($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}"; + case 'describe': + case 'wrap': + $msg[0] = new $msgclass('system.methodHelp', array(), $id); + $msg[0]->addparam(new xmlrpcval($method)); + $msg[1] = new $msgclass('system.methodSignature', array(), $id + 1); + $msg[1]->addparam(new xmlrpcval($method)); + $actionname = 'Description of method "' . $method . '"'; + break; + case 'list': + $msg[0] = new $msgclass('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!"); } - else - { - if (is_numeric($id) || $id == 'false' || $id == 'true' || $id == 'null') - { - $msg[0]->payload .= "$id\n}"; - } - else - { - $msg[0]->payload .= "\"$id\"\n}"; - } + $msg[0] = new $msgclass($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() . + '' . $method . "\n" . + $payload . + "\n" . $msg[0]->xml_footer(); } - } - else - $msg[0]->payload = $msg[0]->xml_header() . - '' . $method . "\n" . - $payload . - "\n" . $msg[0]->xml_footer(); - $actionname = 'Execution of method '.$method; - break; - default: // give a warning - $actionname = '[ERROR: unknown action] "'.$action.'"'; + $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 '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server)." ...

\n"; + echo '

' . htmlspecialchars($actionname) . ' on server ' . htmlspecialchars($server) . " ...

\n"; flush(); $response = null; // execute method(s) - if ($debug) - echo '

Debug info:

'; /// @todo use ob_start instead + if ($debug) { + echo '

Debug info:

'; + } /// @todo use ob_start instead $resp = array(); - $mtime = explode(' ',microtime()); + $mtime = explode(' ', microtime()); $time = (float)$mtime[0] + (float)$mtime[1]; - 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; + 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; + } } - $mtime = explode(' ',microtime()); + $mtime = explode(' ', microtime()); $time = (float)$mtime[0] + (float)$mtime[1] - $time; - if ($debug) - echo "
\n"; - - if ($response) - { - - if ($response->faultCode()) - { - // call failed! echo out error msg! - //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; - echo "

$protoname call FAILED!

\n"; - echo "

Fault code: [" . htmlspecialchars($response->faultCode()) . - "] Reason: '" . htmlspecialchars($response->faultString()) . "'

\n"; - echo (strftime("%d/%b/%Y:%H:%M:%S\n")); + if ($debug) { + echo "
\n"; } - else - { - // call succeeded: parse results - //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; - printf ("

%s call(s) OK (%.2f secs.)

\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->arraysize(); - echo "
\n"; - echo "\n\n\n\n"; - for($i=0; $i < $max; $i++) - { - $rec = $v->arraymem($i); - if ($i%2) $class=' class="oddrow"'; else $class = ' class="evenrow"'; - echo ("".htmlspecialchars($rec->scalarval())."
". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "scalarval()."\" />". - "". - "". - "". - ""); - //echo("
\n"); - - // generate lo scheletro per il method payload per eventuali test - //$methodpayload="\n".$rec->scalarval()."\n\n\n\n"; - - /*echo ("");*/ - echo("\n"); - } - echo "\n
MethodDescription
". - "". - "". - "". - "scalarval()."\" />". - "". - "". - "
"; - } - break; - case 'describe': - - $r1 = $resp[0]->value(); - $r2 = $resp[1]->value(); - - echo "\n"; - echo "\n\n\n\n"; - $desc = htmlspecialchars($r1->scalarval()); - if ($desc == "") - $desc = "-"; - echo "\n"; - $payload=""; - $alt_payload=""; - if ($r2->kindOf()!="array") - echo "\n"; - else - { - for($i=0; $i < $r2->arraysize(); $i++) - { - if ($i+1%2) $class=' class="oddrow"'; else $class = ' class="evenrow"'; - echo "Signature ".($i+1).""; - $x = $r2->arraymem($i); - if ($x->kindOf()=="array") - { - $ret = $x->arraymem(0); - echo "OUT: " . htmlspecialchars($ret->scalarval()) . "
IN: ("; - if ($x->arraysize() > 1) - { - for($k = 1; $k < $x->arraysize(); $k++) - { - $y = $x->arraymem($k); - echo $y->scalarval(); - if ($wstype != 1) - { - $payload = $payload . '<'.htmlspecialchars($y->scalarval()).'>scalarval()).">\n"; - } - $alt_payload .= $y->scalarval(); - if ($k < $x->arraysize()-1) - { - $alt_payload .= ';'; - echo ", "; - } - } - } - echo ")
"; + if ($response) { + if ($response->faultCode()) { + // call failed! echo out error msg! + //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; + echo "

$protoname call FAILED!

\n"; + echo "

Fault code: [" . htmlspecialchars($response->faultCode()) . + "] Reason: '" . htmlspecialchars($response->faultString()) . "'

\n"; + echo(strftime("%d/%b/%Y:%H:%M:%S\n")); + } else { + // call succeeded: parse results + //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; + printf("

%s call(s) OK (%.2f secs.)

\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->arraysize(); + echo "
Method".htmlspecialchars($method)."  
Description$desc
SignatureUnknown 
\n"; + echo "\n\n\n\n"; + for ($i = 0; $i < $max; $i++) { + $rec = $v->arraymem($i); + if ($i % 2) { + $class = ' class="oddrow"'; + } else { + $class = ' class="evenrow"'; + } + echo("" . htmlspecialchars($rec->scalarval()) . "
" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "scalarval() . "\" />" . + "" . + "" . + "" . + ""); + //echo("
\n"); + + // generate lo scheletro per il method payload per eventuali test + //$methodpayload="\n".$rec->scalarval()."\n\n\n\n"; + + /*echo ("");*/ + echo("\n"); + } + echo "\n
MethodDescription
". + "". + "". + "". + "scalarval()."\" />". + "". + "". + "
"; + } + break; + + case 'describe': + + $r1 = $resp[0]->value(); + $r2 = $resp[1]->value(); + + echo "\n"; + echo "\n\n\n\n"; + $desc = htmlspecialchars($r1->scalarval()); + if ($desc == "") { + $desc = "-"; + } + echo "\n"; + $payload = ""; + $alt_payload = ""; + if ($r2->kindOf() != "array") { + echo "\n"; + } else { + for ($i = 0; $i < $r2->arraysize(); $i++) { + if ($i + 1 % 2) { + $class = ' class="oddrow"'; + } else { + $class = ' class="evenrow"'; + } + echo "Signature " . ($i + 1) . ""; + $x = $r2->arraymem($i); + if ($x->kindOf() == "array") { + $ret = $x->arraymem(0); + echo "OUT: " . htmlspecialchars($ret->scalarval()) . "
IN: ("; + if ($x->arraysize() > 1) { + for ($k = 1; $k < $x->arraysize(); $k++) { + $y = $x->arraymem($k); + echo $y->scalarval(); + if ($wstype != 1) { + $payload = $payload . '<' . htmlspecialchars($y->scalarval()) . '>scalarval()) . ">\n"; + } + $alt_payload .= $y->scalarval(); + if ($k < $x->arraysize() - 1) { + $alt_payload .= ';'; + echo ", "; + } + } + } + echo ")
"; + } else { + echo 'Unknown'; + } + echo ''; + //bottone per testare questo metodo + //$payload="\n$method\n\n$payload\n"; + echo "
" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + ""; + if ($wstype != 1) { + echo ""; + } + echo "\n"; + + echo "
" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + ""; + echo "
\n"; + } + } + echo "\n
Method" . htmlspecialchars($method) . "  
Description$desc
SignatureUnknown 
"; + + break; + + case 'wrap': + $r1 = $resp[0]->value(); + $r2 = $resp[1]->value(); + if ($r2->kindOf() != "array" || $r2->arraysize() <= $methodsig) { + echo "Error: signature unknown\n"; + } else { + $mdesc = $r1->scalarval(); + $msig = php_xmlrpc_decode($r2); + $msig = $msig[$methodsig]; + $proto = $protocol == 2 ? 'https' : $protocol == 1 ? 'http11' : ''; + if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression && + $clientcookies == '' + ) { + $opts = 0; // simple client copy in stub code + } else { + $opts = 1; // complete client copy in stub code + } + if ($wstype == 1) { + $prefix = 'jsonrpc'; + } else { + $prefix = 'xmlrpc'; + } + //$code = wrap_xmlrpc_method($client, $method, $methodsig, 0, $proto, '', $opts); + $code = build_remote_method_wrapper_code($client, $method, str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc, $timeout, $proto, $opts, $prefix); + //if ($code) + //{ + echo "
\n"; + highlight_string("'); + echo "\n
"; + //} + //else + //{ + // echo 'Error while building php code stub...'; + } + + break; + + case 'execute': + echo '

Response:

' . htmlspecialchars($response->serialize()) . '
'; + break; + + default: // give a warning } - else - { - echo 'Unknown'; - } - echo ''; - //bottone per testare questo metodo - //$payload="\n$method\n\n$payload\n"; - echo "
". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - ""; - if ($wstype != 1) - echo ""; - echo "
\n"; - - echo "
". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - "". - ""; - echo "
\n"; - - } - } - echo "\n"; - - break; - - case 'wrap': - $r1 = $resp[0]->value(); - $r2 = $resp[1]->value(); - if ($r2->kindOf()!="array" || $r2->arraysize() <= $methodsig) - echo "Error: signature unknown\n"; - else - { - $mdesc = $r1->scalarval(); - $msig = php_xmlrpc_decode($r2); - $msig = $msig[$methodsig]; - $proto = $protocol == 2 ? 'https' : $protocol == 1 ? 'http11' : ''; - if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression && - $clientcookies == '') - { - $opts = 0; // simple client copy in stub code - } - else - { - $opts = 1; // complete client copy in stub code - } - if ($wstype == 1) - { - $prefix = 'jsonrpc'; - } - else - { - $prefix = 'xmlrpc'; - } - //$code = wrap_xmlrpc_method($client, $method, $methodsig, 0, $proto, '', $opts); - $code = build_remote_method_wrapper_code($client, $method, str_replace('.', '_', $prefix.'_'.$method), $msig, $mdesc, $timeout, $proto, $opts, $prefix); - //if ($code) - //{ - echo "
\n"; - highlight_string("'); - echo "\n
"; - //} - //else - //{ - // echo 'Error while building php code stub...'; - } - - break; - - case 'execute': - echo '

Response:

'.htmlspecialchars($response->serialize()).'
'; - break; - - default: // give a warning - } - } // if !$response->faultCode() + } // if !$response->faultCode() } // if $response - } - else - { +} else { // no action taken yet: give some instructions on debugger usage -?> - -

Instructions on usage of the debugger:

-
    -
  1. Run a 'list available methods' action against desired server
  2. -
  3. If list of methods appears, click on 'describe method' for desired method
  4. -
  5. 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'
  6. -
+ ?> + +

Instructions on usage of the debugger:

+
    +
  1. Run a 'list available methods' action against desired server
  2. +
  3. If list of methods appears, click on 'describe method' for desired method
  4. +
  5. 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' +
  6. +
+ You will need to enable the CURL extension to use the HTTPS and HTTP 1.1 transports

\n"; + } + ?> + +

Example:

+

+ Server Address: phpxmlrpc.sourceforge.net
+ Path: /server.php +

+ +

Notice:

+

all usernames and passwords entered on the above form will be written to the web server logs of this server. Use + with care.

+ +

Changelog

+
    +
  • 2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id
  • +
  • 2006-06-26: support building php code stub for calling remote methods
  • +
  • 2006-05-25: better support for long running queries; check for no-curl installs
  • +
  • 2006-05-02: added support for JSON-RPC. Note that many interesting json-rpc features are not implemented + yet, such as notifications or multicall. +
  • +
  • 2006-04-22: added option for setting custom CA certs to verify peer with in SSLmode
  • +
  • 2006-03-05: added option for setting Basic/Digest/NTLM auth type
  • +
  • 2006-01-18: added option echoing to screen xmlrpc request before sending it ('More' debug)
  • +
  • 2005-10-01: added option for setting cookies to be sent to server
  • +
  • 2005-08-07: added switches for compression of requests and responses and http 1.1
  • +
  • 2005-06-27: fixed possible security breach in parsing malformed xml
  • +
  • 2005-06-24: fixed error with calling methods having parameters...
  • +
You will need to enable the CURL extension to use the HTTPS and HTTP 1.1 transports

\n"; - } -?> -

Example:

-

-Server Address: phpxmlrpc.sourceforge.net
-Path: /server.php -

- -

Notice:

-

all usernames and passwords entered on the above form will be written to the web server logs of this server. Use with care.

- -

Changelog

-
    -
  • 2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id
  • -
  • 2006-06-26: support building php code stub for calling remote methods
  • -
  • 2006-05-25: better support for long running queries; check for no-curl installs
  • -
  • 2006-05-02: added support for JSON-RPC. Note that many interesting json-rpc features are not implemented yet, such as notifications or multicall.
  • -
  • 2006-04-22: added option for setting custom CA certs to verify peer with in SSLmode
  • -
  • 2006-03-05: added option for setting Basic/Digest/NTLM auth type
  • -
  • 2006-01-18: added option echoing to screen xmlrpc request before sending it ('More' debug)
  • -
  • 2005-10-01: added option for setting cookies to be sent to server
  • -
  • 2005-08-07: added switches for compression of requests and responses and http 1.1
  • -
  • 2005-06-27: fixed possible security breach in parsing malformed xml
  • -
  • 2005-06-24: fixed error with calling methods having parameters...
  • -
- diff --git a/debugger/common.php b/debugger/common.php index adaf3667..83153bb6 100644 --- a/debugger/common.php +++ b/debugger/common.php @@ -9,72 +9,74 @@ */ // work around magic quotes - if (get_magic_quotes_gpc()) - { +if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? - array_map('stripslashes_deep', $value) : - stripslashes($value); + array_map('stripslashes_deep', $value) : + stripslashes($value); return $value; } - $_GET = array_map('stripslashes_deep', $_GET); - } + $_GET = array_map('stripslashes_deep', $_GET); +} - if ( isset( $_GET['usepost'] ) && $_GET['usepost'] === 'true' ) - { - $_GET = $_POST; - } +if (isset($_GET['usepost']) && $_GET['usepost'] === 'true') { + $_GET = $_POST; +} // 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']; +$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); - else if (strpos($host, 'https://') === 0) - { - $host = substr($host, 8); - $protocol = 2; + 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 ($path && ($path[0]) != '/') { + $path = '/' . $path; + } - if (isset($_GET['debug']) && ($_GET['debug'] == '1' || $_GET['debug'] == '2')) - $debug = $_GET['debug']; + 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'] : ''; + 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'] : ''; + 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; + if (!is_numeric($timeout)) { + $timeout = 0; + } $action = $_GET['action']; $method = isset($_GET['method']) ? $_GET['method'] : ''; @@ -82,27 +84,28 @@ function stripslashes_deep($value) $payload = isset($_GET['methodpayload']) ? $_GET['methodpayload'] : ''; $alt_payload = isset($_GET['altmethodpayload']) ? $_GET['altmethodpayload'] : ''; - if (isset($_GET['run']) && $_GET['run'] == 'now') - $run = true; + 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; + 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 - { +} else { $host = ''; $port = ''; $path = ''; @@ -124,11 +127,10 @@ function stripslashes_deep($value) $requestcompression = 0; $responsecompression = 0; $clientcookies = ''; - } +} - // check input for known XMLRPC attacks against this or other libs - function payload_is_safe($input) - { - return true; - } -?> \ No newline at end of file +// check input for known XMLRPC attacks against this or other libs +function payload_is_safe($input) +{ + return true; +} diff --git a/debugger/controller.php b/debugger/controller.php index 965b2efa..4db99909 100644 --- a/debugger/controller.php +++ b/debugger/controller.php @@ -8,314 +8,424 @@ * @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 **/ - include(__DIR__.'/common.php'); - if ($action == '') +include __DIR__ . '/common.php'; +if ($action == '') { $action = 'list'; +} - // relative path to the visual xmlrpc editing dialog - $editorpath = '../../javascript/debugger/'; - $editorlibs = '../../javascript/lib/'; +// relative path to the visual xmlrpc editing dialog +$editorpath = '../../javascript/debugger/'; +$editorlibs = '../../javascript/lib/'; ?> -XMLRPC Debugger - - - - - - - + + + + function displaydialogeditorbtn(show) { + if (show && ((typeof base64_decode) == 'function')) { + document.getElementById('methodpayloadbtn').innerHTML = '[Edit]'; + } + else { + document.getElementById('methodpayloadbtn').innerHTML = ''; + } + } + + function activateeditor() { + var url = 'visualeditor.php?params='; + 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'; + } + } + + //--> + - -

XMLRPC
-/
JSONRPC Debugger (based on the PHP-XMLRPC library)

+ +

XMLRPC +
+ / +
+ JSONRPC Debugger (based on the PHP-XMLRPC library) +

+ > + + + + + + + + + + + +

Target server

Address:Port: + Path:
- - - - - - - -

Target server

Address:Port:Path:
+ + + + + + + + +

Action

List available methods onclick="switchaction();"/>Describe method onclick="switchaction();"/>Execute method onclick="switchaction();"/>Generate stub for method call onclick="switchaction();"/>
+ - - - - - - - - -

Action

List available methods onclick="switchaction();" />Describe method onclick="switchaction();" />Execute method onclick="switchaction();" />Generate stub for method call onclick="switchaction();" />
- + + + + + + + + + + +

Method

Name:Payload:
- - - - - - - - -

Method

Name:Payload:
Msg id: -
+
+
Msg id: +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Client options

Show debug info: -Timeout:Protocol:
AUTH:Username:Pwd:Type
SSL:Verify Host's CN:Verify Cert: />CA Cert file:
PROXY:Server:Proxy user:Proxy pwd:
COMPRESSION:Request:Response:
COOKIES:Format: 'cookie1=value1, cookie2=value2'
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Client options

Show debug info: + Timeout:Protocol:
AUTH:Username:Pwd:Type
SSL:Verify Host's CN:Verify Cert: />CA Cert file:
PROXY:Server:Proxy user:Proxy pwd:
COMPRESSION:Request:Response:
COOKIES:Format: 'cookie1=value1, cookie2=value2'
- \ No newline at end of file + diff --git a/debugger/index.php b/debugger/index.php index 2f30c9fe..eff10ea9 100644 --- a/debugger/index.php +++ b/debugger/index.php @@ -1,20 +1,21 @@ -XMLRPC Debugger + XMLRPC Debugger - - + + - \ No newline at end of file + From 5b0b061574fa8458d5a92c24c20d077ad832cf63 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 18:52:19 +0000 Subject: [PATCH 039/228] Reformat source code: demos --- demo/client/agesort.php | 2 +- demo/client/client.php | 65 +- demo/client/comment.php | 291 +++---- demo/client/introspect.php | 2 +- demo/client/mail.php | 68 +- demo/client/simple_call.php | 86 +- demo/client/which.php | 2 +- demo/client/wrap.php | 76 +- demo/client/zopetest.php | 36 +- demo/demo3.xml | 36 +- demo/server/discuss.php | 177 ++--- demo/server/proxy.php | 140 ++-- demo/server/server.php | 1492 ++++++++++++++++++----------------- demo/vardemo.php | 134 ++-- 14 files changed, 1319 insertions(+), 1288 deletions(-) diff --git a/demo/client/agesort.php b/demo/client/agesort.php index 86febd17..8ae87ff7 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -1 +1 @@ - xmlrpc

Agesort demo

Send an array of 'name' => 'age' pairs to the server that will send it back sorted.

The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs

24, "Edd" => 45, "Joe" => 37, "Fred" => 27); reset($inAr); print "This is the input data:
";
while (list($key, $val)=each($inAr)) {
  print $key . ", " . $val . "\n";
}
print "
"; // create parameters from the input array: an xmlrpc array of xmlrpc structs $p=array(); foreach($inAr as $key => $val) { $p[]=new xmlrpcval(array("name" => new xmlrpcval($key), "age" => new xmlrpcval($val, "int")), "struct"); } $v=new xmlrpcval($p, "array"); print "Encoded into xmlrpc format it looks like this:
\n" .  htmlentities($v->serialize()). "
\n"; // create client and message objects $f=new xmlrpcmsg('examples.sortByAge', array($v)); $c=new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); // set maximum debug level, to have the complete communication printed to screen $c->setDebug(2); // send request print "Now sending request (detailed debug info follows)"; $r=&$c->send($f); // check response for errors, and take appropriate action if (!$r->faultCode()) { print "The server gave me these results:
";
  $v=$r->value();
  $max=$v->arraysize();
  for($i=0; $i<$max; $i++) {
    $rec=$v->arraymem($i);
    $n=$rec->structmem("name");
    $a=$rec->structmem("age");
    print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";
  }

  print "
For nerds: I got this value back
" .
    htmlentities($r->serialize()). "

\n"; } else { print "An error occurred:
";
  print "Code: " . htmlspecialchars($r->faultCode()) .
    "\nReason: '" . htmlspecialchars($r->faultString()).'\'

'; } ?> \ No newline at end of file + xmlrpc

Agesort demo

Send an array of 'name' => 'age' pairs to the server that will send it back sorted.

The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs

24, "Edd" => 45, "Joe" => 37, "Fred" => 27); reset($inAr); print "This is the input data:
";
while (list($key, $val) = each($inAr)) {
    print $key . ", " . $val . "\n";
}
print "
"; // create parameters from the input array: an xmlrpc array of xmlrpc structs $p = array(); foreach ($inAr as $key => $val) { $p[] = new xmlrpcval(array("name" => new xmlrpcval($key), "age" => new xmlrpcval($val, "int")), "struct"); } $v = new xmlrpcval($p, "array"); print "Encoded into xmlrpc format it looks like this:
\n" . htmlentities($v->serialize()) . "
\n"; // create client and message objects $f = new xmlrpcmsg('examples.sortByAge', array($v)); $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); // set maximum debug level, to have the complete communication printed to screen $c->setDebug(2); // send request print "Now sending request (detailed debug info follows)"; $r = &$c->send($f); // check response for errors, and take appropriate action if (!$r->faultCode()) { print "The server gave me these results:
";
    $v = $r->value();
    $max = $v->arraysize();
    for ($i = 0; $i < $max; $i++) {
        $rec = $v->arraymem($i);
        $n = $rec->structmem("name");
        $a = $rec->structmem("age");
        print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";
    }

    print "
For nerds: I got this value back
" .
        htmlentities($r->serialize()) . "

\n"; } else { print "An error occurred:
";
    print "Code: " . htmlspecialchars($r->faultCode()) .
        "\nReason: '" . htmlspecialchars($r->faultString()) . '\'

'; } ?> \ No newline at end of file diff --git a/demo/client/client.php b/demo/client/client.php index 2db593f4..755729de 100644 --- a/demo/client/client.php +++ b/demo/client/client.php @@ -2,48 +2,43 @@ xmlrpc

Getstatename demo

+

Send a U.S. state number to the server and get back the state name

+

The code demonstrates usage of the php_xmlrpc_encode function

Sending the following request:\n\n" . htmlentities($f->serialize()) . "\n\nDebug info of server data follows...\n\n"; - $c=new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); - $c->setDebug(1); - $r=&$c->send($f); - if(!$r->faultCode()) - { - $v=$r->value(); - print "

State number " . $stateno . " is " - . htmlspecialchars($v->scalarval()) . "
"; - // print "
I got this value back
" .
-            //  htmlentities($r->serialize()). "

\n"; - } - else - { - print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) - . " Reason: '" . htmlspecialchars($r->faultString()) . "'

"; - } - } - else - { - $stateno = ""; +if (isset($HTTP_POST_VARS["stateno"]) && $HTTP_POST_VARS["stateno"] != "") { + $stateno = (integer)$HTTP_POST_VARS["stateno"]; + $f = new xmlrpcmsg('examples.getStateName', + array(php_xmlrpc_encode($stateno)) + ); + print "
Sending the following request:\n\n" . htmlentities($f->serialize()) . "\n\nDebug info of server data follows...\n\n";
+    $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80);
+    $c->setDebug(1);
+    $r = &$c->send($f);
+    if (!$r->faultCode()) {
+        $v = $r->value();
+        print "

State number " . $stateno . " is " + . htmlspecialchars($v->scalarval()) . "
"; + // print "
I got this value back
" .
+        //  htmlentities($r->serialize()). "

\n"; + } else { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) + . " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; } +} else { + $stateno = ""; +} - print "
+print "

Enter a state number to query its name

"; diff --git a/demo/client/comment.php b/demo/client/comment.php index 090c18c8..e457836f 100644 --- a/demo/client/comment.php +++ b/demo/client/comment.php @@ -1,185 +1,210 @@ "; exit(); } -function dispatch($client, $method, $args) { - $msg=new xmlrpcmsg($method, $args); - $resp=$client->send($msg); - if (!$resp) { print "

IO error: ".$client->errstr."

"; bomb(); } +function bomb() +{ + print ""; + exit(); +} + +function dispatch($client, $method, $args) +{ + $msg = new xmlrpcmsg($method, $args); + $resp = $client->send($msg); + if (!$resp) { + print "

IO error: " . $client->errstr . "

"; + bomb(); + } if ($resp->faultCode()) { print "

There was an error: " . $resp->faultCode() . " " . $resp->faultString() . "

"; bomb(); } + return php_xmlrpc_decode($resp->value()); } // create client for discussion server -$dclient=new xmlrpc_client("${mydir}/discuss.php", - "xmlrpc.usefulinc.com", 80); +$dclient = new xmlrpc_client("${mydir}/discuss.php", + "xmlrpc.usefulinc.com", 80); // check if we're posting a comment, and send it if so -@$storyid=$_POST["storyid"]; +@$storyid = $_POST["storyid"]; if ($storyid) { - // print "Returning to " . $HTTP_POST_VARS["returnto"]; - $res=dispatch($dclient, "discuss.addComment", - array(new xmlrpcval($storyid), - new xmlrpcval(stripslashes - (@$_POST["name"])), - new xmlrpcval(stripslashes - (@$_POST["commenttext"])))); + $res = dispatch($dclient, "discuss.addComment", + array(new xmlrpcval($storyid), + new xmlrpcval(stripslashes(@$_POST["name"])), + new xmlrpcval(stripslashes(@$_POST["commenttext"])),)); // send the browser back to the originating page Header("Location: ${mydir}/comment.php?catid=" . - $_POST["catid"] . "&chanid=" . - $_POST["chanid"] . "&oc=" . - $_POST["catid"]); + $_POST["catid"] . "&chanid=" . + $_POST["chanid"] . "&oc=" . + $_POST["catid"]); exit(0); } // now we've got here, we're exploring the story store ?> -meerkat browser + +meerkat browser

Meerkat integration

-

Make a comment on the story

-
-

Your name:

-

Your comment:

- -" /> - - - -
+ ?> +

Make a comment on the story

+
+

Your name:

+ +

Your comment:

+ + "/> + + + +
new xmlrpcval($chanid, "int"), - "ids" => new xmlrpcval(1, "int"), - "descriptions" => new xmlrpcval(200, "int"), - "num_items" => new xmlrpcval(5, "int"), - "dates" => new xmlrpcval(0, "int") - ), "struct"))); + array(new xmlrpcval( + array( + "channel" => new xmlrpcval($chanid, "int"), + "ids" => new xmlrpcval(1, "int"), + "descriptions" => new xmlrpcval(200, "int"), + "num_items" => new xmlrpcval(5, "int"), + "dates" => new xmlrpcval(0, "int"), + ), "struct"))); } -?> -
-

Subject area:
-

- -

News source:
- -

+ ?> + +

Subject area:
+

+ +

News source:
+ +

+ + + ?> -

- -
+

+ + - - -

Stories available

- -"; - print ""; - print "\n"; - // now look for existing comments - $res=dispatch($dclient, "discuss.getComments", - array(new xmlrpcval($v['id']))); - if (sizeof($res)>0) { - print "\n"; - } - print "\n"; - } -?> -
" . $v['title'] . "
"; - print $v['description'] . "
"; - print "Read full story "; - print "Comment on this story"; - print ""; - print "

" . - "Comments on this story:

"; - for($i=0; $iFrom: " . htmlentities($s['name']) . "
"; - print "Comment: " . htmlentities($s['comment']) . "

"; - } - print "

- - + +

Stories available

+ + "; + print ""; + print "\n"; + // now look for existing comments + $res = dispatch($dclient, "discuss.getComments", + array(new xmlrpcval($v['id']))); + if (sizeof($res) > 0) { + print "\n"; + } + print "\n"; + } + ?> +
" . $v['title'] . "
"; + print $v['description'] . "
"; + print "Read full story "; + print "Comment on this story"; + print ""; + print "

" . + "Comments on this story:

"; + for ($i = 0; $i < sizeof($res); $i++) { + $s = $res[$i]; + print "

From: " . htmlentities($s['name']) . "
"; + print "Comment: " . htmlentities($s['comment']) . "

"; + } + print "

+ + -
+

-Meerkat powered, yeah! + Meerkat powered, yeah!

diff --git a/demo/client/introspect.php b/demo/client/introspect.php index f606ba62..1fff47ab 100644 --- a/demo/client/introspect.php +++ b/demo/client/introspect.php @@ -1 +1 @@ - xmlrpc

Introspect demo

Query server for available methods and their description

The code demonstrates usage of multicall and introspection methods

faultCode() . " Reason: '" .$r->faultString()."'
"; } // 'new style' client constuctor $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); print "

methods available at http://" . $c->server . $c->path . "

\n"; $m = new xmlrpcmsg('system.listMethods'); $r =& $c->send($m); if($r->faultCode()) { display_error($r); } else { $v=$r->value(); for($i=0; $i<$v->arraysize(); $i++) { $mname=$v->arraymem($i); print "

" . $mname->scalarval() . "

\n"; // build messages first, add params later $m1 = new xmlrpcmsg('system.methodHelp'); $m2 = new xmlrpcmsg('system.methodSignature'); $val = new xmlrpcval($mname->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); // send multiple messages in one pass. // If server does not support multicall, client will fall back to 2 separate calls $ms = array($m1, $m2); $rs =& $c->send($ms); if($rs[0]->faultCode()) { display_error($rs[0]); } else { $val=$rs[0]->value(); $txt=$val->scalarval(); if($txt != "") { print "

Documentation

${txt}

\n"; } else { print "

No documentation available.

\n"; } } if($rs[1]->faultCode()) { display_error($rs[1]); } else { print "

Signature

\n"; $val = $rs[1]->value(); if($val->kindOf()=="array") { for($j=0; $j<$val->arraysize(); $j++) { $x = $val->arraymem($j); $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " . $mname->scalarval() . "("; if($x->arraysize()>1) { for($k=1; $k<$x->arraysize(); $k++) { $y = $x->arraymem($k); print $y->scalarval(); if($k < $x->arraysize()-1) { print ", "; } } } print ")
\n"; } } else { print "Signature unknown\n"; } print "

\n"; } } } ?> \ No newline at end of file + xmlrpc

Introspect demo

Query server for available methods and their description

The code demonstrates usage of multicall and introspection methods

faultCode() . " Reason: '" . $r->faultString() . "'
"; } // 'new style' client constuctor $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); print "

methods available at http://" . $c->server . $c->path . "

\n"; $m = new xmlrpcmsg('system.listMethods'); $r = &$c->send($m); if ($r->faultCode()) { display_error($r); } else { $v = $r->value(); for ($i = 0; $i < $v->arraysize(); $i++) { $mname = $v->arraymem($i); print "

" . $mname->scalarval() . "

\n"; // build messages first, add params later $m1 = new xmlrpcmsg('system.methodHelp'); $m2 = new xmlrpcmsg('system.methodSignature'); $val = new xmlrpcval($mname->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); // send multiple messages in one pass. // If server does not support multicall, client will fall back to 2 separate calls $ms = array($m1, $m2); $rs = &$c->send($ms); if ($rs[0]->faultCode()) { display_error($rs[0]); } else { $val = $rs[0]->value(); $txt = $val->scalarval(); if ($txt != "") { print "

Documentation

${txt}

\n"; } else { print "

No documentation available.

\n"; } } if ($rs[1]->faultCode()) { display_error($rs[1]); } else { print "

Signature

\n"; $val = $rs[1]->value(); if ($val->kindOf() == "array") { for ($j = 0; $j < $val->arraysize(); $j++) { $x = $val->arraymem($j); $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " . $mname->scalarval() . "("; if ($x->arraysize() > 1) { for ($k = 1; $k < $x->arraysize(); $k++) { $y = $x->arraymem($k); print $y->scalarval(); if ($k < $x->arraysize() - 1) { print ", "; } } } print ")
\n"; } } else { print "Signature unknown\n"; } print "

\n"; } } } ?> \ No newline at end of file diff --git a/demo/client/mail.php b/demo/client/mail.php index 9f6de319..6b6abd44 100644 --- a/demo/client/mail.php +++ b/demo/client/mail.php @@ -1,32 +1,44 @@ xmlrpc

Mail demo

+

This form enables you to send mail via an XML-RPC server. For public use -only the "Userland" server will work (see Dave Winer's message). -When you press Send 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.

+ only the "Userland" server will work (see Dave Winer's + message). + When you press Send 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.

+

You can find the source to this page here: mail.php
-And the source to a functionally identical mail-by-XML-RPC server in the file server.php included with the library (look for the 'mail_send' method)

+ And the source to a functionally identical mail-by-XML-RPC server in the file server.php included with the library (look for the 'mail_send' + method)

addParam(new xmlrpcval($HTTP_POST_VARS["mailto"])); $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailsub"])); $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailmsg"])); @@ -35,9 +47,9 @@ $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailbcc"])); $f->addParam(new xmlrpcval("text/plain")); - $c=new xmlrpc_client($XP, $XS, 80); + $c = new xmlrpc_client($XP, $XS, 80); $c->setDebug(2); - $r=&$c->send($f); + $r = &$c->send($f); if (!$r->faultCode()) { print "Mail sent OK
\n"; } else { @@ -45,25 +57,27 @@ print "Mail send failed
\n"; print "Fault: "; print "Code: " . htmlspecialchars($r->faultCode()) . - " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; + " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; print "
"; } } ?>
-Server -
-From
-
-To
-Cc
-Bcc
-
-Subject -
-Body
- + Server +
+ From
+
+ To
+ Cc
+ Bcc
+
+ Subject +
+ Body
+
diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php index 9764b7fa..8a36eceb 100644 --- a/demo/client/simple_call.php +++ b/demo/client/simple_call.php @@ -1,57 +1,53 @@ send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); + $xmlrpcval_array = array(); + foreach ($varargs as $parameter) { + $xmlrpcval_array[] = php_xmlrpc_encode($parameter); } + + return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); } +} diff --git a/demo/client/which.php b/demo/client/which.php index 8b1ba488..db2d8c17 100644 --- a/demo/client/which.php +++ b/demo/client/which.php @@ -1 +1 @@ - xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if(!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";

		print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";

		print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";

		print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";

		print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";

		print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?> \ No newline at end of file + xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if (!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";


    print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";


    print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";


    print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";


    print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";


    print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?> \ No newline at end of file diff --git a/demo/client/wrap.php b/demo/client/wrap.php index 8ec452cd..27a9794f 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -2,55 +2,49 @@ xmlrpc

Webservice wrappper demo

+

Wrap methods exposed by server into php functions

+

The code demonstrates usage of the most automagic client usage possible:
-1) client that returns php values instead of xmlrpcval objects
-2) wrapping of remote methods into php functions + 1) client that returns php values instead of xmlrpcval objects
+ 2) wrapping of remote methods into php functions

return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals - $r =& $c->send(new xmlrpcmsg('system.listMethods')); - if($r->faultCode()) - { - echo "

Server methods list could not be retrieved: error '".htmlspecialchars($r->faultString())."'

\n"; - } - else - { - $testcase = ''; - echo "

Server methods list retrieved, now wrapping it up...

\n
    \n"; - foreach($r->value() as $methodname) // $r->value is an array of strings - { - // do not wrap remote server system methods - if (strpos($methodname, 'system.') !== 0) - { - $funcname = wrap_xmlrpc_method($c, $methodname); - if($funcname) - { - echo "
  • Remote server method ".htmlspecialchars($methodname)." wrapped into php function ".$funcname."
  • \n"; - } - else - { - echo "
  • Remote server method ".htmlspecialchars($methodname)." could not be wrapped!
  • \n"; - } - if($methodname == 'examples.getStateName') - { - $testcase = $funcname; - } +$c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); +$c->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals +$r = &$c->send(new xmlrpcmsg('system.listMethods')); +if ($r->faultCode()) { + echo "

    Server methods list could not be retrieved: error '" . htmlspecialchars($r->faultString()) . "'

    \n"; +} else { + $testcase = ''; + echo "

    Server methods list retrieved, now wrapping it up...

    \n
      \n"; + foreach ($r->value() as $methodname) { + // $r->value is an array of strings + + // do not wrap remote server system methods + if (strpos($methodname, 'system.') !== 0) { + $funcname = wrap_xmlrpc_method($c, $methodname); + if ($funcname) { + echo "
    • Remote server method " . htmlspecialchars($methodname) . " wrapped into php function " . $funcname . "
    • \n"; + } else { + echo "
    • Remote server method " . htmlspecialchars($methodname) . " could not be wrapped!
    • \n"; + } + if ($methodname == 'examples.getStateName') { + $testcase = $funcname; } } - echo "
    \n"; - if($testcase) - { - echo "Now testing function $testcase: remote method to convert U.S. state number into state name"; - $statenum = 25; - $statename = $testcase($statenum, 2); - echo "State number $statenum is ".htmlspecialchars($statename); - } } + echo "
\n"; + if ($testcase) { + echo "Now testing function $testcase: remote method to convert U.S. state number into state name"; + $statenum = 25; + $statename = $testcase($statenum, 2); + echo "State number $statenum is " . htmlspecialchars($statename); + } +} ?> diff --git a/demo/client/zopetest.php b/demo/client/zopetest.php index 84102a59..ea93525d 100644 --- a/demo/client/zopetest.php +++ b/demo/client/zopetest.php @@ -2,28 +2,26 @@ xmlrpc

Zope test demo

+

The code demonstrates usage of basic authentication to connect to the server

setCredentials("username", "password"); - $c->setDebug(2); - $r = $c->send($f); - if(!$r->faultCode()) - { - $v = $r->value(); - print "I received:" . htmlspecialchars($v->scalarval()) . "
"; - print "
I got this value back
pre>" . - htmlentities($r->serialize()). "\n"; - } - else - { - print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) - . " Reason: '" . ($r->faultString()) . "'
"; - } +$f = new xmlrpcmsg('document_src', array()); +$c = new xmlrpc_client("/index_html", "pingu.heddley.com", 9080); +$c->setCredentials("username", "password"); +$c->setDebug(2); +$r = $c->send($f); +if (!$r->faultCode()) { + $v = $r->value(); + print "I received:" . htmlspecialchars($v->scalarval()) . "
"; + print "
I got this value back
pre>" . + htmlentities($r->serialize()) . "\n"; +} else { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) + . " Reason: '" . ($r->faultString()) . "'
"; +} ?> diff --git a/demo/demo3.xml b/demo/demo3.xml index e77a4af3..ed94aaba 100644 --- a/demo/demo3.xml +++ b/demo/demo3.xml @@ -1,21 +1,21 @@ - - - - - faultCode - - 4 - - - - faultString - - Too many parameters. - - - - - + + + + + faultCode + + 4 + + + + faultString + + Too many parameters. + + + + + diff --git a/demo/server/discuss.php b/demo/server/discuss.php index 6996564f..7e6e4e97 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -1,117 +1,102 @@ 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 - ); - } +function getcomments($m) +{ + global $xmlrpcerruser; + $err = ""; + $ra = array(); + $msgID = php_xmlrpc_decode($m->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 xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - // otherwise, we create the right response - // with the state name - return new xmlrpcresp(php_xmlrpc_encode($ra)); - } } + // if we generated an error, create an error return response + if ($err) { + return new xmlrpcresp(0, $xmlrpcerruser, $err); + } else { + // otherwise, we create the right response + // with the state name + return new xmlrpcresp(php_xmlrpc_encode($ra)); + } +} - $s = new xmlrpc_server(array( - "discuss.addComment" => array( - "function" => "addcomment", - "signature" => $addcomment_sig, - "docstring" => $addcomment_doc - ), - "discuss.getComments" => array( - "function" => "getcomments", - "signature" => $getcomments_sig, - "docstring" => $getcomments_doc - ) - )); +$s = new xmlrpc_server(array( + "discuss.addComment" => array( + "function" => "addcomment", + "signature" => $addcomment_sig, + "docstring" => $addcomment_doc, + ), + "discuss.getComments" => array( + "function" => "getcomments", + "signature" => $getcomments_sig, + "docstring" => $getcomments_doc, + ), +)); diff --git a/demo/server/proxy.php b/demo/server/proxy.php index 4f03f460..80a3f605 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -2,85 +2,83 @@ /** * 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) + * the originating server). * * @author Gaetano Giunta * @copyright (C) 2006-2014 G. Giunta * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt */ +include_once __DIR__ . "/../../vendor/autoload.php"; - include_once(__DIR__."/../../vendor/autoload.php"); +include_once __DIR__ . "/../../lib/xmlrpc.inc"; +include_once __DIR__ . "/../../lib/xmlrpcs.inc"; - include_once(__DIR__."/../../lib/xmlrpc.inc"); - include_once(__DIR__."/../../lib/xmlrpcs.inc"); - - /** - * Forward an xmlrpc request to another server, and return to client the response received. - * @param xmlrpcmsg $m (see method docs below for a description of the expected parameters) - * @return xmlrpcresp - */ - function forward_request($m) - { - // create client - $timeout = 0; - $url = php_xmlrpc_decode($m->getParam(0)); - $c = new xmlrpc_client($url); - if ($m->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 = php_xmlrpc_decode($m->getParam(3)); - foreach($options as $key => $val) - { - switch($key) - { - case 'Cookie': - break; - case 'Credentials': - break; - case 'RequestCompression': - $c->setRequestCompression($val); - break; - case 'SSLVerifyHost': - $c->setSSLVerifyHost($val); - break; - case 'SSLVerifyPeer': - $c->setSSLVerifyPeer($val); - break; - case 'Timeout': - $timeout = (integer) $val; - break; - } // switch - } - } - - // build call for remote server - /// @todo find a weay 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... - $method = php_xmlrpc_decode($m->getParam(1)); - $pars = $m->getParam(2); - $m = new xmlrpcmsg($method); - for ($i = 0; $i < $pars->arraySize(); $i++) - { - $m->addParam($pars->arraymem($i)); +/** + * Forward an xmlrpc request to another server, and return to client the response received. + * + * @param xmlrpcmsg $m (see method docs below for a description of the expected parameters) + * + * @return xmlrpcresp + */ +function forward_request($m) +{ + // create client + $timeout = 0; + $url = php_xmlrpc_decode($m->getParam(0)); + $c = new xmlrpc_client($url); + if ($m->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 = php_xmlrpc_decode($m->getParam(3)); + foreach ($options as $key => $val) { + switch ($key) { + case 'Cookie': + break; + case 'Credentials': + break; + case 'RequestCompression': + $c->setRequestCompression($val); + break; + case 'SSLVerifyHost': + $c->setSSLVerifyHost($val); + break; + case 'SSLVerifyPeer': + $c->setSSLVerifyPeer($val); + break; + case 'Timeout': + $timeout = (integer)$val; + break; + } // switch } + } - // add debug info into response we give back to caller - xmlrpc_debugmsg("Sending to server $url the payload: ".$m->serialize()); - return $c->send($m, $timeout); + // build call for remote server + /// @todo find a weay 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... + $method = php_xmlrpc_decode($m->getParam(1)); + $pars = $m->getParam(2); + $m = new xmlrpcmsg($method); + for ($i = 0; $i < $pars->arraySize(); $i++) { + $m->addParam($pars->arraymem($i)); } - // run the server - $server = new xmlrpc_server( - array( - 'xmlrpcproxy.call' => array( - 'function' => 'forward_request', - 'signature' => array( - array('mixed', 'string', 'string', 'array'), - array('mixed', 'string', 'string', 'array', 'stuct'), - ), - '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' - ) - ) - ); + // add debug info into response we give back to caller + xmlrpc_debugmsg("Sending to server $url the payload: " . $m->serialize()); + + return $c->send($m, $timeout); +} + +// run the server +$server = new xmlrpc_server( + array( + 'xmlrpcproxy.call' => array( + 'function' => 'forward_request', + 'signature' => array( + array('mixed', 'string', 'string', 'array'), + array('mixed', 'string', 'string', 'array', 'stuct'), + ), + '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', + ), + ) +); diff --git a/demo/server/server.php b/demo/server/server.php index 2d37e800..5f34c751 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -7,248 +7,239 @@ * 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'])) -{ +if ($_SERVER['REQUEST_METHOD'] != 'POST' && isset($_GET['showSource'])) { highlight_file(__FILE__); die(); } - include_once(__DIR__."/../../vendor/autoload.php"); +include_once __DIR__ . "/../../vendor/autoload.php"; - include_once(__DIR__."/../../lib/xmlrpc.inc"); - include_once(__DIR__."/../../lib/xmlrpcs.inc"); - include_once(__DIR__."/../../lib/xmlrpc_wrappers.inc"); +include_once __DIR__ . "/../../lib/xmlrpc.inc"; +include_once __DIR__ . "/../../lib/xmlrpcs.inc"; +include_once __DIR__ . "/../../lib/xmlrpc_wrappers.inc"; +/** + * Used to test usage of object methods in dispatch maps and in wrapper code. + */ +class xmlrpc_server_methods_container +{ /** - * Used to test usage of object methods in dispatch maps and in wrapper code - */ - class xmlrpc_server_methods_container + * Method used to test logging of php warnings generated by user functions. + */ + public function phpwarninggenerator($m) { - /** - * Method used to test logging of php warnings generated by user functions. - */ - function phpwarninggenerator($m) - { - $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined - return new xmlrpcresp(new xmlrpcval(1, 'boolean')); - } - - /** - * Method used to testcatching of exceptions in the server. - */ - function exceptiongenerator($m) - { - throw new Exception("it's just a test", 1); - } - - /** - * a PHP version of the state-number server. Send me an integer and i'll sell you a state - * @param integer $s - * @return string - */ - static function findstate($s) - { - return inner_findstate($s); - } + $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined + return new xmlrpcresp(new xmlrpcval(1, 'boolean')); } + /** + * Method used to testcatching of exceptions in the server. + */ + public function exceptiongenerator($m) + { + throw new Exception("it's just a test", 1); + } - // 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" - ); + /* + * a PHP version of the state-number server. Send me an integer and i'll sell you a state + * @param integer $s + * @return string + */ + public static function findstate($s) + { + return inner_findstate($s); + } +} - $findstate_sig=array(array($xmlrpcString, $xmlrpcInt)); - $findstate_doc='When passed an integer between 1 and 51 returns the +// 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($xmlrpcString, $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($m) +{ + global $xmlrpcerruser, $stateNames; + $err = ""; + // get the first param + $sno = $m->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])) { + $sname = $stateNames[$snv - 1]; + } else { + // not, there so complain + $err = "I don't have a state for the index '" . $snv . "'"; + } - function findstate($m) - { - global $xmlrpcerruser, $stateNames; - $err=""; - // get the first param - $sno=$m->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])) - { - $sname=$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 xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - // otherwise, we create the right response - // with the state name - return new xmlrpcresp(new xmlrpcval($sname)); - } + // if we generated an error, create an error return response + if ($err) { + return new xmlrpcresp(0, $xmlrpcerruser, $err); + } else { + // otherwise, we create the right response + // with the state name + return new xmlrpcresp(new xmlrpcval($sname)); } +} - /** - * Inner code of the state-number server. - * Used to test auto-registration of PHP funcions as xmlrpc methods. - * @param integer $stateno the state number - * @return string the name of the state (or error descrption) - */ - function inner_findstate($stateno) - { - global $stateNames; - if (isset($stateNames[$stateno-1])) - { - return $stateNames[$stateno-1]; - } - else - { - // not, there so complain - return "I don't have a state for the index '" . $stateno . "'"; - } +/** + * Inner code of the state-number server. + * Used to test auto-registration of PHP funcions as xmlrpc methods. + * + * @param integer $stateno the state number + * + * @return string the name of the state (or error descrption) + */ +function inner_findstate($stateno) +{ + global $stateNames; + if (isset($stateNames[$stateno - 1])) { + return $stateNames[$stateno - 1]; + } else { + // not, there so complain + return "I don't have a state for the index '" . $stateno . "'"; } - $findstate2_sig = wrap_php_function('inner_findstate'); +} - $findstate3_sig = wrap_php_function(array('xmlrpc_server_methods_container', 'findstate')); +$findstate2_sig = wrap_php_function('inner_findstate'); - $findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); +$findstate3_sig = wrap_php_function(array('xmlrpc_server_methods_container', 'findstate')); - $obj = new xmlrpc_server_methods_container(); - $findstate4_sig = wrap_php_function(array($obj, 'findstate')); +$findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); - $addtwo_sig=array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); - $addtwo_doc='Add two integers together and return the result'; - function addtwo($m) - { - $s=$m->getParam(0); - $t=$m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"int")); - } +$obj = new xmlrpc_server_methods_container(); +$findstate4_sig = wrap_php_function(array($obj, 'findstate')); - $addtwodouble_sig=array(array($xmlrpcDouble, $xmlrpcDouble, $xmlrpcDouble)); - $addtwodouble_doc='Add two doubles together and return the result'; - function addtwodouble($m) - { - $s=$m->getParam(0); - $t=$m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval()+$t->scalarval(),"double")); - } +$addtwo_sig = array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); +$addtwo_doc = 'Add two integers together and return the result'; +function addtwo($m) +{ + $s = $m->getParam(0); + $t = $m->getParam(1); - $stringecho_sig=array(array($xmlrpcString, $xmlrpcString)); - $stringecho_doc='Accepts a string parameter, returns the string.'; - function stringecho($m) - { - // just sends back a string - $s=$m->getParam(0); - $v = $s->scalarval(); - return new xmlrpcresp(new xmlrpcval($s->scalarval())); - } + return new xmlrpcresp(new xmlrpcval($s->scalarval() + $t->scalarval(), "int")); +} - $echoback_sig=array(array($xmlrpcString, $xmlrpcString)); - $echoback_doc='Accepts a string parameter, returns the entire incoming payload'; - function echoback($m) - { - // just sends back a string with what i got - // sent to me, just escaped, that's all - // - // $m is an incoming message - $s="I got the following message:\n" . $m->serialize(); - return new xmlrpcresp(new xmlrpcval($s)); - } +$addtwodouble_sig = array(array($xmlrpcDouble, $xmlrpcDouble, $xmlrpcDouble)); +$addtwodouble_doc = 'Add two doubles together and return the result'; +function addtwodouble($m) +{ + $s = $m->getParam(0); + $t = $m->getParam(1); - $echosixtyfour_sig=array(array($xmlrpcString, $xmlrpcBase64)); - $echosixtyfour_doc='Accepts a base64 parameter and returns it decoded as a string'; - function echosixtyfour($m) - { - // accepts an encoded value, but sends it back - // as a normal string. this is to test base64 encoding - // is working as expected - $incoming=$m->getParam(0); - return new xmlrpcresp(new xmlrpcval($incoming->scalarval(), "string")); - } + return new xmlrpcresp(new xmlrpcval($s->scalarval() + $t->scalarval(), "double")); +} - $bitflipper_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $bitflipper_doc='Accepts an array of booleans, and returns them inverted'; - function bitflipper($m) - { - global $xmlrpcArray; - - $v=$m->getParam(0); - $sz=$v->arraysize(); - $rv=new xmlrpcval(array(), $xmlrpcArray); - - for($j=0; $j<$sz; $j++) - { - $b=$v->arraymem($j); - if ($b->scalarval()) - { - $rv->addScalar(false, "boolean"); - } - else - { - $rv->addScalar(true, "boolean"); - } - } +$stringecho_sig = array(array($xmlrpcString, $xmlrpcString)); +$stringecho_doc = 'Accepts a string parameter, returns the string.'; +function stringecho($m) +{ + // just sends back a string + $s = $m->getParam(0); + $v = $s->scalarval(); - return new xmlrpcresp($rv); - } + return new xmlrpcresp(new xmlrpcval($s->scalarval())); +} - // Sorting demo - // - // send me an array of structs thus: - // - // Dave 35 - // Edd 45 - // Fred 23 - // Barney 37 +$echoback_sig = array(array($xmlrpcString, $xmlrpcString)); +$echoback_doc = 'Accepts a string parameter, returns the entire incoming payload'; +function echoback($m) +{ + // just sends back a string with what i got + // sent to me, just escaped, that's all // - // and I'll return it to you in sorted order + // $m is an incoming message + $s = "I got the following message:\n" . $m->serialize(); - function agesorter_compare($a, $b) - { - global $agesorter_arr; + return new xmlrpcresp(new xmlrpcval($s)); +} + +$echosixtyfour_sig = array(array($xmlrpcString, $xmlrpcBase64)); +$echosixtyfour_doc = 'Accepts a base64 parameter and returns it decoded as a string'; +function echosixtyfour($m) +{ + // accepts an encoded value, but sends it back + // as a normal string. this is to test base64 encoding + // is working as expected + $incoming = $m->getParam(0); - // 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); + return new xmlrpcresp(new xmlrpcval($incoming->scalarval(), "string")); +} - if ($agesorter_arr[$a]==$agesorter_arr[$b]) - { - return 0; +$bitflipper_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$bitflipper_doc = 'Accepts an array of booleans, and returns them inverted'; +function bitflipper($m) +{ + global $xmlrpcArray; + + $v = $m->getParam(0); + $sz = $v->arraysize(); + $rv = new xmlrpcval(array(), $xmlrpcArray); + + for ($j = 0; $j < $sz; $j++) { + $b = $v->arraymem($j); + if ($b->scalarval()) { + $rv->addScalar(false, "boolean"); + } else { + $rv->addScalar(true, "boolean"); } - return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1; } - $agesorter_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $agesorter_doc='Send this method an array of [string, int] structs, eg: + return new xmlrpcresp($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($xmlrpcArray, $xmlrpcArray)); +$agesorter_doc = 'Send this method an array of [string, int] structs, eg:
  Dave   35
  Edd    45
@@ -257,80 +248,69 @@ function agesorter_compare($a, $b)
 
And the array will be returned with the entries sorted by their numbers. '; - function agesorter($m) - { - global $agesorter_arr, $xmlrpcerruser, $s; - - xmlrpc_debugmsg("Entering 'agesorter'"); - // get the parameter - $sno=$m->getParam(0); - // error string for [if|when] things go wrong - $err=""; - // create the output value - $v=new xmlrpcval(); - $agar=array(); - - if (isset($sno) && $sno->kindOf()=="array") - { - $max=$sno->arraysize(); - // TODO: create debug method to print can work once more - // print "\n"; - for($i=0; $i<$max; $i++) - { - $rec=$sno->arraymem($i); - if ($rec->kindOf()!="struct") - { - $err="Found non-struct in array at element $i"; - break; - } - // extract name and age from struct - $n=$rec->structmem("name"); - $a=$rec->structmem("age"); - // $n and $a are xmlrpcvals, - // so get the scalarval from them - $agar[$n->scalarval()]=$a->scalarval(); - } - - $agesorter_arr=$agar; - // hack, must make global as uksort() won't - // allow us to pass any other auxilliary information - uksort($agesorter_arr, agesorter_compare); - $outAr=array(); - while (list( $key, $val ) = each( $agesorter_arr ) ) - { - // recreate each struct element - $outAr[]=new xmlrpcval(array("name" => - new xmlrpcval($key), - "age" => - new xmlrpcval($val, "int")), "struct"); +function agesorter($m) +{ + global $agesorter_arr, $xmlrpcerruser, $s; + + xmlrpc_debugmsg("Entering 'agesorter'"); + // get the parameter + $sno = $m->getParam(0); + // error string for [if|when] things go wrong + $err = ""; + // create the output value + $v = new xmlrpcval(); + $agar = array(); + + if (isset($sno) && $sno->kindOf() == "array") { + $max = $sno->arraysize(); + // TODO: create debug method to print can work once more + // print "\n"; + for ($i = 0; $i < $max; $i++) { + $rec = $sno->arraymem($i); + if ($rec->kindOf() != "struct") { + $err = "Found non-struct in array at element $i"; + break; } - // add this array to the output value - $v->addArray($outAr); - } - else - { - $err="Must be one parameter, an array of structs"; + // extract name and age from struct + $n = $rec->structmem("name"); + $a = $rec->structmem("age"); + // $n and $a are xmlrpcvals, + // so get the scalarval from them + $agar[$n->scalarval()] = $a->scalarval(); } - if ($err) - { - return new xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - return new xmlrpcresp($v); + $agesorter_arr = $agar; + // hack, must make global as uksort() won't + // allow us to pass any other auxilliary information + uksort($agesorter_arr, agesorter_compare); + $outAr = array(); + while (list($key, $val) = each($agesorter_arr)) { + // recreate each struct element + $outAr[] = new xmlrpcval(array("name" => new xmlrpcval($key), + "age" => new xmlrpcval($val, "int"),), "struct"); } + // add this array to the output value + $v->addArray($outAr); + } else { + $err = "Must be one parameter, an array of structs"; } - // signature and instructions, place these in the dispatch - // map - $mail_send_sig=array(array( - $xmlrpcBoolean, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString - )); + if ($err) { + return new xmlrpcresp(0, $xmlrpcerruser, $err); + } else { + return new xmlrpcresp($v); + } +} - $mail_send_doc='mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
+// signature and instructions, place these in the dispatch +// map +$mail_send_sig = array(array( + $xmlrpcBoolean, $xmlrpcString, $xmlrpcString, + $xmlrpcString, $xmlrpcString, $xmlrpcString, + $xmlrpcString, $xmlrpcString, +)); + +$mail_send_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.
subject is a string, the subject of the message.
sender is a string, it\'s the email address of the person sending the message. This string can not be @@ -338,516 +318,562 @@ function agesorter($m) text is a string, it contains the body of the message.
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 mail_send($m) - { - global $xmlrpcerruser, $xmlrpcBoolean; - $err=""; - - $mTo=$m->getParam(0); - $mSub=$m->getParam(1); - $mBody=$m->getParam(2); - $mFrom=$m->getParam(3); - $mCc=$m->getParam(4); - $mBcc=$m->getParam(5); - $mMime=$m->getParam(6); - - if ($mTo->scalarval()=="") - { - $err="Error, no 'To' field specified"; - } - - if ($mFrom->scalarval()=="") - { - $err="Error, no 'From' field specified"; - } +// 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 mail_send($m) +{ + global $xmlrpcerruser, $xmlrpcBoolean; + $err = ""; + + $mTo = $m->getParam(0); + $mSub = $m->getParam(1); + $mBody = $m->getParam(2); + $mFrom = $m->getParam(3); + $mCc = $m->getParam(4); + $mBcc = $m->getParam(5); + $mMime = $m->getParam(6); + + if ($mTo->scalarval() == "") { + $err = "Error, no 'To' field specified"; + } - $msghdr="From: " . $mFrom->scalarval() . "\n"; - $msghdr.="To: ". $mTo->scalarval() . "\n"; + if ($mFrom->scalarval() == "") { + $err = "Error, no 'From' field specified"; + } - 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."; - } - } + $msghdr = "From: " . $mFrom->scalarval() . "\n"; + $msghdr .= "To: " . $mTo->scalarval() . "\n"; - if ($err) - { - return new xmlrpcresp(0, $xmlrpcerruser, $err); - } - else - { - return new xmlrpcresp(new xmlrpcval("true", $xmlrpcBoolean)); + 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."; } } - $getallheaders_sig=array(array($xmlrpcStruct)); - $getallheaders_doc='Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS'; - function getallheaders_xmlrpc($m) - { - global $xmlrpcerruser; - if (function_exists('getallheaders')) - { - return new xmlrpcresp(php_xmlrpc_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 xmlrpcresp(php_xmlrpc_encode($headers)); - } + if ($err) { + return new xmlrpcresp(0, $xmlrpcerruser, $err); + } else { + return new xmlrpcresp(new xmlrpcval("true", $xmlrpcBoolean)); } +} - $setcookies_sig=array(array($xmlrpcInt, $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($m) - { - $m = $m->getParam(0); - while(list($name,$value) = $m->structeach()) - { - $cookiedesc = php_xmlrpc_decode($value); - setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); +$getallheaders_sig = array(array($xmlrpcStruct)); +$getallheaders_doc = 'Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS'; +function getallheaders_xmlrpc($m) +{ + global $xmlrpcerruser; + if (function_exists('getallheaders')) { + return new xmlrpcresp(php_xmlrpc_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 xmlrpcresp(new xmlrpcval(1, 'int')); + + return new xmlrpcresp(php_xmlrpc_encode($headers)); } +} - $getcookies_sig=array(array($xmlrpcStruct)); - $getcookies_doc='Sends to client a response containing all http cookies as received in the request (as struct)'; - function getcookies($m) - { - return new xmlrpcresp(php_xmlrpc_encode($_COOKIE)); +$setcookies_sig = array(array($xmlrpcInt, $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($m) +{ + $m = $m->getParam(0); + while (list($name, $value) = $m->structeach()) { + $cookiedesc = php_xmlrpc_decode($value); + setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); } - $v1_arrayOfStructs_sig=array(array($xmlrpcInt, $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 s. Your handler must add all the struct elements named curly and return the result.'; - function v1_arrayOfStructs($m) - { - $sno=$m->getParam(0); - $numcurly=0; - for($i=0; $i<$sno->arraysize(); $i++) - { - $str=$sno->arraymem($i); - $str->structreset(); - while(list($key,$val)=$str->structeach()) - { - if ($key=="curly") - { - $numcurly+=$val->scalarval(); - } + return new xmlrpcresp(new xmlrpcval(1, 'int')); +} + +$getcookies_sig = array(array($xmlrpcStruct)); +$getcookies_doc = 'Sends to client a response containing all http cookies as received in the request (as struct)'; +function getcookies($m) +{ + return new xmlrpcresp(php_xmlrpc_encode($_COOKIE)); +} + +$v1_arrayOfStructs_sig = array(array($xmlrpcInt, $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 s. Your handler must add all the struct elements named curly and return the result.'; +function v1_arrayOfStructs($m) +{ + $sno = $m->getParam(0); + $numcurly = 0; + for ($i = 0; $i < $sno->arraysize(); $i++) { + $str = $sno->arraymem($i); + $str->structreset(); + while (list($key, $val) = $str->structeach()) { + if ($key == "curly") { + $numcurly += $val->scalarval(); } } - return new xmlrpcresp(new xmlrpcval($numcurly, "int")); } - $v1_easyStruct_sig=array(array($xmlrpcInt, $xmlrpcStruct)); - $v1_easyStruct_doc='This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; - function v1_easyStruct($m) - { - $sno=$m->getParam(0); - $moe=$sno->structmem("moe"); - $larry=$sno->structmem("larry"); - $curly=$sno->structmem("curly"); - $num=$moe->scalarval() + $larry->scalarval() + $curly->scalarval(); - return new xmlrpcresp(new xmlrpcval($num, "int")); - } + return new xmlrpcresp(new xmlrpcval($numcurly, "int")); +} - $v1_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); - $v1_echoStruct_doc='This handler takes a single parameter, a struct. Your handler must return the struct.'; - function v1_echoStruct($m) - { - $sno=$m->getParam(0); - return new xmlrpcresp($sno); - } +$v1_easyStruct_sig = array(array($xmlrpcInt, $xmlrpcStruct)); +$v1_easyStruct_doc = 'This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all <i4>s. Your handler must add the three numbers and return the result.'; +function v1_easyStruct($m) +{ + $sno = $m->getParam(0); + $moe = $sno->structmem("moe"); + $larry = $sno->structmem("larry"); + $curly = $sno->structmem("curly"); + $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval(); + + return new xmlrpcresp(new xmlrpcval($num, "int")); +} + +$v1_echoStruct_sig = array(array($xmlrpcStruct, $xmlrpcStruct)); +$v1_echoStruct_doc = 'This handler takes a single parameter, a struct. Your handler must return the struct.'; +function v1_echoStruct($m) +{ + $sno = $m->getParam(0); - $v1_manyTypes_sig=array(array( - $xmlrpcArray, $xmlrpcInt, $xmlrpcBoolean, - $xmlrpcString, $xmlrpcDouble, $xmlrpcDateTime, - $xmlrpcBase64 + return new xmlrpcresp($sno); +} + +$v1_manyTypes_sig = array(array( + $xmlrpcArray, $xmlrpcInt, $xmlrpcBoolean, + $xmlrpcString, $xmlrpcDouble, $xmlrpcDateTime, + $xmlrpcBase64, +)); +$v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.'; +function v1_manyTypes($m) +{ + return new xmlrpcresp(new xmlrpcval(array( + $m->getParam(0), + $m->getParam(1), + $m->getParam(2), + $m->getParam(3), + $m->getParam(4), + $m->getParam(5),), + "array" )); - $v1_manyTypes_doc='This handler takes six parameters, and returns an array containing all the parameters.'; - function v1_manyTypes($m) - { - return new xmlrpcresp(new xmlrpcval(array( - $m->getParam(0), - $m->getParam(1), - $m->getParam(2), - $m->getParam(3), - $m->getParam(4), - $m->getParam(5)), - "array" - )); - } +} - $v1_moderateSizeArrayCheck_sig=array(array($xmlrpcString, $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($m) - { - $ar=$m->getParam(0); - $sz=$ar->arraysize(); - $first=$ar->arraymem(0); - $last=$ar->arraymem($sz-1); - return new xmlrpcresp(new xmlrpcval($first->scalarval() . +$v1_moderateSizeArrayCheck_sig = array(array($xmlrpcString, $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($m) +{ + $ar = $m->getParam(0); + $sz = $ar->arraysize(); + $first = $ar->arraymem(0); + $last = $ar->arraymem($sz - 1); + + return new xmlrpcresp(new xmlrpcval($first->scalarval() . $last->scalarval(), "string")); - } +} - $v1_simpleStructReturn_sig=array(array($xmlrpcStruct, $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($m) - { - $sno=$m->getParam(0); - $v=$sno->scalarval(); - return new xmlrpcresp(new xmlrpcval(array( - "times10" => new xmlrpcval($v*10, "int"), - "times100" => new xmlrpcval($v*100, "int"), - "times1000" => new xmlrpcval($v*1000, "int")), - "struct" - )); - } +$v1_simpleStructReturn_sig = array(array($xmlrpcStruct, $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($m) +{ + $sno = $m->getParam(0); + $v = $sno->scalarval(); + + return new xmlrpcresp(new xmlrpcval(array( + "times10" => new xmlrpcval($v * 10, "int"), + "times100" => new xmlrpcval($v * 100, "int"), + "times1000" => new xmlrpcval($v * 1000, "int"),), + "struct" + )); +} - $v1_nestedStruct_sig=array(array($xmlrpcInt, $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 <i4>s. Your handler must add the three numbers and return the result.'; - function v1_nestedStruct($m) - { - $sno=$m->getParam(0); - - $twoK=$sno->structmem("2000"); - $april=$twoK->structmem("04"); - $fools=$april->structmem("01"); - $curly=$fools->structmem("curly"); - $larry=$fools->structmem("larry"); - $moe=$fools->structmem("moe"); - return new xmlrpcresp(new xmlrpcval($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); - } +$v1_nestedStruct_sig = array(array($xmlrpcInt, $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 <i4>s. Your handler must add the three numbers and return the result.'; +function v1_nestedStruct($m) +{ + $sno = $m->getParam(0); - $v1_countTheEntities_sig=array(array($xmlrpcStruct, $xmlrpcString)); - $v1_countTheEntities_doc='This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, >, & \' and ".
Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; - function v1_countTheEntities($m) - { - $sno=$m->getParam(0); - $str=$sno->scalarval(); - $gt=0; $lt=0; $ap=0; $qu=0; $amp=0; - for($i=0; $i": - $gt++; - break; - case "<": - $lt++; - break; - case "\"": - $qu++; - break; - case "'": - $ap++; - break; - case "&": - $amp++; - break; - default: - break; - } + $twoK = $sno->structmem("2000"); + $april = $twoK->structmem("04"); + $fools = $april->structmem("01"); + $curly = $fools->structmem("curly"); + $larry = $fools->structmem("larry"); + $moe = $fools->structmem("moe"); + + return new xmlrpcresp(new xmlrpcval($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); +} + +$v1_countTheEntities_sig = array(array($xmlrpcStruct, $xmlrpcString)); +$v1_countTheEntities_doc = 'This handler takes a single parameter, a string, that contains any number of predefined entities, namely <, >, & \' and ".
Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; +function v1_countTheEntities($m) +{ + $sno = $m->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 xmlrpcresp(new xmlrpcval(array( - "ctLeftAngleBrackets" => new xmlrpcval($lt, "int"), - "ctRightAngleBrackets" => new xmlrpcval($gt, "int"), - "ctAmpersands" => new xmlrpcval($amp, "int"), - "ctApostrophes" => new xmlrpcval($ap, "int"), - "ctQuotes" => new xmlrpcval($qu, "int")), - "struct" - )); } - // trivial interop tests - // http://www.xmlrpc.com/stories/storyReader$1636 + return new xmlrpcresp(new xmlrpcval(array( + "ctLeftAngleBrackets" => new xmlrpcval($lt, "int"), + "ctRightAngleBrackets" => new xmlrpcval($gt, "int"), + "ctAmpersands" => new xmlrpcval($amp, "int"), + "ctApostrophes" => new xmlrpcval($ap, "int"), + "ctQuotes" => new xmlrpcval($qu, "int"),), + "struct" + )); +} - $i_echoString_sig=array(array($xmlrpcString, $xmlrpcString)); - $i_echoString_doc="Echoes string."; +// trivial interop tests +// http://www.xmlrpc.com/stories/storyReader$1636 - $i_echoStringArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoStringArray_doc="Echoes string array."; +$i_echoString_sig = array(array($xmlrpcString, $xmlrpcString)); +$i_echoString_doc = "Echoes string."; - $i_echoInteger_sig=array(array($xmlrpcInt, $xmlrpcInt)); - $i_echoInteger_doc="Echoes integer."; +$i_echoStringArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoStringArray_doc = "Echoes string array."; - $i_echoIntegerArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoIntegerArray_doc="Echoes integer array."; +$i_echoInteger_sig = array(array($xmlrpcInt, $xmlrpcInt)); +$i_echoInteger_doc = "Echoes integer."; - $i_echoFloat_sig=array(array($xmlrpcDouble, $xmlrpcDouble)); - $i_echoFloat_doc="Echoes float."; +$i_echoIntegerArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoIntegerArray_doc = "Echoes integer array."; - $i_echoFloatArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoFloatArray_doc="Echoes float array."; +$i_echoFloat_sig = array(array($xmlrpcDouble, $xmlrpcDouble)); +$i_echoFloat_doc = "Echoes float."; - $i_echoStruct_sig=array(array($xmlrpcStruct, $xmlrpcStruct)); - $i_echoStruct_doc="Echoes struct."; +$i_echoFloatArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoFloatArray_doc = "Echoes float array."; - $i_echoStructArray_sig=array(array($xmlrpcArray, $xmlrpcArray)); - $i_echoStructArray_doc="Echoes struct array."; +$i_echoStruct_sig = array(array($xmlrpcStruct, $xmlrpcStruct)); +$i_echoStruct_doc = "Echoes struct."; - $i_echoValue_doc="Echoes any value back."; - $i_echoValue_sig=array(array($xmlrpcValue, $xmlrpcValue)); +$i_echoStructArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoStructArray_doc = "Echoes struct array."; - $i_echoBase64_sig=array(array($xmlrpcBase64, $xmlrpcBase64)); - $i_echoBase64_doc="Echoes base64."; +$i_echoValue_doc = "Echoes any value back."; +$i_echoValue_sig = array(array($xmlrpcValue, $xmlrpcValue)); - $i_echoDate_sig=array(array($xmlrpcDateTime, $xmlrpcDateTime)); - $i_echoDate_doc="Echoes dateTime."; +$i_echoBase64_sig = array(array($xmlrpcBase64, $xmlrpcBase64)); +$i_echoBase64_doc = "Echoes base64."; - function i_echoParam($m) - { - $s=$m->getParam(0); - return new xmlrpcresp($s); - } +$i_echoDate_sig = array(array($xmlrpcDateTime, $xmlrpcDateTime)); +$i_echoDate_doc = "Echoes dateTime."; - function i_echoString($m) { return i_echoParam($m); } - function i_echoInteger($m) { return i_echoParam($m); } - function i_echoFloat($m) { return i_echoParam($m); } - function i_echoStruct($m) { return i_echoParam($m); } - function i_echoStringArray($m) { return i_echoParam($m); } - function i_echoIntegerArray($m) { return i_echoParam($m); } - function i_echoFloatArray($m) { return i_echoParam($m); } - function i_echoStructArray($m) { return i_echoParam($m); } - function i_echoValue($m) { return i_echoParam($m); } - function i_echoBase64($m) { return i_echoParam($m); } - function i_echoDate($m) { return i_echoParam($m); } - - $i_whichToolkit_sig=array(array($xmlrpcStruct)); - $i_whichToolkit_doc="Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; - - function i_whichToolkit($m) - { - global $xmlrpcName, $xmlrpcVersion,$SERVER_SOFTWARE; - $ret=array( - "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", - "toolkitName" => $xmlrpcName, - "toolkitVersion" => $xmlrpcVersion, - "toolkitOperatingSystem" => isset ($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'] - ); - return new xmlrpcresp ( php_xmlrpc_encode($ret)); - } +function i_echoParam($m) +{ + $s = $m->getParam(0); + + return new xmlrpcresp($s); +} + +function i_echoString($m) +{ + return i_echoParam($m); +} + +function i_echoInteger($m) +{ + return i_echoParam($m); +} + +function i_echoFloat($m) +{ + return i_echoParam($m); +} + +function i_echoStruct($m) +{ + return i_echoParam($m); +} + +function i_echoStringArray($m) +{ + return i_echoParam($m); +} + +function i_echoIntegerArray($m) +{ + return i_echoParam($m); +} - $o=new xmlrpc_server_methods_container; - $a=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 - ), - "examples.generatePHPWarning" => array( - "function" => array($o, "phpwarninggenerator") - //'function' => 'xmlrpc_server_methods_container::phpwarninggenerator' - ), - "examples.raiseException" => array( - "function" => array($o, "exceptiongenerator") - ), - "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" => "mail_send", - "signature" => $mail_send_sig, - "docstring" => $mail_send_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 - ) +function i_echoFloatArray($m) +{ + return i_echoParam($m); +} + +function i_echoStructArray($m) +{ + return i_echoParam($m); +} + +function i_echoValue($m) +{ + return i_echoParam($m); +} + +function i_echoBase64($m) +{ + return i_echoParam($m); +} + +function i_echoDate($m) +{ + return i_echoParam($m); +} + +$i_whichToolkit_sig = array(array($xmlrpcStruct)); +$i_whichToolkit_doc = "Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; + +function i_whichToolkit($m) +{ + global $xmlrpcName, $xmlrpcVersion, $SERVER_SOFTWARE; + $ret = array( + "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", + "toolkitName" => $xmlrpcName, + "toolkitVersion" => $xmlrpcVersion, + "toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'], ); - if ($findstate2_sig) - $a['examples.php.getStateName'] = $findstate2_sig; + return new xmlrpcresp(php_xmlrpc_encode($ret)); +} + +$o = new xmlrpc_server_methods_container(); +$a = 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, + ), + "examples.generatePHPWarning" => array( + "function" => array($o, "phpwarninggenerator"), + //'function' => 'xmlrpc_server_methods_container::phpwarninggenerator' + ), + "examples.raiseException" => array( + "function" => array($o, "exceptiongenerator"), + ), + "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" => "mail_send", + "signature" => $mail_send_sig, + "docstring" => $mail_send_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, + ), +); + +if ($findstate2_sig) { + $a['examples.php.getStateName'] = $findstate2_sig; +} - if ($findstate3_sig) - $a['examples.php2.getStateName'] = $findstate3_sig; +if ($findstate3_sig) { + $a['examples.php2.getStateName'] = $findstate3_sig; +} - if ($findstate4_sig) - $a['examples.php3.getStateName'] = $findstate4_sig; +if ($findstate4_sig) { + $a['examples.php3.getStateName'] = $findstate4_sig; +} - if ($findstate5_sig) - $a['examples.php4.getStateName'] = $findstate5_sig; +if ($findstate5_sig) { + $a['examples.php4.getStateName'] = $findstate5_sig; +} - $s=new xmlrpc_server($a, false); - $s->setdebug(3); - $s->compress_response = true; +$s = new xmlrpc_server($a, 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['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($_GET['RESPONSE_ENCODING'])) { + $s->response_charset_encoding = $_GET['RESPONSE_ENCODING']; +} +if (isset($_GET['EXCEPTION_HANDLING'])) { + $s->exception_handling = $_GET['EXCEPTION_HANDLING']; +} +$s->service(); +// that should do all we need! diff --git a/demo/vardemo.php b/demo/vardemo.php index b501cd60..0b542e74 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -2,61 +2,61 @@ xmlrpc Testing value serialization\n"; - - $v = new xmlrpcval(23, "int"); - print "
" . htmlentities($v->serialize()) . "
"; - $v = new xmlrpcval("What are you saying? >> << &&"); - print "
" . htmlentities($v->serialize()) . "
"; - - $v = new xmlrpcval(array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean')), - "array" - ); - - print "
" . htmlentities($v->serialize()) . "
"; - - $v = new xmlrpcval( - array( - "thearray" => new xmlrpcval( - array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean'), - new xmlrpcval(0, 'boolean'), - new xmlrpcval(true, 'boolean'), - new xmlrpcval(false, 'boolean') - ), - "array" +include_once __DIR__ . "/../vendor/autoload.php"; + +include_once __DIR__ . "/../lib/xmlrpc.inc"; + +$f = new xmlrpcmsg('examples.getStateName'); + +print "

Testing value serialization

\n"; + +$v = new xmlrpcval(23, "int"); +print "
" . htmlentities($v->serialize()) . "
"; +$v = new xmlrpcval("What are you saying? >> << &&"); +print "
" . htmlentities($v->serialize()) . "
"; + +$v = new xmlrpcval(array( + new xmlrpcval("ABCDEFHIJ"), + new xmlrpcval(1234, 'int'), + new xmlrpcval(1, 'boolean'),), + "array" +); + +print "
" . htmlentities($v->serialize()) . "
"; + +$v = new xmlrpcval( + array( + "thearray" => new xmlrpcval( + array( + new xmlrpcval("ABCDEFHIJ"), + new xmlrpcval(1234, 'int'), + new xmlrpcval(1, 'boolean'), + new xmlrpcval(0, 'boolean'), + new xmlrpcval(true, 'boolean'), + new xmlrpcval(false, 'boolean'), ), - "theint" => new xmlrpcval(23, 'int'), - "thestring" => new xmlrpcval("foobarwhizz"), - "thestruct" => new xmlrpcval( - array( - "one" => new xmlrpcval(1, 'int'), - "two" => new xmlrpcval(2, 'int') - ), - "struct" - ) + "array" ), - "struct" - ); + "theint" => new xmlrpcval(23, 'int'), + "thestring" => new xmlrpcval("foobarwhizz"), + "thestruct" => new xmlrpcval( + array( + "one" => new xmlrpcval(1, 'int'), + "two" => new xmlrpcval(2, 'int'), + ), + "struct" + ), + ), + "struct" +); - print "
" . htmlentities($v->serialize()) . "
"; +print "
" . htmlentities($v->serialize()) . "
"; - $w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array"); +$w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array"); - print "
" . htmlentities($w->serialize()) . "
"; +print "
" . htmlentities($w->serialize()) . "
"; - $w = new xmlrpcval("Mary had a little lamb, +$w = new xmlrpcval("Mary had a little lamb, Whose fleece was white as snow, And everywhere that Mary went the lamb was sure to go. @@ -65,29 +65,29 @@ She tied it to a pylon Ten thousand volts went down its back And turned it into nylon", "base64" - ); - print "
" . htmlentities($w->serialize()) . "
"; - print "
Value of base64 string is: '" . $w->scalarval() . "'
"; +); +print "
" . htmlentities($w->serialize()) . "
"; +print "
Value of base64 string is: '" . $w->scalarval() . "'
"; - $f->method(''); - $f->addParam(new xmlrpcval("41", "int")); +$f->method(''); +$f->addParam(new xmlrpcval("41", "int")); - print "

Testing request serialization

\n"; - $op = $f->serialize(); - print "
" . htmlentities($op) . "
"; +print "

Testing request serialization

\n"; +$op = $f->serialize(); +print "
" . htmlentities($op) . "
"; - print "

Testing ISO date format

\n";
+print "

Testing ISO date format

\n";
 
-    $t = time();
-    $date = iso8601_encode($t);
-    print "Now is $t --> $date\n";
-    print "Or in UTC, that is " . iso8601_encode($t, 1) . "\n";
-    $tb = iso8601_decode($date);
-    print "That is to say $date --> $tb\n";
-    print "Which comes out at " . iso8601_encode($tb) . "\n";
-    print "Which was the time in UTC at " . iso8601_decode($date, 1) . "\n";
+$t = time();
+$date = iso8601_encode($t);
+print "Now is $t --> $date\n";
+print "Or in UTC, that is " . iso8601_encode($t, 1) . "\n";
+$tb = iso8601_decode($date);
+print "That is to say $date --> $tb\n";
+print "Which comes out at " . iso8601_encode($tb) . "\n";
+print "Which was the time in UTC at " . iso8601_decode($date, 1) . "\n";
 
-    print "
\n"; +print "
\n"; ?> From 05ba4479e2f74f0a51797ca268b1b8751f544614 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 18:58:18 +0000 Subject: [PATCH 040/228] Reformat source code: doc --- doc/convert.php | 47 ++++++++++++++++++++--------------------- doc/custom.fo.xsl | 2 +- doc/custom.xsl | 2 +- doc/highlight.php | 53 ++++++++++++++++++++++------------------------- 4 files changed, 50 insertions(+), 54 deletions(-) diff --git a/doc/convert.php b/doc/convert.php index 4de3b444..a811c4ed 100644 --- a/doc/convert.php +++ b/doc/convert.php @@ -1,57 +1,56 @@ load($doc); -$xsl = new DOMDocument; +$xsl = new DOMDocument(); $xsl->load($xss); // Configure the transformer -$proc = new XSLTProcessor; -if (version_compare(PHP_VERSION,'5.4',"<")) -{ - if(defined('XSL_SECPREF_WRITE_FILE')) +$proc = 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 -{ + } +} else { $proc->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); } $proc->importStyleSheet($xsl); // attach the xsl rules //if ($_SERVER['argc'] >= 4) //{ - if (is_dir($_SERVER['argv'][3])) - { - if (!$proc->setParameter('', 'base.dir', realpath($_SERVER['argv'][3]))) - echo "setting param base.dir KO\n"; - } - else - { - //echo "{$_SERVER['argv'][3]} is not a dir\n"; +if (is_dir($_SERVER['argv'][3])) { + if (!$proc->setParameter('', 'base.dir', realpath($_SERVER['argv'][3]))) { + echo "setting param base.dir KO\n"; } +} else { + //echo "{$_SERVER['argv'][3]} is not a dir\n"; +} //} $out = $proc->transformToXML($xml); -if (!is_dir($_SERVER['argv'][3])) +if (!is_dir($_SERVER['argv'][3])) { file_put_contents($_SERVER['argv'][3], $out); +} echo "OK\n"; diff --git a/doc/custom.fo.xsl b/doc/custom.fo.xsl index f87d9747..54598264 100644 --- a/doc/custom.fo.xsl +++ b/doc/custom.fo.xsl @@ -1,7 +1,7 @@ + xmlns:fo="http://www.w3.org/1999/XSL/Format"> "; - $f=new xmlrpcmsg('examples.stringecho', array( - new xmlrpcval($sendstring, 'string') + " 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: -->"; + $f = new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval($sendstring, 'string'), )); - $v=$this->send($f); - if($v) - { + $v = $this->send($f); + 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) + if ($l1 == $l2) { $this->assertEquals($sendstring, $v->scalarval()); - else + } else { $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendstring), $v->scalarval()); + } } } - function testAddingDoubles() + public function testAddingDoubles() { // note that rounding errors mean we // keep precision to sensible levels here ;-) - $a=12.13; $b=-23.98; - $f=new xmlrpcmsg('examples.addtwodouble',array( + $a = 12.13; + $b = -23.98; + $f = new xmlrpcmsg('examples.addtwodouble', array( new xmlrpcval($a, 'double'), - new xmlrpcval($b, 'double') + new xmlrpcval($b, 'double'), )); - $v=$this->send($f); - if($v) - { - $this->assertEquals($a+$b,$v->scalarval()); + $v = $this->send($f); + if ($v) { + $this->assertEquals($a + $b, $v->scalarval()); } } - function testAdding() + public function testAdding() { - $f=new xmlrpcmsg('examples.addtwo',array( + $f = new xmlrpcmsg('examples.addtwo', array( new xmlrpcval(12, 'int'), - new xmlrpcval(-23, 'int') + new xmlrpcval(-23, 'int'), )); - $v=$this->send($f); - if($v) - { - $this->assertEquals(12-23, $v->scalarval()); + $v = $this->send($f); + if ($v) { + $this->assertEquals(12 - 23, $v->scalarval()); } } - function testInvalidNumber() + public function testInvalidNumber() { - $f=new xmlrpcmsg('examples.addtwo',array( + $f = new xmlrpcmsg('examples.addtwo', array( new xmlrpcval('fred', 'int'), - new xmlrpcval("\"; exec('ls')", 'int') + new xmlrpcval("\"; exec('ls')", 'int'), )); - $v=$this->send($f); + $v = $this->send($f); /// @todo a fault condition should be generated here /// by the server, which we pick up on - if($v) - { + if ($v) { $this->assertEquals(0, $v->scalarval()); } } - function testBoolean() + public function testBoolean() { - $f=new xmlrpcmsg('examples.invertBooleans', array( + $f = new xmlrpcmsg('examples.invertBooleans', array( new xmlrpcval(array( new xmlrpcval(true, 'boolean'), new xmlrpcval(false, 'boolean'), @@ -164,33 +152,28 @@ function testBoolean() //new xmlrpcval('true', 'boolean'), //new xmlrpcval('false', 'boolean') ), - 'array' - ))); - $answer='0101'; - $v=$this->send($f); - if($v) - { - $sz=$v->arraysize(); - $got=''; - for($i=0; $i<$sz; $i++) - { - $b=$v->arraymem($i); - if($b->scalarval()) - { - $got.='1'; - } - else - { - $got.='0'; + 'array' + ),)); + $answer = '0101'; + $v = $this->send($f); + 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); } } - function testBase64() + public function testBase64() { - $sendstring='Mary had a little lamb, + $sendstring = 'Mary had a little lamb, Whose fleece was white as snow, And everywhere that Mary went the lamb was sure to go. @@ -199,51 +182,47 @@ function testBase64() She tied it to a pylon Ten thousand volts went down its back And turned it into nylon'; - $f=new xmlrpcmsg('examples.decode64',array( - new xmlrpcval($sendstring, 'base64') + $f = new xmlrpcmsg('examples.decode64', array( + new xmlrpcval($sendstring, 'base64'), )); - $v=$this->send($f); - if($v) - { - if (strlen($sendstring) == strlen($v->scalarval())) + $v = $this->send($f); + if ($v) { + if (strlen($sendstring) == strlen($v->scalarval())) { $this->assertEquals($sendstring, $v->scalarval()); - else + } else { $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendstring), $v->scalarval()); + } } } - function testDateTime() + 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')) - { + 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'))) - { + if (is_callable(array($datetime, 'setTimestamp'))) { $t3 = new xmlrpcval($datetime->setTimestamp($time), 'dateTime.iso8601'); $this->assertEquals($t1->serialize(), $t3->serialize()); } } } - function testCountEntities() + public function testCountEntities() { $sendstring = "h'fd>onc>>l>>rw&bpu>q>esend($f); - if($v) - { + if ($v) { $got = ''; $expected = '37210'; - $expect_array = array('ctLeftAngleBrackets','ctRightAngleBrackets','ctAmpersands','ctApostrophes','ctQuotes'); - while(list(,$val) = each($expect_array)) - { + $expect_array = array('ctLeftAngleBrackets', 'ctRightAngleBrackets', 'ctAmpersands', 'ctApostrophes', 'ctQuotes'); + while (list(, $val) = each($expect_array)) { $b = $v->structmem($val); $got .= $b->me['int']; } @@ -251,14 +230,15 @@ function testCountEntities() } } - function _multicall_msg($method, $params) + public function _multicall_msg($method, $params) { $struct['methodName'] = new xmlrpcval($method, 'string'); $struct['params'] = new xmlrpcval($params, 'array'); + return new xmlrpcval($struct, 'struct'); } - function testServerMulticall() + public function testServerMulticall() { // We manually construct a system.multicall() call to ensure // that the server supports it. @@ -285,8 +265,7 @@ function testServerMulticall() $f = new xmlrpcmsg('system.multicall', array($arg)); $v = $this->send($f); - if($v) - { + if ($v) { //$this->assertTrue($r->faultCode() == 0, "fault from system.multicall"); $this->assertTrue($v->arraysize() == 4, "bad number of return values"); @@ -316,7 +295,7 @@ function testServerMulticall() } } - function testClientMulticall1() + public function testClientMulticall1() { // NB: This test will NOT pass if server does not support system.multicall. @@ -333,14 +312,12 @@ function testClientMulticall1() ); $r = $this->send(array($good1, $bad, $recursive, $good2)); - if($r) - { + 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()) - { + if (!$r[0]->faultCode()) { $val = $r[0]->value(); $this->assertTrue( $val->kindOf() == 'scalar' && $val->scalartyp() == 'string', @@ -350,8 +327,7 @@ function testClientMulticall1() $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()) - { + if (!$r[3]->faultCode()) { $val = $r[3]->value(); $this->assertTrue($val->kindOf() == 'array', "good2 did not return array"); } @@ -362,7 +338,7 @@ function testClientMulticall1() ); } - function testClientMulticall2() + public function testClientMulticall2() { // NB: This test will NOT pass if server does not support system.multicall. @@ -379,14 +355,12 @@ function testClientMulticall2() ); $r = $this->send(array($good1, $bad, $recursive, $good2)); - if($r) - { + 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()) - { + if (!$r[0]->faultCode()) { $val = $r[0]->value(); $this->assertTrue( $val->kindOf() == 'scalar' && $val->scalartyp() == 'string', @@ -395,14 +369,13 @@ function testClientMulticall2() $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()) - { + if (!$r[3]->faultCode()) { $val = $r[3]->value(); $this->assertTrue($val->kindOf() == 'array', "good2 did not return array"); } } - function testClientMulticall3() + public function testClientMulticall3() { // NB: This test will NOT pass if server does not support system.multicall. @@ -420,190 +393,169 @@ function testClientMulticall3() ); $r = $this->send(array($good1, $bad, $recursive, $good2)); - if($r) - { + 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()) - { + if (!$r[0]->faultCode()) { $val = $r[0]->value(); $this->assertTrue( - is_string($val) , "good1 did not return string"); + 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()) - { + if (!$r[3]->faultCode()) { $val = $r[3]->value(); $this->assertTrue(is_array($val), "good2 did not return array"); } $this->client->return_type = 'xmlrpcvals'; } - function testCatchWarnings() + public function testCatchWarnings() { $f = new xmlrpcmsg('examples.generatePHPWarning', array( - new xmlrpcval('whatever', 'string') + new xmlrpcval('whatever', 'string'), )); $v = $this->send($f); - if($v) - { + if ($v) { $this->assertEquals($v->scalarval(), true); } } - function testCatchExceptions() + public function testCatchExceptions() { $f = new xmlrpcmsg('examples.raiseException', array( - new xmlrpcval('whatever', 'string') + new xmlrpcval('whatever', 'string'), )); $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); - $this->client->path = $this->args['URI'].'?EXCEPTION_HANDLING=1'; + $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1'; $v = $this->send($f, 1); - $this->client->path = $this->args['URI'].'?EXCEPTION_HANDLING=2'; + $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2'; $v = $this->send($f, $GLOBALS['xmlrpcerr']['invalid_return']); } - function testZeroParams() + public function testZeroParams() { $f = new xmlrpcmsg('system.listMethods'); $v = $this->send($f); } - function testCodeInjectionServerSide() + public function testCodeInjectionServerSide() { $f = new xmlrpcmsg('system.MethodHelp'); $f->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; $v = $this->send($f); //$v = $r->faultCode(); - if ($v) - { + if ($v) { $this->assertEquals(0, $v->structsize()); } } - function testAutoRegisteredFunction() + public function testAutoRegisteredFunction() { - $f=new xmlrpcmsg('examples.php.getStateName',array( - new xmlrpcval(23, 'int') + $f = new xmlrpcmsg('examples.php.getStateName', array( + new xmlrpcval(23, 'int'), )); - $v=$this->send($f); - if($v) - { + $v = $this->send($f); + if ($v) { $this->assertEquals('Michigan', $v->scalarval()); - } - else - { + } else { $this->fail('Note: server can only auto register functions if running with PHP 5.0.3 and up'); } } - function testAutoRegisteredClass() + public function testAutoRegisteredClass() { - $f=new xmlrpcmsg('examples.php2.getStateName',array( - new xmlrpcval(23, 'int') + $f = new xmlrpcmsg('examples.php2.getStateName', array( + new xmlrpcval(23, 'int'), )); - $v=$this->send($f); - if($v) - { + $v = $this->send($f); + if ($v) { $this->assertEquals('Michigan', $v->scalarval()); - $f=new xmlrpcmsg('examples.php3.getStateName',array( - new xmlrpcval(23, 'int') - )); - $v=$this->send($f); - if($v) - { + $f = new xmlrpcmsg('examples.php3.getStateName', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + if ($v) { $this->assertEquals('Michigan', $v->scalarval()); } - } - else - { + } else { $this->fail('Note: server can only auto register class methods if running with PHP 5.0.3 and up'); } } - function testAutoRegisteredMethod() + public function testAutoRegisteredMethod() { // 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' => 1)); - if($func == '') - { + $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 1)); + if ($func == '') { $this->fail('Registration of examples.getStateName failed'); - } - else - { - $v=$func(23); + } else { + $v = $func(23); // work around bug in current version of phpunit - if(is_object($v)) - { + if (is_object($v)) { $v = var_export($v, true); } $this->assertEquals('Michigan', $v); } } - function testGetCookies() + 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'), + '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); - $f=new xmlrpcmsg('examples.setcookies',array($cookiesval)); - $r=$this->send($f, 0, true); - if($r) - { + $f = new xmlrpcmsg('examples.setcookies', array($cookiesval)); + $r = $this->send($f, 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'))) + foreach ($rcookies as $c => $v) { + if (!in_array($c, array('c2', 'c3', 'c4', 'c5'))) { unset($rcookies[$c]); - foreach($cookies as $c => $v) - // format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT' + } + } + 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']); + 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); + $this->assertEquals($cookies, $rcookies); + } } } - function testSetCookies() + public function testSetCookies() { // let server set to us some cookies we tell it $cookies = array( 'c0' => null, 'c1' => 1, 'c2' => '2 3', - 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-' + 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-', ); - $f=new xmlrpcmsg('examples.getcookies',array()); - foreach ($cookies as $cookie => $val) - { + $f = new xmlrpcmsg('examples.getcookies', array()); + foreach ($cookies as $cookie => $val) { $this->client->setCookie($cookie, $val); - $cookies[$cookie] = (string) $cookies[$cookie]; + $cookies[$cookie] = (string)$cookies[$cookie]; } $r = $this->client->send($f, $this->timeout, $this->method); - $this->assertEquals($r->faultCode(), 0, 'Error '.$r->faultCode().' connecting to server: '.$r->faultString()); - if(!$r->faultCode()) - { + $this->assertEquals($r->faultCode(), 0, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + if (!$r->faultCode()) { $v = $r->value(); $v = php_xmlrpc_decode($v); // on IIS and Apache getallheaders returns something slightly different... @@ -611,17 +563,16 @@ function testSetCookies() } } - function testSendTwiceSameMsg() + public function testSendTwiceSameMsg() { - $f=new xmlrpcmsg('examples.stringecho', array( - new xmlrpcval('hello world', 'string') + $f = new xmlrpcmsg('examples.stringecho', array( + new xmlrpcval('hello world', 'string'), )); $v1 = $this->send($f); $v2 = $this->send($f); //$v = $r->faultCode(); - if ($v1 && $v2) - { + if ($v1 && $v2) { $this->assertEquals($v2, $v1); } } -} \ No newline at end of file +} diff --git a/tests/ParsingBugsTest.php b/tests/ParsingBugsTest.php index 93626c71..db03a478 100644 --- a/tests/ParsingBugsTest.php +++ b/tests/ParsingBugsTest.php @@ -1,22 +1,22 @@ assertEquals($u->scalarval(), $v->scalarval()); } - function testUnicodeInMemberName(){ - $str = "G".chr(252)."nter, El".chr(232)."ne"; + 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(); @@ -26,14 +26,14 @@ function testUnicodeInMemberName(){ $this->assertEquals($v->structmemexists($str), true); } - function testUnicodeInErrorString() + public function testUnicodeInErrorString() { $response = utf8_encode( ' - + @@ -44,7 +44,7 @@ function testUnicodeInErrorString()
faultString -'.chr(224).chr(252).chr(232).'àüè +' . chr(224) . chr(252) . chr(232) . 'àüè
@@ -53,13 +53,13 @@ function testUnicodeInErrorString() $m = new xmlrpcmsg('dummy'); $r = $m->parseResponse($response); $v = $r->faultString(); - $this->assertEquals(chr(224).chr(252).chr(232).chr(224).chr(252).chr(232), $v); + $this->assertEquals(chr(224) . chr(252) . chr(232) . chr(224) . chr(252) . chr(232), $v); } - function testValidNumbers() + public function testValidNumbers() { $m = new xmlrpcmsg('dummy'); - $fp= + $fp = ' @@ -91,13 +91,13 @@ function testValidNumbers() '; - $r=$m->parseResponse($fp); - $v=$r->value(); - $s=$v->structmem('integer1'); - $t=$v->structmem('float1'); - $u=$v->structmem('integer2'); - $w=$v->structmem('float2'); - $x=$v->structmem('float3'); + $r = $m->parseResponse($fp); + $v = $r->value(); + $s = $v->structmem('integer1'); + $t = $v->structmem('float1'); + $u = $v->structmem('integer2'); + $w = $v->structmem('float2'); + $x = $v->structmem('float3'); $this->assertEquals(1, $s->scalarval()); $this->assertEquals(1.1, $t->scalarval()); $this->assertEquals(1, $u->scalarval()); @@ -105,15 +105,15 @@ function testValidNumbers() $this->assertEquals(-110.0, $x->scalarval()); } - function testAddScalarToStruct() + public function testAddScalarToStruct() { $v = new xmlrpcval(array('a' => 'b'), 'struct'); // use @ operator in case error_log gets on screen - $r = @$v->addscalar('c'); + $r = @$v->addscalar('c'); $this->assertEquals(0, $r); } - function testAddStructToStruct() + public function testAddStructToStruct() { $v = new xmlrpcval(array('a' => new xmlrpcval('b')), 'struct'); $r = $v->addstruct(array('b' => new xmlrpcval('c'))); @@ -123,7 +123,7 @@ function testAddStructToStruct() $this->assertEquals(2, $v->structsize()); } - function testAddArrayToArray() + public function testAddArrayToArray() { $v = new xmlrpcval(array(new xmlrpcval('a'), new xmlrpcval('b')), 'array'); $r = $v->addarray(array(new xmlrpcval('b'), new xmlrpcval('c'))); @@ -131,20 +131,20 @@ function testAddArrayToArray() $this->assertEquals(1, $r); } - function testEncodeArray() + public function testEncodeArray() { $r = range(1, 100); $v = php_xmlrpc_encode($r); $this->assertEquals('array', $v->kindof()); } - function testEncodeRecursive() + public function testEncodeRecursive() { $v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string')); $this->assertEquals('scalar', $v->kindof()); } - function testBrokenRequests() + public function testBrokenRequests() { $s = new xmlrpc_server(); // omitting the 'params' tag: not tolerated by the lib anymore @@ -179,7 +179,7 @@ function testBrokenRequests() $this->assertEquals(15, $r->faultCode()); } - function testBrokenResponses() + public function testBrokenResponses() { $m = new xmlrpcmsg('dummy'); //$m->debug = 1; @@ -212,7 +212,7 @@ function testBrokenResponses() $this->assertEquals(2, $r->faultCode()); } - function testBuggyHttp() + public function testBuggyHttp() { $s = new xmlrpcmsg('dummy'); $f = 'HTTP/1.1 100 Welcome to the jungle @@ -239,7 +239,7 @@ function testBuggyHttp() $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval()); } - function testStringBug() + public function testStringBug() { $s = new xmlrpcmsg('dummy'); $f = ' @@ -275,7 +275,7 @@ function testStringBug() $this->assertEquals('S300510007I', $s->scalarval()); } - function testWhiteSpace() + public function testWhiteSpace() { $s = new xmlrpcmsg('dummy'); $f = 'userid311127 @@ -290,7 +290,7 @@ function testWhiteSpace() $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval()); } - function testDoubleDataInArrayTag() + public function testDoubleDataInArrayTag() { $s = new xmlrpcmsg('dummy'); $f = ' @@ -311,7 +311,7 @@ function testDoubleDataInArrayTag() $this->assertEquals(2, $v); } - function testDoubleStuffInValueTag() + public function testDoubleStuffInValueTag() { $s = new xmlrpcmsg('dummy'); $f = ' @@ -340,7 +340,7 @@ function testDoubleStuffInValueTag() $this->assertEquals(2, $v); } - function testAutodecodeResponse() + public function testAutodecodeResponse() { $s = new xmlrpcmsg('dummy'); $f = 'userid311127 @@ -355,7 +355,7 @@ function testAutodecodeResponse() $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s); } - function testNoDecodeResponse() + public function testNoDecodeResponse() { $s = new xmlrpcmsg('dummy'); $f = 'userid311127 @@ -368,7 +368,7 @@ function testNoDecodeResponse() $this->assertEquals($f, $v); } - function testAutoCoDec() + 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); @@ -387,9 +387,9 @@ function testAutoCoDec() $this->assertEquals($m1, $m2); } - function testUTF8Request() + public function testUTF8Request() { - $sendstring='κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! + $sendstring = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; \PhpXmlRpc\PhpXmlRpc::importGlobals(); $f = new xmlrpcval($sendstring, 'string'); @@ -399,18 +399,18 @@ function testUTF8Request() \PhpXmlRpc\PhpXmlRpc::importGlobals(); } - function testUTF8Response() + public function testUTF8Response() { $s = new xmlrpcmsg('dummy'); - $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n".'userid311127 -dateCreated20011126T09:17:52content'.utf8_encode('').'postid7414222 + $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . 'userid311127 +dateCreated20011126T09:17:52content' . utf8_encode('') . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; $this->assertEquals("", $v); $f = 'userid311127 -dateCreated20011126T09:17:52content'.utf8_encode('').'postid7414222 +dateCreated20011126T09:17:52content' . utf8_encode('') . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); @@ -418,21 +418,21 @@ function testUTF8Response() $this->assertEquals("", $v); } - function testUTF8IntString() + public function testUTF8IntString() { $v = new xmlrpcval(100, 'int'); $s = $v->serialize('UTF-8'); $this->assertequals("100\n", $s); } - function testStringInt() + public function testStringInt() { $v = new xmlrpcval('hello world', 'int'); $s = $v->serialize(); $this->assertequals("0\n", $s); } - function testStructMemExists() + public function testStructMemExists() { $v = php_xmlrpc_encode(array('hello' => 'world')); $b = $v->structmemexists('hello'); @@ -441,7 +441,7 @@ function testStructMemExists() $this->assertequals(false, $b); } - function testNilvalue() + public function testNilvalue() { // default case: we do not accept nil values received $v = new xmlrpcval('hello', 'null'); @@ -462,7 +462,7 @@ function testNilvalue() // serialization $v = new xmlrpcval('hello', 'null'); $s = $v->serialize(); - $this->assertequals(1, preg_match( '##', $s )); + $this->assertequals(1, preg_match('##', $s)); // deserialization $r = new xmlrpcresp($v); $s = $r->serialize(); @@ -475,27 +475,21 @@ function testNilvalue() $this->assertequals(2, $r->faultCode()); } - function TestLocale() + 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) - { + if (setlocale(LC_NUMERIC, 'deu', 'de_DE@euro', 'de_DE', 'de', 'ge') !== false) { $v = new xmlrpcval(1.1, 'double'); - if (strpos($v->scalarval(), ',') == 1) - { + if (strpos($v->scalarval(), ',') == 1) { $r = $v->serialize(); $this->assertequals(false, strpos($r, ',')); setlocale(LC_NUMERIC, $locale); - } - else - { + } else { setlocale(LC_NUMERIC, $locale); $this->markTestSkipped('did not find a locale which sets decimal separator to comma'); } - } - else - { + } else { $this->markTestSkipped('did not find a locale which sets decimal separator to comma'); } } diff --git a/tests/benchmark.php b/tests/benchmark.php index 59a9cb8c..62d6ef6f 100644 --- a/tests/benchmark.php +++ b/tests/benchmark.php @@ -1,6 +1,7 @@ \n\n\n$title\n\n\n

$title

\n
\n";
-}
-else
-{
+} else {
     echo "$title\n\n";
 }
 
-if($is_web)
-{
-    echo "

Using lib version: ".PhpXmlRpc::$xmlrpcVersion." on PHP version: ".phpversion()."

\n"; - if ($xd) echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."

\n"; +if ($is_web) { + echo "

Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "

\n"; + if ($xd) { + echo "

XDEBUG profiling enabled: skipping remote tests. Trace file is: " . htmlspecialchars(xdebug_get_profiler_filename()) . "

\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"; +} 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 'old style' data encoding vs. 'automatic style' encoding begin_test('Data encoding (large array)', 'manual encoding'); -for ($i = 0; $i < $num_tests; $i++) -{ +for ($i = 0; $i < $num_tests; $i++) { $vals = array(); - for ($j = 0; $j < 10; $j++) - { + for ($j = 0; $j < 10; $j++) { $valarray = array(); - foreach ($data[$j] as $key => $val) - { + foreach ($data[$j] as $key => $val) { $values = array(); $values[] = new Value($val[0], 'int'); $values[] = new Value($val[1], 'double'); @@ -116,24 +115,21 @@ function end_test($test_name, $test_case, $test_result) begin_test('Data encoding (large array)', 'automatic encoding'); $encoder = new Encoder(); -for ($i = 0; $i < $num_tests; $i++) -{ +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')) -{ +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) - { + 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); @@ -142,23 +138,19 @@ function end_test($test_name, $test_case, $test_result) // test 'old style' data decoding vs. 'automatic style' decoding $dummy = new Request(''); $out = new Response($value); -$in = ''."\n".$out->serialize(); +$in = '' . "\n" . $out->serialize(); begin_test('Data decoding (large array)', 'manual decoding'); -for ($i = 0; $i < $num_tests; $i++) -{ +for ($i = 0; $i < $num_tests; $i++) { $response = $dummy->ParseResponse($in, true); $value = $response->value(); $result = array(); - for ($k = 0; $k < $value->arraysize(); $k++) - { + for ($k = 0; $k < $value->arraysize(); $k++) { $val1 = $value->arraymem($k); $out = array(); - while (list($name, $val) = $val1->structeach()) - { + while (list($name, $val) = $val1->structeach()) { $out[$name] = array(); - for ($j = 0; $j < $val->arraysize(); $j++) - { + for ($j = 0; $j < $val->arraysize(); $j++) { $data = $val->arraymem($j); $out[$name][] = $data->scalarval(); } @@ -169,42 +161,36 @@ function end_test($test_name, $test_case, $test_result) end_test('Data decoding (large array)', 'manual decoding', $result); begin_test('Data decoding (large array)', 'automatic decoding'); -for ($i = 0; $i < $num_tests; $i++) -{ +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')) -{ +if (function_exists('xmlrpc_decode')) { begin_test('Data decoding (large array)', 'xmlrpc-epi decoding'); - for ($i = 0; $i < $num_tests; $i++) - { + 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) -{ +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++) + for ($i = 0; $i < 25; $i++) { $reqs[] = $req; + } $server = explode(':', $args['LOCALSERVER']); - if(count($server) > 1) - { + if (count($server) > 1) { $srv = $server[1] . '://' . $server[0] . $args['URI']; $c = new Client($args['URI'], $server[0], $server[1]); - } - else - { + } else { $srv = $args['LOCALSERVER'] . $args['URI']; $c = new Client($args['URI'], $args['LOCALSERVER']); } @@ -219,19 +205,16 @@ function end_test($test_name, $test_case, $test_result) } begin_test($testName, 'http 10'); $response = array(); - for ($i = 0; $i < 25; $i++) - { + for ($i = 0; $i < 25; $i++) { $resp = $c->send($req); $response[] = $resp->value(); } end_test($testName, 'http 10', $response); - if (function_exists('curl_init')) - { + if (function_exists('curl_init')) { begin_test($testName, 'http 11 w. keep-alive'); $response = array(); - for ($i = 0; $i < 25; $i++) - { + for ($i = 0; $i < 25; $i++) { $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } @@ -240,8 +223,7 @@ function end_test($test_name, $test_case, $test_result) $c->keepalive = false; begin_test($testName, 'http 11'); $response = array(); - for ($i = 0; $i < 25; $i++) - { + for ($i = 0; $i < 25; $i++) { $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } @@ -250,32 +232,27 @@ function end_test($test_name, $test_case, $test_result) begin_test($testName, 'multicall'); $response = $c->send($reqs); - foreach ($response as $key =>& $val) - { + foreach ($response as $key => & $val) { $val = $val->value(); } end_test($testName, 'multicall', $response); - if (function_exists('gzinflate')) - { + 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++) - { + 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')) - { + if (function_exists('curl_init')) { begin_test($testName, 'http 11 w. keep-alive and compression'); $response = array(); - for ($i = 0; $i < 25; $i++) - { + for ($i = 0; $i < 25; $i++) { $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } @@ -284,8 +261,7 @@ function end_test($test_name, $test_case, $test_result) $c->keepalive = false; begin_test($testName, 'http 11 w. compression'); $response = array(); - for ($i = 0; $i < 25; $i++) - { + for ($i = 0; $i < 25; $i++) { $resp = $c->send($req, 10, 'http11'); $response[] = $resp->value(); } @@ -294,26 +270,22 @@ function end_test($test_name, $test_case, $test_result) begin_test($testName, 'multicall w. compression'); $response = $c->send($reqs); - foreach ($response as $key =>& $val) - { + 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) -{ +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"; + foreach ($results as $case => $data) { + echo " $case: {$data['time']} secs - Output data CRC: " . crc32(serialize($data['result'])) . "\n"; + } } - -if($is_web) -{ +if ($is_web) { echo "\n
\n\n\n"; } diff --git a/tests/parse_args.php b/tests/parse_args.php index 18b6bc37..4397e640 100644 --- a/tests/parse_args.php +++ b/tests/parse_args.php @@ -1,6 +1,7 @@ false, 'PROXYSERVER' => null, 'NOPROXY' => false, - 'LOCALPATH' => __DIR__ + 'LOCALPATH' => __DIR__, ); // check for command line vs web page input params - if(!isset($_SERVER['REQUEST_METHOD'])) - { - if(isset($argv)) - { - foreach($argv as $param) - { + if (!isset($_SERVER['REQUEST_METHOD'])) { + if (isset($argv)) { + foreach ($argv as $param) { $param = explode('=', $param); - if(count($param) > 1) - { + if (count($param) > 1) { $pname = strtoupper(ltrim($param[0], '-')); - $$pname=$param[1]; + $$pname = $param[1]; } } } - } - else - { + } else { // NB: we might as well consider using $_GET stuff later on... extract($_GET); extract($_POST); } - if(isset($DEBUG)) - { + if (isset($DEBUG)) { $args['DEBUG'] = intval($DEBUG); } - if(isset($LOCALSERVER)) - { + if (isset($LOCALSERVER)) { $args['LOCALSERVER'] = $LOCALSERVER; - } - else - { - if(isset($HTTP_HOST)) - { + } else { + if (isset($HTTP_HOST)) { $args['LOCALSERVER'] = $HTTP_HOST; - } - elseif(isset($_SERVER['HTTP_HOST'])) - { + } elseif (isset($_SERVER['HTTP_HOST'])) { $args['LOCALSERVER'] = $_SERVER['HTTP_HOST']; } } - if(isset($HTTPSSERVER)) - { + if (isset($HTTPSSERVER)) { $args['HTTPSSERVER'] = $HTTPSSERVER; } - if(isset($HTTPSURI)) - { + if (isset($HTTPSURI)) { $args['HTTPSURI'] = $HTTPSURI; } - if(isset($HTTPSIGNOREPEER)) - { + if (isset($HTTPSIGNOREPEER)) { $args['HTTPSIGNOREPEER'] = bool($HTTPSIGNOREPEER); } - if(isset($PROXY)) - { + if (isset($PROXY)) { $arr = explode(':', $PROXY); $args['PROXYSERVER'] = $arr[0]; - if(count($arr) > 1) - { + if (count($arr) > 1) { $args['PROXYPORT'] = $arr[1]; - } - else - { + } else { $args['PROXYPORT'] = 8080; } } // used to silence testsuite warnings about proxy code not being tested - if(isset($NOPROXY)) - { + if (isset($NOPROXY)) { $args['NOPROXY'] = true; } - if(!isset($URI)) - { + 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)) - { + 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'])) - { + } 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 - { + } else { $URI = '/demo/server/server.php'; } } - if($URI[0] != '/') - { - $URI = '/'.$URI; + if ($URI[0] != '/') { + $URI = '/' . $URI; } $args['URI'] = $URI; - if(isset($LOCALPATH)) - { - $args['LOCALPATH'] =$LOCALPATH; + if (isset($LOCALPATH)) { + $args['LOCALPATH'] = $LOCALPATH; } return $args; } - -} \ No newline at end of file +} diff --git a/tests/verify_compat.php b/tests/verify_compat.php index c9c4ad24..85dee628 100644 --- a/tests/verify_compat.php +++ b/tests/verify_compat.php @@ -1,6 +1,6 @@ -PHP XMLRPC compatibility assessment - + PHP XMLRPC compatibility assessment +

PHPXMLRPC compatibility assessment with the current PHP install

For phpxmlrpc version 4.0 or later

+

Server usage

- - - - - $result) - { - echo '\n"; - } -?> - + + + + + + + + $result) { + echo '\n"; + } + ?> +
TestResult
'.htmlspecialchars($test).''.htmlspecialchars($result['description'])."
TestResult
' . htmlspecialchars($test) . '' . htmlspecialchars($result['description']) . "

Client usage

- - - - - $result) - { - echo '\n"; - } -?> - + + + + + + + + $result) { + echo '\n"; + } + ?> +
TestResult
'.htmlspecialchars($test).''.htmlspecialchars($result['description'])."
TestResult
' . htmlspecialchars($test) . '' . htmlspecialchars($result['description']) . "
- \ No newline at end of file + From 35d2340eea9a168983b8f20d54c399422790f816 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 19:24:57 +0000 Subject: [PATCH 042/228] Reformat source code: the library --- src/Client.php | 702 +++++++++++++------------------ src/Encoder.php | 218 ++++------ src/Helper/Charset.php | 100 +++-- src/Helper/Date.php | 49 +-- src/Helper/Http.php | 32 +- src/Helper/XMLParser.php | 284 ++++++------- src/PhpXmlRpc.php | 106 +++-- src/Request.php | 417 ++++++++----------- src/Response.php | 82 ++-- src/Server.php | 869 ++++++++++++++++----------------------- src/Value.php | 327 ++++++++------- src/Wrapper.php | 784 +++++++++++++++-------------------- 12 files changed, 1692 insertions(+), 2278 deletions(-) diff --git a/src/Client.php b/src/Client.php index c12d4070..a5c64770 100644 --- a/src/Client.php +++ b/src/Client.php @@ -7,34 +7,34 @@ class Client /// @todo: do these need to be public? public $path; public $server; - public $port=0; - public $method='http'; + public $port = 0; + public $method = 'http'; public $errno; public $errstr; - public $debug=0; - public $username=''; - public $password=''; - public $authtype=1; - public $cert=''; - public $certpass=''; - public $cacert=''; - public $cacertdir=''; - public $key=''; - public $keypass=''; - public $verifypeer=true; - public $verifyhost=2; - public $no_multicall=false; - public $proxy=''; - public $proxyport=0; - public $proxy_user=''; - public $proxy_pass=''; - public $proxy_authtype=1; - public $cookies=array(); - public $extracurlopts=array(); + public $debug = 0; + public $username = ''; + public $password = ''; + public $authtype = 1; + public $cert = ''; + public $certpass = ''; + public $cacert = ''; + public $cacertdir = ''; + public $key = ''; + public $keypass = ''; + public $verifypeer = true; + public $verifyhost = 2; + public $no_multicall = false; + public $proxy = ''; + public $proxyport = 0; + public $proxy_user = ''; + public $proxy_pass = ''; + public $proxy_authtype = 1; + public $cookies = array(); + public $extracurlopts = array(); /** * List of http compression methods accepted by the client for responses. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib. * * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since * in those cases it will be up to CURL to decide the compression methods @@ -44,12 +44,12 @@ class Client public $accepted_compression = array(); /** * Name of compression scheme to be used for sending requests. - * Either null, gzip or deflate + * Either null, gzip or deflate. */ public $request_compression = ''; /** * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see: - * http://curl.haxx.se/docs/faq.html#7.3) + * http://curl.haxx.se/docs/faq.html#7.3). */ public $xmlrpc_curl_handle = null; /// Whether to use persistent connections for http 1.1 and https @@ -60,11 +60,11 @@ class Client public $request_charset_encoding = ''; /** * Decides the content of Response objects returned by calls to send() - * valid strings are 'xmlrpcvals', 'phpvals' or 'xml' + * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'. */ public $return_type = 'xmlrpcvals'; /** - * Sent to servers in http headers + * Sent to servers in http headers. */ public $user_agent; @@ -74,63 +74,51 @@ class Client * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed */ - function __construct($path, $server='', $port='', $method='') + public function __construct($path, $server = '', $port = '', $method = '') { // allow user to specify all params in $path - if($server == '' and $port == '' and $method == '') - { + if ($server == '' and $port == '' and $method == '') { $parts = parse_url($path); $server = $parts['host']; $path = isset($parts['path']) ? $parts['path'] : ''; - if(isset($parts['query'])) - { - $path .= '?'.$parts['query']; + if (isset($parts['query'])) { + $path .= '?' . $parts['query']; } - if(isset($parts['fragment'])) - { - $path .= '#'.$parts['fragment']; + if (isset($parts['fragment'])) { + $path .= '#' . $parts['fragment']; } - if(isset($parts['port'])) - { + if (isset($parts['port'])) { $port = $parts['port']; } - if(isset($parts['scheme'])) - { + if (isset($parts['scheme'])) { $method = $parts['scheme']; } - if(isset($parts['user'])) - { + if (isset($parts['user'])) { $this->username = $parts['user']; } - if(isset($parts['pass'])) - { + if (isset($parts['pass'])) { $this->password = $parts['pass']; } } - if($path == '' || $path[0] != '/') - { - $this->path='/'.$path; + if ($path == '' || $path[0] != '/') { + $this->path = '/' . $path; + } else { + $this->path = $path; } - else - { - $this->path=$path; + $this->server = $server; + if ($port != '') { + $this->port = $port; } - $this->server=$server; - if($port != '') - { - $this->port=$port; - } - if($method != '') - { - $this->method=$method; + if ($method != '') { + $this->method = $method; } // if ZLIB is enabled, let the client by default accept compressed responses - if(function_exists('gzinflate') || ( - function_exists('curl_init') && (($info = curl_version()) && - ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) - )) - { + if (function_exists('gzinflate') || ( + function_exists('curl_init') && (($info = curl_version()) && + ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) + ) + ) { $this->accepted_compression = array('gzip', 'deflate'); } @@ -145,29 +133,32 @@ function_exists('curl_init') && (($info = curl_version()) && } /** - * Enables/disables the echoing to screen of the xmlrpc responses received + * Enables/disables the echoing to screen of the xmlrpc responses received. + * * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response) */ public function setDebug($in) { - $this->debug=$in; + $this->debug = $in; } /** - * Add some http BASIC AUTH credentials, used by the client to authenticate + * Add some http BASIC AUTH credentials, used by the client to authenticate. + * * @param string $u username * @param string $p password * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth) */ - public function setCredentials($u, $p, $t=1) + public function setCredentials($u, $p, $t = 1) { - $this->username=$u; - $this->password=$p; - $this->authtype=$t; + $this->username = $u; + $this->password = $p; + $this->authtype = $t; } /** - * Add a client-side https certificate + * Add a client-side https certificate. + * * @param string $cert * @param string $certpass */ @@ -179,18 +170,16 @@ public function setCertificate($cert, $certpass) /** * Add a CA certificate to verify server with (see man page about - * CURLOPT_CAINFO for more details) + * CURLOPT_CAINFO for more details). + * * @param string $cacert certificate file name (or dir holding certificates) * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false */ - public function setCaCertificate($cacert, $is_dir=false) + public function setCaCertificate($cacert, $is_dir = false) { - if ($is_dir) - { + if ($is_dir) { $this->cacertdir = $cacert; - } - else - { + } else { $this->cacert = $cacert; } } @@ -198,7 +187,8 @@ public function setCaCertificate($cacert, $is_dir=false) /** * Set attributes for SSL communication: private SSL key * NB: does not work in older php/curl installs - * Thanks to Daniel Convissor + * Thanks to Daniel Convissor. + * * @param string $key The name of a file containing a private SSL key * @param string $keypass The secret password needed to use the private SSL key */ @@ -209,7 +199,8 @@ public function setKey($key, $keypass) } /** - * Set attributes for SSL communication: verify server certificate + * Set attributes for SSL communication: verify server certificate. + * * @param bool $i enable/disable verification of peer certificate */ public function setSSLVerifyPeer($i) @@ -218,7 +209,8 @@ public function setSSLVerifyPeer($i) } /** - * Set attributes for SSL communication: verify match of server cert w. hostname + * Set attributes for SSL communication: verify match of server cert w. hostname. + * * @param int $i */ public function setSSLVerifyHost($i) @@ -227,7 +219,8 @@ public function setSSLVerifyHost($i) } /** - * Set proxy info + * Set proxy info. + * * @param string $proxyhost * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS * @param string $proxyusername Leave blank if proxy has public access @@ -248,23 +241,25 @@ public function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypass * Note that enabling reception of compressed responses merely adds some standard * http headers to xmlrpc requests. It is up to the xmlrpc server to return * compressed responses when receiving such requests. + * * @param string $compmethod either 'gzip', 'deflate', 'any' or '' */ public function setAcceptedCompression($compmethod) { - if ($compmethod == 'any') + if ($compmethod == 'any') { $this->accepted_compression = array('gzip', 'deflate'); - else - if ($compmethod == false ) - $this->accepted_compression = array(); - else - $this->accepted_compression = array($compmethod); + } elseif ($compmethod == false) { + $this->accepted_compression = array(); + } else { + $this->accepted_compression = array($compmethod); + } } /** * Enables/disables http compression of xmlrpc request. * Take care when sending compressed requests: servers might not support them - * (and automatic fallback to uncompressed requests is not yet implemented) + * (and automatic fallback to uncompressed requests is not yet implemented). + * * @param string $compmethod either 'gzip', 'deflate' or '' */ public function setRequestCompression($compmethod) @@ -275,7 +270,8 @@ public function setRequestCompression($compmethod) /** * Adds a cookie to list of cookies that will be sent to server. * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie: - * do not do it unless you know what you are doing + * do not do it unless you know what you are doing. + * * @param string $name * @param string $value * @param string $path @@ -284,75 +280,71 @@ public function setRequestCompression($compmethod) * * @todo check correctness of urlencoding cookie value (copied from php way of doing it...) */ - public function setCookie($name, $value='', $path='', $domain='', $port=null) + public function setCookie($name, $value = '', $path = '', $domain = '', $port = null) { $this->cookies[$name]['value'] = urlencode($value); - if ($path || $domain || $port) - { + if ($path || $domain || $port) { $this->cookies[$name]['path'] = $path; $this->cookies[$name]['domain'] = $domain; $this->cookies[$name]['port'] = $port; $this->cookies[$name]['version'] = 1; - } - else - { + } else { $this->cookies[$name]['version'] = 0; } } /** * Directly set cURL options, for extra flexibility - * It allows eg. to bind client to a specific IP interface / address + * It allows eg. to bind client to a specific IP interface / address. + * * @param array $options */ - function SetCurlOptions( $options ) + public function SetCurlOptions($options) { $this->extracurlopts = $options; } /** * Set user-agent string that will be used by this client instance - * in http headers sent to the server + * in http headers sent to the server. */ - function SetUserAgent( $agentstring ) + public function SetUserAgent($agentstring) { $this->user_agent = $agentstring; } /** - * Send an xmlrpc request + * Send an xmlrpc request. + * * @param mixed $msg The request object, or an array of requests for using multicall, or the complete xml representation of a request * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used + * * @return Response */ - public function& send($msg, $timeout=0, $method='') + public function & send($msg, $timeout = 0, $method = '') { // if user deos not specify http protocol, use native method of this client // (i.e. method set during call to constructor) - if($method == '') - { + if ($method == '') { $method = $this->method; } - if(is_array($msg)) - { + if (is_array($msg)) { // $msg is an array of Requests $r = $this->multicall($msg, $timeout, $method); + return $r; - } - elseif(is_string($msg)) - { + } elseif (is_string($msg)) { $n = new Message(''); $n->payload = $msg; $msg = $n; } // where msg is a Request - $msg->debug=$this->debug; + $msg->debug = $this->debug; - if($method == 'https') - { + if ($method == 'https') { $r = $this->sendPayloadHTTPS( $msg, $this->server, @@ -374,9 +366,7 @@ public function& send($msg, $timeout=0, $method='') $this->key, $this->keypass ); - } - elseif($method == 'http11') - { + } elseif ($method == 'http11') { $r = $this->sendPayloadCURL( $msg, $this->server, @@ -397,9 +387,7 @@ public function& send($msg, $timeout=0, $method='') 'http', $this->keepalive ); - } - else - { + } else { $r = $this->sendPayloadHTTP10( $msg, $this->server, @@ -419,87 +407,68 @@ public function& send($msg, $timeout=0, $method='') return $r; } - private function sendPayloadHTTP10($msg, $server, $port, $timeout=0, - $username='', $password='', $authtype=1, $proxyhost='', - $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1) + private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, + $username = '', $password = '', $authtype = 1, $proxyhost = '', + $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) { - if($port==0) - { - $port=80; + if ($port == 0) { + $port = 80; } // Only create the payload if it was not created previously - if(empty($msg->payload)) - { + if (empty($msg->payload)) { $msg->createPayload($this->request_charset_encoding); } $payload = $msg->payload; // Deflate request body and set appropriate request headers - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { + if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { + if ($this->request_compression == 'gzip') { $a = @gzencode($payload); - if($a) - { + if ($a) { $payload = $a; $encoding_hdr = "Content-Encoding: gzip\r\n"; } - } - else - { + } else { $a = @gzcompress($payload); - if($a) - { + if ($a) { $payload = $a; $encoding_hdr = "Content-Encoding: deflate\r\n"; } } - } - else - { + } else { $encoding_hdr = ''; } // thanks to Grant Rauscher for this - $credentials=''; - if($username!='') - { - $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; - if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0'); + $credentials = ''; + if ($username != '') { + $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; + if ($authtype != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0'); } } $accepted_encoding = ''; - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { + if (is_array($this->accepted_compression) && count($this->accepted_compression)) { $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; } $proxy_credentials = ''; - if($proxyhost) - { - if($proxyport == 0) - { + if ($proxyhost) { + if ($proxyport == 0) { $proxyport = 8080; } $connectserver = $proxyhost; $connectport = $proxyport; - $uri = 'http://'.$server.':'.$port.$this->path; - if($proxyusername != '') - { - if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0'); + $uri = 'http://' . $server . ':' . $port . $this->path; + if ($proxyusername != '') { + if ($proxyauthtype != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0'); } - $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n"; + $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername . ':' . $proxypassword) . "\r\n"; } - } - else - { + } else { $connectserver = $server; $connectport = $port; $uri = $this->path; @@ -507,25 +476,23 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout=0, // Cookie generation, as per rfc2965 (version 1 cookies) or // netscape's rules (version 0 cookies) - $cookieheader=''; - if (count($this->cookies)) - { + $cookieheader = ''; + if (count($this->cookies)) { $version = ''; - foreach ($this->cookies as $name => $cookie) - { - if ($cookie['version']) - { + foreach ($this->cookies as $name => $cookie) { + if ($cookie['version']) { $version = ' $Version="' . $cookie['version'] . '";'; $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; - if ($cookie['path']) + if ($cookie['path']) { $cookieheader .= ' $Path="' . $cookie['path'] . '";'; - if ($cookie['domain']) + } + if ($cookie['domain']) { $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; - if ($cookie['port']) + } + if ($cookie['port']) { $cookieheader .= ' $Port="' . $cookie['port'] . '";'; - } - else - { + } + } else { $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; } } @@ -535,9 +502,9 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout=0, // omit port if 80 $port = ($port == 80) ? '' : (':' . $port); - $op= 'POST ' . $uri. " HTTP/1.0\r\n" . + $op = 'POST ' . $uri . " HTTP/1.0\r\n" . 'User-Agent: ' . $this->user_agent . "\r\n" . - 'Host: '. $server . $port . "\r\n" . + 'Host: ' . $server . $port . "\r\n" . $credentials . $proxy_credentials . $accepted_encoding . @@ -548,70 +515,61 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout=0, strlen($payload) . "\r\n\r\n" . $payload; - if($this->debug > 1) - { + if ($this->debug > 1) { print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; // let the client see this now in case http times out... flush(); } - if($timeout>0) - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); - } - else - { - $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr); + if ($timeout > 0) { + $fp = @fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); + } else { + $fp = @fsockopen($connectserver, $connectport, $this->errno, $this->errstr); } - if($fp) - { - if($timeout>0 && function_exists('stream_set_timeout')) - { + if ($fp) { + if ($timeout > 0 && function_exists('stream_set_timeout')) { stream_set_timeout($fp, $timeout); } - } - else - { - $this->errstr='Connect error: '.$this->errstr; - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + } else { + $this->errstr = 'Connect error: ' . $this->errstr; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr . ' (' . $this->errno . ')'); + return $r; } - if(!fputs($fp, $op, strlen($op))) - { + if (!fputs($fp, $op, strlen($op))) { fclose($fp); - $this->errstr='Write error'; - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr); + $this->errstr = 'Write error'; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], $this->errstr); + return $r; - } - else - { + } else { // reset errno and errstr on successful socket connection $this->errstr = ''; } // G. Giunta 2005/10/24: close socket before parsing. // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects) - $ipd=''; - do - { + $ipd = ''; + do { // shall we check for $data === FALSE? // as per the manual, it signals an error - $ipd.=fread($fp, 32768); - } while(!feof($fp)); + $ipd .= fread($fp, 32768); + } while (!feof($fp)); fclose($fp); $r = $msg->parseResponse($ipd, false, $this->return_type); - return $r; + return $r; } - private function sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, - $keepalive=false, $key='', $keypass='') + private function sendPayloadHTTPS($msg, $server, $port, $timeout = 0, $username = '', + $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', + $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, + $keepalive = false, $key = '', $keypass = '') { $r = $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); + return $r; } @@ -620,99 +578,80 @@ private function sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='' * Requires curl to be built into PHP * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! */ - private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', - $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='', - $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https', - $keepalive=false, $key='', $keypass='') + private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '', + $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', + $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, $method = 'https', + $keepalive = false, $key = '', $keypass = '') { - if(!function_exists('curl_init')) - { - $this->errstr='CURL unavailable on this install'; - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); + if (!function_exists('curl_init')) { + $this->errstr = 'CURL unavailable on this install'; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); + return $r; } - if($method == 'https') - { - if(($info = curl_version()) && - ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version'])))) - { - $this->errstr='SSL unavailable on this install'; - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); + if ($method == 'https') { + if (($info = curl_version()) && + ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))) + ) { + $this->errstr = 'SSL unavailable on this install'; + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); + return $r; } } - if($port == 0) - { - if($method == 'http') - { + if ($port == 0) { + if ($method == 'http') { $port = 80; - } - else - { + } else { $port = 443; } } // Only create the payload if it was not created previously - if(empty($msg->payload)) - { + if (empty($msg->payload)) { $msg->createPayload($this->request_charset_encoding); } // Deflate request body and set appropriate request headers $payload = $msg->payload; - if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) - { - if($this->request_compression == 'gzip') - { + if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { + if ($this->request_compression == 'gzip') { $a = @gzencode($payload); - if($a) - { + if ($a) { $payload = $a; $encoding_hdr = 'Content-Encoding: gzip'; } - } - else - { + } else { $a = @gzcompress($payload); - if($a) - { + if ($a) { $payload = $a; $encoding_hdr = 'Content-Encoding: deflate'; } } - } - else - { + } else { $encoding_hdr = ''; } - if($this->debug > 1) - { + if ($this->debug > 1) { print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; // let the client see this now in case http times out... flush(); } - if(!$keepalive || !$this->xmlrpc_curl_handle) - { + if (!$keepalive || !$this->xmlrpc_curl_handle) { $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); - if($keepalive) - { + if ($keepalive) { $this->xmlrpc_curl_handle = $curl; } - } - else - { + } else { $curl = $this->xmlrpc_curl_handle; } // results into variable curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - if($this->debug) - { + if ($this->debug) { curl_setopt($curl, CURLOPT_VERBOSE, 1); } curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); @@ -727,81 +666,65 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', // NB: if we set an empty string, CURL will add http header indicating // ALL methods it is supporting. This is possibly a better option than // letting the user tell what curl can / cannot do... - if(is_array($this->accepted_compression) && count($this->accepted_compression)) - { + if (is_array($this->accepted_compression) && count($this->accepted_compression)) { //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression)); // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if (count($this->accepted_compression) == 1) - { + if (count($this->accepted_compression) == 1) { curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]); - } - else + } else { curl_setopt($curl, CURLOPT_ENCODING, ''); + } } // extra headers - $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + $headers = array('Content-Type: ' . $msg->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); // if no keepalive is wanted, let the server know it in advance - if(!$keepalive) - { + if (!$keepalive) { $headers[] = 'Connection: close'; } // request compression header - if($encoding_hdr) - { + if ($encoding_hdr) { $headers[] = $encoding_hdr; } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // timeout is borked - if($timeout) - { + if ($timeout) { curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1); } - if($username && $password) - { - curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password); - if (defined('CURLOPT_HTTPAUTH')) - { + if ($username && $password) { + curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password); + if (defined('CURLOPT_HTTPAUTH')) { curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); - } - else if ($authtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install'); + } elseif ($authtype != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install'); } } - if($method == 'https') - { + if ($method == 'https') { // set cert file - if($cert) - { + if ($cert) { curl_setopt($curl, CURLOPT_SSLCERT, $cert); } // set cert password - if($certpass) - { + if ($certpass) { curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); } // whether to verify remote host's cert curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); // set ca certificates file/dir - if($cacert) - { + if ($cacert) { curl_setopt($curl, CURLOPT_CAINFO, $cacert); } - if($cacertdir) - { + if ($cacertdir) { curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); } // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($key) - { + if ($key) { curl_setopt($curl, CURLOPT_SSLKEY, $key); } // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if($keypass) - { + if ($keypass) { curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); } // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used @@ -809,24 +732,18 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', } // proxy info - if($proxyhost) - { - if($proxyport == 0) - { + if ($proxyhost) { + if ($proxyport == 0) { $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 } - curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport); + curl_setopt($curl, CURLOPT_PROXY, $proxyhost . ':' . $proxyport); //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); - if($proxyusername) - { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword); - if (defined('CURLOPT_PROXYAUTH')) - { + if ($proxyusername) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername . ':' . $proxypassword); + if (defined('CURLOPT_PROXYAUTH')) { curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); - } - else if ($proxyauthtype != 1) - { - error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); + } elseif ($proxyauthtype != 1) { + error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); } } } @@ -834,30 +751,24 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', // NB: should we build cookie http headers by hand rather than let CURL do it? // the following code does not honour 'expires', 'path' and 'domain' cookie attributes // set to client obj the the user... - if (count($this->cookies)) - { + if (count($this->cookies)) { $cookieheader = ''; - foreach ($this->cookies as $name => $cookie) - { + foreach ($this->cookies as $name => $cookie) { $cookieheader .= $name . '=' . $cookie['value'] . '; '; } curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); } - foreach ($this->extracurlopts as $opt => $val) - { + foreach ($this->extracurlopts as $opt => $val) { curl_setopt($curl, $opt, $val); } $result = curl_exec($curl); - if ($this->debug > 1) - { + if ($this->debug > 1) { print "
\n---CURL INFO---\n";
-            foreach(curl_getinfo($curl) as $name => $val)
-            {
-                if (is_array($val))
-                {
+            foreach (curl_getinfo($curl) as $name => $val) {
+                if (is_array($val)) {
                     $val = implode("\n", $val);
                 }
                 print $name . ': ' . htmlentities($val) . "\n";
@@ -866,30 +777,27 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
             print "---END---\n
"; } - if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'? - { - $this->errstr='no response'; - $resp=new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail']. ': '. curl_error($curl)); + if (!$result) { + /// @todo we should use a better check here - what if we get back '' or '0'? + + $this->errstr = 'no response'; + $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl)); curl_close($curl); - if($keepalive) - { + if ($keepalive) { $this->xmlrpc_curl_handle = null; } - } - else - { - if(!$keepalive) - { + } else { + if (!$keepalive) { curl_close($curl); } $resp = $msg->parseResponse($result, true, $this->return_type); // if we got back a 302, we can not reuse the curl handle for later calls - if($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepalive) - { + if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepalive) { curl_close($curl); $this->xmlrpc_curl_handle = null; } } + return $resp; } @@ -912,90 +820,72 @@ private function sendPayloadCURL($msg, $server, $port, $timeout=0, $username='', * @param integer $timeout connection timeout (in seconds) * @param string $method the http protocol variant to be used * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted + * * @return array */ - public function multicall($msgs, $timeout=0, $method='', $fallback=true) + public function multicall($msgs, $timeout = 0, $method = '', $fallback = true) { - if ($method == '') - { + if ($method == '') { $method = $this->method; } - if(!$this->no_multicall) - { + if (!$this->no_multicall) { $results = $this->_try_multicall($msgs, $timeout, $method); - if(is_array($results)) - { + if (is_array($results)) { // System.multicall succeeded return $results; - } - else - { + } else { // either system.multicall is unsupported by server, // or call failed for some other reason. - if ($fallback) - { + if ($fallback) { // Don't try it next time... $this->no_multicall = true; - } - else - { - if (is_a($results, '\PhpXmlRpc\Response')) - { + } else { + if (is_a($results, '\PhpXmlRpc\Response')) { $result = $results; - } - else - { + } else { $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$xmlrpcstr['multicall_error']); } } } - } - else - { + } else { // override fallback, in case careless user tries to do two // opposite things at the same time $fallback = true; } $results = array(); - if ($fallback) - { + if ($fallback) { // system.multicall is (probably) unsupported by server: // emulate multicall via multiple requests - foreach($msgs as $msg) - { + foreach ($msgs as $msg) { $results[] = $this->send($msg, $timeout, $method); } - } - else - { + } else { // user does NOT want to fallback on many single calls: // since we should always return an array of responses, // return an array with the same error repeated n times - foreach($msgs as $msg) - { + foreach ($msgs as $msg) { $results[] = $result; } } + return $results; } /** * Attempt to boxcar $msgs via system.multicall. * Returns either an array of xmlrpcreponses, an xmlrpc error response - * or false (when received response does not respect valid multicall syntax) + * or false (when received response does not respect valid multicall syntax). */ private function _try_multicall($msgs, $timeout, $method) { // Construct multicall request $calls = array(); - foreach($msgs as $msg) - { - $call['methodName'] = new Value($msg->method(),'string'); + foreach ($msgs as $msg) { + $call['methodName'] = new Value($msg->method(), 'string'); $numParams = $msg->getNumParams(); $params = array(); - for($i = 0; $i < $numParams; $i++) - { + for ($i = 0; $i < $numParams; $i++) { $params[$i] = $msg->getParam($i); } $call['params'] = new Value($params, 'array'); @@ -1007,8 +897,7 @@ private function _try_multicall($msgs, $timeout, $method) // Attempt RPC call $result = $this->send($multicall, $timeout, $method); - if($result->faultCode() != 0) - { + if ($result->faultCode() != 0) { // call to system.multicall failed return $result; } @@ -1016,36 +905,28 @@ private function _try_multicall($msgs, $timeout, $method) // Unpack responses. $rets = $result->value(); - if ($this->return_type == 'xml') - { - return $rets; - } - else if ($this->return_type == 'phpvals') - { + if ($this->return_type == 'xml') { + return $rets; + } elseif ($this->return_type == 'phpvals') { ///@todo test this code branch... $rets = $result->value(); - if(!is_array($rets)) - { + if (!is_array($rets)) { return false; // bad return type from system.multicall } $numRets = count($rets); - if($numRets != count($msgs)) - { + if ($numRets != count($msgs)) { return false; // wrong number of return values. } $response = array(); - for($i = 0; $i < $numRets; $i++) - { + for ($i = 0; $i < $numRets; $i++) { $val = $rets[$i]; if (!is_array($val)) { return false; } - switch(count($val)) - { + switch (count($val)) { case 1: - if(!isset($val[0])) - { + if (!isset($val[0])) { return false; // Bad value } // Normal return value @@ -1054,13 +935,11 @@ private function _try_multicall($msgs, $timeout, $method) case 2: /// @todo remove usage of @: it is apparently quite slow $code = @$val['faultCode']; - if(!is_int($code)) - { + if (!is_int($code)) { return false; } $str = @$val['faultString']; - if(!is_string($str)) - { + if (!is_string($str)) { return false; } $response[$i] = new Response(0, $code, $str); @@ -1069,30 +948,26 @@ private function _try_multicall($msgs, $timeout, $method) return false; } } + return $response; - } - else // return type == 'xmlrpcvals' - { + } else { + // return type == 'xmlrpcvals' + $rets = $result->value(); - if($rets->kindOf() != 'array') - { + if ($rets->kindOf() != 'array') { return false; // bad return type from system.multicall } $numRets = $rets->arraysize(); - if($numRets != count($msgs)) - { + if ($numRets != count($msgs)) { return false; // wrong number of return values. } $response = array(); - for($i = 0; $i < $numRets; $i++) - { + for ($i = 0; $i < $numRets; $i++) { $val = $rets->arraymem($i); - switch($val->kindOf()) - { + switch ($val->kindOf()) { case 'array': - if($val->arraysize() != 1) - { + if ($val->arraysize() != 1) { return false; // Bad value } // Normal return value @@ -1100,13 +975,11 @@ private function _try_multicall($msgs, $timeout, $method) break; case 'struct': $code = $val->structmem('faultCode'); - if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') - { + if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') { return false; } $str = $val->structmem('faultString'); - if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') - { + if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') { return false; } $response[$i] = new Response(0, $code->scalarval(), $str->scalarval()); @@ -1115,6 +988,7 @@ private function _try_multicall($msgs, $timeout, $method) return false; } } + return $response; } } diff --git a/src/Encoder.php b/src/Encoder.php index 371237ba..e192d6bb 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -25,61 +25,58 @@ class Encoder * * @param Value|Request $xmlrpc_val * @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 */ - function decode($xmlrpc_val, $options=array()) + public function decode($xmlrpc_val, $options = array()) { - switch($xmlrpc_val->kindOf()) - { + switch ($xmlrpc_val->kindOf()) { case 'scalar': - if (in_array('extension_api', $options)) - { + if (in_array('extension_api', $options)) { reset($xmlrpc_val->me); - list($typ,$val) = each($xmlrpc_val->me); - switch ($typ) - { + list($typ, $val) = each($xmlrpc_val->me); + switch ($typ) { case 'dateTime.iso8601': $xmlrpc_val->scalar = $val; $xmlrpc_val->type = 'datetime'; $xmlrpc_val->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val); + return $xmlrpc_val; case 'base64': $xmlrpc_val->scalar = $val; $xmlrpc_val->type = $typ; + return $xmlrpc_val; default: return $xmlrpc_val->scalarval(); } } - if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') - { + if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') { // we return a Datetime object instead of a string // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, // we cater to all 3 cases here $out = $xmlrpc_val->scalarval(); - if (is_string($out)) - { + if (is_string($out)) { $out = strtotime($out); } - if (is_int($out)) - { + if (is_int($out)) { $result = new \Datetime(); $result->setTimestamp($out); + return $result; - } - elseif (is_a($out, 'Datetime')) - { + } elseif (is_a($out, 'Datetime')) { return $out; } } + return $xmlrpc_val->scalarval(); case 'array': $size = $xmlrpc_val->arraysize(); $arr = array(); - for($i = 0; $i < $size; $i++) - { + for ($i = 0; $i < $size; $i++) { $arr[] = $this->decode($xmlrpc_val->arraymem($i), $options); } + return $arr; case 'struct': $xmlrpc_val->structreset(); @@ -88,33 +85,31 @@ function decode($xmlrpc_val, $options=array()) // shall we check for proper subclass of xmlrpcval instead of // presence of _php_class to detect what we can do? if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != '' - && class_exists($xmlrpc_val->_php_class)) - { - $obj = @new $xmlrpc_val->_php_class; - while(list($key,$value)=$xmlrpc_val->structeach()) - { + && class_exists($xmlrpc_val->_php_class) + ) { + $obj = @new $xmlrpc_val->_php_class(); + while (list($key, $value) = $xmlrpc_val->structeach()) { $obj->$key = $this->decode($value, $options); } + return $obj; - } - else - { + } else { $arr = array(); - while(list($key,$value)=$xmlrpc_val->structeach()) - { + while (list($key, $value) = $xmlrpc_val->structeach()) { $arr[$key] = $this->decode($value, $options); } + return $arr; } case 'msg': $paramcount = $xmlrpc_val->getNumParams(); $arr = array(); - for($i = 0; $i < $paramcount; $i++) - { + for ($i = 0; $i < $paramcount; $i++) { $arr[] = $this->decode($xmlrpc_val->getParam($i)); } + return $arr; - } + } } /** @@ -132,18 +127,19 @@ function decode($xmlrpc_val, $options=array()) * * @param mixed $php_val the value to be converted into an xmlrpcval object * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api' + * * @return \PhpXmlrpc\Value */ - function encode($php_val, $options=array()) + public function encode($php_val, $options = array()) { $type = gettype($php_val); - switch($type) - { + 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}$/', $php_val)) + if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val)) { $xmlrpc_val = new Value($php_val, Value::$xmlrpcDateTime); - else + } else { $xmlrpc_val = new Value($php_val, Value::$xmlrpcString); + } break; case 'integer': $xmlrpc_val = new Value($php_val, Value::$xmlrpcInt); @@ -151,12 +147,12 @@ function encode($php_val, $options=array()) case 'double': $xmlrpc_val = new Value($php_val, Value::$xmlrpcDouble); break; - // - // Add support for encoding/decoding of booleans, since they are supported in PHP + // + // Add support for encoding/decoding of booleans, since they are supported in PHP case 'boolean': $xmlrpc_val = new Value($php_val, Value::$xmlrpcBoolean); break; - // + // 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 @@ -166,44 +162,32 @@ function encode($php_val, $options=array()) $j = 0; $arr = array(); $ko = false; - foreach($php_val as $key => $val) - { + foreach ($php_val as $key => $val) { $arr[$key] = $this->encode($val, $options); - if(!$ko && $key !== $j) - { + if (!$ko && $key !== $j) { $ko = true; } $j++; } - if($ko) - { + if ($ko) { $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); - } - else - { + } else { $xmlrpc_val = new Value($arr, Value::$xmlrpcArray); } break; case 'object': - if(is_a($php_val, 'PhpXmlRpc\Value')) - { + if (is_a($php_val, 'PhpXmlRpc\Value')) { $xmlrpc_val = $php_val; - } - else if(is_a($php_val, 'DateTime')) - { + } elseif (is_a($php_val, 'DateTime')) { $xmlrpc_val = new Value($php_val->format('Ymd\TH:i:s'), Value::$xmlrpcStruct); - } - else - { + } else { $arr = array(); reset($php_val); - while(list($k,$v) = each($php_val)) - { + while (list($k, $v) = each($php_val)) { $arr[$k] = $this->encode($v, $options); } $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); - if (in_array('encode_php_objs', $options)) - { + if (in_array('encode_php_objs', $options)) { // let's save original class name into xmlrpcval: // might be useful later on... $xmlrpc_val->_php_class = get_class($php_val); @@ -211,26 +195,18 @@ function encode($php_val, $options=array()) } break; case 'NULL': - if (in_array('extension_api', $options)) - { + if (in_array('extension_api', $options)) { $xmlrpc_val = new Value('', Value::$xmlrpcString); - } - else if (in_array('null_extension', $options)) - { + } elseif (in_array('null_extension', $options)) { $xmlrpc_val = new Value('', Value::$xmlrpcNull); - } - else - { + } else { $xmlrpc_val = new Value(); } break; case 'resource': - if (in_array('extension_api', $options)) - { + if (in_array('extension_api', $options)) { $xmlrpc_val = new Value((int)$php_val, Value::$xmlrpcInt); - } - else - { + } else { $xmlrpc_val = new Value(); } // catch "user function", "unknown type" @@ -240,18 +216,21 @@ function encode($php_val, $options=array()) // an empty object in case, not a boolean. $xmlrpc_val = new Value(); break; - } - return $xmlrpc_val; + } + + return $xmlrpc_val; } /** * Convert the xml representation of a method response, method request or single - * xmlrpc value into the appropriate object (a.k.a. deserialize) + * xmlrpc value into the appropriate object (a.k.a. deserialize). + * * @param string $xml_val * @param array $options + * * @return mixed false on error, or an instance of either Value, Request or Response */ - function decode_xml($xml_val, $options=array()) + public function decode_xml($xml_val, $options = array()) { /// @todo 'guestimate' encoding @@ -259,12 +238,9 @@ function decode_xml($xml_val, $options=array()) 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'))) - { + 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 - { + } else { xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); } @@ -274,42 +250,41 @@ function decode_xml($xml_val, $options=array()) 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, $xml_val, 1)) - { + if (!xml_parse($parser, $xml_val, 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)); + 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??? - { + 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']) - { + switch ($xmlRpcParser->_xh['rt']) { case 'methodresponse': - $v =& $xmlRpcParser->_xh['value']; - if ($xmlRpcParser->_xh['isf'] == 1) - { + $v = &$xmlRpcParser->_xh['value']; + if ($xmlRpcParser->_xh['isf'] == 1) { $vc = $v->structmem('faultCode'); $vs = $v->structmem('faultString'); $r = new Response(0, $vc->scalarval(), $vs->scalarval()); - } - else - { + } else { $r = new Response($v); } + return $r; case 'methodcall': $m = new Request($xmlRpcParser->_xh['method']); - for($i=0; $i < count($xmlRpcParser->_xh['params']); $i++) - { + for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) { $m->addParam($xmlRpcParser->_xh['params'][$i]); } + return $m; case 'value': return $xmlRpcParser->_xh['value']; @@ -318,7 +293,6 @@ function decode_xml($xml_val, $options=array()) } } - /** * xml charset encoding guessing helper function. * Tries to determine the charset encoding of an XML chunk received over HTTP. @@ -333,7 +307,7 @@ function decode_xml($xml_val, $options=array()) * * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!! */ - static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null) + public static function guess_encoding($httpheader = '', $xmlchunk = '', $encoding_prefs = null) { // discussion: see http://www.yale.edu/pclt/encoding/ // 1 - test if encoding is specified in HTTP HEADERS @@ -351,8 +325,7 @@ static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=nul /// @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)) - { + if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpheader, $matches)) { return strtoupper(trim($matches[1], " \t\"")); } @@ -363,16 +336,11 @@ static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=nul // 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)) - { + 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)) - { + } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk)) { return 'UTF-16'; - } - elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk)) - { + } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk)) { return 'UTF-8'; } @@ -380,35 +348,28 @@ static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=nul // 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_.:-]+'))". + 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)) - { + $xmlchunk, $matches)) { return strtoupper(substr($matches[2], 1, -1)); } // 4 - if mbstring is available, let it do the guesswork // NB: we favour finding an encoding that is compatible with what we can process - if(extension_loaded('mbstring')) - { - if($encoding_prefs) - { + if (extension_loaded('mbstring')) { + if ($encoding_prefs) { $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); - } - else - { + } 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; + if ($enc == 'ASCII') { + $enc = 'US-' . $enc; } + return $enc; - } - else - { + } 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. @@ -416,5 +377,4 @@ static function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=nul return PhpXmlRpc::$xmlrpc_defencoding; } } - -} \ No newline at end of file +} diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index db301cc7..6d5eb6a2 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -6,7 +6,6 @@ class Charset { - // tables used for transcoding different charsets into us-ascii xml protected $xml_iso88591_Entities = array("in" => array(), "out" => array()); @@ -27,23 +26,23 @@ class Charset */ protected $charset_supersets = array( - 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', + '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') + 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',), ); protected static $instance = null; /** - * This class is singleton for performance reasons + * This class is singleton for performance reasons. + * * @return Charset */ public static function instance() { - if(self::$instance === null) - { + if (self::$instance === null) { self::$instance = new self(); } @@ -52,12 +51,12 @@ public static function instance() private function __construct() { - for($i = 0; $i < 32; $i++) { + 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++) { + for ($i = 160; $i < 256; $i++) { $this->xml_iso88591_Entities["in"][] = chr($i); $this->xml_iso88591_Entities["out"][] = "&#{$i};"; } @@ -66,7 +65,6 @@ private function __construct() { $this->xml_cp1252_Entities['in'][] = chr($i); }*/ - } /** @@ -86,18 +84,17 @@ private function __construct() * @param string $data * @param string $src_encoding * @param string $dest_encoding + * * @return string */ - public function encode_entities($data, $src_encoding='', $dest_encoding='') + public function encode_entities($data, $src_encoding = '', $dest_encoding = '') { - if ($src_encoding == '') - { + if ($src_encoding == '') { // lame, but we know no better... $src_encoding = PhpXmlRpc::$xmlrpc_internalencoding; } - switch(strtoupper($src_encoding.'_'.$dest_encoding)) - { + switch (strtoupper($src_encoding . '_' . $dest_encoding)) { case 'ISO-8859-1_': case 'ISO-8859-1_US-ASCII': $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); @@ -122,17 +119,15 @@ public function encode_entities($data, $src_encoding='', $dest_encoding='') // NB: this will choke on invalid UTF-8, going most likely beyond EOF $escaped_data = ''; // be kind to users creating string xmlrpcvals out of different php types - $data = (string) $data; - $ns = strlen ($data); - for ($nn = 0; $nn < $ns; $nn++) - { + $data = (string)$data; + $ns = strlen($data); + for ($nn = 0; $nn < $ns; $nn++) { $ch = $data[$nn]; $ii = ord($ch); //1 7 0bbbbbbb (127) - if ($ii < 128) - { + if ($ii < 128) { /// @todo shall we replace this with a (supposedly) faster str_replace? - switch($ii){ + switch ($ii) { case 34: $escaped_data .= '"'; break; @@ -151,43 +146,37 @@ public function encode_entities($data, $src_encoding='', $dest_encoding='') default: $escaped_data .= $ch; } // switch - } - //2 11 110bbbbb 10bbbbbb (2047) - else if ($ii>>5 == 6) - { + } //2 11 110bbbbb 10bbbbbb (2047) + elseif ($ii >> 5 == 6) { $b1 = ($ii & 31); - $ii = ord($data[$nn+1]); + $ii = ord($data[$nn + 1]); $b2 = ($ii & 63); $ii = ($b1 * 64) + $b2; - $ent = sprintf ('&#%d;', $ii); + $ent = sprintf('&#%d;', $ii); $escaped_data .= $ent; $nn += 1; - } - //3 16 1110bbbb 10bbbbbb 10bbbbbb - else if ($ii>>4 == 14) - { + } //3 16 1110bbbb 10bbbbbb 10bbbbbb + elseif ($ii >> 4 == 14) { $b1 = ($ii & 15); - $ii = ord($data[$nn+1]); + $ii = ord($data[$nn + 1]); $b2 = ($ii & 63); - $ii = ord($data[$nn+2]); + $ii = ord($data[$nn + 2]); $b3 = ($ii & 63); $ii = ((($b1 * 64) + $b2) * 64) + $b3; - $ent = sprintf ('&#%d;', $ii); + $ent = sprintf('&#%d;', $ii); $escaped_data .= $ent; $nn += 2; - } - //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - else if ($ii>>3 == 30) - { + } //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + elseif ($ii >> 3 == 30) { $b1 = ($ii & 7); - $ii = ord($data[$nn+1]); + $ii = ord($data[$nn + 1]); $b2 = ($ii & 63); - $ii = ord($data[$nn+2]); + $ii = ord($data[$nn + 2]); $b3 = ($ii & 63); - $ii = ord($data[$nn+3]); + $ii = ord($data[$nn + 3]); $b4 = ($ii & 63); $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4; - $ent = sprintf ('&#%d;', $ii); + $ent = sprintf('&#%d;', $ii); $escaped_data .= $ent; $nn += 3; } @@ -216,31 +205,36 @@ public function encode_entities($data, $src_encoding='', $dest_encoding='') $escaped_data = ''; error_log("Converting from $src_encoding to $dest_encoding: not supported..."); } + return $escaped_data; } /** * 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 + * 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 is_valid_charset($encoding, $validList) { - - if (is_string($validList)) + if (is_string($validList)) { $validList = explode(',', $validList); - if (@in_array(strtoupper($encoding), $validList)) + } + if (@in_array(strtoupper($encoding), $validList)) { return true; - else - { - if (array_key_exists($encoding, $this->charset_supersets)) - foreach ($validList as $allowed) - if (in_array($allowed, $this->charset_supersets[$encoding])) + } 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; } } - -} \ No newline at end of file +} diff --git a/src/Helper/Date.php b/src/Helper/Date.php index 9501a9b9..8bd79937 100644 --- a/src/Helper/Date.php +++ b/src/Helper/Date.php @@ -19,50 +19,45 @@ class Date * * @param int $timet (timestamp) * @param int $utc (0 or 1) + * * @return string */ - public static function iso8601_encode($timet, $utc=0) + public static function iso8601_encode($timet, $utc = 0) { - if(!$utc) - { - $t=strftime("%Y%m%dT%H:%M:%S", $timet); - } - else - { - if(function_exists('gmstrftime')) - { + 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')); + $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 + * 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 iso8601_decode($idate, $utc=0) + public static function iso8601_decode($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]); + $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; } -} \ No newline at end of file +} diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 83a37371..02bfd578 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -7,9 +7,10 @@ class Http /** * decode a string that is encoded w/ "chunked" transfer encoding * as defined in rfc2068 par. 19.4.6 - * code shamelessly stolen from nusoap library by Dietrich Ayala + * code shamelessly stolen from nusoap library by Dietrich Ayala. * * @param string $buffer the string to be decoded + * * @return string */ public static function decode_chunked($buffer) @@ -20,18 +21,16 @@ public static function decode_chunked($buffer) // 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); - $chunk_size = hexdec( trim($temp) ); + $chunkend = strpos($buffer, "\r\n") + 2; + $temp = substr($buffer, 0, $chunkend); + $chunk_size = hexdec(trim($temp)); $chunkstart = $chunkend; - while($chunk_size > 0) - { + while ($chunk_size > 0) { $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); // just in case we got a broken connection - if($chunkend == false) - { - $chunk = substr($buffer,$chunkstart); + if ($chunkend == false) { + $chunk = substr($buffer, $chunkstart); // append chunk-data to entity-body $new .= $chunk; $length += strlen($chunk); @@ -39,7 +38,7 @@ public static function decode_chunked($buffer) } // read chunk-data and crlf - $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); + $chunk = substr($buffer, $chunkstart, $chunkend - $chunkstart); // append chunk-data to entity-body $new .= $chunk; // length := length + chunk-size @@ -47,16 +46,15 @@ public static function decode_chunked($buffer) // read chunk-size and crlf $chunkstart = $chunkend + 2; - $chunkend = strpos($buffer,"\r\n",$chunkstart)+2; - if($chunkend == false) - { + $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); - $chunk_size = hexdec( trim($temp) ); + $temp = substr($buffer, $chunkstart, $chunkend - $chunkstart); + $chunk_size = hexdec(trim($temp)); $chunkstart = $chunkend; } + return $new; } - -} \ No newline at end of file +} diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index 6803ebf4..734ada7e 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -6,7 +6,7 @@ use PhpXmlRpc\Value; /** - * Deals with parsing the XML + * Deals with parsing the XML. */ class XMLParser { @@ -33,7 +33,7 @@ class XMLParser 'method' => false, // so we can check later if we got a methodname or not 'params' => array(), 'pt' => array(), - 'rt' => '' + 'rt' => '', ); public $xmlrpc_valid_parents = array( @@ -55,56 +55,50 @@ class XMLParser 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), 'FAULT' => array('METHODRESPONSE'), 'NIL' => array('VALUE'), // only used when extension activated - 'EX: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 + * xml parser handler function for opening element tags. */ - function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) + public function xmlrpc_se($parser, $name, $attrs, $accept_single_vals = false) { // if invalid xmlrpc already detected, skip all processing - if ($this->_xh['isf'] < 2) - { + 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 (count($this->_xh['stack']) == 0) { if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( - $name != 'VALUE' && !$accept_single_vals)) - { + $name != 'VALUE' && !$accept_single_vals) + ) { $this->_xh['isf'] = 2; $this->_xh['isf_reason'] = 'missing top level xmlrpc element'; + return; - } - else - { + } else { $this->_xh['rt'] = strtolower($name); } - } - else - { + } 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])) - { + 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) - { + 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; + $this->_xh['vt'] = 'value'; // indicator: no value found yet + $this->_xh['ac'] = ''; + $this->_xh['lv'] = 1; + $this->_xh['php_class'] = null; break; case 'I4': case 'INT': @@ -113,22 +107,22 @@ function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - if ($this->_xh['vt']!='value') - { + 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 + $this->_xh['ac'] = ''; // reset the accumulator break; case 'STRUCT': case 'ARRAY': - if ($this->_xh['vt']!='value') - { + 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 @@ -137,19 +131,18 @@ function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) $cur_val['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'])) - { + if (@isset($attrs['PHP_CLASS'])) { $cur_val['php_class'] = $attrs['PHP_CLASS']; } $this->_xh['valuestack'][] = $cur_val; - $this->_xh['vt']='data'; // be prepared for a data element next + $this->_xh['vt'] = 'data'; // be prepared for a data element next break; case 'DATA': - if ($this->_xh['vt']!='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': @@ -160,31 +153,30 @@ function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) case 'METHODNAME': case 'NAME': /// @todo we could check for 2 NAME elements inside a MEMBER element - $this->_xh['ac']=''; + $this->_xh['ac'] = ''; break; case 'FAULT': - $this->_xh['isf']=1; + $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['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; + $this->_xh['vt'] = null; break; case 'NIL': case 'EX:NIL': - if (PhpXmlRpc::$xmlrpc_null_extension) - { - if ($this->_xh['vt']!='value') - { + 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 + $this->_xh['ac'] = ''; // reset the accumulator break; } // we do not support the extension, so @@ -200,79 +192,68 @@ function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false) $this->_xh['stack'][] = $name; /// @todo optimization creep: move this inside the big switch() above - if($name!='VALUE') - { - $this->_xh['lv']=0; + if ($name != 'VALUE') { + $this->_xh['lv'] = 0; } } } /** - * Used in decoding xml chunks that might represent single xmlrpc values + * Used in decoding xml chunks that might represent single xmlrpc values. */ - function xmlrpc_se_any($parser, $name, $attrs) + public function xmlrpc_se_any($parser, $name, $attrs) { $this->xmlrpc_se($parser, $name, $attrs, true); } /** - * xml parser handler function for close element tags + * xml parser handler function for close element tags. */ - function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) + public function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) { - if ($this->_xh['isf'] < 2) - { + 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 == $curr_elem. // we also checked for proper nesting at start of elements... $curr_elem = array_pop($this->_xh['stack']); - switch($name) - { + switch ($name) { case 'VALUE': // This if() detects if no scalar was inside - if ($this->_xh['vt']=='value') - { - $this->_xh['value']=$this->_xh['ac']; - $this->_xh['vt']=Value::$xmlrpcString; + if ($this->_xh['vt'] == 'value') { + $this->_xh['value'] = $this->_xh['ac']; + $this->_xh['vt'] = Value::$xmlrpcString; } - if ($rebuild_xmlrpcvals) - { + if ($rebuild_xmlrpcvals) { // 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'])) + 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 - { + if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') { + $this->_xh['valuestack'][$vscount - 1]['values'][] = $temp; + } else { $this->_xh['value'] = $temp; } - } - else - { + } 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'])) - { + 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']; + if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') { + $this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value']; } } break; @@ -283,133 +264,110 @@ function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - $this->_xh['vt']=strtolower($name); + $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: invalid value received in DATETIME: '.$this->_xh['ac']); + 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: invalid value received in DATETIME: ' . $this->_xh['ac']); } - $this->_xh['vt']=Value::$xmlrpcDateTime; - $this->_xh['value']=$this->_xh['ac']; - } - elseif ($name=='BASE64') - { + $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') - { + $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 - { + 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: invalid value received in BOOLEAN: '.$this->_xh['ac']); - $this->_xh['value']=false; + if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) { + error_log('XML-RPC: invalid value received in BOOLEAN: ' . $this->_xh['ac']); + } + $this->_xh['value'] = false; } - } - elseif ($name=='DOUBLE') - { + } elseif ($name == 'DOUBLE') { // we have a DOUBLE // we must check that only 0123456789-. are characters here // NOTE: regexp could be much stricter than this... - if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) - { + if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) { /// @todo: find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in DOUBLE: '.$this->_xh['ac']); - $this->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { + error_log('XML-RPC: 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']; + $this->_xh['value'] = (double)$this->_xh['ac']; } - } - else - { + } else { // we have an I4/INT // we must check that only 0123456789- are characters here - if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) - { + if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) { /// @todo find a better way of throwing an error than this! - error_log('XML-RPC: non numeric value received in INT: '.$this->_xh['ac']); - $this->_xh['value']='ERROR_NON_NUMERIC_FOUND'; - } - else - { + error_log('XML-RPC: 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['value'] = (int)$this->_xh['ac']; } } //$this->_xh['ac']=''; // is this necessary? - $this->_xh['lv']=3; // indicate we've found a value + $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']; + $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac']; break; case 'MEMBER': //$this->_xh['ac']=''; // is this necessary? // add to array in the stack the last element built, // unless no VALUE was found - if ($this->_xh['vt']) - { + 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 + $this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value']; + } else { error_log('XML-RPC: missing VALUE inside STRUCT in received xml'); + } break; case 'DATA': //$this->_xh['ac']=''; // is this necessary? - $this->_xh['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty + $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 $curr_val = array_pop($this->_xh['valuestack']); $this->_xh['value'] = $curr_val['values']; - $this->_xh['vt']=strtolower($name); - if (isset($curr_val['php_class'])) - { + $this->_xh['vt'] = strtolower($name); + if (isset($curr_val['php_class'])) { $this->_xh['php_class'] = $curr_val['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 + if ($this->_xh['vt']) { + $this->_xh['params'][] = $this->_xh['value']; + $this->_xh['pt'][] = $this->_xh['vt']; + } else { error_log('XML-RPC: missing VALUE inside PARAM in received xml'); + } break; case 'METHODNAME': - $this->_xh['method']=preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']); + $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; + 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 @@ -427,25 +385,23 @@ function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) } /** - * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values + * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values. */ - function xmlrpc_ee_fast($parser, $name) + public function xmlrpc_ee_fast($parser, $name) { $this->xmlrpc_ee($parser, $name, false); } /** - * xml parser handler function for character data + * xml parser handler function for character data. */ - function xmlrpc_cd($parser, $data) + public function xmlrpc_cd($parser, $data) { // skip processing if xml fault already detected - if ($this->_xh['isf'] < 2) - { + 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) - { + if ($this->_xh['lv'] != 3) { // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 //if($this->_xh['lv']==1) //{ @@ -458,7 +414,7 @@ function xmlrpc_cd($parser, $data) //{ // $this->_xh['ac'] = ''; //} - $this->_xh['ac'].=$data; + $this->_xh['ac'] .= $data; } } } @@ -467,22 +423,20 @@ function xmlrpc_cd($parser, $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... */ - function xmlrpc_dh($parser, $data) + 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) == ';') - { + if ($this->_xh['isf'] < 2) { + if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') { // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 //if($this->_xh['lv']==1) //{ // $this->_xh['lv']=2; //} - $this->_xh['ac'].=$data; + $this->_xh['ac'] .= $data; } } + return true; } - -} \ No newline at end of file +} diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 529406d3..dff38967 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -5,57 +5,57 @@ 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, + '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 + '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', + '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' + '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 @@ -91,14 +91,12 @@ class PhpXmlRpc public static function exportGlobals() { $reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc'); - foreach ($reflection->getStaticProperties() as $name => $value) - { + foreach ($reflection->getStaticProperties() as $name => $value) { $GLOBALS[$name] = $value; } $reflection = new \ReflectionClass('PhpXmlRpc\Value'); - foreach ($reflection->getStaticProperties() as $name => $value) - { + foreach ($reflection->getStaticProperties() as $name => $value) { $GLOBALS[$name] = $value; } } @@ -111,16 +109,16 @@ public static function exportGlobals() * 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 + * 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])) + foreach ($staticProperties as $name => $value) { + if (isset($GLOBALS[$name])) { self::$$name = $GLOBALS[$name]; + } } } } diff --git a/src/Request.php b/src/Request.php index 7c93a220..7004b545 100644 --- a/src/Request.php +++ b/src/Request.php @@ -7,12 +7,11 @@ class Request { - /// @todo: do these need to be public? public $payload; public $methodname; - public $params=array(); - public $debug=0; + public $params = array(); + public $debug = 0; public $content_type = 'text/xml'; // holds data while parsing the response. NB: Not a full Response object @@ -22,23 +21,19 @@ class Request * @param string $methodName the name of the method to invoke * @param array $params array of parameters to be passed to the method (xmlrpcval objects) */ - function __construct($methodName, $params=array()) + public function __construct($methodName, $params = array()) { $this->methodname = $methodName; - foreach($params as $param) - { + foreach ($params as $param) { $this->addParam($param); } } - public function xml_header($charset_encoding='') + public function xml_header($charset_encoding = '') { - if ($charset_encoding != '') - { + if ($charset_encoding != '') { return "\n\n"; - } - else - { + } else { return "\n\n"; } } @@ -49,7 +44,8 @@ public function xml_footer() } /** - * Kept the old name even if class was renamed, for compatibility + * Kept the old name even if class was renamed, for compatibility. + * * @return string */ private function kindOf() @@ -57,80 +53,94 @@ private function kindOf() return 'msg'; } - public function createPayload($charset_encoding='') + public function createPayload($charset_encoding = '') { - if ($charset_encoding != '') + if ($charset_encoding != '') { $this->content_type = 'text/xml; charset=' . $charset_encoding; - else + } else { $this->content_type = 'text/xml'; - $this->payload=$this->xml_header($charset_encoding); - $this->payload.='' . $this->methodname . "\n"; - $this->payload.="\n"; - foreach($this->params as $p) - { - $this->payload.="\n" . $p->serialize($charset_encoding) . - "\n"; } - $this->payload.="\n"; - $this->payload.=$this->xml_footer(); + $this->payload = $this->xml_header($charset_encoding); + $this->payload .= '' . $this->methodname . "\n"; + $this->payload .= "\n"; + foreach ($this->params as $p) { + $this->payload .= "\n" . $p->serialize($charset_encoding) . + "\n"; + } + $this->payload .= "\n"; + $this->payload .= $this->xml_footer(); } /** - * Gets/sets the xmlrpc method to be invoked + * Gets/sets the xmlrpc method to be invoked. + * * @param string $meth the method to be set (leave empty not to set it) + * * @return string the method that will be invoked */ - public function method($methodName='') + public function method($methodName = '') { - if($methodName!='') - { - $this->methodname=$methodName; + if ($methodName != '') { + $this->methodname = $methodName; } + return $this->methodname; } /** - * Returns xml representation of the message. XML prologue included + * Returns xml representation of the message. XML prologue included. + * * @param string $charset_encoding + * * @return string the xml representation of the message, xml prologue included */ - public function serialize($charset_encoding='') + public function serialize($charset_encoding = '') { $this->createPayload($charset_encoding); + return $this->payload; } /** - * Add a parameter to the list of parameters to be used upon method invocation + * Add a parameter to the list of parameters to be used upon method invocation. + * * @param Value $par + * * @return boolean false on failure */ public function addParam($param) { // add check: do not add to self params which are not xmlrpcvals - if(is_object($param) && is_a($param, 'PhpXmlRpc\Value')) - { - $this->params[]=$param; + if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) { + $this->params[] = $param; + return true; - } - else - { + } 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]; } + public function getParam($i) + { + return $this->params[$i]; + } /** * Returns the number of parameters in the messge. + * * @return integer the number of parameters currently set */ - public function getNumParams() { return count($this->params); } + public function getNumParams() + { + return count($this->params); + } /** * Given an open file handle, read all data available and parse it as axmlrpc response. @@ -140,16 +150,18 @@ public function getNumParams() { return count($this->params); } * 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; + $ipd = ''; + while ($data = fread($fp, 32768)) { + $ipd .= $data; } //fclose($fp); return $this->parseResponse($ipd); @@ -157,86 +169,72 @@ public function parseResponseFile($fp) /** * Parses HTTP headers and separates them from data. + * * @return null|Response null on success, or a Response on error */ - private function parseResponseHeaders(&$data, $headers_processed=false) + private function parseResponseHeaders(&$data, $headers_processed = false) { $this->httpResponse['headers'] = array(); $this->httpResponse['cookies'] = array(); // Support "web-proxy-tunelling" connections for https through proxies - if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) - { + 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 - { + $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) - { + 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'); - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)'); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)'); + return $r; } } // Strip HTTP 1.1 100 Continue header if present - while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) - { + 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 - { + 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); - $r=new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error']. ' (' . $errstr . ')'); + 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); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')'); + return $r; } // 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 - { + $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; @@ -244,70 +242,55 @@ private function parseResponseHeaders(&$data, $headers_processed=false) } // be tolerant to line endings, and extra empty lines $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos))); - while(list(,$line) = @each($ar)) - { + while (list(, $line) = @each($ar)) { // take care of multi-line headers and cookies - $arr = explode(':',$line,2); - if(count($arr) > 1) - { + $arr = explode(':', $line, 2); + if (count($arr) > 1) { $header_name = 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'][$header_name] /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') - { - if ($header_name == 'set-cookie2') - { + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') { + if ($header_name == 'set-cookie2') { // version 2 cookies: // there could be many cookies on one line, comma separated $cookies = explode(',', $arr[1]); - } - else - { + } else { $cookies = array($arr[1]); } - foreach ($cookies as $cookie) - { + foreach ($cookies as $cookie) { // glue together all received cookies, using a comma to separate them // (same as php does with getallheaders()) - if (isset($this->httpResponse['headers'][$header_name])) + if (isset($this->httpResponse['headers'][$header_name])) { $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie); - else + } else { $this->httpResponse['headers'][$header_name] = 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) - { + 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) - { + if ($pos == 0) { $cookiename = $tag; $this->httpResponse['cookies'][$tag] = array(); $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val); - } - else - { - if ($tag != 'value') - { + } else { + if ($tag != 'value') { $this->httpResponse['cookies'][$cookiename][$tag] = $val; } } } } - } - else - { + } else { $this->httpResponse['headers'][$header_name] = trim($arr[1]); } - } - elseif(isset($header_name)) - { + } elseif (isset($header_name)) { /// @todo version1 cookies might span multiple lines, thus breaking the parsing above $this->httpResponse['headers'][$header_name] .= ' ' . trim($line); } @@ -316,15 +299,12 @@ private function parseResponseHeaders(&$data, $headers_processed=false) $data = substr($data, $bd); /// @todo when in CLI mode, do not html-encode the output - if($this->debug && count($this->httpResponse['headers'])) - { + if ($this->debug && count($this->httpResponse['headers'])) { print "\n"; - foreach($this->httpResponse['headers'] as $header => $value) - { + foreach ($this->httpResponse['headers'] as $header => $value) { print htmlentities("HEADER: $header: $value\n"); } - foreach($this->httpResponse['cookies'] as $header => $value) - { + foreach ($this->httpResponse['cookies'] as $header => $value) { print htmlentities("COOKIE: $header={$value['value']}\n"); } print "\n"; @@ -332,72 +312,65 @@ private function parseResponseHeaders(&$data, $headers_processed=false) // if CURL was used for the call, http headers have been processed, // and dechunking + reinflating have been carried out - if(!$headers_processed) - { + if (!$headers_processed) { // Decode chunked encoding sent by http 1.1 servers - if(isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') - { - if(!$data = Http::decode_chunked($data)) - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server'); + if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') { + if (!$data = Http::decode_chunked($data)) { + error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server'); $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']); + return $r; } } // Decode gzip-compressed stuff // code shamelessly inspired from nusoap library by Dietrich Ayala - if(isset($this->httpResponse['headers']['content-encoding'])) - { + if (isset($this->httpResponse['headers']['content-encoding'])) { $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']); - if($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') - { + if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') { // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')) - { - if($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) - { + if (function_exists('gzinflate')) { + if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - elseif($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) - { + if ($this->debug) { + print "
---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n" . htmlentities($data) . "\n---END---
"; + } + } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; - if($this->debug) - print "
---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---
"; - } - else - { - error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server'); + if ($this->debug) { + print "
---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n" . htmlentities($data) . "\n---END---
"; + } + } else { + error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server'); $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']); + return $r; } - } - else - { - error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']); + return $r; } } } } // end of 'if needed, de-chunk, re-inflate response' - return null; + return; } /** * Parse the xmlrpc response contained in the string $data and return a Response object. + * * @param string $data the xmlrpc response, eventually including http headers * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * * @return Response */ - public function parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals') + public function parseResponse($data = '', $headers_processed = false, $return_type = 'xmlrpcvals') { - if($this->debug) - { + if ($this->debug) { // by maHo, replaced htmlspecialchars with htmlentities print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; } @@ -407,35 +380,32 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' $this->httpResponse['headers'] = array(); $this->httpResponse['cookies'] = array(); - if($data == '') - { - error_log('XML-RPC: '.__METHOD__.': no response received from server.'); + if ($data == '') { + error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.'); $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']); + return $r; } // parse the HTTP headers of the response, if present, and separate them from data - if(substr($data, 0, 4) == 'HTTP') - { + if (substr($data, 0, 4) == 'HTTP') { $r = $this->parseResponseHeaders($data, $headers_processed); - if ($r) - { + if ($r) { // failed processing of HTTP response headers // save into response obj the full payload received, for debugging $r->raw_data = $data; + return $r; } } - if($this->debug) - { + if ($this->debug) { $start = strpos($data, '', $start); - $comments = substr($data, $start, $end-$start); - print "
---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n
"; + $comments = substr($data, $start, $end - $start); + print "
---SERVER DEBUG INFO (DECODED) ---\n\t" . htmlentities(str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n
"; } } @@ -447,18 +417,17 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts) // idea from Luca Mariano originally in PEARified version of the lib $pos = strrpos($data, '
'); - if($pos !== false) - { - $data = substr($data, 0, $pos+17); + if ($pos !== false) { + $data = substr($data, 0, $pos + 17); } // if user wants back raw xml, give it to him - if ($return_type == 'xml') - { + if ($return_type == '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; } @@ -467,12 +436,12 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' // if response charset encoding is not known / supported, try to use // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - { - error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding); + if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + // the following code might be better for mb_string enabled installs, but + // makes the lib about 200% slower... + //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding); $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding; } $parser = xml_parser_create($resp_encoding); @@ -483,24 +452,18 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' // 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'))) - { + 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 - { + } else { xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding); } $xmlRpcParser = new XMLParser(); xml_set_object($parser, $xmlRpcParser); - if ($return_type == 'phpvals') - { + if ($return_type == 'phpvals') { xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); - } - else - { + } else { xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); } @@ -508,57 +471,47 @@ public function parseResponse($data='', $headers_processed=false, $return_type=' xml_set_default_handler($parser, 'xmlrpc_dh'); // first error check: xml not well formed - if(!xml_parse($parser, $data, count($data))) - { + if (!xml_parse($parser, $data, count($data))) { // thanks to Peter Kocks - if((xml_get_current_line_number($parser)) == 1) - { + if ((xml_get_current_line_number($parser)) == 1) { $errstr = 'XML error at line 1, check URL'; - } - else - { + } 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.')'); + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errstr . ')'); xml_parser_free($parser); - if($this->debug) - { + 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) - { + 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']); + 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 ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) - { + elseif ($return_type == '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'], + $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return']); - } - else - { - if ($this->debug) - { + } else { + if ($this->debug) { print "
---PARSED---\n";
                 // somehow htmlentities chokes on var_export, and some full html string...
                 //print htmlentitites(var_export($xmlRpcParser->_xh['value'], true));
@@ -567,42 +520,36 @@ public function parseResponse($data='', $headers_processed=false, $return_type='
             }
 
             // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
-            $v =& $xmlRpcParser->_xh['value'];
+            $v = &$xmlRpcParser->_xh['value'];
 
-            if($xmlRpcParser->_xh['isf'])
-            {
+            if ($xmlRpcParser->_xh['isf']) {
                 /// @todo we should test here if server sent an int and a string,
                 /// and/or coerce them into such...
-                if ($return_type == 'xmlrpcvals')
-                {
+                if ($return_type == 'xmlrpcvals') {
                     $errno_v = $v->structmem('faultCode');
                     $errstr_v = $v->structmem('faultString');
                     $errno = $errno_v->scalarval();
                     $errstr = $errstr_v->scalarval();
-                }
-                else
-                {
+                } else {
                     $errno = $v['faultCode'];
                     $errstr = $v['faultString'];
                 }
 
-                if($errno == 0)
-                {
+                if ($errno == 0) {
                     // FAULT returned, errno needs to reflect that
                     $errno = -1;
                 }
 
                 $r = new Response(0, $errno, $errstr);
-            }
-            else
-            {
-                $r=new Response($v, 0, '', $return_type);
+            } else {
+                $r = new Response($v, 0, '', $return_type);
             }
         }
 
         $r->hdrs = $this->httpResponse['headers'];
         $r->_cookies = $this->httpResponse['cookies'];
-        $r->raw_data = $this->httpResponse['raw_data'];;
+        $r->raw_data = $this->httpResponse['raw_data'];
+
         return $r;
     }
 }
diff --git a/src/Response.php b/src/Response.php
index fe945c13..efadfb57 100644
--- a/src/Response.php
+++ b/src/Response.php
@@ -6,7 +6,6 @@
 
 class Response
 {
-
     /// @todo: do these need to be public?
     public $val = 0;
     public $valtyp;
@@ -28,37 +27,26 @@ class Response
      * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
      * php val, or a complete xml chunk, depending on usage of Client::send() inside which creator is called...
      */
-    function __construct($val, $fcode = 0, $fstr = '', $valtyp='')
+    public function __construct($val, $fcode = 0, $fstr = '', $valtyp = '')
     {
-        if($fcode != 0)
-        {
+        if ($fcode != 0) {
             // error response
             $this->errno = $fcode;
             $this->errstr = $fstr;
             //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
-        }
-        else
-        {
+        } else {
             // successful response
             $this->val = $val;
-            if ($valtyp == '')
-            {
+            if ($valtyp == '') {
                 // user did not declare type of response value: try to guess it
-                if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value'))
-                {
+                if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
                     $this->valtyp = 'xmlrpcvals';
-                }
-                else if (is_string($this->val))
-                {
+                } elseif (is_string($this->val)) {
                     $this->valtyp = 'xml';
-                }
-                else
-                {
+                } else {
                     $this->valtyp = 'phpvals';
                 }
-            }
-            else
-            {
+            } else {
                 // user declares type of resp value: believe him
                 $this->valtyp = $valtyp;
             }
@@ -67,6 +55,7 @@ function __construct($val, $fcode = 0, $fstr = '', $valtyp='')
 
     /**
      * Returns the error code of the response.
+     *
      * @return integer the error code of this response (0 for not-error responses)
      */
     public function faultCode()
@@ -76,6 +65,7 @@ public function faultCode()
 
     /**
      * Returns the error code of the response.
+     *
      * @return string the error string of this response ('' for not-error responses)
      */
     public function faultString()
@@ -85,6 +75,7 @@ public function faultString()
 
     /**
      * Returns the value received by the server.
+     *
      * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects
      */
     public function value()
@@ -99,7 +90,8 @@ public function value()
      * 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
+     * request to the server (using Client::setCookie) or not.
+     *
      * @return array array of cookies received from the server
      */
     public function cookies()
@@ -108,53 +100,44 @@ public function cookies()
     }
 
     /**
-     * Returns xml representation of the response. XML prologue not included
+     * Returns xml representation of the response. XML prologue not included.
+     *
      * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
+     *
      * @return string the xml representation of the response
      */
-    public function serialize($charset_encoding='')
+    public function serialize($charset_encoding = '')
     {
-        if ($charset_encoding != '')
+        if ($charset_encoding != '') {
             $this->content_type = 'text/xml; charset=' . $charset_encoding;
-        else
+        } else {
             $this->content_type = 'text/xml';
-        if (PhpXmlRpc::$xmlrpc_null_apache_encoding)
-        {
-            $result = "\n";
         }
-        else
-        {
+        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
+            $result = "\n";
+        } else {
             $result = "\n";
         }
-        if($this->errno)
-        {
+        if ($this->errno) {
             // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
             // by xml-encoding non ascii chars
             $charsetEncoder =
             $result .= "\n" .
-"\nfaultCode\n" . $this->errno .
-"\n\n\nfaultString\n" .
-Charset::instance()->encode_entities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" .
-"\n\n";
-        }
-        else
-        {
-            if(!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value'))
-            {
-                if (is_string($this->val) && $this->valtyp == 'xml')
-                {
+                "\nfaultCode\n" . $this->errno .
+                "\n\n\nfaultString\n" .
+                Charset::instance()->encode_entities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" .
+                "\n\n";
+        } else {
+            if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) {
+                if (is_string($this->val) && $this->valtyp == 'xml') {
                     $result .= "\n\n" .
                         $this->val .
                         "\n";
-                }
-                else
-                {
+                } else {
                     /// @todo try to build something serializable?
                     die('cannot serialize xmlrpc response objects whose content is native php values');
                 }
-            }
-            else
-            {
+            } else {
                 $result .= "\n\n" .
                     $this->val->serialize($charset_encoding) .
                     "\n";
@@ -162,6 +145,7 @@ public function serialize($charset_encoding='')
         }
         $result .= "\n";
         $this->payload = $result;
+
         return $result;
     }
 }
diff --git a/src/Server.php b/src/Server.php
index 81da9ee8..5d28c45f 100644
--- a/src/Server.php
+++ b/src/Server.php
@@ -8,46 +8,46 @@
 class Server
 {
     /**
-    * Array defining php functions exposed as xmlrpc methods by this server
-    */
-    protected $dmap=array();
-    /**
+     * Array defining php functions exposed as xmlrpc methods by this server.
+     */
+    protected $dmap = array();
+    /*
     * Defines how functions in dmap will be invoked: either using an xmlrpc msg object
     * or plain php values.
     * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
     */
-    var $functions_parameters_type='xmlrpcvals';
-    /**
+    public $functions_parameters_type = 'xmlrpcvals';
+    /*
     * Option used for fine-tuning the encoding the php values returned from
     * functions registered in the dispatch map when the functions_parameters_types
     * member is set to 'phpvals'
     * @see php_xmlrpc_encode for a list of values
     */
-    var $phpvals_encoding_options = array( 'auto_dates' );
+    public $phpvals_encoding_options = array('auto_dates');
     /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3
-    var $debug = 1;
-    /**
+    public $debug = 1;
+    /*
     * Controls behaviour of server when invoked user function throws an exception:
     * 0 = catch it and return an 'internal error' xmlrpc response (default)
     * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
     * 2 = allow the exception to float to the upper layers
     */
-    var $exception_handling = 0;
-    /**
+    public $exception_handling = 0;
+    /*
     * When set to true, it will enable HTTP compression of the response, in case
     * the client has declared its support for compression in the request.
     */
-    var $compress_response = false;
-    /**
+    public $compress_response = false;
+    /*
     * List of http compression methods accepted by the server for requests.
     * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
     */
-    var $accepted_compression = array();
+    public $accepted_compression = array();
     /// shall we serve calls to system.* methods?
-    var $allow_system_funcs = true;
+    public $allow_system_funcs = true;
     /// list of charset encodings natively accepted for requests
-    var $accepted_charset_encodings = array();
-    /**
+    public $accepted_charset_encodings = array();
+    /*
     * charset encoding to be used for response.
     * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
     * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
@@ -56,30 +56,29 @@ class Server
     * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway).
     * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
     */
-    var $response_charset_encoding = '';
+    public $response_charset_encoding = '';
     /**
-    * Storage for internal debug info
-    */
+     * Storage for internal debug info.
+     */
     protected $debug_info = '';
-    /**
+    /*
     * Extra data passed at runtime to method handling functions. Used only by EPI layer
     */
-    var $user_data = null;
+    public $user_data = null;
 
-    static protected $_xmlrpc_debuginfo = '';
-    static protected $_xmlrpcs_occurred_errors = '';
-    static $_xmlrpcs_prev_ehandler = '';
+    protected static $_xmlrpc_debuginfo = '';
+    protected static $_xmlrpcs_occurred_errors = '';
+    public static $_xmlrpcs_prev_ehandler = '';
 
     /**
-    * @param array $dispmap the dispatch map with definition of exposed services
-    * @param boolean $servicenow set to false to prevent the server from running upon construction
-    */
-    function __construct($dispMap=null, $serviceNow=true)
+     * @param array $dispmap the dispatch map with definition of exposed services
+     * @param boolean $servicenow set to false to prevent the server from running upon construction
+     */
+    public function __construct($dispMap = null, $serviceNow = true)
     {
         // if ZLIB is enabled, let the server by default accept compressed requests,
         // and compress responses sent to clients that support them
-        if(function_exists('gzinflate'))
-        {
+        if (function_exists('gzinflate')) {
             $this->accepted_compression = array('gzip', 'deflate');
             $this->compress_response = true;
         }
@@ -96,32 +95,31 @@ function __construct($dispMap=null, $serviceNow=true)
             * instead, you can use the class add_to_map() function
             * to add functions manually (borrowed from SOAPX4)
             */
-        if($dispMap)
-        {
+        if ($dispMap) {
             $this->dmap = $dispMap;
-            if($serviceNow)
-            {
+            if ($serviceNow) {
                 $this->service();
             }
         }
     }
 
     /**
-    * Set debug level of server.
-    * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
-    * 0 = no debug info,
-    * 1 = msgs set from user with debugmsg(),
-    * 2 = add complete xmlrpc request (headers and body),
-    * 3 = add also all processing warnings happened during method processing
-    * (NB: this involves setting a custom error handler, and might interfere
-    * with the standard processing of the php function exposed as method. In
-    * particular, triggering an USER_ERROR level error will not halt script
-    * execution anymore, but just end up logged in the xmlrpc response)
-    * Note that info added at level 2 and 3 will be base64 encoded
-    */
-    function setDebug($in)
+     * Set debug level of server.
+     *
+     * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
+     *                    0 = no debug info,
+     *                    1 = msgs set from user with debugmsg(),
+     *                    2 = add complete xmlrpc request (headers and body),
+     *                    3 = add also all processing warnings happened during method processing
+     *                    (NB: this involves setting a custom error handler, and might interfere
+     *                    with the standard processing of the php function exposed as method. In
+     *                    particular, triggering an USER_ERROR level error will not halt script
+     *                    execution anymore, but just end up logged in the xmlrpc response)
+     *                    Note that info added at level 2 and 3 will be base64 encoded
+     */
+    public function setDebug($in)
     {
-        $this->debug=$in;
+        $this->debug = $in;
     }
 
     /**
@@ -129,6 +127,7 @@ function setDebug($in)
      * as part of the response message.
      * Note that for best compatibility, the debug string should be encoded using
      * the PhpXmlRpc::$xmlrpc_internalencoding character set.
+     *
      * @param string $m
      * @access public
      */
@@ -143,11 +142,13 @@ public static function error_occurred($m)
     }
 
     /**
-    * Return a string with the serialized representation of all debug info
-    * @param string $charset_encoding the target charset encoding for the serialization
-    * @return string an XML comment (or two)
-    */
-    function serializeDebug($charset_encoding='')
+     * Return a string with the serialized representation of all debug info.
+     *
+     * @param string $charset_encoding the target charset encoding for the serialization
+     *
+     * @return string an XML comment (or two)
+     */
+    public function serializeDebug($charset_encoding = '')
     {
         // Tough encoding problem: which internal charset should we assume for debug info?
         // It might contain a copy of raw data received from client, ie with unknown encoding,
@@ -155,31 +156,30 @@ function serializeDebug($charset_encoding='')
         // so we split it: system debug is base 64 encoded,
         // user debug info should be encoded by the end user using the INTERNAL_ENCODING
         $out = '';
-        if ($this->debug_info != '')
-        {
-            $out .= "\n";
+        if ($this->debug_info != '') {
+            $out .= "\n";
         }
-        if( static::$_xmlrpc_debuginfo!='')
-        {
-
+        if (static::$_xmlrpc_debuginfo != '') {
             $out .= "\n";
             // NB: a better solution MIGHT be to use CDATA, but we need to insert it
             // into return payload AFTER the beginning tag
             //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n";
         }
+
         return $out;
     }
 
     /**
-     * Execute the xmlrpc request, printing the response
+     * Execute the xmlrpc request, printing the response.
+     *
      * @param string $data the request body. If null, the http POST request will be examined
      * @param bool $return_payload When true, return the response but do not echo it or any http header
+     *
      * @return Response the response object (usually not used by caller...)
      */
-    function service($data=null, $return_payload=false)
+    public function service($data = null, $return_payload = false)
     {
-        if ($data === null)
-        {
+        if ($data === null) {
             // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA
             $data = file_get_contents('php://input');
         }
@@ -189,50 +189,43 @@ function service($data=null, $return_payload=false)
         $this->debug_info = '';
 
         // Echo back what we received, before parsing it
-        if($this->debug > 1)
-        {
+        if ($this->debug > 1) {
             $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
         }
 
         $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);
-        if (!$r)
-        {
-            $r=$this->parseRequest($data, $req_charset);
+        if (!$r) {
+            $r = $this->parseRequest($data, $req_charset);
         }
 
         // save full body of request into response, for more debugging usages
         $r->raw_data = $raw_data;
 
-        if($this->debug > 2 && static::$_xmlrpcs_occurred_errors)
-        {
+        if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) {
             $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
                 static::$_xmlrpcs_occurred_errors . "+++END+++");
         }
 
-        $payload=$this->xml_header($resp_charset);
-        if($this->debug > 0)
-        {
+        $payload = $this->xml_header($resp_charset);
+        if ($this->debug > 0) {
             $payload = $payload . $this->serializeDebug($resp_charset);
         }
 
         // G. Giunta 2006-01-27: do not create response serialization if it has
         // already happened. Helps building json magic
-        if (empty($r->payload))
-        {
+        if (empty($r->payload)) {
             $r->serialize($resp_charset);
         }
         $payload = $payload . $r->payload;
 
-        if ($return_payload)
-        {
+        if ($return_payload) {
             return $payload;
         }
 
         // if we get a warning/error that has output some text before here, then we cannot
         // add a new header. We cannot say we are sending xml, either...
-        if(!headers_sent())
-        {
-            header('Content-Type: '.$r->content_type);
+        if (!headers_sent()) {
+            header('Content-Type: ' . $r->content_type);
             // we do not know if client actually told us an accepted charset, but if he did
             // we have to tell him what we did
             header("Vary: Accept-Charset");
@@ -241,17 +234,14 @@ function service($data=null, $return_payload=false)
             // if we can do it, and we want to do it, and client asked us to,
             // and php ini settings do not force it already
             $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
-            if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
-                && $php_no_self_compress)
-            {
-                if(strpos($resp_encoding, 'gzip') !== false)
-                {
+            if ($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
+                && $php_no_self_compress
+            ) {
+                if (strpos($resp_encoding, 'gzip') !== false) {
                     $payload = gzencode($payload);
                     header("Content-Encoding: gzip");
                     header("Vary: Accept-Encoding");
-                }
-                elseif (strpos($resp_encoding, 'deflate') !== false)
-                {
+                } elseif (strpos($resp_encoding, 'deflate') !== false) {
                     $payload = gzcompress($payload);
                     header("Content-Encoding: deflate");
                     header("Vary: Accept-Encoding");
@@ -260,14 +250,11 @@ function service($data=null, $return_payload=false)
 
             // do not output content-length header if php is compressing output for us:
             // it will mess up measurements
-            if($php_no_self_compress)
-            {
+            if ($php_no_self_compress) {
                 header('Content-Length: ' . (int)strlen($payload));
             }
-        }
-        else
-        {
-            error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages');
+        } else {
+            error_log('XML-RPC: ' . __METHOD__ . ': http headers already sent before response is fully generated. Check for php warning or error messages');
         }
 
         print $payload;
@@ -277,163 +264,132 @@ function service($data=null, $return_payload=false)
     }
 
     /**
-    * Add a method to the dispatch map
-    * @param string $methodname the name with which the method will be made available
-    * @param string $function the php function that will get invoked
-    * @param array $sig the array of valid method signatures
-    * @param string $doc method documentation
-    * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)
-    */
-    function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false)
+     * Add a method to the dispatch map.
+     *
+     * @param string $methodname the name with which the method will be made available
+     * @param string $function the php function that will get invoked
+     * @param array $sig the array of valid method signatures
+     * @param string $doc method documentation
+     * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)
+     */
+    public function add_to_map($methodname, $function, $sig = null, $doc = false, $sigdoc = false)
     {
         $this->dmap[$methodname] = array(
             'function' => $function,
-            'docstring' => $doc
+            'docstring' => $doc,
         );
-        if ($sig)
-        {
+        if ($sig) {
             $this->dmap[$methodname]['signature'] = $sig;
         }
-        if ($sigdoc)
-        {
+        if ($sigdoc) {
             $this->dmap[$methodname]['signature_docs'] = $sigdoc;
         }
     }
 
     /**
-    * Verify type and number of parameters received against a list of known signatures
-    * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
-    * @param array $sig array of known signatures to match against
-    * @return array
-    */
+     * Verify type and number of parameters received against a list of known signatures.
+     *
+     * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
+     * @param array $sig array of known signatures to match against
+     *
+     * @return array
+     */
     protected function verifySignature($in, $sig)
     {
         // check each possible signature in turn
-        if (is_object($in))
-        {
+        if (is_object($in)) {
             $numParams = $in->getNumParams();
-        }
-        else
-        {
+        } else {
             $numParams = count($in);
         }
-        foreach($sig as $cursig)
-        {
-            if(count($cursig)==$numParams+1)
-            {
-                $itsOK=1;
-                for($n=0; $n<$numParams; $n++)
-                {
-                    if (is_object($in))
-                    {
-                        $p=$in->getParam($n);
-                        if($p->kindOf() == 'scalar')
-                        {
-                            $pt=$p->scalartyp();
-                        }
-                        else
-                        {
-                            $pt=$p->kindOf();
+        foreach ($sig as $cursig) {
+            if (count($cursig) == $numParams + 1) {
+                $itsOK = 1;
+                for ($n = 0; $n < $numParams; $n++) {
+                    if (is_object($in)) {
+                        $p = $in->getParam($n);
+                        if ($p->kindOf() == 'scalar') {
+                            $pt = $p->scalartyp();
+                        } else {
+                            $pt = $p->kindOf();
                         }
-                    }
-                    else
-                    {
-                        $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
+                    } else {
+                        $pt = $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
                     }
 
                     // param index is $n+1, as first member of sig is return type
-                    if($pt != $cursig[$n+1] && $cursig[$n+1] != Value::$xmlrpcValue)
-                    {
-                        $itsOK=0;
-                        $pno=$n+1;
-                        $wanted=$cursig[$n+1];
-                        $got=$pt;
+                    if ($pt != $cursig[$n + 1] && $cursig[$n + 1] != Value::$xmlrpcValue) {
+                        $itsOK = 0;
+                        $pno = $n + 1;
+                        $wanted = $cursig[$n + 1];
+                        $got = $pt;
                         break;
                     }
                 }
-                if($itsOK)
-                {
-                    return array(1,'');
+                if ($itsOK) {
+                    return array(1, '');
                 }
             }
         }
-        if(isset($wanted))
-        {
+        if (isset($wanted)) {
             return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
-        }
-        else
-        {
+        } else {
             return array(0, "No method signature matches number of parameters");
         }
     }
 
     /**
-    * Parse http headers received along with xmlrpc request. If needed, inflate request
-    * @return mixed null on success or a Response
-    */
+     * Parse http headers received along with xmlrpc request. If needed, inflate request.
+     *
+     * @return mixed null on success or a Response
+     */
     protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
     {
         // check if $_SERVER is populated: it might have been disabled via ini file
         // (this is true even when in CLI mode)
-        if (count($_SERVER) == 0)
-        {
-            error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');
+        if (count($_SERVER) == 0) {
+            error_log('XML-RPC: ' . __METHOD__ . ': cannot parse request headers as $_SERVER is not populated');
         }
 
-        if($this->debug > 1)
-        {
-            if(function_exists('getallheaders'))
-            {
+        if ($this->debug > 1) {
+            if (function_exists('getallheaders')) {
                 $this->debugmsg(''); // empty line
-                foreach(getallheaders() as $name => $val)
-                {
+                foreach (getallheaders() as $name => $val) {
                     $this->debugmsg("HEADER: $name: $val");
                 }
             }
-
         }
 
-        if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
-        {
+        if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) {
             $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
-        }
-        else
-        {
+        } else {
             $content_encoding = '';
         }
 
         // check if request body has been compressed and decompress it
-        if($content_encoding != '' && strlen($data))
-        {
-            if($content_encoding == 'deflate' || $content_encoding == 'gzip')
-            {
+        if ($content_encoding != '' && strlen($data)) {
+            if ($content_encoding == 'deflate' || $content_encoding == 'gzip') {
                 // if decoding works, use it. else assume data wasn't gzencoded
-                if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
-                {
-                    if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
-                    {
+                if (function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) {
+                    if ($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) {
                         $data = $degzdata;
-                        if($this->debug > 1)
-                        {
-                            $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
+                        if ($this->debug > 1) {
+                            $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
                         }
-                    }
-                    elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
-                    {
+                    } elseif ($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
                         $data = $degzdata;
-                        if($this->debug > 1)
-                            $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
-                    }
-                    else
-                    {
+                        if ($this->debug > 1) {
+                            $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++");
+                        }
+                    } else {
                         $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
+
                         return $r;
                     }
-                }
-                else
-                {
+                } else {
                     //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']);
+
                     return $r;
                 }
             }
@@ -441,41 +397,34 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding,
 
         // check if client specified accepted charsets, and if we know how to fulfill
         // the request
-        if ($this->response_charset_encoding == 'auto')
-        {
+        if ($this->response_charset_encoding == 'auto') {
             $resp_encoding = '';
-            if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
-            {
+            if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
                 // here we should check if we can match the client-requested encoding
                 // with the encodings we know we can generate.
                 /// @todo we should parse q=0.x preferences instead of getting first charset specified...
                 $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
                 // Give preference to internal encoding
                 $known_charsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
-                foreach ($known_charsets as $charset)
-                {
-                    foreach ($client_accepted_charsets as $accepted)
-                        if (strpos($accepted, $charset) === 0)
-                        {
+                foreach ($known_charsets as $charset) {
+                    foreach ($client_accepted_charsets as $accepted) {
+                        if (strpos($accepted, $charset) === 0) {
                             $resp_encoding = $charset;
                             break;
                         }
-                    if ($resp_encoding)
+                    }
+                    if ($resp_encoding) {
                         break;
+                    }
                 }
             }
-        }
-        else
-        {
+        } else {
             $resp_encoding = $this->response_charset_encoding;
         }
 
-        if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
-        {
+        if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
             $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
-        }
-        else
-        {
+        } else {
             $resp_compression = '';
         }
 
@@ -484,17 +433,19 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding,
         $req_encoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
             $data);
 
-        return null;
+        return;
     }
 
     /**
-    * Parse an xml chunk containing an xmlrpc request and execute the corresponding
-    * php function registered with the server
-    * @param string $data the xml request
-    * @param string $req_encoding (optional) the charset encoding of the xml request
-    * @return Response
-    */
-    public function parseRequest($data, $req_encoding='')
+     * Parse an xml chunk containing an xmlrpc request and execute the corresponding
+     * php function registered with the server.
+     *
+     * @param string $data the xml request
+     * @param string $req_encoding (optional) the charset encoding of the xml request
+     *
+     * @return Response
+     */
+    public function parseRequest($data, $req_encoding = '')
     {
         // 2005/05/07 commented and moved into caller function code
         //if($data=='')
@@ -507,23 +458,20 @@ public function parseRequest($data, $req_encoding='')
         //$data = xmlrpc_html_entity_xlate($data);
 
         // decompose incoming XML into request structure
-        if ($req_encoding != '')
-        {
-            if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
-            // the following code might be better for mb_string enabled installs, but
-            // makes the lib about 200% slower...
-            //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
-            {
-                error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding);
+        if ($req_encoding != '') {
+            if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
+                // the following code might be better for mb_string enabled installs, but
+                // makes the lib about 200% slower...
+                //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
+
+                error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $req_encoding);
                 $req_encoding = PhpXmlRpc::$xmlrpc_defencoding;
             }
             /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
             // the encoding is not UTF8 and there are non-ascii chars in the text...
             /// @todo use an empty string for php 5 ???
             $parser = xml_parser_create($req_encoding);
-        }
-        else
-        {
+        } else {
             $parser = xml_parser_create();
         }
 
@@ -534,98 +482,84 @@ public function parseRequest($data, $req_encoding='')
         // 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')))
-        {
+        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
-        {
+        } else {
             xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
         }
 
         $xmlRpcParser = new XMLParser();
         xml_set_object($parser, $xmlRpcParser);
 
-        if ($this->functions_parameters_type != 'xmlrpcvals')
+        if ($this->functions_parameters_type != 'xmlrpcvals') {
             xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
-        else
+        } 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');
-        if(!xml_parse($parser, $data, 1))
-        {
+        if (!xml_parse($parser, $data, 1)) {
             // return XML error as a faultCode
-            $r=new Response(0,
-                PhpXmlRpc::$xmlrpcerrxml+xml_get_error_code($parser),
-            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)));
+            $r = new Response(0,
+                PhpXmlRpc::$xmlrpcerrxml + xml_get_error_code($parser),
+                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)));
             xml_parser_free($parser);
-        }
-        elseif ($xmlRpcParser->_xh['isf'])
-        {
+        } elseif ($xmlRpcParser->_xh['isf']) {
             xml_parser_free($parser);
-            $r=new Response(0,
+            $r = new Response(0,
                 PhpXmlRpc::$xmlrpcerr['invalid_request'],
                 PhpXmlRpc::$xmlrpcstr['invalid_request'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
-        }
-        else
-        {
+        } else {
             xml_parser_free($parser);
             // small layering violation in favor of speed and memory usage:
             // we should allow the 'execute' method handle this, but in the
             // most common scenario (xmlrpcvals type server with some methods
             // registered as phpvals) that would mean a useless encode+decode pass
-            if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals')))
-            {
-                if($this->debug > 1)
-                {
-                    $this->debugmsg("\n+++PARSED+++\n".var_export($xmlRpcParser->_xh['params'], true)."\n+++END+++");
+            if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) {
+                if ($this->debug > 1) {
+                    $this->debugmsg("\n+++PARSED+++\n" . var_export($xmlRpcParser->_xh['params'], true) . "\n+++END+++");
                 }
                 $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']);
-            }
-            else
-            {
+            } else {
                 // build a Request object with data parsed from xml
-                $m=new Request($xmlRpcParser->_xh['method']);
+                $m = new Request($xmlRpcParser->_xh['method']);
                 // now add parameters in
-                for($i=0; $i_xh['params']); $i++)
-                {
+                for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
                     $m->addParam($xmlRpcParser->_xh['params'][$i]);
                 }
 
-                if($this->debug > 1)
-                {
-                    $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");
+                if ($this->debug > 1) {
+                    $this->debugmsg("\n+++PARSED+++\n" . var_export($m, true) . "\n+++END+++");
                 }
                 $r = $this->execute($m);
             }
         }
+
         return $r;
     }
 
     /**
-    * Execute a method invoked by the client, checking parameters used
-    * @param mixed $m either a Request obj or a method name
-    * @param array $params array with method parameters as php types (if m is method name only)
-    * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
-    * @return Response
-    */
-    protected function execute($m, $params=null, $paramtypes=null)
+     * Execute a method invoked by the client, checking parameters used.
+     *
+     * @param mixed $m either a Request obj or a method name
+     * @param array $params array with method parameters as php types (if m is method name only)
+     * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
+     *
+     * @return Response
+     */
+    protected function execute($m, $params = null, $paramtypes = null)
     {
-        if (is_object($m))
-        {
+        if (is_object($m)) {
             $methName = $m->method();
-        }
-        else
-        {
+        } else {
             $methName = $m;
         }
         $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
         $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
 
-        if(!isset($dmap[$methName]['function']))
-        {
+        if (!isset($dmap[$methName]['function'])) {
             // No such method
             return new Response(0,
                 PhpXmlRpc::$xmlrpcerr['unknown_method'],
@@ -633,19 +567,14 @@ protected function execute($m, $params=null, $paramtypes=null)
         }
 
         // Check signature
-        if(isset($dmap[$methName]['signature']))
-        {
+        if (isset($dmap[$methName]['signature'])) {
             $sig = $dmap[$methName]['signature'];
-            if (is_object($m))
-            {
+            if (is_object($m)) {
                 list($ok, $errstr) = $this->verifySignature($m, $sig);
-            }
-            else
-            {
+            } else {
                 list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
             }
-            if(!$ok)
-            {
+            if (!$ok) {
                 // Didn't match.
                 return new Response(
                     0,
@@ -657,14 +586,13 @@ protected function execute($m, $params=null, $paramtypes=null)
 
         $func = $dmap[$methName]['function'];
         // let the 'class::function' syntax be accepted in dispatch maps
-        if(is_string($func) && strpos($func, '::'))
-        {
+        if (is_string($func) && strpos($func, '::')) {
             $func = explode('::', $func);
         }
         // verify that function to be invoked is in fact callable
-        if(!is_callable($func))
-        {
-            error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");
+        if (!is_callable($func)) {
+            error_log("XML-RPC: " . __METHOD__ . ": function $func registered as method handler is not callable");
+
             return new Response(
                 0,
                 PhpXmlRpc::$xmlrpcerr['server_error'],
@@ -674,32 +602,22 @@ protected function execute($m, $params=null, $paramtypes=null)
 
         // If debug level is 3, we should catch all errors generated during
         // processing of user function, and log them as part of response
-        if($this->debug > 2)
-        {
+        if ($this->debug > 2) {
             $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'));
         }
-        try
-        {
+        try {
             // Allow mixed-convention servers
-            if (is_object($m))
-            {
-                if($sysCall)
-                {
+            if (is_object($m)) {
+                if ($sysCall) {
                     $r = call_user_func($func, $this, $m);
-                }
-                else
-                {
+                } else {
                     $r = call_user_func($func, $m);
                 }
-                if (!is_a($r, 'PhpXmlRpc\Response'))
-                {
-                    error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpc response object");
-                    if (is_a($r, 'PhpXmlRpc\Value'))
-                    {
+                if (!is_a($r, 'PhpXmlRpc\Response')) {
+                    error_log("XML-RPC: " . __METHOD__ . ": function $func registered as method handler does not return an xmlrpc response object");
+                    if (is_a($r, 'PhpXmlRpc\Value')) {
                         $r = new Response($r);
-                    }
-                    else
-                    {
+                    } else {
                         $r = new Response(
                             0,
                             PhpXmlRpc::$xmlrpcerr['server_error'],
@@ -707,54 +625,39 @@ protected function execute($m, $params=null, $paramtypes=null)
                         );
                     }
                 }
-            }
-            else
-            {
+            } else {
                 // call a 'plain php' function
-                if($sysCall)
-                {
+                if ($sysCall) {
                     array_unshift($params, $this);
                     $r = call_user_func_array($func, $params);
-                }
-                else
-                {
+                } else {
                     // 3rd API convention for method-handling functions: EPI-style
-                    if ($this->functions_parameters_type == 'epivals')
-                    {
+                    if ($this->functions_parameters_type == 'epivals') {
                         $r = call_user_func_array($func, array($methName, $params, $this->user_data));
                         // mimic EPI behaviour: if we get an array that looks like an error, make it
                         // an eror response
-                        if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
-                        {
+                        if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) {
                             $r = new Response(0, (integer)$r['faultCode'], (string)$r['faultString']);
-                        }
-                        else
-                        {
+                        } else {
                             // functions using EPI api should NOT return resp objects,
                             // so make sure we encode the return type correctly
                             $r = new Response(php_xmlrpc_encode($r, array('extension_api')));
                         }
-                    }
-                    else
-                    {
+                    } else {
                         $r = call_user_func_array($func, $params);
                     }
                 }
                 // the return type can be either a Response object or a plain php value...
-                if (!is_a($r, '\PhpXmlRpc\Response'))
-                {
+                if (!is_a($r, '\PhpXmlRpc\Response')) {
                     // what should we assume here about automatic encoding of datetimes
                     // and php classes instances???
                     $r = new Response(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
                 }
             }
-        }
-        catch(\Exception $e)
-        {
+        } catch (\Exception $e) {
             // (barring errors in the lib) an uncatched exception happened
             // in the called function, we wrap it in a proper error-response
-            switch($this->exception_handling)
-            {
+            switch ($this->exception_handling) {
                 case 2:
                     throw $e;
                     break;
@@ -765,50 +668,45 @@ protected function execute($m, $params=null, $paramtypes=null)
                     $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$xmlrpcstr['server_error']);
             }
         }
-        if($this->debug > 2)
-        {
+        if ($this->debug > 2) {
             // note: restore the error handler we found before calling the
             // user func, even if it has been changed inside the func itself
-            if($GLOBALS['_xmlrpcs_prev_ehandler'])
-            {
+            if ($GLOBALS['_xmlrpcs_prev_ehandler']) {
                 set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
-            }
-            else
-            {
+            } else {
                 restore_error_handler();
             }
         }
+
         return $r;
     }
 
     /**
-    * add a string to the 'internal debug message' (separate from 'user debug message')
-    * @param string $string
-    */
+     * add a string to the 'internal debug message' (separate from 'user debug message').
+     *
+     * @param string $string
+     */
     protected function debugmsg($string)
     {
-        $this->debug_info .= $string."\n";
+        $this->debug_info .= $string . "\n";
     }
 
-    protected function xml_header($charset_encoding='')
+    protected function xml_header($charset_encoding = '')
     {
-        if ($charset_encoding != '')
-        {
+        if ($charset_encoding != '') {
             return "\n";
-        }
-        else
-        {
+        } else {
             return "\n";
         }
     }
 
     /**
-    * A debugging routine: just echoes back the input packet as a string value
-    * DEPRECATED!
-    */
-    function echoInput()
+     * A debugging routine: just echoes back the input packet as a string value
+     * DEPRECATED!
+     */
+    public function echoInput()
     {
-        $r=new Response(new Value( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
+        $r = new Response(new Value("'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
         print $r->serialize();
     }
 
@@ -847,203 +745,168 @@ public function getSystemDispatchMap()
                 'function' => 'PhpXmlRpc\Server::_xmlrpcs_getCapabilities',
                 'signature' => array(array(Value::$xmlrpcStruct)),
                 'docstring' => 'This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to',
-                'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec'))
-            )
+                'signature_docs' => array(array('list of capabilities, described as structs with a version number and url for the spec')),
+            ),
         );
     }
 
-    public static function _xmlrpcs_getCapabilities($server, $m=null)
+    public static function _xmlrpcs_getCapabilities($server, $m = null)
     {
         $outAr = array(
             // xmlrpc spec: always supported
             'xmlrpc' => new Value(array(
                 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'),
-                'specVersion' => new Value(1, 'int')
+                'specVersion' => new Value(1, 'int'),
             ), 'struct'),
             // if we support system.xxx functions, we always support multicall, too...
             // Note that, as of 2006/09/17, the following URL does not respond anymore
             'system.multicall' => new Value(array(
                 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
-                'specVersion' => new Value(1, 'int')
+                'specVersion' => new Value(1, 'int'),
             ), 'struct'),
             // introspection: version 2! we support 'mixed', too
             'introspection' => new Value(array(
                 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
-                'specVersion' => new Value(2, 'int')
-            ), 'struct')
+                'specVersion' => new Value(2, 'int'),
+            ), 'struct'),
         );
 
         // NIL extension
         if (PhpXmlRpc::$xmlrpc_null_extension) {
             $outAr['nil'] = new Value(array(
                 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
-                'specVersion' => new Value(1, 'int')
+                'specVersion' => new Value(1, 'int'),
             ), 'struct');
         }
+
         return new Response(new Value($outAr, 'struct'));
     }
 
-    public static function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
+    public static function _xmlrpcs_listMethods($server, $m = null) // if called in plain php values mode, second param is missing
     {
-
-        $outAr=array();
-        foreach($server->dmap as $key => $val)
-        {
-            $outAr[]=new Value($key, 'string');
+        $outAr = array();
+        foreach ($server->dmap as $key => $val) {
+            $outAr[] = new Value($key, 'string');
         }
-        if($server->allow_system_funcs)
-        {
-            foreach($server->getSystemDispatchMap() as $key => $val)
-            {
-                $outAr[]=new Value($key, 'string');
+        if ($server->allow_system_funcs) {
+            foreach ($server->getSystemDispatchMap() as $key => $val) {
+                $outAr[] = new Value($key, 'string');
             }
         }
+
         return new Response(new Value($outAr, 'array'));
     }
 
     public static function _xmlrpcs_methodSignature($server, $m)
     {
         // let accept as parameter both an xmlrpcval or string
-        if (is_object($m))
-        {
-            $methName=$m->getParam(0);
-            $methName=$methName->scalarval();
-        }
-        else
-        {
-            $methName=$m;
-        }
-        if(strpos($methName, "system.") === 0)
-        {
-            $dmap=$server->getSystemDispatchMap();
-        }
-        else
-        {
-            $dmap=$server->dmap;
-        }
-        if(isset($dmap[$methName]))
-        {
-            if(isset($dmap[$methName]['signature']))
-            {
-                $sigs=array();
-                foreach($dmap[$methName]['signature'] as $inSig)
-                {
-                    $cursig=array();
-                    foreach($inSig as $sig)
-                    {
-                        $cursig[]=new Value($sig, 'string');
+        if (is_object($m)) {
+            $methName = $m->getParam(0);
+            $methName = $methName->scalarval();
+        } else {
+            $methName = $m;
+        }
+        if (strpos($methName, "system.") === 0) {
+            $dmap = $server->getSystemDispatchMap();
+        } else {
+            $dmap = $server->dmap;
+        }
+        if (isset($dmap[$methName])) {
+            if (isset($dmap[$methName]['signature'])) {
+                $sigs = array();
+                foreach ($dmap[$methName]['signature'] as $inSig) {
+                    $cursig = array();
+                    foreach ($inSig as $sig) {
+                        $cursig[] = new Value($sig, 'string');
                     }
-                    $sigs[]=new Value($cursig, 'array');
+                    $sigs[] = new Value($cursig, 'array');
                 }
-                $r=new Response(new Value($sigs, 'array'));
-            }
-            else
-            {
+                $r = new Response(new Value($sigs, 'array'));
+            } else {
                 // NB: according to the official docs, we should be returning a
                 // "none-array" here, which means not-an-array
-                $r=new Response(new Value('undef', 'string'));
+                $r = new Response(new Value('undef', 'string'));
             }
+        } else {
+            $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
         }
-        else
-        {
-            $r=new Response(0,PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
-        }
+
         return $r;
     }
 
     public static function _xmlrpcs_methodHelp($server, $m)
     {
         // let accept as parameter both an xmlrpcval or string
-        if (is_object($m))
-        {
-            $methName=$m->getParam(0);
-            $methName=$methName->scalarval();
-        }
-        else
-        {
-            $methName=$m;
-        }
-        if(strpos($methName, "system.") === 0)
-        {
-            $dmap=$server->getSystemDispatchMap();
-        }
-        else
-        {
-            $dmap=$server->dmap;
-        }
-        if(isset($dmap[$methName]))
-        {
-            if(isset($dmap[$methName]['docstring']))
-            {
-                $r=new Response(new Value($dmap[$methName]['docstring']), 'string');
-            }
-            else
-            {
-                $r=new Response(new Value('', 'string'));
-            }
+        if (is_object($m)) {
+            $methName = $m->getParam(0);
+            $methName = $methName->scalarval();
+        } else {
+            $methName = $m;
+        }
+        if (strpos($methName, "system.") === 0) {
+            $dmap = $server->getSystemDispatchMap();
+        } else {
+            $dmap = $server->dmap;
         }
-        else
-        {
-            $r=new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
+        if (isset($dmap[$methName])) {
+            if (isset($dmap[$methName]['docstring'])) {
+                $r = new Response(new Value($dmap[$methName]['docstring']), 'string');
+            } else {
+                $r = new Response(new Value('', 'string'));
+            }
+        } else {
+            $r = new Response(0, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
         }
+
         return $r;
     }
 
     public static function _xmlrpcs_multicall_error($err)
     {
-        if(is_string($err))
-        {
+        if (is_string($err)) {
             $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
             $code = PhpXmlRpc::$xmlrpcerr["multicall_${err}"];
-        }
-        else
-        {
+        } else {
             $code = $err->faultCode();
             $str = $err->faultString();
         }
         $struct = array();
         $struct['faultCode'] = new Value($code, 'int');
         $struct['faultString'] = new Value($str, 'string');
+
         return new Value($struct, 'struct');
     }
 
     public static function _xmlrpcs_multicall_do_call($server, $call)
     {
-        if($call->kindOf() != 'struct')
-        {
+        if ($call->kindOf() != 'struct') {
             return static::_xmlrpcs_multicall_error('notstruct');
         }
         $methName = @$call->structmem('methodName');
-        if(!$methName)
-        {
+        if (!$methName) {
             return static::_xmlrpcs_multicall_error('nomethod');
         }
-        if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string')
-        {
+        if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') {
             return static::_xmlrpcs_multicall_error('notstring');
         }
-        if($methName->scalarval() == 'system.multicall')
-        {
+        if ($methName->scalarval() == 'system.multicall') {
             return static::_xmlrpcs_multicall_error('recursion');
         }
 
         $params = @$call->structmem('params');
-        if(!$params)
-        {
+        if (!$params) {
             return static::_xmlrpcs_multicall_error('noparams');
         }
-        if($params->kindOf() != 'array')
-        {
+        if ($params->kindOf() != 'array') {
             return static::_xmlrpcs_multicall_error('notarray');
         }
         $numParams = $params->arraysize();
 
         $msg = new Request($methName->scalarval());
-        for($i = 0; $i < $numParams; $i++)
-        {
-            if(!$msg->addParam($params->arraymem($i)))
-            {
+        for ($i = 0; $i < $numParams; $i++) {
+            if (!$msg->addParam($params->arraymem($i))) {
                 $i++;
+
                 return static::_xmlrpcs_multicall_error(new Response(0,
                     PhpXmlRpc::$xmlrpcerr['incorrect_params'],
                     PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
@@ -1052,8 +915,7 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
 
         $result = $server->execute($msg);
 
-        if($result->faultCode() != 0)
-        {
+        if ($result->faultCode() != 0) {
             return static::_xmlrpcs_multicall_error($result); // Method returned fault.
         }
 
@@ -1062,28 +924,22 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
 
     public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
     {
-        if(!is_array($call))
-        {
+        if (!is_array($call)) {
             return static::_xmlrpcs_multicall_error('notstruct');
         }
-        if(!array_key_exists('methodName', $call))
-        {
+        if (!array_key_exists('methodName', $call)) {
             return static::_xmlrpcs_multicall_error('nomethod');
         }
-        if (!is_string($call['methodName']))
-        {
+        if (!is_string($call['methodName'])) {
             return static::_xmlrpcs_multicall_error('notstring');
         }
-        if($call['methodName'] == 'system.multicall')
-        {
+        if ($call['methodName'] == 'system.multicall') {
             return static::_xmlrpcs_multicall_error('recursion');
         }
-        if(!array_key_exists('params', $call))
-        {
+        if (!array_key_exists('params', $call)) {
             return static::_xmlrpcs_multicall_error('noparams');
         }
-        if(!is_array($call['params']))
-        {
+        if (!is_array($call['params'])) {
             return static::_xmlrpcs_multicall_error('notarray');
         }
 
@@ -1091,13 +947,13 @@ public static function _xmlrpcs_multicall_do_call_phpvals($server, $call)
         // base64 or datetime values, but they will be listed as strings here...
         $numParams = count($call['params']);
         $pt = array();
-        foreach($call['params'] as $val)
+        foreach ($call['params'] as $val) {
             $pt[] = php_2_xmlrpc_type(gettype($val));
+        }
 
         $result = $server->execute($call['methodName'], $call['params'], $pt);
 
-        if($result->faultCode() != 0)
-        {
+        if ($result->faultCode() != 0) {
             return static::_xmlrpcs_multicall_error($result); // Method returned fault.
         }
 
@@ -1108,21 +964,16 @@ public static function _xmlrpcs_multicall($server, $m)
     {
         $result = array();
         // let accept a plain list of php parameters, beside a single xmlrpc msg object
-        if (is_object($m))
-        {
+        if (is_object($m)) {
             $calls = $m->getParam(0);
             $numCalls = $calls->arraysize();
-            for($i = 0; $i < $numCalls; $i++)
-            {
+            for ($i = 0; $i < $numCalls; $i++) {
                 $call = $calls->arraymem($i);
                 $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call);
             }
-        }
-        else
-        {
-            $numCalls=count($m);
-            for($i = 0; $i < $numCalls; $i++)
-            {
+        } else {
+            $numCalls = count($m);
+            for ($i = 0; $i < $numCalls; $i++) {
                 $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);
             }
         }
@@ -1137,46 +988,36 @@ public static function _xmlrpcs_multicall($server, $m)
      * that a PHP execution error on the server generally entails.
      *
      * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
-     *
      */
-    public static function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)
+    public static function _xmlrpcs_errorHandler($errcode, $errstring, $filename = null, $lineno = null, $context = null)
     {
         // obey the @ protocol
-        if (error_reporting() == 0)
+        if (error_reporting() == 0) {
             return;
+        }
 
         //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)
-        if($errcode != E_STRICT)
-        {
+        if ($errcode != E_STRICT) {
             \PhpXmlRpc\Server::error_occurred($errstring);
         }
         // Try to avoid as much as possible disruption to the previous error handling
         // mechanism in place
-        if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')
-        {
+        if ($GLOBALS['_xmlrpcs_prev_ehandler'] == '') {
             // The previous error handler was the default: all we should do is log error
             // to the default error log (if level high enough)
-            if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))
-            {
+            if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) {
                 error_log($errstring);
             }
-        }
-        else
-        {
+        } else {
             // Pass control on to previous error handler, trying to avoid loops...
-            if($GLOBALS['_xmlrpcs_prev_ehandler'] != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'))
-            {
-                if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))
-                {
+            if ($GLOBALS['_xmlrpcs_prev_ehandler'] != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) {
+                if (is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) {
                     // the following works both with static class methods and plain object methods as error handler
                     call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context));
-                }
-                else
-                {
+                } else {
                     $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);
                 }
             }
         }
     }
-
 }
diff --git a/src/Value.php b/src/Value.php
index 04df2ebf..76d3a029 100644
--- a/src/Value.php
+++ b/src/Value.php
@@ -28,29 +28,28 @@ class Value
         "base64" => 1,
         "array" => 2,
         "struct" => 3,
-        "null" => 1
-        );
+        "null" => 1,
+    );
 
     /// @todo: does these need to be public?
-    public $me=array();
-    public $mytype=0;
-    public $_php_class=null;
+    public $me = array();
+    public $mytype = 0;
+    public $_php_class = null;
 
     /**
-      * @param mixed $val
-      * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
-      */
-    function __construct($val=-1, $type='') {
+     * @param mixed $val
+     * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
+     */
+    public function __construct($val = -1, $type = '')
+    {
         /// @todo: optimization creep - do not call addXX, do it all inline.
         /// downside: booleans will not be coerced anymore
-        if($val!==-1 || $type!='')
-        {
+        if ($val !== -1 || $type != '') {
             // optimization creep: inlined all work done by constructor
-            switch($type)
-            {
+            switch ($type) {
                 case '':
-                    $this->mytype=1;
-                    $this->me['string']=$val;
+                    $this->mytype = 1;
+                    $this->me['string'] = $val;
                     break;
                 case 'i4':
                 case 'int':
@@ -60,19 +59,19 @@ function __construct($val=-1, $type='') {
                 case 'dateTime.iso8601':
                 case 'base64':
                 case 'null':
-                    $this->mytype=1;
-                    $this->me[$type]=$val;
+                    $this->mytype = 1;
+                    $this->me[$type] = $val;
                     break;
                 case 'array':
-                    $this->mytype=2;
-                    $this->me['array']=$val;
+                    $this->mytype = 2;
+                    $this->me['array'] = $val;
                     break;
                 case 'struct':
-                    $this->mytype=3;
-                    $this->me['struct']=$val;
+                    $this->mytype = 3;
+                    $this->me['struct'] = $val;
                     break;
                 default:
-                    error_log("XML-RPC: ".__METHOD__.": not a known type ($type)");
+                    error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
             }
             /*if($type=='')
             {
@@ -94,46 +93,45 @@ function __construct($val=-1, $type='') {
     }
 
     /**
-      * Add a single php value to an (unitialized) xmlrpcval
-      * @param mixed $val
-      * @param string $type
-      * @return int 1 or 0 on failure
-      */
-    function addScalar($val, $type='string')
+     * Add a single php value to an (unitialized) xmlrpcval.
+     *
+     * @param mixed $val
+     * @param string $type
+     *
+     * @return int 1 or 0 on failure
+     */
+    public function addScalar($val, $type = 'string')
     {
         $typeof = null;
-        if(isset(static::$xmlrpcTypes[$type])) {
+        if (isset(static::$xmlrpcTypes[$type])) {
             $typeof = static::$xmlrpcTypes[$type];
         }
 
-        if($typeof!=1)
-        {
-            error_log("XML-RPC: ".__METHOD__.": not a scalar type ($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 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;
+        if ($type == static::$xmlrpcBoolean) {
+            if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
+                $val = true;
+            } else {
+                $val = false;
             }
         }
 
-        switch($this->mytype)
-        {
+        switch ($this->mytype) {
             case 1:
-                error_log('XML-RPC: '.__METHOD__.': scalar xmlrpc value can have only one value');
+                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');
+                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
@@ -141,80 +139,82 @@ function addScalar($val, $type='string')
                 //$ar[]=new Value($val, $type);
                 //$this->me['array']=$ar;
                 // Faster (?) avoid all the costly array-copy-by-val done here...
-                $this->me['array'][]=new Value($val, $type);
+                $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;
+                $this->me[$type] = $val;
+                $this->mytype = $typeof;
+
                 return 1;
         }
     }
 
     /**
-      * Add an array of xmlrpcval objects to an xmlrpcval
-      * @param array $vals
-      * @return int 1 or 0 on failure
-      *
-      * @todo add some checking for $vals to be an array of xmlrpcvals?
-      */
+     * Add an array of xmlrpcval objects to an xmlrpcval.
+     *
+     * @param array $vals
+     *
+     * @return int 1 or 0 on failure
+     *
+     * @todo add some checking for $vals to be an array of xmlrpcvals?
+     */
     public function addArray($vals)
     {
-        if($this->mytype==0)
-        {
-            $this->mytype=static::$xmlrpcTypes['array'];
-            $this->me['array']=$vals;
+        if ($this->mytype == 0) {
+            $this->mytype = static::$xmlrpcTypes['array'];
+            $this->me['array'] = $vals;
+
             return 1;
-        }
-        elseif($this->mytype==2)
-        {
+        } elseif ($this->mytype == 2) {
             // we're adding to an array here
             $this->me['array'] = array_merge($this->me['array'], $vals);
+
             return 1;
-        }
-        else
-        {
-            error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');
+        } else {
+            error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
+
             return 0;
         }
     }
 
     /**
-     * Add an array of named xmlrpcval objects to an xmlrpcval
+     * Add an array of named xmlrpcval objects to an xmlrpcval.
+     *
      * @param array $vals
+     *
      * @return int 1 or 0 on failure
      *
      * @todo add some checking for $vals to be an array?
      */
     public function addStruct($vals)
     {
-        if($this->mytype==0)
-        {
-            $this->mytype=static::$xmlrpcTypes['struct'];
-            $this->me['struct']=$vals;
+        if ($this->mytype == 0) {
+            $this->mytype = static::$xmlrpcTypes['struct'];
+            $this->me['struct'] = $vals;
+
             return 1;
-        }
-        elseif($this->mytype==3)
-        {
+        } elseif ($this->mytype == 3) {
             // we're adding to a struct here
             $this->me['struct'] = array_merge($this->me['struct'], $vals);
+
             return 1;
-        }
-        else
-        {
-            error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');
+        } else {
+            error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
+
             return 0;
         }
     }
 
     /**
-     * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
+     * Returns a string containing "struct", "array" or "scalar" describing the base type of the value.
+     *
      * @return string
      */
     public function kindOf()
     {
-        switch($this->mytype)
-        {
+        switch ($this->mytype) {
             case 3:
                 return 'struct';
                 break;
@@ -229,33 +229,31 @@ public function kindOf()
         }
     }
 
-    private function serializedata($typ, $val, $charset_encoding='')
+    private function serializedata($typ, $val, $charset_encoding = '')
     {
-        $rs='';
+        $rs = '';
 
-        if(!isset(static::$xmlrpcTypes[$typ])) {
+        if (!isset(static::$xmlrpcTypes[$typ])) {
             return $rs;
         }
 
-        switch(static::$xmlrpcTypes[$typ])
-        {
+        switch (static::$xmlrpcTypes[$typ]) {
             case 1:
-                switch($typ)
-                {
+                switch ($typ) {
                     case static::$xmlrpcBase64:
-                        $rs.="<${typ}>" . base64_encode($val) . "";
+                        $rs .= "<${typ}>" . base64_encode($val) . "";
                         break;
                     case static::$xmlrpcBoolean:
-                        $rs.="<${typ}>" . ($val ? '1' : '0') . "";
+                        $rs .= "<${typ}>" . ($val ? '1' : '0') . "";
                         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()->encode_entities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding). "";
+                        $rs .= "<${typ}>" . Charset::instance()->encode_entities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "";
                         break;
                     case static::$xmlrpcInt:
                     case static::$xmlrpcI4:
-                        $rs.="<${typ}>".(int)$val."";
+                        $rs .= "<${typ}>" . (int)$val . "";
                         break;
                     case static::$xmlrpcDouble:
                         // avoid using standard conversion of float to string because it is locale-dependent,
@@ -263,112 +261,104 @@ private function serializedata($typ, $val, $charset_encoding='')
                         // 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, '.', ''))."";
+                        $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "";
                         break;
                     case static::$xmlrpcDateTime:
-                        if (is_string($val))
-                        {
-                            $rs.="<${typ}>${val}";
-                        }
-                        else if(is_a($val, 'DateTime'))
-                        {
-                            $rs.="<${typ}>".$val->format('Ymd\TH:i:s')."";
-                        }
-                        else if(is_int($val))
-                        {
-                            $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val)."";
-                        }
-                        else
-                        {
+                        if (is_string($val)) {
+                            $rs .= "<${typ}>${val}";
+                        } elseif (is_a($val, 'DateTime')) {
+                            $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "";
+                        } elseif (is_int($val)) {
+                            $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "";
+                        } else {
                             // not really a good idea here: but what shall we output anyway? left for backward compat...
-                            $rs.="<${typ}>${val}";
+                            $rs .= "<${typ}>${val}";
                         }
                         break;
                     case static::$xmlrpcNull:
-                        if (PhpXmlRpc::$xmlrpc_null_apache_encoding)
-                        {
-                            $rs.="";
-                        }
-                        else
-                        {
-                            $rs.="";
+                        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
+                            $rs .= "";
+                        } else {
+                            $rs .= "";
                         }
                         break;
                     default:
                         // no standard type value should arrive here, but provide a possibility
                         // for xmlrpcvals of unknown type...
-                        $rs.="<${typ}>${val}";
+                        $rs .= "<${typ}>${val}";
                 }
                 break;
             case 3:
                 // struct
-                if ($this->_php_class)
-                {
-                    $rs.='\n";
-                }
-                else
-                {
-                    $rs.="\n";
+                if ($this->_php_class) {
+                    $rs .= '\n";
+                } else {
+                    $rs .= "\n";
                 }
                 $charsetEncoder = Charset::instance();
-                foreach($val as $key2 => $val2)
-                {
-                    $rs.=''.$charsetEncoder->encode_entities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding)."\n";
+                foreach ($val as $key2 => $val2) {
+                    $rs .= '' . $charsetEncoder->encode_entities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n";
                     //$rs.=$this->serializeval($val2);
-                    $rs.=$val2->serialize($charset_encoding);
-                    $rs.="\n";
+                    $rs .= $val2->serialize($charset_encoding);
+                    $rs .= "\n";
                 }
-                $rs.='';
+                $rs .= '';
                 break;
             case 2:
                 // array
-                $rs.="\n\n";
-                foreach($val as $element)
-                {
+                $rs .= "\n\n";
+                foreach ($val as $element) {
                     //$rs.=$this->serializeval($val[$i]);
-                    $rs.=$element->serialize($charset_encoding);
+                    $rs .= $element->serialize($charset_encoding);
                 }
-                $rs.="\n";
+                $rs .= "\n";
                 break;
             default:
                 break;
         }
+
         return $rs;
     }
 
     /**
-     * Returns xml representation of the value. XML prologue not included
+     * Returns xml representation of the value. XML prologue not included.
+     *
      * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
+     *
      * @return string
      */
-    public function serialize($charset_encoding='')
+    public function serialize($charset_encoding = '')
     {
         // 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')))
         //{
-            reset($this->me);
-            list($typ, $val) = each($this->me);
-            return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n";
+        reset($this->me);
+        list($typ, $val) = each($this->me);
+
+        return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n";
         //}
     }
 
     // DEPRECATED
-    function serializeval($o)
+    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 '' . $this->serializedata($typ, $val) . "\n";
+        $ar = $o->me;
+        reset($ar);
+        list($typ, $val) = each($ar);
+
+        return '' . $this->serializedata($typ, $val) . "\n";
         //}
     }
 
     /**
      * Checks whether a struct member with a given name is present.
      * Works only on xmlrpcvals of type struct.
+     *
      * @param string $m the name of the struct member to be looked up
+     *
      * @return boolean
      */
     public function structmemexists($m)
@@ -378,8 +368,10 @@ public function structmemexists($m)
 
     /**
      * Returns the value of a given struct member (an xmlrpcval object in itself).
-     * Will raise a php warning if struct member of given name does not exist
+     * Will raise a php warning if struct member of given name does not exist.
+     *
      * @param string $m the name of the struct member to be looked up
+     *
      * @return xmlrpcval
      */
     public function structmem($m)
@@ -397,6 +389,7 @@ public function structreset()
 
     /**
      * Return next member element for xmlrpcvals of type struct.
+     *
      * @return xmlrpcval
      */
     public function structeach()
@@ -406,37 +399,32 @@ public function structeach()
 
     // 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?
-    function getval()
+    public function getval()
     {
         // UNSTABLE
         reset($this->me);
-        list($a,$b)=each($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))
-        {
+        if (is_array($b)) {
             @reset($b);
-            while(list($id,$cont) = @each($b))
-            {
+            while (list($id, $cont) = @each($b)) {
                 $b[$id] = $cont->scalarval();
             }
         }
 
         // add support for structures directly encoding php objects
-        if(is_object($b))
-        {
+        if (is_object($b)) {
             $t = get_object_vars($b);
             @reset($t);
-            while(list($id,$cont) = @each($t))
-            {
+            while (list($id, $cont) = @each($t)) {
                 $t[$id] = $cont->scalarval();
             }
             @reset($t);
-            while(list($id,$cont) = @each($t))
-            {
+            while (list($id, $cont) = @each($t)) {
                 @$b->$id = $cont;
             }
         }
@@ -445,35 +433,40 @@ function getval()
     }
 
     /**
-     * Returns the value of a scalar xmlrpcval
+     * Returns the value of a scalar xmlrpcval.
+     *
      * @return mixed
      */
     public function scalarval()
     {
         reset($this->me);
-        list(,$b)=each($this->me);
+        list(, $b) = each($this->me);
+
         return $b;
     }
 
     /**
      * Returns the type of the xmlrpcval.
-     * For integers, 'int' is always returned in place of 'i4'
+     * For integers, 'int' is always returned in place of 'i4'.
+     *
      * @return string
      */
     public function scalartyp()
     {
         reset($this->me);
-        list($a,)=each($this->me);
-        if($a==static::$xmlrpcI4)
-        {
-            $a=static::$xmlrpcInt;
+        list($a,) = each($this->me);
+        if ($a == static::$xmlrpcI4) {
+            $a = static::$xmlrpcInt;
         }
+
         return $a;
     }
 
     /**
-     * Returns the m-th member of an xmlrpcval of struct type
+     * Returns the m-th member of an xmlrpcval of struct type.
+     *
      * @param integer $m the index of the value to be retrieved (zero based)
+     *
      * @return xmlrpcval
      */
     public function arraymem($m)
@@ -482,7 +475,8 @@ public function arraymem($m)
     }
 
     /**
-     * Returns the number of members in an xmlrpcval of array type
+     * Returns the number of members in an xmlrpcval of array type.
+     *
      * @return integer
      */
     public function arraysize()
@@ -491,7 +485,8 @@ public function arraysize()
     }
 
     /**
-     * Returns the number of members in an xmlrpcval of struct type
+     * Returns the number of members in an xmlrpcval of struct type.
+     *
      * @return integer
      */
     public function structsize()
diff --git a/src/Wrapper.php b/src/Wrapper.php
index 3b7addd2..dc40e391 100644
--- a/src/Wrapper.php
+++ b/src/Wrapper.php
@@ -19,20 +19,20 @@
  */
 class Wrapper
 {
-
     /**
-    * 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
-    * for php arrays always return array, even though arrays sometimes serialize as json structs
-    * @param string $phptype
-    * @return string
-    */
+     * 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
+     * for php arrays always return array, even though arrays sometimes serialize as json structs.
+     *
+     * @param string $phptype
+     *
+     * @return string
+     */
     public function php_2_xmlrpc_type($phptype)
     {
-        switch(strtolower($phptype))
-        {
+        switch (strtolower($phptype)) {
             case 'string':
                 return Value::$xmlrpcString;
             case 'integer':
@@ -53,12 +53,9 @@ public function php_2_xmlrpc_type($phptype)
             case 'resource':
                 return '';
             default:
-                if(class_exists($phptype))
-                {
+                if (class_exists($phptype)) {
                     return Value::$xmlrpcStruct;
-                }
-                else
-                {
+                } else {
                     // unknown: might be any 'extended' xmlrpc type
                     return Value::$xmlrpcValue;
                 }
@@ -66,14 +63,15 @@ public function php_2_xmlrpc_type($phptype)
     }
 
     /**
-    * Given a string defining a phpxmlrpc type return corresponding php type.
-    * @param string $xmlrpctype
-    * @return string
-    */
+     * Given a string defining a phpxmlrpc type return corresponding php type.
+     *
+     * @param string $xmlrpctype
+     *
+     * @return string
+     */
     public function xmlrpc_2_php_type($xmlrpctype)
     {
-        switch(strtolower($xmlrpctype))
-        {
+        switch (strtolower($xmlrpctype)) {
             case 'base64':
             case 'datetime.iso8601':
             case 'string':
@@ -97,54 +95,55 @@ public function xmlrpc_2_php_type($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:
-    * - 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 Request 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') and array('class', 'methodname') are ok too
-    * @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 returning an empty string value...
-    * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
-    * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
-    * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
-    */
-    public function wrap_php_function($funcname, $newfuncname='', $extra_options=array())
+     * 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:
+     * - 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 Request 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') and array('class', 'methodname') are ok too
+     * @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 returning an empty string value...
+     * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
+     * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
+     * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
+     */
+    public 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';
@@ -153,104 +152,86 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
         $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
 
         $exists = false;
-        if (is_string($funcname) && strpos($funcname, '::') !== false)
-        {
+        if (is_string($funcname) && strpos($funcname, '::') !== false) {
             $funcname = explode('::', $funcname);
         }
-        if(is_array($funcname))
-        {
-            if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0])))
-            {
+        if (is_array($funcname)) {
+            if (count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) {
                 error_log('XML-RPC: syntax for function to be wrapped is wrong');
+
                 return false;
             }
-            if(is_string($funcname[0]))
-            {
+            if (is_string($funcname[0])) {
                 $plainfuncname = implode('::', $funcname);
-            }
-            elseif(is_object($funcname[0]))
-            {
+            } elseif (is_object($funcname[0])) {
                 $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
             }
             $exists = method_exists($funcname[0], $funcname[1]);
-        }
-        else
-        {
+        } else {
             $plainfuncname = $funcname;
             $exists = function_exists($funcname);
         }
 
-        if(!$exists)
-        {
-            error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname);
+        if (!$exists) {
+            error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname);
+
             return false;
-        }
-        else
-        {
+        } else {
             // determine name of new php function
-            if($newfuncname == '')
-            {
-                if(is_array($funcname))
-                {
-                    if(is_string($funcname[0]))
-                        $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);
-                    else
-                        $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1];
-                }
-                else
-                {
+            if ($newfuncname == '') {
+                if (is_array($funcname)) {
+                    if (is_string($funcname[0])) {
+                        $xmlrpcfuncname = "{$prefix}_" . implode('_', $funcname);
+                    } else {
+                        $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1];
+                    }
+                } else {
                     $xmlrpcfuncname = "{$prefix}_$funcname";
                 }
-            }
-            else
-            {
+            } else {
                 $xmlrpcfuncname = $newfuncname;
             }
-            while($buildit && function_exists($xmlrpcfuncname))
-            {
+            while ($buildit && function_exists($xmlrpcfuncname)) {
                 $xmlrpcfuncname .= 'x';
             }
 
             // start to introspect PHP code
-            if(is_array($funcname))
-            {
+            if (is_array($funcname)) {
                 $func = new \ReflectionMethod($funcname[0], $funcname[1]);
-                if($func->isPrivate())
-                {
-                    error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname);
+                if ($func->isPrivate()) {
+                    error_log('XML-RPC: method to be wrapped is private: ' . $plainfuncname);
+
                     return false;
                 }
-                if($func->isProtected())
-                {
-                    error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname);
+                if ($func->isProtected()) {
+                    error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname);
+
                     return false;
                 }
-                if($func->isConstructor())
-                {
-                    error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname);
+                if ($func->isConstructor()) {
+                    error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname);
+
                     return false;
                 }
-                if($func->isDestructor())
-                {
-                    error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname);
+                if ($func->isDestructor()) {
+                    error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname);
+
                     return false;
                 }
-                if($func->isAbstract())
-                {
-                    error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname);
+                if ($func->isAbstract()) {
+                    error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname);
+
                     return false;
                 }
                 /// @todo add more checks for static vs. nonstatic?
-            }
-            else
-            {
+            } else {
                 $func = new \ReflectionFunction($funcname);
             }
-            if($func->isInternal())
-            {
+            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: '.$plainfuncname);
+                error_log('XML-RPC: function to be wrapped is internal: ' . $plainfuncname);
+
                 return false;
             }
 
@@ -266,49 +247,35 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
             $paramDocs = array();
 
             $docs = $func->getDocComment();
-            if($docs != '')
-            {
+            if ($docs != '') {
                 $docs = explode("\n", $docs);
                 $i = 0;
-                foreach($docs as $doc)
-                {
+                foreach ($docs as $doc) {
                     $doc = trim($doc, " \r\t/*");
-                    if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)
-                    {
-                        if($desc)
-                        {
+                    if (strlen($doc) && strpos($doc, '@') !== 0 && !$i) {
+                        if ($desc) {
                             $desc .= "\n";
                         }
                         $desc .= $doc;
-                    }
-                    elseif(strpos($doc, '@param') === 0)
-                    {
+                    } 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], '|'))
-                            {
+                        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
-                            {
+                            } else {
                                 $paramDocs[$i]['type'] = $matches[1];
                             }
                             $paramDocs[$i]['name'] = trim($matches[2]);
                             $paramDocs[$i]['doc'] = $matches[3];
                         }
                         $i++;
-                    }
-                    elseif(strpos($doc, '@return') === 0)
-                    {
+                    } elseif (strpos($doc, '@return') === 0) {
                         // syntax: @return type desc
                         //$returns = preg_split('/\s+/', $doc);
-                        if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))
-                        {
+                        if (preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches)) {
                             $returns = php_2_xmlrpc_type($matches[1]);
-                            if(isset($matches[2]))
-                            {
+                            if (isset($matches[2])) {
                                 $returnsDocs = $matches[2];
                             }
                         }
@@ -319,53 +286,43 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
             // execute introspection of actual function prototype
             $params = array();
             $i = 0;
-            foreach($func->getParameters() as $paramobj)
-            {
+            foreach ($func->getParameters() as $paramobj) {
                 $params[$i] = array();
-                $params[$i]['name'] = '$'.$paramobj->getName();
+                $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']))
-                {
+            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'])
-                {
+                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)
-                {
+                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
-                {
+                } 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'])
-                {
+                if ($param['isoptional']) {
                     $innercode .= "}\n";
                 }
-                if($i == $pnum)
-                {
+                if ($i == $pnum) {
                     // last allowed parameters combination
                     $parsvariations[] = $pars;
                 }
@@ -373,56 +330,42 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
 
             $sigs = array();
             $psigs = array();
-            if(count($parsvariations) == 0)
-            {
+            if (count($parsvariations) == 0) {
                 // only known good synopsis = no parameters
                 $parsvariations[] = array();
                 $minpars = 0;
-            }
-            else
-            {
+            } else {
                 $minpars = count($parsvariations[0]);
             }
 
-            if($minpars)
-            {
+            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, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."');\n" . $innercode;
-            }
-            else
-            {
+                    "if (\$paramcount < $minpars) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode;
+            } else {
                 $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
             }
 
             $innercode .= "\$np = false;\n";
             // since there are no closures in php, if we are given an object instance,
             // we store a pointer to it in a global var...
-            if ( is_array($funcname) && is_object($funcname[0]) )
-            {
-                $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0];
+            if (is_array($funcname) && is_object($funcname[0])) {
+                $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] = &$funcname[0];
                 $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
-                $realfuncname = '$obj->'.$funcname[1];
-            }
-            else
-            {
+                $realfuncname = '$obj->' . $funcname[1];
+            } else {
                 $realfuncname = $plainfuncname;
             }
-            foreach($parsvariations as $pars)
-            {
+            foreach ($parsvariations as $pars) {
                 $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . 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']))
-                    {
+                for ($i = 0; $i < count($pars); $i++) {
+                    if (isset($paramDocs[$i]['type'])) {
                         $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']);
-                    }
-                    else
-                    {
+                    } else {
                         $sig[] = Value::$xmlrpcValue;
                     }
                     $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
@@ -431,35 +374,32 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
                 $psigs[] = $psig;
             }
             $innercode .= "\$np = true;\n";
-            $innercode .= "if (\$np) return new {$prefix}resp(0, ".PhpXmlRpc::$xmlrpcerr['incorrect_params'].", '".PhpXmlRpc::$xmlrpcerr['incorrect_params']."'); else {\n";
+            $innercode .= "if (\$np) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n";
             //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
             $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
-            if($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64)
-            {
+            if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) {
                 $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
-            }
-            else
-            {
-                if ($encode_php_objects)
+            } else {
+                if ($encode_php_objects) {
                     $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
-                else
+                } 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)
-            {
+            if ($buildit) {
                 $allOK = 0;
-                eval($code.'$allOK=1;');
+                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 '.$plainfuncname);
+                if (!$allOK) {
+                    error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname);
+
                     return false;
                 }
             }
@@ -468,101 +408,98 @@ public function wrap_php_function($funcname, $newfuncname='', $extra_options=arr
             /// 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 a user-defined PHP class or php object, map its methods onto a list of
-    * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
-    * object and called from remote clients (as well as their corresponding signature info).
-    *
-    * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
-    * @param array $extra_options see the docs for wrap_php_method for more options
-    *        string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
-    * @return array or false on failure
-    *
-    * @todo get_class_methods will return both static and non-static methods.
-    *       we have to differentiate the action, depending on wheter we recived a class name or object
-    */
-    public function wrap_php_class($classname, $extra_options=array())
+     * Given a user-defined PHP class or php object, map its methods onto a list of
+     * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
+     * object and called from remote clients (as well as their corresponding signature info).
+     *
+     * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
+     * @param array $extra_options see the docs for wrap_php_method for more options
+     *                             string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
+     *
+     * @return array or false on failure
+     *
+     * @todo get_class_methods will return both static and non-static methods.
+     *       we have to differentiate the action, depending on wheter we recived a class name or object
+     */
+    public function wrap_php_class($classname, $extra_options = array())
     {
         $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
         $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
 
         $result = array();
         $mlist = get_class_methods($classname);
-        foreach($mlist as $mname)
-        {
-            if ($methodfilter == '' || preg_match($methodfilter, $mname))
-            {
+        foreach ($mlist as $mname) {
+            if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
                 // echo $mlist."\n";
                 $func = new ReflectionMethod($classname, $mname);
-                if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract())
-                {
-                    if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
-                        (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))))
-                    {
+                if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
+                    if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
+                        (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))
+                    ) {
                         $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
-                        if ( $methodwrap )
-                        {
+                        if ($methodwrap) {
                             $result[$methodwrap['function']] = $methodwrap['function'];
                         }
                     }
                 }
             }
         }
+
         return $result;
     }
 
     /**
-    * 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 a Response
-    * object 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 principle 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 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 options 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 unspecified, 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 Response 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...
-    */
-    public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')
+     * 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 a Response
+     * object 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 principle 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 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 options 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 unspecified, 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 Response 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...
+     */
+    public 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 options) - we really love backward compat, don't we?
-        if (!is_array($extra_options))
-        {
+        if (!is_array($extra_options)) {
             $signum = $extra_options;
             $extra_options = array();
-        }
-        else
-        {
+        } 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'] : '';
@@ -578,59 +515,47 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $time
         $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']))
-        {
+        if (isset($extra_options['return_on_fault'])) {
             $decode_fault = true;
             $fault_response = $extra_options['return_on_fault'];
-        }
-        else
-        {
+        } 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';
+        $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);
+        if ($response->faultCode()) {
+            error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodname);
+
             return false;
-        }
-        else
-        {
+        } else {
             $msig = $response->value();
-            if ($client->return_type != 'phpvals')
-            {
+            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);
+            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
-            {
+            } else {
                 // pick a suitable name for the new function, avoiding collisions
-                if($newfuncname != '')
-                {
+                if ($newfuncname != '') {
                     $xmlrpcfuncname = $newfuncname;
-                }
-                else
-                {
+                } 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);
+                    $xmlrpcfuncname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
+                            array('_', ''), $methodname);
                 }
-                while($buildit && function_exists($xmlrpcfuncname))
-                {
+                while ($buildit && function_exists($xmlrpcfuncname)) {
                     $xmlrpcfuncname .= 'x';
                 }
 
@@ -638,16 +563,13 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $time
                 $mdesc = '';
                 // if in 'offline' mode, get method description too.
                 // in online mode, favour speed of operation
-                if(!$buildit)
-                {
+                if (!$buildit) {
                     $msg = new $msgclass('system.methodHelp');
                     $msg->addparam(new $valclass($methodname));
                     $response = $client->send($msg, $timeout, $protocol);
-                    if (!$response->faultCode())
-                    {
+                    if (!$response->faultCode()) {
                         $mdesc = $response->value();
-                        if ($client->return_type != 'phpvals')
-                        {
+                        if ($client->return_type != 'phpvals') {
                             $mdesc = $mdesc->scalarval();
                         }
                     }
@@ -659,25 +581,21 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $time
                     $fault_response);
 
                 //print_r($code);
-                if ($buildit)
-                {
+                if ($buildit) {
                     $allOK = 0;
-                    eval($results['source'].'$allOK=1;');
+                    eval($results['source'] . '$allOK=1;');
                     // alternative
                     //$xmlrpcfuncname = create_function('$m', $innercode);
-                    if($allOK)
-                    {
+                    if ($allOK) {
                         return $xmlrpcfuncname;
-                    }
-                    else
-                    {
-                        error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
+                    } else {
+                        error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname);
+
                         return false;
                     }
-                }
-                else
-                {
+                } else {
                     $results['function'] = $xmlrpcfuncname;
+
                     return $results;
                 }
             }
@@ -685,14 +603,16 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $time
     }
 
     /**
-    * 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 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)
-    */
-    public function wrap_xmlrpc_server($client, $extra_options=array())
+     * 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 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)
+     */
+    public 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;
@@ -705,43 +625,34 @@ public function wrap_xmlrpc_server($client, $extra_options=array())
         $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
         $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
 
-        $msgclass = $prefix.'msg';
+        $msgclass = $prefix . 'msg';
         //$valclass = $prefix.'val';
-        $decodefunc = 'php_'.$prefix.'_decode';
+        $decodefunc = 'php_' . $prefix . '_decode';
 
         $msg = new $msgclass('system.listMethods');
         $response = $client->send($msg, $timeout, $protocol);
-        if($response->faultCode())
-        {
+        if ($response->faultCode()) {
             error_log('XML-RPC: could not retrieve method list from remote server');
+
             return false;
-        }
-        else
-        {
+        } else {
             $mlist = $response->value();
-            if ($client->return_type != 'phpvals')
-            {
+            if ($client->return_type != 'phpvals') {
                 $mlist = $decodefunc($mlist);
             }
-            if(!is_array($mlist) || !count($mlist))
-            {
+            if (!is_array($mlist) || !count($mlist)) {
                 error_log('XML-RPC: could not retrieve meaningful method list from remote server');
+
                 return false;
-            }
-            else
-            {
+            } else {
                 // pick a suitable name for the new function, avoiding collisions
-                if($newclassname != '')
-                {
+                if ($newclassname != '') {
                     $xmlrpcclassname = $newclassname;
+                } else {
+                    $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
+                            array('_', ''), $client->server) . '_client';
                 }
-                else
-                {
-                    $xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
-                        array('_', ''), $client->server).'_client';
-                }
-                while($buildit && class_exists($xmlrpcclassname))
-                {
+                while ($buildit && class_exists($xmlrpcclassname)) {
                     $xmlrpcclassname .= 'x';
                 }
 
@@ -753,49 +664,38 @@ public function wrap_xmlrpc_server($client, $extra_options=array())
                 $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
-                    );
+                    'decode_php_objs' => $decode_php_objects,
+                );
                 /// @todo build javadoc for class definition, too
-                foreach($mlist as $mname)
-                {
-                    if ($methodfilter == '' || preg_match($methodfilter, $mname))
-                    {
+                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)
-                            {
+                        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 .= $methodwrap['source'] . "\n";
+                        } else {
+                            error_log('XML-RPC: will not create class method to wrap remote method ' . $mname);
                         }
                     }
                 }
                 $source .= "}\n";
-                if ($buildit)
-                {
+                if ($buildit) {
                     $allOK = 0;
-                    eval($source.'$allOK=1;');
+                    eval($source . '$allOK=1;');
                     // alternative
                     //$xmlrpcfuncname = create_function('$m', $innercode);
-                    if($allOK)
-                    {
+                    if ($allOK) {
                         return $xmlrpcclassname;
-                    }
-                    else
-                    {
-                        error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
+                    } else {
+                        error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server);
+
                         return false;
                     }
-                }
-                else
-                {
+                } else {
                     return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
                 }
             }
@@ -803,126 +703,101 @@ public function wrap_xmlrpc_server($client, $extra_options=array())
     }
 
     /**
-    * 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...
-    */
+     * 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...
+     */
     protected 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='')
+                                                        $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)
-        {
+        if ($client_copy_mode < 2) {
             // client copy mode 0 or 1 == partial / full client copy in emitted code
             $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix);
             $innercode .= "\$client->setDebug(\$debug);\n";
             $this_ = '';
-        }
-        else
-        {
+        } else {
             // client copy mode 2 == no client copy in emitted code
             $innercode = '';
             $this_ = 'this->';
         }
         $innercode .= "\$msg = new {$prefix}msg('$methodname');\n";
 
-        if ($mdesc != '')
-        {
+        if ($mdesc != '') {
             // take care that PHP comment is not terminated unwillingly by method description
-            $mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
-        }
-        else
-        {
+            $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n";
+        } else {
             $mdesc = "/**\nFunction $xmlrpcfuncname\n";
         }
 
         // param parsing
         $plist = array();
         $pcount = count($msig);
-        for($i = 1; $i < $pcount; $i++)
-        {
+        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')
-            {
+            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)
-                {
+            } else {
+                if ($encode_php_objects) {
                     $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
-                }
-                else
-                {
+                } else {
                     $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i);\n";
                 }
             }
             $innercode .= "\$msg->addparam(\$p$i);\n";
-            $mdesc .= '* @param '.$this->xmlrpc_2_php_type($ptype)." \$p$i\n";
+            $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n";
         }
-        if ($client_copy_mode < 2)
-        {
+        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 '.$this->xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";
+        $mdesc .= '* @return ' . $this->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
-            {
+        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
-        {
+        } else {
             $respcode = '$res';
         }
-        if ($decode_php_objects)
-        {
+        if ($decode_php_objects) {
             $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
-        }
-        else
-        {
+        } else {
             $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
         }
 
-        $code = $code . $plist. ") {\n" . $innercode . "\n}\n";
+        $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.
-    */
-    protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
+     * 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.
+     */
+    protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc')
     {
-        $code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).
+        $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')
-                {
+        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";
                 }
@@ -933,5 +808,4 @@ protected function build_client_wrapper_code($client, $verbatim_client_copy, $pr
         //$code .= "\$client->setDebug(\$debug);\n";
         return $code;
     }
-
-}
\ No newline at end of file
+}

From 885d7355f6b00f4b7f931d4d50c0e7b31d29bb32 Mon Sep 17 00:00:00 2001
From: gggeek 
Date: Sat, 21 Feb 2015 19:28:19 +0000
Subject: [PATCH 043/228] Welcome 2015

---
 debugger/action.php         | 2 +-
 debugger/common.php         | 2 +-
 debugger/controller.php     | 2 +-
 demo/client/simple_call.php | 2 +-
 demo/server/proxy.php       | 2 +-
 doc/convert.php             | 2 +-
 doc/custom.fo.xsl           | 2 +-
 doc/custom.xsl              | 2 +-
 doc/highlight.php           | 2 +-
 src/Wrapper.php             | 2 +-
 tests/benchmark.php         | 2 +-
 tests/verify_compat.php     | 2 +-
 12 files changed, 12 insertions(+), 12 deletions(-)

diff --git a/debugger/action.php b/debugger/action.php
index b12da804..4c39c629 100644
--- a/debugger/action.php
+++ b/debugger/action.php
@@ -1,7 +1,7 @@
 
diff --git a/doc/custom.xsl b/doc/custom.xsl
index b362d421..5efa6666 100644
--- a/doc/custom.xsl
+++ b/doc/custom.xsl
@@ -4,7 +4,7 @@
 
diff --git a/doc/highlight.php b/doc/highlight.php
index 82afde54..9f44b2cd 100644
--- a/doc/highlight.php
+++ b/doc/highlight.php
@@ -3,7 +3,7 @@
  * takes a dir as arg, highlights all php code found in html files inside.
  *
  * @author Gaetano Giunta
- * @copyright (c) 2007-2014 G. Giunta
+ * @copyright (c) 2007-2015 G. Giunta
  */
 function highlight($file)
 {
diff --git a/src/Wrapper.php b/src/Wrapper.php
index dc40e391..6ca36699 100644
--- a/src/Wrapper.php
+++ b/src/Wrapper.php
@@ -1,7 +1,7 @@
 
Date: Sat, 21 Feb 2015 19:39:33 +0000
Subject: [PATCH 044/228] Move license file inside the lib and away from sf.net

---
 debugger/action.php         |  2 +-
 debugger/common.php         |  2 +-
 debugger/controller.php     |  2 +-
 demo/client/simple_call.php |  2 +-
 demo/server/proxy.php       |  2 +-
 doc/custom.fo.xsl           |  2 +-
 doc/custom.xsl              |  2 +-
 license.txt                 | 29 +++++++++++++++++++++++++++++
 src/Wrapper.php             |  2 +-
 tests/benchmark.php         |  2 +-
 tests/parse_args.php        |  2 +-
 tests/verify_compat.php     |  2 +-
 12 files changed, 40 insertions(+), 11 deletions(-)
 create mode 100644 license.txt

diff --git a/debugger/action.php b/debugger/action.php
index 4c39c629..2e5e4c56 100644
--- a/debugger/action.php
+++ b/debugger/action.php
@@ -2,7 +2,7 @@
 /**
  * @author Gaetano Giunta
  * @copyright (C) 2005-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @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?
diff --git a/debugger/common.php b/debugger/common.php
index 69b89ba8..642326ab 100644
--- a/debugger/common.php
+++ b/debugger/common.php
@@ -2,7 +2,7 @@
 /**
  * @author Gaetano Giunta
  * @copyright (C) 2005-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @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 do some more sanitization of received parameters
diff --git a/debugger/controller.php b/debugger/controller.php
index 2435c023..d5c86109 100644
--- a/debugger/controller.php
+++ b/debugger/controller.php
@@ -2,7 +2,7 @@
 /**
  * @author Gaetano Giunta
  * @copyright (C) 2005-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @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
diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php
index ffb66dda..f2c03e07 100644
--- a/demo/client/simple_call.php
+++ b/demo/client/simple_call.php
@@ -3,7 +3,7 @@
  * Helper function for the terminally lazy.
  *
  * @copyright (c) 2006-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @license code licensed under the BSD License: see file license.txt
  */
 
 /**
diff --git a/demo/server/proxy.php b/demo/server/proxy.php
index 3f09d7e3..c78d8902 100644
--- a/demo/server/proxy.php
+++ b/demo/server/proxy.php
@@ -6,7 +6,7 @@
  *
  * @author Gaetano Giunta
  * @copyright (C) 2006-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @license code licensed under the BSD License: see file license.txt
  */
 include_once __DIR__ . "/../../vendor/autoload.php";
 
diff --git a/doc/custom.fo.xsl b/doc/custom.fo.xsl
index 215a12f0..1fe0ddac 100644
--- a/doc/custom.fo.xsl
+++ b/doc/custom.fo.xsl
@@ -6,7 +6,7 @@
  Customization xsl stylesheet for docbook to pdf transform
  @author Gaetano Giunta
  @copyright (c) 2007-2015 G. Giunta
- @license
+ @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
 -->
 
diff --git a/doc/custom.xsl b/doc/custom.xsl
index 5efa6666..7a2e6bb2 100644
--- a/doc/custom.xsl
+++ b/doc/custom.xsl
@@ -5,7 +5,7 @@
  Customization xsl stylesheet for docbook to chunked html transform
  @author Gaetano Giunta
  @copyright (c) 2007-2015 G. Giunta
- @license
+ @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
 -->
 
diff --git a/license.txt b/license.txt
new file mode 100644
index 00000000..37313ac2
--- /dev/null
+++ b/license.txt
@@ -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.
diff --git a/src/Wrapper.php b/src/Wrapper.php
index 6ca36699..8e573e39 100644
--- a/src/Wrapper.php
+++ b/src/Wrapper.php
@@ -2,7 +2,7 @@
 /**
  * @author Gaetano Giunta
  * @copyright (C) 2006-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @license code licensed under the BSD License: see file license.txt
  */
 
 namespace PhpXmlRpc;
diff --git a/tests/benchmark.php b/tests/benchmark.php
index 32a3fed5..01087011 100644
--- a/tests/benchmark.php
+++ b/tests/benchmark.php
@@ -4,7 +4,7 @@
  *
  * @author Gaetano Giunta
  * @copyright (c) 2005-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @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
diff --git a/tests/parse_args.php b/tests/parse_args.php
index 4397e640..744afbff 100644
--- a/tests/parse_args.php
+++ b/tests/parse_args.php
@@ -12,7 +12,7 @@
  * @param string  NOPROXY
  *
  * @copyright (C) 2007-20014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @license code licensed under the BSD License: see file license.txt
  **/
 class argParser
 {
diff --git a/tests/verify_compat.php b/tests/verify_compat.php
index 7d6d38a9..1d9f90cf 100644
--- a/tests/verify_compat.php
+++ b/tests/verify_compat.php
@@ -4,7 +4,7 @@
  *
  * @author Gaetano Giunta
  * @copyright (C) 2006-2015 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @license code licensed under the BSD License: see file license.txt
  *
  * @todo add a test for php output buffering?
  */

From 0a32cafa0ec6f46a899630b762000ee443566217 Mon Sep 17 00:00:00 2001
From: gggeek 
Date: Sat, 21 Feb 2015 20:27:57 +0000
Subject: [PATCH 045/228] Improve documentation for v4; fix one typo in a
 comment

---
 INSTALL        | 70 ++++++++++++++++++++++++++++++++++++++++----------
 NEWS           | 25 ++++++++++++------
 src/Client.php |  2 +-
 3 files changed, 75 insertions(+), 22 deletions(-)

diff --git a/INSTALL b/INSTALL
index b5eeddf1..b016c13b 100644
--- a/INSTALL
+++ b/INSTALL
@@ -3,8 +3,8 @@ XMLRPC for PHP
 Requirements
 ------------
 
-The following requirements should be met prior to using 'XMLRPC for PHP': 
-. PHP 5.1.0 or later
+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
 
@@ -17,22 +17,66 @@ Installation instructions
 
 Installation of the library is quite easy:
 
-1. copy the contents of the lib/ folder to any location required by your
-   application (it can be inside the web server root or not).
+1. Via Composer (highly recommended):
 
-2. make sure your app can include those files. This can be achieved by setting
-   the PHP include path, either in the php.ini file or directly in the php code
-   of your application, using the 'set_include_path' function
+    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.
 
-Example of php code allowing an application to import the library:
+    3. Open a terminal and use Composer to grab the library.
 
-set_include_path(get_include_path() . PATH_SEPARATOR . '/path/to/phpxmlrpc/lib/');
-require_once( 'xmlrpc.inc' );
-require_once( 'xmlrpcs.inc' );
-require_once( 'xmlrpc_wrappers.inc' );
+            $ 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)
+
+    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.
 
 
 Please note that usage of the 'make' command for installation of the library is
 not recommended, as it will generally involve editing of the makefile for a
-succesfull run.
+successful run.
diff --git a/NEWS b/NEWS
index 62b43ee0..f3cb5304 100644
--- a/NEWS
+++ b/NEWS
@@ -7,14 +7,23 @@ but some breackage is to be expected.
 
 PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade.
 
-The minimum requied php version has been increase to 5.3,
-even though we stronly urge you to use more recent versions.
+The minimum required php version has been increased to 5.3,
+even though we strongly urge you to use more recent versions.
+
+* new: introduction of namespaces.
+
+  All php classes have been renamed and moved to separate files.
+  Class autoloading can now be done in accord with the PSR-4 standard.
+  Backward compatibility is maintained via lib/xmlrpc.inc, lib/xmlrpcs.inc and lib/xmlrpc_wrappers.inc.
+
+* improved: all php code is now formatted according to the PSR-2 standard
 
 * improved: this release is now tested using Travis ( https://travis-ci.org/ ).
 
-* improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds
+* improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https
+  with recent curl builds
 
-* improved: phpunit is now installed via composer, not bundled anymore 
+* improved: phpunit is now installed via composer, not bundled anymore
 
 
 XML-RPC for PHP version 3.0.0 - 2014/6/15
@@ -164,7 +173,7 @@ CHANGELOG IN DETAIL:
 * 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 incmoing xmlrpc messages: two more invalid cases are now detected
+* 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?)
@@ -259,7 +268,7 @@ HTTPS support:
    $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
-   sned() method call fails for some reason
+   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
@@ -336,9 +345,9 @@ 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 runnning PHP5).
+development platform (and some warnings will be emitted when running PHP5).
 
-Notheworthy changes include:
+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
diff --git a/src/Client.php b/src/Client.php
index a5c64770..57410a8a 100644
--- a/src/Client.php
+++ b/src/Client.php
@@ -324,7 +324,7 @@ public function SetUserAgent($agentstring)
      */
     public function & send($msg, $timeout = 0, $method = '')
     {
-        // if user deos not specify http protocol, use native method of this client
+        // if user does not specify http protocol, use native method of this client
         // (i.e. method set during call to constructor)
         if ($method == '') {
             $method = $this->method;

From e0700142eed999020cb1fb3451588faa6b7f84ce Mon Sep 17 00:00:00 2001
From: gggeek 
Date: Sat, 21 Feb 2015 20:40:20 +0000
Subject: [PATCH 046/228] Fix one testcase apparently broken by automatic
 formatting tools

---
 tests/LocalhostTest.php | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php
index ec2ad1ec..e35e236f 100644
--- a/tests/LocalhostTest.php
+++ b/tests/LocalhostTest.php
@@ -525,7 +525,8 @@ public function testGetCookies()
                     unset($rcookies[$c]);
                 }
             }
-            foreach ($cookies as $c => $v) {// format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT'
+            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'], '-')) {
@@ -534,8 +535,9 @@ public function testGetCookies()
                         $cookies[$c]['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $cookies[$c]['expires']);
                     }
                 }
-                $this->assertEquals($cookies, $rcookies);
             }
+
+            $this->assertEquals($cookies, $rcookies);
         }
     }
 

From 5f01a1f84d32893310c1d13e6d2720370a93f57d Mon Sep 17 00:00:00 2001
From: gggeek 
Date: Sat, 21 Feb 2015 20:56:31 +0000
Subject: [PATCH 047/228] Fix two bugs (missed porting to new class names /
 namespaces), thanks SensiolabsInsight

---
 src/Client.php  | 2 +-
 src/Wrapper.php | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/Client.php b/src/Client.php
index 57410a8a..4af4dcbf 100644
--- a/src/Client.php
+++ b/src/Client.php
@@ -336,7 +336,7 @@ public function & send($msg, $timeout = 0, $method = '')
 
             return $r;
         } elseif (is_string($msg)) {
-            $n = new Message('');
+            $n = new Request('');
             $n->payload = $msg;
             $msg = $n;
         }
diff --git a/src/Wrapper.php b/src/Wrapper.php
index 8e573e39..a710fddd 100644
--- a/src/Wrapper.php
+++ b/src/Wrapper.php
@@ -437,7 +437,7 @@ public function wrap_php_class($classname, $extra_options = array())
         foreach ($mlist as $mname) {
             if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
                 // echo $mlist."\n";
-                $func = new ReflectionMethod($classname, $mname);
+                $func = new \ReflectionMethod($classname, $mname);
                 if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
                     if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
                         (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname))))

From d5fba766c7c3b7ef3e615d7cb0bbc3042855718f Mon Sep 17 00:00:00 2001
From: gggeek 
Date: Sat, 21 Feb 2015 21:23:53 +0000
Subject: [PATCH 048/228] Fix newlines (to satisfy automated code quality
 scanners)

---
 composer.json              |  2 +-
 demo/client/introspect.php | 80 +++++++++++++++++++++++++++++++++++++-
 demo/client/which.php      | 27 ++++++++++++-
 doc/.gitignore             |  2 +-
 4 files changed, 107 insertions(+), 4 deletions(-)

diff --git a/composer.json b/composer.json
index 30644908..7e1a9af2 100644
--- a/composer.json
+++ b/composer.json
@@ -18,4 +18,4 @@
     "autoload": {
         "psr-4": {"PhpXmlRpc\\": "src/"}
     }
-}
\ No newline at end of file
+}
diff --git a/demo/client/introspect.php b/demo/client/introspect.php
index 1fff47ab..cd084233 100644
--- a/demo/client/introspect.php
+++ b/demo/client/introspect.php
@@ -1 +1,79 @@
-

xmlrpc



Introspect demo

Query server for available methods and their description

The code demonstrates usage of multicall and introspection methods

faultCode() . " Reason: '" . $r->faultString() . "'
"; } // 'new style' client constuctor $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); print "

methods available at http://" . $c->server . $c->path . "

\n"; $m = new xmlrpcmsg('system.listMethods'); $r = &$c->send($m); if ($r->faultCode()) { display_error($r); } else { $v = $r->value(); for ($i = 0; $i < $v->arraysize(); $i++) { $mname = $v->arraymem($i); print "

" . $mname->scalarval() . "

\n"; // build messages first, add params later $m1 = new xmlrpcmsg('system.methodHelp'); $m2 = new xmlrpcmsg('system.methodSignature'); $val = new xmlrpcval($mname->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); // send multiple messages in one pass. // If server does not support multicall, client will fall back to 2 separate calls $ms = array($m1, $m2); $rs = &$c->send($ms); if ($rs[0]->faultCode()) { display_error($rs[0]); } else { $val = $rs[0]->value(); $txt = $val->scalarval(); if ($txt != "") { print "

Documentation

${txt}

\n"; } else { print "

No documentation available.

\n"; } } if ($rs[1]->faultCode()) { display_error($rs[1]); } else { print "

Signature

\n"; $val = $rs[1]->value(); if ($val->kindOf() == "array") { for ($j = 0; $j < $val->arraysize(); $j++) { $x = $val->arraymem($j); $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " . $mname->scalarval() . "("; if ($x->arraysize() > 1) { for ($k = 1; $k < $x->arraysize(); $k++) { $y = $x->arraymem($k); print $y->scalarval(); if ($k < $x->arraysize() - 1) { print ", "; } } } print ")
\n"; } } else { print "Signature unknown\n"; } print "

\n"; } } } ?> \ No newline at end of file + +xmlrpc + +

Introspect demo

+

Query server for available methods and their description

+

The code demonstrates usage of multicall and introspection methods

+faultCode() + . " Reason: '" . $r->faultString() . "'
"; +} +// 'new style' client constructor +$c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); +print "

methods available at http://" . $c->server . $c->path . "

\n"; +$m = new xmlrpcmsg('system.listMethods'); +$r = &$c->send($m); +if ($r->faultCode()) { + display_error($r); +} else { + $v = $r->value(); + for ($i = 0; $i < $v->arraysize(); $i++) { + $mname = $v->arraymem($i); + print "

" . $mname->scalarval() . "

\n"; + // build messages first, add params later + $m1 = new xmlrpcmsg('system.methodHelp'); + $m2 = new xmlrpcmsg('system.methodSignature'); + $val = new xmlrpcval($mname->scalarval(), "string"); + $m1->addParam($val); + $m2->addParam($val); + // send multiple messages in one pass. + // If server does not support multicall, client will fall back to 2 separate calls + $ms = array($m1, $m2); + $rs = &$c->send($ms); + if ($rs[0]->faultCode()) { + display_error($rs[0]); + } else { + $val = $rs[0]->value(); + $txt = $val->scalarval(); + if ($txt != "") { + print "

Documentation

${txt}

\n"; + } else { + print "

No documentation available.

\n"; + } + } + if ($rs[1]->faultCode()) { + display_error($rs[1]); + } else { + print "

Signature

\n"; + $val = $rs[1]->value(); + if ($val->kindOf() == "array") { + for ($j = 0; $j < $val->arraysize(); $j++) { + $x = $val->arraymem($j); + $ret = $x->arraymem(0); + print "" . $ret->scalarval() . " " + . $mname->scalarval() . "("; + if ($x->arraysize() > 1) { + for ($k = 1; $k < $x->arraysize(); $k++) { + $y = $x->arraymem($k); + print $y->scalarval(); + if ($k < $x->arraysize() - 1) { + print ", "; + } + } + } + print ")
\n"; + } + } else { + print "Signature unknown\n"; + } + print "

\n"; + } + } +} +?> + + diff --git a/demo/client/which.php b/demo/client/which.php index db2d8c17..f6ef45d1 100644 --- a/demo/client/which.php +++ b/demo/client/which.php @@ -1 +1,26 @@ - xmlrpc

Which toolkit demo

Query server for toolkit information

The code demonstrates usage of the php_xmlrpc_decode function

send($f); if (!$r->faultCode()) { $v = php_xmlrpc_decode($r->value()); print "
";


    print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";


    print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";


    print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";


    print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";


    print "
"; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; } ?> \ No newline at end of file + +xmlrpc + +

Which toolkit demo

+

Query server for toolkit information

+

The code demonstrates usage of the php_xmlrpc_decode function

+send($f); +if (!$r->faultCode()) { + $v = php_xmlrpc_decode($r->value()); + print "
";
+    print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";
+    print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";
+    print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";
+    print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";
+    print "
"; +} else { + print "An error occurred: "; + print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; +} +?> + + diff --git a/doc/.gitignore b/doc/.gitignore index 898ede16..bace1405 100644 --- a/doc/.gitignore +++ b/doc/.gitignore @@ -1,4 +1,4 @@ out/ javadoc-out/ xmlrpc_php.pdf -xmlrpc_php.fo.xml \ No newline at end of file +xmlrpc_php.fo.xml From 16d00b78deb6d0d7f602581e1a339e0cb60c14c3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 21:25:08 +0000 Subject: [PATCH 049/228] More newline fixes --- demo/client/agesort.php | 65 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/demo/client/agesort.php b/demo/client/agesort.php index 8ae87ff7..6e00de0c 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -1 +1,64 @@ - xmlrpc

Agesort demo

Send an array of 'name' => 'age' pairs to the server that will send it back sorted.

The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs

24, "Edd" => 45, "Joe" => 37, "Fred" => 27); reset($inAr); print "This is the input data:
";
while (list($key, $val) = each($inAr)) {
    print $key . ", " . $val . "\n";
}
print "
"; // create parameters from the input array: an xmlrpc array of xmlrpc structs $p = array(); foreach ($inAr as $key => $val) { $p[] = new xmlrpcval(array("name" => new xmlrpcval($key), "age" => new xmlrpcval($val, "int")), "struct"); } $v = new xmlrpcval($p, "array"); print "Encoded into xmlrpc format it looks like this:
\n" . htmlentities($v->serialize()) . "
\n"; // create client and message objects $f = new xmlrpcmsg('examples.sortByAge', array($v)); $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); // set maximum debug level, to have the complete communication printed to screen $c->setDebug(2); // send request print "Now sending request (detailed debug info follows)"; $r = &$c->send($f); // check response for errors, and take appropriate action if (!$r->faultCode()) { print "The server gave me these results:
";
    $v = $r->value();
    $max = $v->arraysize();
    for ($i = 0; $i < $max; $i++) {
        $rec = $v->arraymem($i);
        $n = $rec->structmem("name");
        $a = $rec->structmem("age");
        print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";
    }

    print "
For nerds: I got this value back
" .
        htmlentities($r->serialize()) . "

\n"; } else { print "An error occurred:
";
    print "Code: " . htmlspecialchars($r->faultCode()) .
        "\nReason: '" . htmlspecialchars($r->faultString()) . '\'

'; } ?> \ No newline at end of file + +xmlrpc + +

Agesort demo

+ +

Send an array of 'name' => 'age' pairs to the server that will send it back sorted.

+ +

The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs

+ +

+ 24, "Edd" => 45, "Joe" => 37, "Fred" => 27); +reset($inAr); +print "This is the input data:
";
+while (list($key, $val) = each($inAr)) {
+    print $key . ", " . $val . "\n";
+}
+print "
"; + +// create parameters from the input array: an xmlrpc array of xmlrpc structs +$p = array(); +foreach ($inAr as $key => $val) { + $p[] = new xmlrpcval(array("name" => new xmlrpcval($key), + "age" => new xmlrpcval($val, "int")), "struct"); +} +$v = new xmlrpcval($p, "array"); +print "Encoded into xmlrpc format it looks like this:
\n" . htmlentities($v->serialize()) . "
\n"; + +// create client and message objects +$f = new xmlrpcmsg('examples.sortByAge', array($v)); +$c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); + +// set maximum debug level, to have the complete communication printed to screen +$c->setDebug(2); + +// send request +print "Now sending request (detailed debug info follows)"; +$r = &$c->send($f); + +// check response for errors, and take appropriate action +if (!$r->faultCode()) { + print "The server gave me these results:
";
+    $v = $r->value();
+    $max = $v->arraysize();
+    for ($i = 0; $i < $max; $i++) {
+        $rec = $v->arraymem($i);
+        $n = $rec->structmem("name");
+        $a = $rec->structmem("age");
+        print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";
+    }
+
+    print "
For nerds: I got this value back
" .
+        htmlentities($r->serialize()) . "

\n"; +} else { + print "An error occurred:
";
+    print "Code: " . htmlspecialchars($r->faultCode()) .
+        "\nReason: '" . htmlspecialchars($r->faultString()) . '\'

'; +} + +?> + + From 040d77ff5a5c9316b092bfccc9eea4b88673578b Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 21:48:13 +0000 Subject: [PATCH 050/228] Make sure convert.php works with php5.6.1 on linux --- doc/convert.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/doc/convert.php b/doc/convert.php index 9cfe0f3f..a7e08cbc 100644 --- a/doc/convert.php +++ b/doc/convert.php @@ -33,7 +33,12 @@ ini_set("xsl.security_prefs", XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); } } else { - $proc->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + // the php online docs only mention setSecurityPrefs, but somehow some installs have setSecurityPreferences... + if (method_exists('XSLTProcessor', 'setSecurityPrefs')) { + $proc->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + } else { + $proc->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); + } } $proc->importStyleSheet($xsl); // attach the xsl rules From ab48ab0912c7c2fae7a9f74d14ed2b35bcbe1c72 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 22:58:10 +0000 Subject: [PATCH 051/228] Fix list of files in makefile --- Makefile | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index 4b4e4efa..c6d49850 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ ### USER EDITABLE VARS - can be passed as command-line options ### # path to PHP executable, preferably CLI version -PHP=/usr/local/bin/php +PHP=php # path were xmlrpc lib files will be copied to PHPINCLUDEDIR=/usr/local/lib/php @@ -23,7 +23,8 @@ DOS2UNIX=dos2unix # on unix shells lasts char should be \\2/g ) export VERSION=$(shell grep -E "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) -LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc +LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc \ + src/*.php src/Helper/*.php EXTRAFILES=extras/test.pl \ extras/test.py \ @@ -31,9 +32,9 @@ EXTRAFILES=extras/test.pl \ extras/workspace.testPhpServer.fttb DEMOFILES=demo/vardemo.php \ - demo/demo1.txt \ - demo/demo2.txt \ - demo/demo3.txt + demo/demo1.xml \ + demo/demo2.xml \ + demo/demo3.xml DEMOSFILES=demo/server/discuss.php \ demo/server/server.php \ @@ -50,11 +51,12 @@ DEMOCFILES=demo/client/agesort.php \ demo/client/zopetest.php TESTFILES=test/testsuite.php \ - test/benchmark.php \ - test/parse_args.php \ - test/phpunit.php \ - test/verify_compat.php \ - test/PHPUnit/*.php + tests/benchmark.php \ + tests/parse_args.php \ + test/InvalidHostTest.php \ + test/LocalHostTest.php \ + test/ParsingBugsTest.php \ + tests/verify_compat.php INFOFILES=Changelog \ Makefile \ From f8c46583190c7004883b6ae412dce9cf6010eb4c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Feb 2015 23:18:59 +0000 Subject: [PATCH 052/228] Fix some example code in the manual --- doc/xmlrpc_php.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/xmlrpc_php.xml b/doc/xmlrpc_php.xml index 139ef6c7..363f8a73 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/xmlrpc_php.xml @@ -1322,10 +1322,10 @@ PHP-XMLRPC User manual Examples: -$myInt = new xmlrpcvalue(1267, "int"); -$myString = new xmlrpcvalue("Hello, World!", "string"); -$myBool = new xmlrpcvalue(1, "boolean"); -$myString2 = new xmlrpcvalue(1.24, "string"); // note: this will serialize a php float value as xmlrpc string +$myInt = new xmlrpcval(1267, "int"); +$myString = new xmlrpcval("Hello, World!", "string"); +$myBool = new xmlrpcval(1, "boolean"); +$myString2 = new xmlrpcval(1.24, "string"); // note: this will serialize a php float value as xmlrpc string The fourth constructor form can be used to compose complex From a8670a714a4edcdd597b31059b6491b4595d9407 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 21:56:53 +0000 Subject: [PATCH 053/228] Add php 7 testing on travis --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 58ff96da..9e6531e1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm install: From dd7a1b795bdbfd7fd0bdadd33eeb019acdd9bb08 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 22:16:33 +0000 Subject: [PATCH 054/228] 1st test in using local apache for testsuite --- .travis.yml | 16 ++++++++++++++-- .travis/apache_vhost | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 .travis/apache_vhost diff --git a/.travis.yml b/.travis.yml index 9e6531e1..8d7f4820 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,13 +13,25 @@ install: before_script: # Disable xdebug. NB: this should NOT be done for hhvm... - - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then phpenv config-rm xdebug.ini; fi + - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi # TODO: we should set up an Apache instance inside the Travis VM and test it. # But it looks a bit complex, esp. as it seems that php has to be set up differently (cgi vs fpm) depending on version # So for now we just take an easy way out using a known remote server. # See: https://gist.github.com/roderik/3123962 # See: http://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP + - sudo apt-get install apache2 libapache2-mod-fastcgi + + # enable php-fpm + - sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf + - sudo a2enmod rewrite actions fastcgi alias + - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm + # configure apache virtual hosts + - sudo cp -f .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 script: - phpunit tests LOCALSERVER=gggeek.altervista.org URI=/sw/xmlrpc/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 diff --git a/.travis/apache_vhost b/.travis/apache_vhost new file mode 100644 index 00000000..26f70feb --- /dev/null +++ b/.travis/apache_vhost @@ -0,0 +1,23 @@ +# Configuration file for Apache running on Travis. +# PHP setup in FCGI mode + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Wire up Apache to use Travis CI's php-fpm. + + 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 + + + \ No newline at end of file From 09bea8a40014c810cd773daf3d6535daf61e245a Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 22:25:00 +0000 Subject: [PATCH 055/228] 2nd try at travis/apache --- .travis.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8d7f4820..b6b4cb50 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,19 +8,19 @@ php: - 7.0 - hhvm +before_install: + - sudo apt-get update -qq + install: - composer self-update && composer install + - sudo apt-get install -y apache2 libapache2-mod-fastcgi before_script: # Disable xdebug. NB: this should NOT be done for hhvm... - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi - # TODO: we should set up an Apache instance inside the Travis VM and test it. - # But it looks a bit complex, esp. as it seems that php has to be set up differently (cgi vs fpm) depending on version - # So for now we just take an easy way out using a known remote server. - # See: https://gist.github.com/roderik/3123962 + # We set up an Apache instance inside the Travis VM and test it. # See: http://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP - - sudo apt-get install apache2 libapache2-mod-fastcgi # enable php-fpm - sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf From b9d737d3f3fed06fdd1c71f4b3e67e5bf74b7743 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 22:41:15 +0000 Subject: [PATCH 056/228] Fix one test failing with php 5.5 fcgi --- tests/LocalhostTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php index e35e236f..f413d40b 100644 --- a/tests/LocalhostTest.php +++ b/tests/LocalhostTest.php @@ -524,6 +524,10 @@ public function testGetCookies() 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' From 0ac1e7a37814d6be2a38962aaef84a2af6421854 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 23:32:47 +0000 Subject: [PATCH 057/228] Improve support for hhvm on travis --- .travis.yml | 16 ++++++++++++---- .travis/apache_vhost_hhvm | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 .travis/apache_vhost_hhvm diff --git a/.travis.yml b/.travis.yml index b6b4cb50..6b46ce5a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,16 +22,24 @@ before_script: # We set up an Apache instance inside the Travis VM and test it. # See: http://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP - # enable php-fpm - - sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf + # enable php-fpm/hhvm-fcgi - sudo a2enmod rewrite actions fastcgi alias + - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm + - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm + - if [ $TRAVIS_PHP_VERSION = "hhvm" ]; then hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true # configure apache virtual hosts - - sudo cp -f .travis/apache_vhost /etc/apache2/sites-available/default + - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then sudo cp -f .travis/apache_vhost /etc/apache2/sites-available/default + - if [ $TRAVIS_PHP_VERSION = "hhvm" ]; then sudo cp -f .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 script: + # to have code coverage: --coverage-clover=coverage.clover phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 + +#after_script: +# # upload code-coverage to Scrutinizer +# - wget https://scrutinizer-ci.com/ocular.phar +# - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/.travis/apache_vhost_hhvm b/.travis/apache_vhost_hhvm new file mode 100644 index 00000000..93436f6d --- /dev/null +++ b/.travis/apache_vhost_hhvm @@ -0,0 +1,26 @@ +# Configuration file for Apache running on Travis. +# HHVM setup in FCGI mode + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Configure Apache for HHVM FastCGI. + # See https://github.com/facebook/hhvm/wiki/fastcgi + + + SetHandler hhvm-php-extension + + Alias /hhvm /hhvm + Action hhvm-php-extension /hhvm virtual + FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 + + + \ No newline at end of file From 14800d0367e92816271d87ee4202f1db915b17bc Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 15 Mar 2015 23:47:28 +0000 Subject: [PATCH 058/228] Yet one more try at travis+fcgi --- .travis.yml | 16 ++-------------- .travis/install_apache.sh | 17 +++++++++++++++++ .travis/install_apache_hhvm.sh | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 14 deletions(-) create mode 100644 .travis/install_apache.sh create mode 100644 .travis/install_apache_hhvm.sh diff --git a/.travis.yml b/.travis.yml index 6b46ce5a..da4e646a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,20 +20,8 @@ before_script: - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi # We set up an Apache instance inside the Travis VM and test it. - # See: http://docs.travis-ci.com/user/languages/php/#Apache-%2B-PHP - - # enable php-fpm/hhvm-fcgi - - sudo a2enmod rewrite actions fastcgi alias - - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf - - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm - - if [ $TRAVIS_PHP_VERSION = "hhvm" ]; then hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true - # configure apache virtual hosts - - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; then sudo cp -f .travis/apache_vhost /etc/apache2/sites-available/default - - if [ $TRAVIS_PHP_VERSION = "hhvm" ]; then sudo cp -f .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 + - sh -c "if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./.travis/install_apache.sh; fi" + - sh -c "if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./.travis/install_apache_hhvm.sh; fi" script: # to have code coverage: --coverage-clover=coverage.clover diff --git a/.travis/install_apache.sh b/.travis/install_apache.sh new file mode 100644 index 00000000..e7a5fe53 --- /dev/null +++ b/.travis/install_apache.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +# enable php-fpm +# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php + +sudo apt-get install apache2 libapache2-mod-fastcgi +sudo a2enmod rewrite actions fastcgi alias + +# enable php-fpm +sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf +echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini +~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm + +# configure apache virtual hosts +sudo cp -f .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 diff --git a/.travis/install_apache_hhvm.sh b/.travis/install_apache_hhvm.sh new file mode 100644 index 00000000..9e2869d2 --- /dev/null +++ b/.travis/install_apache_hhvm.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +# enable hhvm-fcgi +# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php + +sudo apt-get install apache2 libapache2-mod-fastcgi +sudo a2enmod rewrite actions fastcgi alias + +# start HHVM +hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true + +# configure apache virtual hosts +sudo cp -f .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 \ No newline at end of file From 71b78026d7caaf3aa3804d1a0b01eda3f94a2dbb Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 16 Mar 2015 00:05:36 +0000 Subject: [PATCH 059/228] Changing file permissions for Travis --- .travis/install_apache.sh | 0 .travis/install_apache_hhvm.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 .travis/install_apache.sh mode change 100644 => 100755 .travis/install_apache_hhvm.sh diff --git a/.travis/install_apache.sh b/.travis/install_apache.sh old mode 100644 new mode 100755 diff --git a/.travis/install_apache_hhvm.sh b/.travis/install_apache_hhvm.sh old mode 100644 new mode 100755 From ec4b9530ba869e72f1c18acf41d161cae0feb334 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 16 Mar 2015 00:57:05 +0000 Subject: [PATCH 060/228] Fix (hopefully) one test case for HHVM --- tests/LocalhostTest.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php index f413d40b..90822518 100644 --- a/tests/LocalhostTest.php +++ b/tests/LocalhostTest.php @@ -59,7 +59,12 @@ public function send($msg, $errrorcode = 0, $return_response = false) if (is_array($r)) { return $r; } - $this->assertEquals($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + if (is_array($errrorcode)) { + $this->assertContains($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + } + else { + $this->assertEquals($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + } if (!$r->faultCode()) { if ($return_response) { return $r; @@ -432,7 +437,9 @@ public function testCatchExceptions() $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1'; $v = $this->send($f, 1); $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2'; - $v = $this->send($f, $GLOBALS['xmlrpcerr']['invalid_return']); + // 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($f, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error'])); } public function testZeroParams() From 2ba26aa6bc64d6cf742f3360920308b5bdbbd911 Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 19 Mar 2015 22:13:11 +0000 Subject: [PATCH 061/228] Move travis config in a subdir of tests; enable debug to help with travis/php5.6 --- .travis.yml | 6 +- doc/custom.xsl | 176 +++++++++--------- {.travis => tests/ci/travis}/apache_vhost | 0 .../ci/travis}/apache_vhost_hhvm | 0 .../ci/travis}/install_apache.sh | 2 +- .../ci/travis}/install_apache_hhvm.sh | 2 +- 6 files changed, 95 insertions(+), 91 deletions(-) rename {.travis => tests/ci/travis}/apache_vhost (100%) rename {.travis => tests/ci/travis}/apache_vhost_hhvm (100%) rename {.travis => tests/ci/travis}/install_apache.sh (90%) mode change 100755 => 100644 rename {.travis => tests/ci/travis}/install_apache_hhvm.sh (85%) mode change 100755 => 100644 diff --git a/.travis.yml b/.travis.yml index da4e646a..a41255c6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,12 +20,12 @@ before_script: - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi # We set up an Apache instance inside the Travis VM and test it. - - sh -c "if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./.travis/install_apache.sh; fi" - - sh -c "if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./.travis/install_apache_hhvm.sh; fi" + - sh -c "if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/install_apache.sh; fi" + - sh -c "if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/install_apache_hhvm.sh; fi" script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 DEBUG=1 #after_script: # # upload code-coverage to Scrutinizer diff --git a/doc/custom.xsl b/doc/custom.xsl index 7a2e6bb2..f648887a 100644 --- a/doc/custom.xsl +++ b/doc/custom.xsl @@ -1,87 +1,91 @@ - - - - - - - - - - -no -ansi -xmlrpc.css -0 - - - - - - - - - - ( - - - - - - - - - - - - void ) - - - - ... - ) - - - - - - - , - - - ) - - - - - - - - - - - - - - - - - - - - - - - - = - - - - + + + + + + + + + + +no +ansi +xmlrpc.css +0 + + + + + + + + + + ( + + + + + + + + + + + + void ) + + + + ... + ) + + + + + + + , + + + ) + + + + + + + + + + + + + + + + + + + + + + + + = + + + + \ No newline at end of file diff --git a/.travis/apache_vhost b/tests/ci/travis/apache_vhost similarity index 100% rename from .travis/apache_vhost rename to tests/ci/travis/apache_vhost diff --git a/.travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm similarity index 100% rename from .travis/apache_vhost_hhvm rename to tests/ci/travis/apache_vhost_hhvm diff --git a/.travis/install_apache.sh b/tests/ci/travis/install_apache.sh old mode 100755 new mode 100644 similarity index 90% rename from .travis/install_apache.sh rename to tests/ci/travis/install_apache.sh index e7a5fe53..c5b0875e --- a/.travis/install_apache.sh +++ b/tests/ci/travis/install_apache.sh @@ -12,6 +12,6 @@ echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm # configure apache virtual hosts -sudo cp -f .travis/apache_vhost /etc/apache2/sites-available/default +sudo cp -f tests/ci/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 diff --git a/.travis/install_apache_hhvm.sh b/tests/ci/travis/install_apache_hhvm.sh old mode 100755 new mode 100644 similarity index 85% rename from .travis/install_apache_hhvm.sh rename to tests/ci/travis/install_apache_hhvm.sh index 9e2869d2..1ff3ddd8 --- a/.travis/install_apache_hhvm.sh +++ b/tests/ci/travis/install_apache_hhvm.sh @@ -10,6 +10,6 @@ sudo a2enmod rewrite actions fastcgi alias hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true # configure apache virtual hosts -sudo cp -f .travis/apache_vhost_hhvm /etc/apache2/sites-available/default +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 \ No newline at end of file From cd480e485efe208c24df5e835c550d601ed4d3f0 Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 19 Mar 2015 23:38:53 +0000 Subject: [PATCH 062/228] Add proxy setup for travis tests --- .travis.yml | 7 ++++--- tests/ci/travis/install_nginx.sh | 7 +++++++ tests/ci/travis/nginx.conf | 21 +++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 tests/ci/travis/install_nginx.sh create mode 100644 tests/ci/travis/nginx.conf diff --git a/.travis.yml b/.travis.yml index a41255c6..8f125db4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,12 +20,13 @@ before_script: - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi # We set up an Apache instance inside the Travis VM and test it. - - sh -c "if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/install_apache.sh; fi" - - sh -c "if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/install_apache_hhvm.sh; fi" + - if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/install_apache.sh; fi + - if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/install_apache_hhvm.sh; fi + - ./tests/ci/travis/install_nginx.sh script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php NOPROXY=1 DEBUG=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 DEBUG=1 #after_script: # # upload code-coverage to Scrutinizer diff --git a/tests/ci/travis/install_nginx.sh b/tests/ci/travis/install_nginx.sh new file mode 100644 index 00000000..c64ac205 --- /dev/null +++ b/tests/ci/travis/install_nginx.sh @@ -0,0 +1,7 @@ +#!/bin/sh + +# enable nginx (to serve as proxy) + +apt-get install nginx +sudo cp -f tests/ci/nginx.conf /etc/nginx/nginx.conf +sudo service nginx restart diff --git a/tests/ci/travis/nginx.conf b/tests/ci/travis/nginx.conf new file mode 100644 index 00000000..7b63ccf8 --- /dev/null +++ b/tests/ci/travis/nginx.conf @@ -0,0 +1,21 @@ +worker_processes 1; + +events { + worker_connections 1024; +} + +http { + #include mime.types; + #default_type application/octet-stream; + gzip on; + + server { + listen 8080; + location / { + proxy_pass http://localhost; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_redirect off; + } + } +} \ No newline at end of file From 72af9c92b555dad4627802973504d6b2b6f96730 Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 19 Mar 2015 23:40:21 +0000 Subject: [PATCH 063/228] Fix executable fix for travis scripts --- tests/ci/travis/install_apache.sh | 0 tests/ci/travis/install_apache_hhvm.sh | 0 tests/ci/travis/install_nginx.sh | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 tests/ci/travis/install_apache.sh mode change 100644 => 100755 tests/ci/travis/install_apache_hhvm.sh mode change 100644 => 100755 tests/ci/travis/install_nginx.sh diff --git a/tests/ci/travis/install_apache.sh b/tests/ci/travis/install_apache.sh old mode 100644 new mode 100755 diff --git a/tests/ci/travis/install_apache_hhvm.sh b/tests/ci/travis/install_apache_hhvm.sh old mode 100644 new mode 100755 diff --git a/tests/ci/travis/install_nginx.sh b/tests/ci/travis/install_nginx.sh old mode 100644 new mode 100755 From d583074301a8357e73039c64de9f5a9fdbe9d7e3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 00:10:02 +0000 Subject: [PATCH 064/228] One more fix for travis --- tests/ci/travis/install_nginx.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ci/travis/install_nginx.sh b/tests/ci/travis/install_nginx.sh index c64ac205..b83f8c10 100755 --- a/tests/ci/travis/install_nginx.sh +++ b/tests/ci/travis/install_nginx.sh @@ -2,6 +2,6 @@ # enable nginx (to serve as proxy) -apt-get install nginx -sudo cp -f tests/ci/nginx.conf /etc/nginx/nginx.conf +sudo apt-get install nginx +sudo cp -f tests/ci/travis/nginx.conf /etc/nginx/nginx.conf sudo service nginx restart From 964c756207a405a0aa24722bab26ad0e8ab4fcd1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 01:54:52 +0000 Subject: [PATCH 065/228] Add the multiTest suite; minor test fixes --- tests/InvalidHostTest.php | 1 + tests/LocalhostMultiTest.php | 206 +++++++++++++++++++++++++++++++++++ tests/LocalhostTest.php | 5 +- tests/parse_args.php | 2 +- 4 files changed, 212 insertions(+), 2 deletions(-) create mode 100644 tests/LocalhostMultiTest.php diff --git a/tests/InvalidHostTest.php b/tests/InvalidHostTest.php index 1ac111f7..685bd598 100644 --- a/tests/InvalidHostTest.php +++ b/tests/InvalidHostTest.php @@ -6,6 +6,7 @@ class InvalidHostTest extends PHPUnit_Framework_TestCase { + /** @var xmlrpc_client $client */ public $client = null; public $args = array(); diff --git a/tests/LocalhostMultiTest.php b/tests/LocalhostMultiTest.php new file mode 100644 index 00000000..e855f216 --- /dev/null +++ b/tests/LocalhostMultiTest.php @@ -0,0 +1,206 @@ +$method(); + } + /*if ($this->_failed) + { + break; + }*/ + } + } + + function testDeflate() + { + if(!function_exists('gzdeflate')) + { + $this->fail('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->fail('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->fail('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->fail('PROXY definition missing: cannot test proxy'); + } + + function testHttp11() + { + if(!function_exists('curl_init')) + { + $this->fail('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->fail('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->fail('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->fail('CURL missing: cannot test http 1.1 w. proxy'); + return; + } + else if ($this->args['PROXYSERVER'] == '') + { + $this->fail('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->fail('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->_runtests(); + } + + function testHttpsProxy() + { + if(!function_exists('curl_init')) + { + $this->fail('CURL missing: cannot test https functionality'); + return; + } + else if ($this->args['PROXYSERVER'] == '') + { + $this->fail('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->_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(); + } +} diff --git a/tests/LocalhostTest.php b/tests/LocalhostTest.php index 90822518..562dbb51 100644 --- a/tests/LocalhostTest.php +++ b/tests/LocalhostTest.php @@ -7,6 +7,7 @@ class LocalhostTest extends PHPUnit_Framework_TestCase { + /** @var xmlrpc_client $client */ public $client = null; public $method = 'http'; public $timeout = 10; @@ -14,6 +15,8 @@ class LocalhostTest extends PHPUnit_Framework_TestCase public $accepted_compression = ''; public $args = array(); + protected static $failed_tests = array(); + public static function fail($message = '') { // save in global var that this particular test has failed @@ -23,7 +26,7 @@ public static function fail($message = '') $trace = debug_backtrace(); for ($i = 0; $i < count($trace); $i++) { if (strpos($trace[$i]['function'], 'test') === 0) { - $failed_tests[$trace[$i]['function']] = true; + self::$failed_tests[$trace[$i]['function']] = true; break; } } diff --git a/tests/parse_args.php b/tests/parse_args.php index 744afbff..e9f2e2eb 100644 --- a/tests/parse_args.php +++ b/tests/parse_args.php @@ -67,7 +67,7 @@ public static function getArgs() $args['HTTPSURI'] = $HTTPSURI; } if (isset($HTTPSIGNOREPEER)) { - $args['HTTPSIGNOREPEER'] = bool($HTTPSIGNOREPEER); + $args['HTTPSIGNOREPEER'] = (bool)$HTTPSIGNOREPEER; } if (isset($PROXY)) { $arr = explode(':', $PROXY); From 2ec50890fc53ff0981e7a0b3ee335b10e12f08da Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 02:04:40 +0000 Subject: [PATCH 066/228] Replace nginx with privoxy for travis testing --- .travis.yml | 9 ++++---- tests/ci/travis/install_nginx.sh | 7 ------- tests/ci/travis/nginx.conf | 21 ------------------- tests/ci/travis/privoxy | 1 + .../{install_apache.sh => setup_apache.sh} | 3 ++- ...ll_apache_hhvm.sh => setup_apache_hhvm.sh} | 3 +-- tests/ci/travis/setup_privoxy.sh | 6 ++++++ 7 files changed, 15 insertions(+), 35 deletions(-) delete mode 100755 tests/ci/travis/install_nginx.sh delete mode 100644 tests/ci/travis/nginx.conf create mode 100644 tests/ci/travis/privoxy rename tests/ci/travis/{install_apache.sh => setup_apache.sh} (93%) mode change 100755 => 100644 rename tests/ci/travis/{install_apache_hhvm.sh => setup_apache_hhvm.sh} (85%) mode change 100755 => 100644 create mode 100644 tests/ci/travis/setup_privoxy.sh diff --git a/.travis.yml b/.travis.yml index 8f125db4..d8fbb48f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,17 +12,18 @@ before_install: - sudo apt-get update -qq install: - - composer self-update && composer install - sudo apt-get install -y apache2 libapache2-mod-fastcgi + - sudo apt-get install -y privoxy + - composer self-update && composer install before_script: # Disable xdebug. NB: this should NOT be done for hhvm... - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi # We set up an Apache instance inside the Travis VM and test it. - - if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/install_apache.sh; fi - - if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/install_apache_hhvm.sh; fi - - ./tests/ci/travis/install_nginx.sh + - if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/setup_apache.sh; fi + - if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/setup_apache_hhvm.sh; fi + - ./tests/ci/travis/setup_privoxy.sh script: # to have code coverage: --coverage-clover=coverage.clover diff --git a/tests/ci/travis/install_nginx.sh b/tests/ci/travis/install_nginx.sh deleted file mode 100755 index b83f8c10..00000000 --- a/tests/ci/travis/install_nginx.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -# enable nginx (to serve as proxy) - -sudo apt-get install nginx -sudo cp -f tests/ci/travis/nginx.conf /etc/nginx/nginx.conf -sudo service nginx restart diff --git a/tests/ci/travis/nginx.conf b/tests/ci/travis/nginx.conf deleted file mode 100644 index 7b63ccf8..00000000 --- a/tests/ci/travis/nginx.conf +++ /dev/null @@ -1,21 +0,0 @@ -worker_processes 1; - -events { - worker_connections 1024; -} - -http { - #include mime.types; - #default_type application/octet-stream; - gzip on; - - server { - listen 8080; - location / { - proxy_pass http://localhost; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_redirect off; - } - } -} \ No newline at end of file diff --git a/tests/ci/travis/privoxy b/tests/ci/travis/privoxy new file mode 100644 index 00000000..67d8ff89 --- /dev/null +++ b/tests/ci/travis/privoxy @@ -0,0 +1 @@ +listen-address 127.0.0.1:8080 diff --git a/tests/ci/travis/install_apache.sh b/tests/ci/travis/setup_apache.sh old mode 100755 new mode 100644 similarity index 93% rename from tests/ci/travis/install_apache.sh rename to tests/ci/travis/setup_apache.sh index c5b0875e..e5a4c7c0 --- a/tests/ci/travis/install_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -3,7 +3,6 @@ # enable php-fpm # @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php -sudo apt-get install apache2 libapache2-mod-fastcgi sudo a2enmod rewrite actions fastcgi alias # enable php-fpm @@ -15,3 +14,5 @@ echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php sudo cp -f tests/ci/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 + +sudo echo "$(pwd) !!!" diff --git a/tests/ci/travis/install_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh old mode 100755 new mode 100644 similarity index 85% rename from tests/ci/travis/install_apache_hhvm.sh rename to tests/ci/travis/setup_apache_hhvm.sh index 1ff3ddd8..b604f831 --- a/tests/ci/travis/install_apache_hhvm.sh +++ b/tests/ci/travis/setup_apache_hhvm.sh @@ -3,7 +3,6 @@ # enable hhvm-fcgi # @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php -sudo apt-get install apache2 libapache2-mod-fastcgi sudo a2enmod rewrite actions fastcgi alias # start HHVM @@ -12,4 +11,4 @@ hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=tru # 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 \ No newline at end of file +sudo service apache2 restart diff --git a/tests/ci/travis/setup_privoxy.sh b/tests/ci/travis/setup_privoxy.sh new file mode 100644 index 00000000..12e0e614 --- /dev/null +++ b/tests/ci/travis/setup_privoxy.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +# configure privoxy + +sudo cp -f tests/ci/travis/privoxy /etc/privoxy/config +sudo service privoxy restart From f01b57aaef7c73d0d7886c068e486154c9f8d412 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 02:11:58 +0000 Subject: [PATCH 067/228] Fix once more executable bit for travis scripts --- tests/ci/travis/setup_apache.sh | 0 tests/ci/travis/setup_apache_hhvm.sh | 0 tests/ci/travis/setup_privoxy.sh | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 tests/ci/travis/setup_apache.sh mode change 100644 => 100755 tests/ci/travis/setup_apache_hhvm.sh mode change 100644 => 100755 tests/ci/travis/setup_privoxy.sh diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh old mode 100644 new mode 100755 diff --git a/tests/ci/travis/setup_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh old mode 100644 new mode 100755 diff --git a/tests/ci/travis/setup_privoxy.sh b/tests/ci/travis/setup_privoxy.sh old mode 100644 new mode 100755 From 1324df0d98180046cac8d8bdcb97a670ef4909bc Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 02:17:49 +0000 Subject: [PATCH 068/228] Fix tests for linux (broken with multitests inclusion) --- tests/LocalhostMultiTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/LocalhostMultiTest.php b/tests/LocalhostMultiTest.php index e855f216..333ee644 100644 --- a/tests/LocalhostMultiTest.php +++ b/tests/LocalhostMultiTest.php @@ -5,7 +5,7 @@ include_once __DIR__ . '/parse_args.php'; -include_once __DIR__ . '/LocalHostTest.php'; +include_once __DIR__ . '/LocalhostTest.php'; class LocalhostMultiTest extends LocalhostTest { From a124a39067ed378b96ad838200c734ddb5171d08 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 09:59:40 +0000 Subject: [PATCH 069/228] Improve debug messages when running on command line --- src/Client.php | 31 +++++++++++++++++++++++-------- src/Request.php | 36 +++++++++++++++++++++++++++--------- 2 files changed, 50 insertions(+), 17 deletions(-) diff --git a/src/Client.php b/src/Client.php index 4af4dcbf..6ec59eb7 100644 --- a/src/Client.php +++ b/src/Client.php @@ -516,9 +516,7 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, $payload; if ($this->debug > 1) { - print "
\n---SENDING---\n" . htmlentities($op) . "\n---END---\n
"; - // let the client see this now in case http times out... - flush(); + $this->debugMessage("---SENDING---\n$op\n---END---"); } if ($timeout > 0) { @@ -634,7 +632,7 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = } if ($this->debug > 1) { - print "
\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n
"; + $this->debugMessage("---SENDING---\n$payload\n---END---"); // let the client see this now in case http times out... flush(); } @@ -766,15 +764,15 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = $result = curl_exec($curl); if ($this->debug > 1) { - print "
\n---CURL INFO---\n";
+            $message = "---CURL INFO---\n";
             foreach (curl_getinfo($curl) as $name => $val) {
                 if (is_array($val)) {
                     $val = implode("\n", $val);
                 }
-                print $name . ': ' . htmlentities($val) . "\n";
+                $message .= $name . ': ' . $val . "\n";
             }
-
-            print "---END---\n
"; + $message .= "---END---"; + $this->debugMessage($message); } if (!$result) { @@ -992,4 +990,21 @@ private function _try_multicall($msgs, $timeout, $method) return $response; } } + + /** + * Echoes a debug message, taking care of escaping it when not in console mode + * + * @param string $message + */ + protected function debugMessage($message) + { + if (PHP_SAPI != 'cli') { + print "
\n".htmlentities($message)."\n
"; + } + else { + print "\n$message\n"; + } + // let the client see this now in case http times out... + flush(); + } } diff --git a/src/Request.php b/src/Request.php index 7004b545..a466a508 100644 --- a/src/Request.php +++ b/src/Request.php @@ -333,12 +333,12 @@ private function parseResponseHeaders(&$data, $headers_processed = false) if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; if ($this->debug) { - print "
---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n" . htmlentities($data) . "\n---END---
"; + $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); } } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; if ($this->debug) { - print "
---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n" . htmlentities($data) . "\n---END---
"; + $this->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'); @@ -372,7 +372,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty { if ($this->debug) { // by maHo, replaced htmlspecialchars with htmlentities - print "
---GOT---\n" . htmlentities($data) . "\n---END---\n
"; + $this->debugMessage("---GOT---\n$data\n---END---"); } $this->httpResponse = array(); @@ -405,7 +405,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty $start += strlen('', $start); $comments = substr($data, $start, $end - $start); - print "
---SERVER DEBUG INFO (DECODED) ---\n\t" . htmlentities(str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n
"; + $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n
"; } } @@ -512,11 +512,9 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty PhpXmlRpc::$xmlrpcstr['invalid_return']); } else { if ($this->debug) { - print "
---PARSED---\n";
-                // somehow htmlentities chokes on var_export, and some full html string...
-                //print htmlentitites(var_export($xmlRpcParser->_xh['value'], true));
-                print htmlspecialchars(var_export($xmlRpcParser->_xh['value'], true));
-                print "\n---END---
"; + $this->debugMessage( + "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false + ); } // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object. @@ -552,4 +550,24 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty return $r; } + + /** + * Echoes a debug message, taking care of escaping it when not in console mode + * + * @param string $message + */ + protected function debugMessage($message, $encodeEntities = true) + { + if (PHP_SAPI != 'cli') { + if ($encodeEntities) + print "
\n".htmlentities($message)."\n
"; + else + print "
\n".htmlspecialchars($message)."\n
"; + } + else { + print "\n$message\n"; + } + // let the client see this now in case http times out... + flush(); + } } From c2302e5a79c0d99ab7056144d99021694f789611 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 10:05:52 +0000 Subject: [PATCH 070/228] Fix last commit: make it closer to original code --- NEWS | 2 ++ src/Request.php | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index f3cb5304..b1b1e49a 100644 --- a/NEWS +++ b/NEWS @@ -25,6 +25,8 @@ even though we strongly urge you to use more recent versions. * improved: phpunit is now installed via composer, not bundled anymore +* improved: debug messages are not html-escaped when executing from the command line + XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/src/Request.php b/src/Request.php index a466a508..835767a8 100644 --- a/src/Request.php +++ b/src/Request.php @@ -567,7 +567,5 @@ protected function debugMessage($message, $encodeEntities = true) else { print "\n$message\n"; } - // let the client see this now in case http times out... - flush(); } } From 7b485e551efb17e5268fd8c9108865f01792fffa Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 10:21:06 +0000 Subject: [PATCH 071/228] More playing around with travis --- .travis.yml | 2 +- tests/ci/travis/setup_apache.sh | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d8fbb48f..f942a8c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 DEBUG=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 #after_script: # # upload code-coverage to Scrutinizer diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index e5a4c7c0..04a4f8a9 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -16,3 +16,4 @@ sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-availa sudo service apache2 restart sudo echo "$(pwd) !!!" +suco cat /etc/apache2/sites-available/default From 08e34076bdb75f21ce7129deaec1abecc7161b7f Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 10:32:36 +0000 Subject: [PATCH 072/228] Fix travis? --- tests/ci/travis/setup_apache.sh | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index 04a4f8a9..0f2d4e9e 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -11,9 +11,6 @@ echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm # configure apache virtual hosts -sudo cp -f tests/ci/apache_vhost /etc/apache2/sites-available/default +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 - -sudo echo "$(pwd) !!!" -suco cat /etc/apache2/sites-available/default From e29f0952990433bb8589b8da9b6c4fe61807c6b6 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 10:57:10 +0000 Subject: [PATCH 073/228] Display apache logs in travis console --- .travis.yml | 3 ++- tests/ci/travis/apache_vhost | 3 +++ tests/ci/travis/apache_vhost_hhvm | 3 +++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index f942a8c8..c1a57b3f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,7 +29,8 @@ script: # to have code coverage: --coverage-clover=coverage.clover phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 -#after_script: +after_script: + cat $TRAVIS_BUILD_DIR/apache_error.log $TRAVIS_BUILD_DIR/apache_access.log /tmp/hhvm.log # # upload code-coverage to Scrutinizer # - wget https://scrutinizer-ci.com/ocular.phar # - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/tests/ci/travis/apache_vhost b/tests/ci/travis/apache_vhost index 26f70feb..6f052023 100644 --- a/tests/ci/travis/apache_vhost +++ b/tests/ci/travis/apache_vhost @@ -5,6 +5,9 @@ DocumentRoot %TRAVIS_BUILD_DIR% + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + Options FollowSymLinks MultiViews ExecCGI AllowOverride All diff --git a/tests/ci/travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm index 93436f6d..94dfefe1 100644 --- a/tests/ci/travis/apache_vhost_hhvm +++ b/tests/ci/travis/apache_vhost_hhvm @@ -5,6 +5,9 @@ DocumentRoot %TRAVIS_BUILD_DIR% + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + Options FollowSymLinks MultiViews ExecCGI AllowOverride All From 40f550bcdcfddeee3f3533378c7adf673913acef Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 11:22:47 +0000 Subject: [PATCH 074/228] More travis fixes --- .travis.yml | 12 ++++++++---- src/Server.php | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index c1a57b3f..0f0c4212 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,19 +18,23 @@ install: before_script: # Disable xdebug. NB: this should NOT be done for hhvm... - - if [ $TRAVIS_PHP_VERSION != "hhvm" -a $TRAVIS_PHP_VERSION != "7.0" ]; then phpenv config-rm xdebug.ini; fi + - if [ "$TRAVIS_PHP_VERSION" != "hhvm" -a "$TRAVIS_PHP_VERSION" != "7.0" ]; then phpenv config-rm xdebug.ini; fi # We set up an Apache instance inside the Travis VM and test it. - - if [ '$TRAVIS_PHP_VERSION' != 'hhvm' ]; then ./tests/ci/travis/setup_apache.sh; fi - - if [ '$TRAVIS_PHP_VERSION' = 'hhvm' ]; then ./tests/ci/travis/setup_apache_hhvm.sh; fi + - if [ "$TRAVIS_PHP_VERSION" != "hhvm" ]; then ./tests/ci/travis/setup_apache.sh; fi + - if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then ./tests/ci/travis/setup_apache_hhvm.sh; fi - ./tests/ci/travis/setup_privoxy.sh script: # to have code coverage: --coverage-clover=coverage.clover phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 +after_failure: + - cat apache_error.log + - cat apache_access.log + - cat /tmp/hhvm.log + after_script: - cat $TRAVIS_BUILD_DIR/apache_error.log $TRAVIS_BUILD_DIR/apache_access.log /tmp/hhvm.log # # upload code-coverage to Scrutinizer # - wget https://scrutinizer-ci.com/ocular.phar # - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/src/Server.php b/src/Server.php index 5d28c45f..1669e17d 100644 --- a/src/Server.php +++ b/src/Server.php @@ -706,7 +706,7 @@ protected function xml_header($charset_encoding = '') */ public function echoInput() { - $r = new Response(new Value("'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string')); + $r = new Response(new Value("'Aha said I: '" . file_get_contents('php://input'), 'string')); print $r->serialize(); } From 2aa7311f9f86db1115264936be4587fd6c86a813 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 11:34:13 +0000 Subject: [PATCH 075/228] One more travis fix --- src/Server.php | 1 - tests/ci/travis/setup_apache.sh | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Server.php b/src/Server.php index 1669e17d..e1035d3d 100644 --- a/src/Server.php +++ b/src/Server.php @@ -180,7 +180,6 @@ public function serializeDebug($charset_encoding = '') public function service($data = null, $return_payload = false) { if ($data === null) { - // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA $data = file_get_contents('php://input'); } $raw_data = $data; diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index 0f2d4e9e..f3caeb70 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -8,6 +8,7 @@ sudo a2enmod rewrite actions fastcgi alias # enable php-fpm sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf 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 # configure apache virtual hosts From 349c912d9033eda55e2ba735ace21ab3cebb3782 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 22:05:13 +0000 Subject: [PATCH 076/228] Try fixing Travis/php7 --- tests/ci/travis/setup_apache.sh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index f3caeb70..b000f7f9 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -7,6 +7,16 @@ sudo a2enmod rewrite actions fastcgi alias # 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 + echo "[www]" > ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "user = travis" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "listen = 127.0.0.1:9000" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "pm = dynamic" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "pm.max_children = 5" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "pm.min_spare_servers = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + echo "pm.max_spare_servers = 3" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.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 From 39b782fc694ef1ea3e1a2cff1c0bc82212e47273 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 22:14:30 +0000 Subject: [PATCH 077/228] Alternative take on last fix --- tests/ci/travis/setup_apache.sh | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index b000f7f9..bdb57498 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -9,13 +9,7 @@ sudo a2enmod rewrite actions fastcgi alias 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 - echo "[www]" > ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "user = travis" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "listen = 127.0.0.1:9000" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "pm = dynamic" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "pm.max_children = 5" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "pm.min_spare_servers = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf - echo "pm.max_spare_servers = 3" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/travis.conf + 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 From 048358caae836a0e0d6a28956acf80c84e480aa3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 20 Mar 2015 23:31:55 +0000 Subject: [PATCH 078/228] Rename the test files to insure a better test execution order --- tests/{ParsingBugsTest.php => 1ParsingBugsTest.php} | 0 tests/{InvalidHostTest.php => 2InvalidHostTest.php} | 0 tests/{LocalhostTest.php => 3LocalhostTest.php} | 0 tests/{LocalhostMultiTest.php => 4LocalhostMultiTest.php} | 2 +- 4 files changed, 1 insertion(+), 1 deletion(-) rename tests/{ParsingBugsTest.php => 1ParsingBugsTest.php} (100%) rename tests/{InvalidHostTest.php => 2InvalidHostTest.php} (100%) rename tests/{LocalhostTest.php => 3LocalhostTest.php} (100%) rename tests/{LocalhostMultiTest.php => 4LocalhostMultiTest.php} (99%) diff --git a/tests/ParsingBugsTest.php b/tests/1ParsingBugsTest.php similarity index 100% rename from tests/ParsingBugsTest.php rename to tests/1ParsingBugsTest.php diff --git a/tests/InvalidHostTest.php b/tests/2InvalidHostTest.php similarity index 100% rename from tests/InvalidHostTest.php rename to tests/2InvalidHostTest.php diff --git a/tests/LocalhostTest.php b/tests/3LocalhostTest.php similarity index 100% rename from tests/LocalhostTest.php rename to tests/3LocalhostTest.php diff --git a/tests/LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php similarity index 99% rename from tests/LocalhostMultiTest.php rename to tests/4LocalhostMultiTest.php index 333ee644..15387f0b 100644 --- a/tests/LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -5,7 +5,7 @@ include_once __DIR__ . '/parse_args.php'; -include_once __DIR__ . '/LocalhostTest.php'; +include_once __DIR__ . '/3LocalhostTest.php'; class LocalhostMultiTest extends LocalhostTest { From 542252a999f0662c41a8d2790a560a2b0f6426fe Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 00:23:25 +0000 Subject: [PATCH 079/228] Ignore test coverage data --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index a344dca6..70c1a68e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ composer.phar composer.lock /vendor/* +/tests/coverage/* From ca57a23c74972cfd6fae0e8a79d7f5e8226c6077 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 00:24:07 +0000 Subject: [PATCH 080/228] Try using localhost for https tests on Travis --- .travis.yml | 2 +- tests/ci/travis/setup_apache.sh | 3 ++- tests/ci/travis/setup_apache_hhvm.sh | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0f0c4212..70c2801b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=gggeek.ssl.altervista.org HTTPSURI=/sw/xmlrpc/demo/server/server.php PROXY=localhost:8080 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 after_failure: - cat apache_error.log diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index bdb57498..d375e68e 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -3,7 +3,8 @@ # enable 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 +sudo a2enmod rewrite actions fastcgi alias ssl +sudo a2ensite default-ssl # enable php-fpm sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf diff --git a/tests/ci/travis/setup_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh index b604f831..80ed1c00 100755 --- a/tests/ci/travis/setup_apache_hhvm.sh +++ b/tests/ci/travis/setup_apache_hhvm.sh @@ -3,7 +3,8 @@ # enable 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 +sudo a2enmod rewrite actions fastcgi alias ssl +sudo a2ensite default-ssl # start HHVM hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true From d4600d3552724e83c4018ca7fc46cda355a05db7 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 00:36:08 +0000 Subject: [PATCH 081/228] 2nd try at local https on travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 70c2801b..1f977c72 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSIGNOREPEER=1 after_failure: - cat apache_error.log From 21102fbba8e01df255cf378126fe55f17c7d1114 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 00:53:19 +0000 Subject: [PATCH 082/228] travis testing --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1f977c72..287dc4eb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,7 +32,7 @@ script: after_failure: - cat apache_error.log - cat apache_access.log - - cat /tmp/hhvm.log + - cat /etc/apache2/sites-available/default-ssl after_script: # # upload code-coverage to Scrutinizer From b0038f511df6f08e5cfbad06c7c139761722302f Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 01:10:49 +0000 Subject: [PATCH 083/228] One more travis https test --- .travis.yml | 2 +- tests/ci/travis/apache_vhost | 43 +++++++++++++++++++++++++- tests/ci/travis/apache_vhost_hhvm | 46 +++++++++++++++++++++++++++- tests/ci/travis/setup_apache.sh | 1 - tests/ci/travis/setup_apache_hhvm.sh | 1 - 5 files changed, 88 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 287dc4eb..b446cc68 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,7 +32,7 @@ script: after_failure: - cat apache_error.log - cat apache_access.log - - cat /etc/apache2/sites-available/default-ssl + - cat /etc/ssl/certs/ssl-cert-snakeoil.pem after_script: # # upload code-coverage to Scrutinizer diff --git a/tests/ci/travis/apache_vhost b/tests/ci/travis/apache_vhost index 6f052023..e4d2bf75 100644 --- a/tests/ci/travis/apache_vhost +++ b/tests/ci/travis/apache_vhost @@ -23,4 +23,45 @@ FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization - \ No newline at end of file + + + + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Wire up Apache to use Travis CI's php-fpm. + + 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 + + + SSLEngine on + SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem + SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key + + + SSLOptions +StdEnvVars + + + BrowserMatch "MSIE [2-6]" \ + nokeepalive ssl-unclean-shutdown \ + downgrade-1.0 force-response-1.0 + BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown + + + + \ No newline at end of file diff --git a/tests/ci/travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm index 94dfefe1..1afe0ff5 100644 --- a/tests/ci/travis/apache_vhost_hhvm +++ b/tests/ci/travis/apache_vhost_hhvm @@ -26,4 +26,48 @@ FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 - \ No newline at end of file + + + + + + + DocumentRoot %TRAVIS_BUILD_DIR% + + ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log" + CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined + + + Options FollowSymLinks MultiViews ExecCGI + AllowOverride All + Order deny,allow + Allow from all + + + # Configure Apache for HHVM FastCGI. + # See https://github.com/facebook/hhvm/wiki/fastcgi + + + SetHandler hhvm-php-extension + + Alias /hhvm /hhvm + Action hhvm-php-extension /hhvm virtual + FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 + + + SSLEngine on + SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem + SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key + + + SSLOptions +StdEnvVars + + + BrowserMatch "MSIE [2-6]" \ + nokeepalive ssl-unclean-shutdown \ + downgrade-1.0 force-response-1.0 + BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown + + + + \ No newline at end of file diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index d375e68e..4aff745a 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -4,7 +4,6 @@ # @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 -sudo a2ensite default-ssl # enable php-fpm sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf diff --git a/tests/ci/travis/setup_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh index 80ed1c00..7d86a091 100755 --- a/tests/ci/travis/setup_apache_hhvm.sh +++ b/tests/ci/travis/setup_apache_hhvm.sh @@ -4,7 +4,6 @@ # @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 -sudo a2ensite default-ssl # start HHVM hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true From 4cb5eddd5dad8aa31c9a5d3fa69294989207f1bd Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 01:15:36 +0000 Subject: [PATCH 084/228] one more --- tests/ci/travis/apache_vhost | 2 +- tests/ci/travis/apache_vhost_hhvm | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ci/travis/apache_vhost b/tests/ci/travis/apache_vhost index e4d2bf75..12448940 100644 --- a/tests/ci/travis/apache_vhost +++ b/tests/ci/travis/apache_vhost @@ -46,7 +46,7 @@ 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 + #FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization SSLEngine on diff --git a/tests/ci/travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm index 1afe0ff5..f0ad9f48 100644 --- a/tests/ci/travis/apache_vhost_hhvm +++ b/tests/ci/travis/apache_vhost_hhvm @@ -52,7 +52,7 @@ Alias /hhvm /hhvm Action hhvm-php-extension /hhvm virtual - FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 + #FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300 SSLEngine on From e640c12e8f1cbc263f766035b0113ad132285e2a Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 17:28:26 +0000 Subject: [PATCH 085/228] Fix (hopefully) the Travis tests using https for localhost --- .travis.yml | 3 +-- tests/3LocalhostTest.php | 2 +- tests/4LocalhostMultiTest.php | 2 ++ tests/ci/travis/apache_vhost | 3 ++- tests/ci/travis/apache_vhost_hhvm | 3 ++- tests/parse_args.php | 8 +++++++- 6 files changed, 15 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index b446cc68..66de8b09 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,12 +27,11 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSIGNOREPEER=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 after_failure: - cat apache_error.log - cat apache_access.log - - cat /etc/ssl/certs/ssl-cert-snakeoil.pem after_script: # # upload code-coverage to Scrutinizer diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 562dbb51..a7735486 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -23,7 +23,7 @@ public static function fail($message = '') // (but only if not called from subclass objects / multitests) if (function_exists('debug_backtrace') && strtolower(get_called_class()) == 'localhosttests') { global $failed_tests; - $trace = debug_backtrace(); + $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; diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 15387f0b..2b2ba670 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -154,6 +154,7 @@ function testHttps() $this->client->method = 'https'; $this->client->path = $this->args['HTTPSURI']; $this->client->setSSLVerifyPeer( !$this->args['HTTPSIGNOREPEER'] ); + $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST'] ); $this->_runtests(); } @@ -175,6 +176,7 @@ function testHttpsProxy() $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->_runtests(); } diff --git a/tests/ci/travis/apache_vhost b/tests/ci/travis/apache_vhost index 12448940..87841d6e 100644 --- a/tests/ci/travis/apache_vhost +++ b/tests/ci/travis/apache_vhost @@ -50,6 +50,7 @@ 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 @@ -64,4 +65,4 @@ - \ No newline at end of file + diff --git a/tests/ci/travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm index f0ad9f48..63e57dae 100644 --- a/tests/ci/travis/apache_vhost_hhvm +++ b/tests/ci/travis/apache_vhost_hhvm @@ -56,6 +56,7 @@ 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 @@ -70,4 +71,4 @@ - \ No newline at end of file + diff --git a/tests/parse_args.php b/tests/parse_args.php index e9f2e2eb..0d211915 100644 --- a/tests/parse_args.php +++ b/tests/parse_args.php @@ -10,8 +10,10 @@ * @param string HTTPSSURI * @param string PROXY * @param string NOPROXY + * @param bool HTTPSIGNOREPEER + * @param int HTTPSVERIFYHOST * - * @copyright (C) 2007-20014 G. Giunta + * @copyright (C) 2007-2015 G. Giunta * @license code licensed under the BSD License: see file license.txt **/ class argParser @@ -26,6 +28,7 @@ public static function getArgs() 'HTTPSSERVER' => 'gggeek.ssl.altervista.org', 'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php', 'HTTPSIGNOREPEER' => false, + 'HTTPSVERIFYHOST' => 2, 'PROXYSERVER' => null, 'NOPROXY' => false, 'LOCALPATH' => __DIR__, @@ -69,6 +72,9 @@ public static function getArgs() if (isset($HTTPSIGNOREPEER)) { $args['HTTPSIGNOREPEER'] = (bool)$HTTPSIGNOREPEER; } + if (isset($HTTPSVERIFYHOST)) { + $args['HTTPSVERIFYHOST'] = (int)$HTTPSVERIFYHOST; + } if (isset($PROXY)) { $arr = explode(':', $PROXY); $args['PROXYSERVER'] = $arr[0]; From 2b78aa61211d40a72b60322bc27737b5d09bba8c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 17:40:01 +0000 Subject: [PATCH 086/228] one more try --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 66de8b09..3e08e6b5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 after_failure: - cat apache_error.log From 9423ab9a69fe854e751673920b0974a79ca52ee8 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 18:05:18 +0000 Subject: [PATCH 087/228] Allow the tests to use a version of SSL which should not conflict with curl/gnutls for travis... --- .travis.yml | 3 ++- src/Client.php | 22 ++++++++++++++++++---- tests/4LocalhostMultiTest.php | 10 ++++++---- tests/parse_args.php | 5 +++++ 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3e08e6b5..9d27df43 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,11 +27,12 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 SSLVERSION=3 after_failure: - cat apache_error.log - cat apache_access.log + - php -i after_script: # # upload code-coverage to Scrutinizer diff --git a/src/Client.php b/src/Client.php index 6ec59eb7..4586b707 100644 --- a/src/Client.php +++ b/src/Client.php @@ -23,6 +23,7 @@ class Client public $keypass = ''; public $verifypeer = true; public $verifyhost = 2; + public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT public $no_multicall = false; public $proxy = ''; public $proxyport = 0; @@ -218,6 +219,16 @@ public function setSSLVerifyHost($i) $this->verifyhost = $i; } + /** + * Set attributes for SSL communication: SSL version to use. Best left at 0 (default value ): let cURL decide + * + * @param int $i + */ + public function setSSLVersion($i) + { + $this->sslversion = $i; + } + /** * Set proxy info. * @@ -364,7 +375,8 @@ public function & send($msg, $timeout = 0, $method = '') $this->proxy_authtype, $this->keepalive, $this->key, - $this->keypass + $this->keypass, + $this->sslversion ); } elseif ($method == 'http11') { $r = $this->sendPayloadCURL( @@ -562,11 +574,11 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, private function sendPayloadHTTPS($msg, $server, $port, $timeout = 0, $username = '', $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, - $keepalive = false, $key = '', $keypass = '') + $keepalive = false, $key = '', $keypass = '', $sslversion = 0) { $r = $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, - $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass); + $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass, $sslversion); return $r; } @@ -579,7 +591,7 @@ private function sendPayloadHTTPS($msg, $server, $port, $timeout = 0, $username private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '', $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, $method = 'https', - $keepalive = false, $key = '', $keypass = '') + $keepalive = false, $key = '', $keypass = '', $sslversion = 0) { if (!function_exists('curl_init')) { $this->errstr = 'CURL unavailable on this install'; @@ -727,6 +739,8 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = } // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); + // allow usage of different SSL versions + curl_setopt($curl, CURLOPT_SSLVERSION, $sslversion); } // proxy info diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 2b2ba670..51a89332 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -153,8 +153,9 @@ function testHttps() $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->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']); + $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']); + $this->client->setSSLVersion($this->args['SSLVERSION']); $this->_runtests(); } @@ -175,8 +176,9 @@ function testHttpsProxy() $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->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']); + $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']); + $this->client->setSSLVersion($this->args['SSLVERSION']); $this->_runtests(); } diff --git a/tests/parse_args.php b/tests/parse_args.php index 0d211915..b2e438ea 100644 --- a/tests/parse_args.php +++ b/tests/parse_args.php @@ -12,6 +12,7 @@ * @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 @@ -29,6 +30,7 @@ public static function getArgs() 'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php', 'HTTPSIGNOREPEER' => false, 'HTTPSVERIFYHOST' => 2, + 'SSLVERSION' => 0, 'PROXYSERVER' => null, 'NOPROXY' => false, 'LOCALPATH' => __DIR__, @@ -75,6 +77,9 @@ public static function getArgs() if (isset($HTTPSVERIFYHOST)) { $args['HTTPSVERIFYHOST'] = (int)$HTTPSVERIFYHOST; } + if (isset($SSLVERSION)) { + $args['SSLVERSION'] = (int)$SSLVERSION; + } if (isset($PROXY)) { $arr = explode(':', $PROXY); $args['PROXYSERVER'] = $arr[0]; From c19e9f69d58624c56cd835ed8344498d8ec1ba40 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 18:11:02 +0000 Subject: [PATCH 088/228] Nth time is a charm? --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9d27df43..ecb7e356 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ before_script: script: # to have code coverage: --coverage-clover=coverage.clover - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 SSLVERSION=3 + phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 after_failure: - cat apache_error.log From f608df9f126422c61d8555e84613f0cc87f585bb Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 18:29:53 +0000 Subject: [PATCH 089/228] Reorganize travis scripts for clarity --- .travis.yml | 16 ++++++++++------ tests/ci/travis/setup_apache.sh | 12 +----------- tests/ci/travis/setup_apache_hhvm.sh | 5 +---- tests/ci/travis/setup_hhvm.sh | 4 ++++ tests/ci/travis/setup_php_fpm.sh | 11 +++++++++++ 5 files changed, 27 insertions(+), 21 deletions(-) create mode 100644 tests/ci/travis/setup_hhvm.sh create mode 100644 tests/ci/travis/setup_php_fpm.sh diff --git a/.travis.yml b/.travis.yml index ecb7e356..1ad93c5d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,32 +9,36 @@ php: - hhvm before_install: + # This is mandatory or the 'apt-get install' calls following will fail - sudo apt-get update -qq - -install: - 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. NB: this should NOT be done for hhvm... - if [ "$TRAVIS_PHP_VERSION" != "hhvm" -a "$TRAVIS_PHP_VERSION" != "7.0" ]; then phpenv config-rm xdebug.ini; fi - # We set up an Apache instance inside the Travis VM and test it. - - if [ "$TRAVIS_PHP_VERSION" != "hhvm" ]; then ./tests/ci/travis/setup_apache.sh; fi - - if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then ./tests/ci/travis/setup_apache_hhvm.sh; 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: # to have code coverage: --coverage-clover=coverage.clover + # 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 phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 after_failure: + # Save as much info as we can to help developers - cat apache_error.log - cat apache_access.log - php -i after_script: -# # upload code-coverage to Scrutinizer +# # Upload code-coverage to Scrutinizer # - wget https://scrutinizer-ci.com/ocular.phar # - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh index 4aff745a..a39d6762 100755 --- a/tests/ci/travis/setup_apache.sh +++ b/tests/ci/travis/setup_apache.sh @@ -1,20 +1,10 @@ #!/bin/sh -# enable php-fpm +# 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 -# 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 - # 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 diff --git a/tests/ci/travis/setup_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh index 7d86a091..a72941d8 100755 --- a/tests/ci/travis/setup_apache_hhvm.sh +++ b/tests/ci/travis/setup_apache_hhvm.sh @@ -1,13 +1,10 @@ #!/bin/sh -# enable hhvm-fcgi +# 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 -# start HHVM -hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true - # 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 diff --git a/tests/ci/travis/setup_hhvm.sh b/tests/ci/travis/setup_hhvm.sh new file mode 100644 index 00000000..289e7509 --- /dev/null +++ b/tests/ci/travis/setup_hhvm.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +# start HHVM +hhvm -m daemon -vServer.Type=fastcgi -vServer.Port=9000 -vServer.FixPathInfo=true diff --git a/tests/ci/travis/setup_php_fpm.sh b/tests/ci/travis/setup_php_fpm.sh new file mode 100644 index 00000000..7788fdca --- /dev/null +++ b/tests/ci/travis/setup_php_fpm.sh @@ -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 From f2b6751edc41d60ec887103d5553b795df54b18c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 21 Mar 2015 18:31:13 +0000 Subject: [PATCH 090/228] Set executable bit on shell scripts --- tests/ci/travis/setup_hhvm.sh | 0 tests/ci/travis/setup_php_fpm.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 tests/ci/travis/setup_hhvm.sh mode change 100644 => 100755 tests/ci/travis/setup_php_fpm.sh diff --git a/tests/ci/travis/setup_hhvm.sh b/tests/ci/travis/setup_hhvm.sh old mode 100644 new mode 100755 diff --git a/tests/ci/travis/setup_php_fpm.sh b/tests/ci/travis/setup_php_fpm.sh old mode 100644 new mode 100755 From 9dd901312ce5ac5a1d4b7da7b90167c9b782f1ed Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 00:21:43 +0000 Subject: [PATCH 091/228] When using phpunit to generate code coverage, take into account what is executed server-side --- NEWS | 9 ++++- demo/server/server.php | 19 ++++++++++- tests/3LocalhostTest.php | 69 ++++++++++++++++++++++++++++++++------ tests/phpunit_coverage.php | 16 +++++++++ 4 files changed, 101 insertions(+), 12 deletions(-) create mode 100644 tests/phpunit_coverage.php diff --git a/NEWS b/NEWS index b1b1e49a..236358c5 100644 --- a/NEWS +++ b/NEWS @@ -19,13 +19,20 @@ even though we strongly urge you to use more recent versions. * improved: all php code is now formatted according to the PSR-2 standard * improved: this release 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 * improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds * improved: phpunit is now installed via composer, not bundled anymore -* improved: debug messages are not html-escaped when executing from the command line +* improved: when phpunit is used to generate code-coverage data, the code executed server-side is accounted for + +* improved: debug messages are not html-escaped any more when executing from the command line + +* improved: a specific option allow 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 Travis) XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/demo/server/server.php b/demo/server/server.php index 5f34c751..b6fa5261 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -17,6 +17,17 @@ 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"; +} + include_once __DIR__ . "/../../lib/xmlrpc.inc"; include_once __DIR__ . "/../../lib/xmlrpcs.inc"; include_once __DIR__ . "/../../lib/xmlrpc_wrappers.inc"; @@ -36,7 +47,7 @@ public function phpwarninggenerator($m) } /** - * Method used to testcatching of exceptions in the server. + * Method used to test catching of exceptions in the server. */ public function exceptiongenerator($m) { @@ -877,3 +888,9 @@ function i_whichToolkit($m) } $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"; +} \ No newline at end of file diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index a7735486..0dce5682 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -8,21 +8,25 @@ class LocalhostTest extends PHPUnit_Framework_TestCase { /** @var xmlrpc_client $client */ - public $client = null; - public $method = 'http'; - public $timeout = 10; - public $request_compression = null; - public $accepted_compression = ''; - public $args = array(); + 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 global var that this particular test has failed + // 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') { - global $failed_tests; $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); for ($i = 0; $i < count($trace); $i++) { if (strpos($trace[$i]['function'], 'test') === 0) { @@ -36,8 +40,41 @@ public static function fail($message = '') } /** - * @todo be smarter with setup, do not use global variables anymore + * 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(); @@ -53,10 +90,16 @@ public function setUp() } $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'] ); } - public function send($msg, $errrorcode = 0, $return_response = false) + protected function send($msg, $errrorcode = 0, $return_response = 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)) { @@ -574,6 +617,12 @@ public function testSetCookies() 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($v, $cookies); } diff --git a/tests/phpunit_coverage.php b/tests/phpunit_coverage.php new file mode 100644 index 00000000..ae7b998b --- /dev/null +++ b/tests/phpunit_coverage.php @@ -0,0 +1,16 @@ + Date: Sun, 22 Mar 2015 11:17:52 +0000 Subject: [PATCH 092/228] 1st attempt at having code-coverage info for tests uploaded to online QA services --- .travis.yml | 17 ++++++++++------- composer.json | 4 +++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1ad93c5d..6c822694 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,8 +18,10 @@ install: - composer self-update && composer install before_script: - # Disable xdebug. NB: this should NOT be done for hhvm... - - if [ "$TRAVIS_PHP_VERSION" != "hhvm" -a "$TRAVIS_PHP_VERSION" != "7.0" ]; then phpenv config-rm xdebug.ini; fi + # 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 @@ -27,10 +29,9 @@ before_script: - ./tests/ci/travis/setup_privoxy.sh script: - # to have code coverage: --coverage-clover=coverage.clover # 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 - phpunit tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 + phpunit tests --coverage-clover=coverage.clover LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 after_failure: # Save as much info as we can to help developers @@ -39,6 +40,8 @@ after_failure: - php -i after_script: -# # Upload code-coverage to Scrutinizer -# - wget https://scrutinizer-ci.com/ocular.phar -# - php ocular.phar code-coverage:upload --format=php-clover coverage.clover + # 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; fi diff --git a/composer.json b/composer.json index 7e1a9af2..bae04ba9 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,9 @@ "ext-xml": "*" }, "require-dev": { - "phpunit/phpunit": ">=4.0.0" + "phpunit/phpunit": ">=4.0.0", + "phpunit/phpunit-selenium": "*", + "codeclimate/php-test-reporter": "dev-master" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", From 2beedd345c6647f1f6086ee28b10814111438460 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 11:28:13 +0000 Subject: [PATCH 093/228] 2nd try at code coverage upload --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6c822694..b0aaab30 100644 --- a/.travis.yml +++ b/.travis.yml @@ -44,4 +44,4 @@ after_script: - 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; fi + - if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then CODECLIMATE_REPO_TOKEN=7fa6ee01e345090e059e5e42f3bfbcc8692feb8340396382dd76390a3019ac13 ./vendor/bin/test-reporter --coverage-report=coverage.clover; fi From fa84f7b07a820b4a666239e0e2dc3ce1c5f2bfd5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 11:32:00 +0000 Subject: [PATCH 094/228] Try again at generating test coverage --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b0aaab30..02bdd53a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,7 @@ before_script: 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 - phpunit tests --coverage-clover=coverage.clover LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 + 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 after_failure: # Save as much info as we can to help developers From ca1f975d1fca1ff738a239081e48541f0f465e79 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 11:41:30 +0000 Subject: [PATCH 095/228] Add badges with code coverage results for scrutinizer and code-climate --- NEWS | 3 ++- README.md | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 236358c5..fc174fb8 100644 --- a/NEWS +++ b/NEWS @@ -19,7 +19,8 @@ even though we strongly urge you to use more recent versions. * improved: all php code is now formatted according to the PSR-2 standard * improved: this release 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 + 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: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds diff --git a/README.md b/README.md index 037b73f6..7f431208 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ [![Build Status](https://travis-ci.org/gggeek/phpxmlrpc.svg?branch=php53)](https://travis-ci.org/gggeek/phpxmlrpc) +[![Code Climate](https://codeclimate.com/github/gggeek/phpxmlrpc/badges/gpa.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) XMLRPC for PHP ============== From 8304a6a27040163f2675482608ded9ed6d17fd63 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 11:44:03 +0000 Subject: [PATCH 096/228] Fix badge linking to code coverage --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f431208..81c27b13 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ [![Build Status](https://travis-ci.org/gggeek/phpxmlrpc.svg?branch=php53)](https://travis-ci.org/gggeek/phpxmlrpc) -[![Code Climate](https://codeclimate.com/github/gggeek/phpxmlrpc/badges/gpa.svg)](https://codeclimate.com/github/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) XMLRPC for PHP From e75bfc4ad39a6f30b0b9840f3c63b2f14a1c12c4 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 18:51:02 +0000 Subject: [PATCH 097/228] Improve phpdocs; fix Request dumping http headers with proper format --- src/Request.php | 21 ++++++++++----------- src/Value.php | 8 ++++---- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/Request.php b/src/Request.php index 835767a8..a136bb32 100644 --- a/src/Request.php +++ b/src/Request.php @@ -19,7 +19,7 @@ class Request /** * @param string $methodName the name of the method to invoke - * @param array $params array of parameters to be passed to the method (xmlrpcval objects) + * @param Value[] $params array of parameters to be passed to the method (Value objects) */ public function __construct($methodName, $params = array()) { @@ -74,7 +74,7 @@ public function createPayload($charset_encoding = '') /** * Gets/sets the xmlrpc method to be invoked. * - * @param string $meth the method to be set (leave empty not to set it) + * @param string $methodName the method to be set (leave empty not to set it) * * @return string the method that will be invoked */ @@ -104,7 +104,7 @@ public function serialize($charset_encoding = '') /** * Add a parameter to the list of parameters to be used upon method invocation. * - * @param Value $par + * @param Value $param * * @return boolean false on failure */ @@ -133,7 +133,7 @@ public function getParam($i) } /** - * Returns the number of parameters in the messge. + * Returns the number of parameters in the message. * * @return integer the number of parameters currently set */ @@ -143,7 +143,7 @@ public function getNumParams() } /** - * Given an open file handle, read all data available and parse it as axmlrpc response. + * 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). @@ -297,17 +297,16 @@ private function parseResponseHeaders(&$data, $headers_processed = false) } $data = substr($data, $bd); - - /// @todo when in CLI mode, do not html-encode the output + if ($this->debug && count($this->httpResponse['headers'])) { - print "
\n"; + $msg = ''; foreach ($this->httpResponse['headers'] as $header => $value) { - print htmlentities("HEADER: $header: $value\n"); + $msg .= "HEADER: $header: $value\n"; } foreach ($this->httpResponse['cookies'] as $header => $value) { - print htmlentities("COOKIE: $header={$value['value']}\n"); + $msg .= "COOKIE: $header={$value['value']}\n"; } - print "
\n"; + $this->debugMessage($msg); } // if CURL was used for the call, http headers have been processed, diff --git a/src/Value.php b/src/Value.php index 76d3a029..e47e954b 100644 --- a/src/Value.php +++ b/src/Value.php @@ -154,7 +154,7 @@ public function addScalar($val, $type = 'string') /** * Add an array of xmlrpcval objects to an xmlrpcval. * - * @param array $vals + * @param Value[] $vals * * @return int 1 or 0 on failure * @@ -182,7 +182,7 @@ public function addArray($vals) /** * Add an array of named xmlrpcval objects to an xmlrpcval. * - * @param array $vals + * @param Value[] $vals * * @return int 1 or 0 on failure * @@ -372,7 +372,7 @@ public function structmemexists($m) * * @param string $m the name of the struct member to be looked up * - * @return xmlrpcval + * @return Value */ public function structmem($m) { @@ -467,7 +467,7 @@ public function scalartyp() * * @param integer $m the index of the value to be retrieved (zero based) * - * @return xmlrpcval + * @return Value */ public function arraymem($m) { From 6fb8db98b4fb1f9813d8426bb576fba08d46b4ff Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 18:51:22 +0000 Subject: [PATCH 098/228] Avoid use of return-by-ref for send() calls --- src/Client.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Client.php b/src/Client.php index 4586b707..ce1d6a5c 100644 --- a/src/Client.php +++ b/src/Client.php @@ -327,13 +327,13 @@ public function SetUserAgent($agentstring) /** * Send an xmlrpc request. * - * @param mixed $msg The request object, or an array of requests for using multicall, or the complete xml representation of a request + * @param Request|Request[]|string $msg The Request object, or an array of requests for using multicall, or the complete xml representation of a request * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used * * @return Response */ - public function & send($msg, $timeout = 0, $method = '') + public function send($msg, $timeout = 0, $method = '') { // if user does not specify http protocol, use native method of this client // (i.e. method set during call to constructor) From e63c9427bdc9c398acbe906dfb3538727e05ae81 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 22 Mar 2015 18:52:31 +0000 Subject: [PATCH 099/228] Add an autoloader --- src/Autoloader.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/Autoloader.php diff --git a/src/Autoloader.php b/src/Autoloader.php new file mode 100644 index 00000000..b03b1cb3 --- /dev/null +++ b/src/Autoloader.php @@ -0,0 +1,36 @@ + Date: Sun, 22 Mar 2015 18:53:09 +0000 Subject: [PATCH 100/228] Start clean up of demo code: use new API, camelCase variables, readable variables, usage of autoloader, simpler client constructor --- demo/client/agesort.php | 48 ++++++++++++---------- demo/client/client.php | 34 ++++++++------- demo/client/comment.php | 41 ++++++++++--------- demo/client/introspect.php | 29 +++++++------ demo/client/mail.php | 52 +++++++++++------------ demo/client/simple_call.php | 10 +++-- demo/client/which.php | 30 ++++++++------ demo/client/wrap.php | 46 +++++++++++---------- demo/client/zopetest.php | 28 +++++++------ demo/server/discuss.php | 10 ++--- demo/server/proxy.php | 8 ++-- demo/server/server.php | 82 ++++++++++++++++++------------------- demo/vardemo.php | 46 ++++++++++----------- 13 files changed, 239 insertions(+), 225 deletions(-) diff --git a/demo/client/agesort.php b/demo/client/agesort.php index 6e00de0c..7f870c63 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -1,5 +1,5 @@ -xmlrpc +xmlrpc - Agesort demo

Agesort demo

@@ -9,12 +9,13 @@

24, "Edd" => 45, "Joe" => 37, "Fred" => 27); -reset($inAr); print "This is the input data:
";
-while (list($key, $val) = each($inAr)) {
+foreach($inAr as $key => $val) {
     print $key . ", " . $val . "\n";
 }
 print "
"; @@ -22,41 +23,46 @@ // create parameters from the input array: an xmlrpc array of xmlrpc structs $p = array(); foreach ($inAr as $key => $val) { - $p[] = new xmlrpcval(array("name" => new xmlrpcval($key), - "age" => new xmlrpcval($val, "int")), "struct"); + $p[] = new PhpXmlRpc\Value( + array( + "name" => new PhpXmlRpc\Value($key), + "age" => new PhpXmlRpc\Value($val, "int") + ), + "struct" + ); } -$v = new xmlrpcval($p, "array"); +$v = new PhpXmlRpc\Value($p, "array"); print "Encoded into xmlrpc format it looks like this:
\n" . htmlentities($v->serialize()) . "
\n"; // create client and message objects -$f = new xmlrpcmsg('examples.sortByAge', array($v)); -$c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); +$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 -$c->setDebug(2); +$client->setDebug(2); // send request print "Now sending request (detailed debug info follows)"; -$r = &$c->send($f); +$resp = $client->send($req); // check response for errors, and take appropriate action -if (!$r->faultCode()) { +if (!$resp->faultCode()) { print "The server gave me these results:
";
-    $v = $r->value();
-    $max = $v->arraysize();
+    $value = $resp->value();
+    $max = $value->arraysize();
     for ($i = 0; $i < $max; $i++) {
-        $rec = $v->arraymem($i);
-        $n = $rec->structmem("name");
-        $a = $rec->structmem("age");
-        print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";
+        $struct = $value->arraymem($i);
+        $name = $struct->structmem("name");
+        $age = $struct->structmem("age");
+        print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
     }
 
     print "
For nerds: I got this value back
" .
-        htmlentities($r->serialize()) . "

\n"; + htmlentities($resp->serialize()) . "

\n"; } else { print "An error occurred:
";
-    print "Code: " . htmlspecialchars($r->faultCode()) .
-        "\nReason: '" . htmlspecialchars($r->faultString()) . '\'

'; + print "Code: " . htmlspecialchars($resp->faultCode()) . + "\nReason: '" . htmlspecialchars($resp->faultString()) . '\'
'; } ?> diff --git a/demo/client/client.php b/demo/client/client.php index 755729de..06a256a1 100644 --- a/demo/client/client.php +++ b/demo/client/client.php @@ -1,5 +1,5 @@ -xmlrpc +xmlrpc - Getstatename demo

Getstatename demo

@@ -7,26 +7,24 @@

The code demonstrates usage of the php_xmlrpc_encode function

encode($stateNo)) ); - print "
Sending the following request:\n\n" . htmlentities($f->serialize()) . "\n\nDebug info of server data follows...\n\n";
-    $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80);
-    $c->setDebug(1);
-    $r = &$c->send($f);
+    print "Sending the following request:
\n\n" . htmlentities($req->serialize()) . "\n\n
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 "

State number " . $stateno . " is " - . htmlspecialchars($v->scalarval()) . "
"; + print "
State number " . $stateNo . " is " + . htmlspecialchars($v->scalarval()) . "
"; // print "
I got this value back
" .
         //  htmlentities($r->serialize()). "

\n"; } else { @@ -35,11 +33,11 @@ . " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; } } else { - $stateno = ""; + $stateNo = ""; } print "
-
+

Enter a state number to query its name

"; ?> diff --git a/demo/client/comment.php b/demo/client/comment.php index e457836f..2c34d3f2 100644 --- a/demo/client/comment.php +++ b/demo/client/comment.php @@ -1,7 +1,9 @@ send($msg); + $req = new PhpXmlRpc\Request($method, $args); + $resp = $client->send($req); if (!$resp) { print "

IO error: " . $client->errstr . "

"; bomb(); @@ -24,12 +26,12 @@ function dispatch($client, $method, $args) bomb(); } - return php_xmlrpc_decode($resp->value()); + $encoder = new PhpXmlRpc\Encoder(); + return $encoder->decode($resp->value()); } // create client for discussion server -$dclient = new xmlrpc_client("${mydir}/discuss.php", - "xmlrpc.usefulinc.com", 80); +$dclient = new PhpXmlRpc\Client("http://xmlrpc.usefulinc.com/${mydir}discuss.php"); // check if we're posting a comment, and send it if so @$storyid = $_POST["storyid"]; @@ -38,9 +40,9 @@ function dispatch($client, $method, $args) // print "Returning to " . $HTTP_POST_VARS["returnto"]; $res = dispatch($dclient, "discuss.addComment", - array(new xmlrpcval($storyid), - new xmlrpcval(stripslashes(@$_POST["name"])), - new xmlrpcval(stripslashes(@$_POST["commenttext"])),)); + array(new PhpXmlRpc\Value($storyid), + new PhpXmlRpc\Value(stripslashes(@$_POST["name"])), + new PhpXmlRpc\Value(stripslashes(@$_POST["commenttext"])),)); // send the browser back to the originating page Header("Location: ${mydir}/comment.php?catid=" . @@ -65,8 +67,7 @@ function dispatch($client, $method, $args) $chanid = 0; } -$client = new xmlrpc_client("/meerkat/xml-rpc/server.php", - "www.oreillynet.com", 80); +$client = new PhpXmlRpc\Client("http://www.oreillynet.com/meerkat/xml-rpc/server.php"); if (@$_GET["comment"] && (!@$_GET["cdone"]) @@ -98,17 +99,17 @@ function dispatch($client, $method, $args) $categories = dispatch($client, "meerkat.getCategories", array()); if ($catid) { $sources = dispatch($client, "meerkat.getChannelsByCategory", - array(new xmlrpcval($catid, "int"))); + array(new PhpXmlRpc\Value($catid, "int"))); } if ($chanid) { $stories = dispatch($client, "meerkat.getItems", - array(new xmlrpcval( + array(new PhpXmlRpc\Value( array( - "channel" => new xmlrpcval($chanid, "int"), - "ids" => new xmlrpcval(1, "int"), - "descriptions" => new xmlrpcval(200, "int"), - "num_items" => new xmlrpcval(5, "int"), - "dates" => new xmlrpcval(0, "int"), + "channel" => new PhpXmlRpc\Value($chanid, "int"), + "ids" => new PhpXmlRpc\Value(1, "int"), + "descriptions" => new PhpXmlRpc\Value(200, "int"), + "num_items" => new PhpXmlRpc\Value(5, "int"), + "dates" => new PhpXmlRpc\Value(0, "int"), ), "struct"))); } ?> @@ -178,7 +179,7 @@ function dispatch($client, $method, $args) print "\n"; // now look for existing comments $res = dispatch($dclient, "discuss.getComments", - array(new xmlrpcval($v['id']))); + array(new PhpXmlRpc\Value($v['id']))); if (sizeof($res) > 0) { print "

" . "Comments on this story:

"; diff --git a/demo/client/introspect.php b/demo/client/introspect.php index cd084233..72006048 100644 --- a/demo/client/introspect.php +++ b/demo/client/introspect.php @@ -1,11 +1,14 @@ -xmlrpc +xmlrpc - Introspect demo

Introspect demo

Query server for available methods and their description

The code demonstrates usage of multicall and introspection methods

faultString() . "'
"; } // 'new style' client constructor -$c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); -print "

methods available at http://" . $c->server . $c->path . "

\n"; -$m = new xmlrpcmsg('system.listMethods'); -$r = &$c->send($m); -if ($r->faultCode()) { - display_error($r); +$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php"); +print "

methods available at http://" . $client->server . $client->path . "

\n"; +$req = new PhpXmlRpc\Request('system.listMethods'); +$resp = $client->send($req); +if ($resp->faultCode()) { + display_error($resp); } else { - $v = $r->value(); + $v = $resp->value(); for ($i = 0; $i < $v->arraysize(); $i++) { $mname = $v->arraymem($i); print "

" . $mname->scalarval() . "

\n"; // build messages first, add params later - $m1 = new xmlrpcmsg('system.methodHelp'); - $m2 = new xmlrpcmsg('system.methodSignature'); - $val = new xmlrpcval($mname->scalarval(), "string"); + $m1 = new PhpXmlRpc\Request('system.methodHelp'); + $m2 = new PhpXmlRpc\Request('system.methodSignature'); + $val = new PhpXmlRpc\Value($mname->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); // send multiple messages in one pass. // If server does not support multicall, client will fall back to 2 separate calls $ms = array($m1, $m2); - $rs = &$c->send($ms); + $rs = $client->send($ms); if ($rs[0]->faultCode()) { display_error($rs[0]); } else { diff --git a/demo/client/mail.php b/demo/client/mail.php index 6b6abd44..e1966b38 100644 --- a/demo/client/mail.php +++ b/demo/client/mail.php @@ -1,14 +1,12 @@ -xmlrpc +xmlrpc - Mail demo

Mail demo

@@ -23,41 +21,37 @@ href="../server/server.php?showSource=1">server.php included with the library (look for the 'mail_send' method)

addParam(new xmlrpcval($HTTP_POST_VARS["mailto"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailsub"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailmsg"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailfrom"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailcc"])); - $f->addParam(new xmlrpcval($HTTP_POST_VARS["mailbcc"])); - $f->addParam(new xmlrpcval("text/plain")); + $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") + )); - $c = new xmlrpc_client($XP, $XS, 80); - $c->setDebug(2); - $r = &$c->send($f); - if (!$r->faultCode()) { + $client = new PhpXmlRpc\Client($server); + $client->setDebug(2); + $resp = $client->send($req); + if (!$resp->faultCode()) { print "Mail sent OK
\n"; } else { print ""; print "Mail send failed
\n"; print "Fault: "; - print "Code: " . htmlspecialchars($r->faultCode()) . - " Reason: '" . htmlspecialchars($r->faultString()) . "'
"; + print "Code: " . htmlspecialchars($resp->faultCode()) . + " Reason: '" . htmlspecialchars($resp->faultString()) . "'
"; print "
"; } } diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php index f2c03e07..4e904bea 100644 --- a/demo/client/simple_call.php +++ b/demo/client/simple_call.php @@ -6,6 +6,9 @@ * @license code licensed under the BSD License: see file license.txt */ +include_once __DIR__ . "/../../src/Autoloader.php"; +PhpXmlRpc\Autoloader::register(); + /** * Takes a client object, a remote method name, and a variable numbers of * php values, and calls the method with the supplied parameters. The @@ -43,11 +46,12 @@ function xmlrpccall_simple() return false; } - $xmlrpcval_array = array(); + $valueArray = array(); + $encoder = new PhpXmlRpc\Encoder(); foreach ($varargs as $parameter) { - $xmlrpcval_array[] = php_xmlrpc_encode($parameter); + $valueArray[] = $encoder->encode($parameter); } - return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array)); + return $client->send(new PhpXmlRpc\Request($remote_function_name, $valueArray)); } } diff --git a/demo/client/which.php b/demo/client/which.php index f6ef45d1..5d332159 100644 --- a/demo/client/which.php +++ b/demo/client/which.php @@ -1,25 +1,29 @@ -xmlrpc +xmlrpc - Which toolkit demo

Which toolkit demo

Query server for toolkit information

-

The code demonstrates usage of the php_xmlrpc_decode function

+

The code demonstrates usage of the PhpXmlRpc\Encoder class

send($f); -if (!$r->faultCode()) { - $v = php_xmlrpc_decode($r->value()); + +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 "
";
-    print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";
-    print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";
-    print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";
-    print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";
+    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 "
"; } else { print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n"; + print "Code: " . htmlspecialchars($resp->faultCode()) . " Reason: '" . htmlspecialchars($resp->faultString()) . "'\n"; } ?> diff --git a/demo/client/wrap.php b/demo/client/wrap.php index 27a9794f..13ffabb4 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -1,48 +1,50 @@ -xmlrpc +xmlrpc - Webservice wrappper demo

Webservice wrappper demo

Wrap methods exposed by server into php functions

The code demonstrates usage of the most automagic client usage possible:
- 1) client that returns php values instead of xmlrpcval objects
+ 1) client that returns php values instead of xmlrpc value objects
2) wrapping of remote methods into php functions

return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals -$r = &$c->send(new xmlrpcmsg('system.listMethods')); -if ($r->faultCode()) { +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 "

Server methods list could not be retrieved: error '" . htmlspecialchars($r->faultString()) . "'

\n"; } else { - $testcase = ''; + $testCase = ''; + $wrapper = new PhpXmlRpc\Wrapper(); echo "

Server methods list retrieved, now wrapping it up...

\n
    \n"; - foreach ($r->value() as $methodname) { + foreach ($resp->value() as $methodName) { // $r->value is an array of strings // do not wrap remote server system methods - if (strpos($methodname, 'system.') !== 0) { - $funcname = wrap_xmlrpc_method($c, $methodname); - if ($funcname) { - echo "
  • Remote server method " . htmlspecialchars($methodname) . " wrapped into php function " . $funcname . "
  • \n"; + if (strpos($methodName, 'system.') !== 0) { + $funcName = $wrapper->wrap_xmlrpc_method($client, $methodName); + if ($funcName) { + echo "
  • Remote server method " . htmlspecialchars($methodName) . " wrapped into php function " . $funcName . "
  • \n"; } else { - echo "
  • Remote server method " . htmlspecialchars($methodname) . " could not be wrapped!
  • \n"; + echo "
  • Remote server method " . htmlspecialchars($methodName) . " could not be wrapped!
  • \n"; } - if ($methodname == 'examples.getStateName') { - $testcase = $funcname; + if ($methodName == 'examples.getStateName') { + $testCase = $funcName; } } } echo "
\n"; - if ($testcase) { - echo "Now testing function $testcase: remote method to convert U.S. state number into state name"; - $statenum = 25; - $statename = $testcase($statenum, 2); - echo "State number $statenum is " . htmlspecialchars($statename); + if ($testCase) { + echo "Now testing function $testCase: remote method to convert U.S. state number into state name"; + $stateNum = 25; + $stateName = $testCase($stateNum, 2); + echo "State number $stateNum is " . htmlspecialchars($stateName); } } ?> diff --git a/demo/client/zopetest.php b/demo/client/zopetest.php index ea93525d..39e705e4 100644 --- a/demo/client/zopetest.php +++ b/demo/client/zopetest.php @@ -1,26 +1,28 @@ -xmlrpc +xmlrpc - Zope test demo

Zope test demo

The code demonstrates usage of basic authentication to connect to the server

setCredentials("username", "password"); -$c->setDebug(2); -$r = $c->send($f); -if (!$r->faultCode()) { - $v = $r->value(); - print "I received:" . htmlspecialchars($v->scalarval()) . "
"; +include_once __DIR__ . "/../../src/Autoloader.php"; +PhpXmlRpc\Autoloader::register(); + +$req = new PhpXmlRpc\Request('document_src', array()); +$client = new PhpXmlRpc\Client("pingu.heddley.com:9080/index_html"); +$client->setCredentials("username", "password"); +$client->setDebug(2); +$resp = $client->send($req); +if (!$resp->faultCode()) { + $value = $resp->value(); + print "I received:" . htmlspecialchars($value->scalarval()) . "
"; print "
I got this value back
pre>" . - htmlentities($r->serialize()) . "\n"; + htmlentities($resp->serialize()) . "\n"; } else { print "An error occurred: "; - print "Code: " . htmlspecialchars($r->faultCode()) - . " Reason: '" . ($r->faultString()) . "'
"; + print "Code: " . htmlspecialchars($resp->faultCode()) + . " Reason: '" . ($resp->faultString()) . "'
"; } ?> diff --git a/demo/server/discuss.php b/demo/server/discuss.php index 7e6e4e97..2a137e8e 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -42,11 +42,11 @@ function addcomment($m) } // if we generated an error, create an error return response if ($err) { - return new xmlrpcresp(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); } else { // otherwise, we create the right response // with the state name - return new xmlrpcresp(new xmlrpcval($count, "int")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($count, "int")); } } @@ -80,15 +80,15 @@ function getcomments($m) } // if we generated an error, create an error return response if ($err) { - return new xmlrpcresp(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); } else { // otherwise, we create the right response // with the state name - return new xmlrpcresp(php_xmlrpc_encode($ra)); + return new PhpXmlRpc\Response(php_xmlrpc_encode($ra)); } } -$s = new xmlrpc_server(array( +$s = new PhpXmlRpc\Server(array( "discuss.addComment" => array( "function" => "addcomment", "signature" => $addcomment_sig, diff --git a/demo/server/proxy.php b/demo/server/proxy.php index c78d8902..64ad4598 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -25,7 +25,7 @@ function forward_request($m) // create client $timeout = 0; $url = php_xmlrpc_decode($m->getParam(0)); - $c = new xmlrpc_client($url); + $c = new PhpXmlRpc\Client($url); if ($m->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... @@ -53,12 +53,12 @@ function forward_request($m) } // build call for remote server - /// @todo find a weay to forward client info (such as IP) to server, either + /// @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... $method = php_xmlrpc_decode($m->getParam(1)); $pars = $m->getParam(2); - $m = new xmlrpcmsg($method); + $m = new PhpXmlRpc\Request($method); for ($i = 0; $i < $pars->arraySize(); $i++) { $m->addParam($pars->arraymem($i)); } @@ -70,7 +70,7 @@ function forward_request($m) } // run the server -$server = new xmlrpc_server( +$server = new PhpXmlRpc\Server( array( 'xmlrpcproxy.call' => array( 'function' => 'forward_request', diff --git a/demo/server/server.php b/demo/server/server.php index b6fa5261..eefaa385 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -43,7 +43,7 @@ class xmlrpc_server_methods_container public function phpwarninggenerator($m) { $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined - return new xmlrpcresp(new xmlrpcval(1, 'boolean')); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value(1, 'boolean')); } /** @@ -108,11 +108,11 @@ function findstate($m) // if we generated an error, create an error return response if ($err) { - return new xmlrpcresp(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); } else { // otherwise, we create the right response // with the state name - return new xmlrpcresp(new xmlrpcval($sname)); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($sname)); } } @@ -141,7 +141,7 @@ function inner_findstate($stateno) $findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); -$obj = new xmlrpc_server_methods_container(); +$obj = new PhpXmlRpc\Server_methods_container(); $findstate4_sig = wrap_php_function(array($obj, 'findstate')); $addtwo_sig = array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); @@ -151,7 +151,7 @@ function addtwo($m) $s = $m->getParam(0); $t = $m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval() + $t->scalarval(), "int")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($s->scalarval() + $t->scalarval(), "int")); } $addtwodouble_sig = array(array($xmlrpcDouble, $xmlrpcDouble, $xmlrpcDouble)); @@ -161,7 +161,7 @@ function addtwodouble($m) $s = $m->getParam(0); $t = $m->getParam(1); - return new xmlrpcresp(new xmlrpcval($s->scalarval() + $t->scalarval(), "double")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($s->scalarval() + $t->scalarval(), "double")); } $stringecho_sig = array(array($xmlrpcString, $xmlrpcString)); @@ -172,7 +172,7 @@ function stringecho($m) $s = $m->getParam(0); $v = $s->scalarval(); - return new xmlrpcresp(new xmlrpcval($s->scalarval())); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($s->scalarval())); } $echoback_sig = array(array($xmlrpcString, $xmlrpcString)); @@ -185,7 +185,7 @@ function echoback($m) // $m is an incoming message $s = "I got the following message:\n" . $m->serialize(); - return new xmlrpcresp(new xmlrpcval($s)); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($s)); } $echosixtyfour_sig = array(array($xmlrpcString, $xmlrpcBase64)); @@ -197,7 +197,7 @@ function echosixtyfour($m) // is working as expected $incoming = $m->getParam(0); - return new xmlrpcresp(new xmlrpcval($incoming->scalarval(), "string")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($incoming->scalarval(), "string")); } $bitflipper_sig = array(array($xmlrpcArray, $xmlrpcArray)); @@ -208,7 +208,7 @@ function bitflipper($m) $v = $m->getParam(0); $sz = $v->arraysize(); - $rv = new xmlrpcval(array(), $xmlrpcArray); + $rv = new PhpXmlRpc\Value(array(), $xmlrpcArray); for ($j = 0; $j < $sz; $j++) { $b = $v->arraymem($j); @@ -219,7 +219,7 @@ function bitflipper($m) } } - return new xmlrpcresp($rv); + return new PhpXmlRpc\Response($rv); } // Sorting demo @@ -269,7 +269,7 @@ function agesorter($m) // error string for [if|when] things go wrong $err = ""; // create the output value - $v = new xmlrpcval(); + $v = new PhpXmlRpc\Value(); $agar = array(); if (isset($sno) && $sno->kindOf() == "array") { @@ -297,8 +297,8 @@ function agesorter($m) $outAr = array(); while (list($key, $val) = each($agesorter_arr)) { // recreate each struct element - $outAr[] = new xmlrpcval(array("name" => new xmlrpcval($key), - "age" => new xmlrpcval($val, "int"),), "struct"); + $outAr[] = new PhpXmlRpc\Value(array("name" => new PhpXmlRpc\Value($key), + "age" => new PhpXmlRpc\Value($val, "int"),), "struct"); } // add this array to the output value $v->addArray($outAr); @@ -307,9 +307,9 @@ function agesorter($m) } if ($err) { - return new xmlrpcresp(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); } else { - return new xmlrpcresp($v); + return new PhpXmlRpc\Response($v); } } @@ -378,9 +378,9 @@ function mail_send($m) } if ($err) { - return new xmlrpcresp(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); } else { - return new xmlrpcresp(new xmlrpcval("true", $xmlrpcBoolean)); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value("true", $xmlrpcBoolean)); } } @@ -390,7 +390,7 @@ function getallheaders_xmlrpc($m) { global $xmlrpcerruser; if (function_exists('getallheaders')) { - return new xmlrpcresp(php_xmlrpc_encode(getallheaders())); + return new PhpXmlRpc\Response(php_xmlrpc_encode(getallheaders())); } else { $headers = array(); // IIS: poor man's version of getallheaders @@ -401,7 +401,7 @@ function getallheaders_xmlrpc($m) } } - return new xmlrpcresp(php_xmlrpc_encode($headers)); + return new PhpXmlRpc\Response(php_xmlrpc_encode($headers)); } } @@ -415,14 +415,14 @@ function setcookies($m) setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); } - return new xmlrpcresp(new xmlrpcval(1, 'int')); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value(1, 'int')); } $getcookies_sig = array(array($xmlrpcStruct)); $getcookies_doc = 'Sends to client a response containing all http cookies as received in the request (as struct)'; function getcookies($m) { - return new xmlrpcresp(php_xmlrpc_encode($_COOKIE)); + return new PhpXmlRpc\Response(php_xmlrpc_encode($_COOKIE)); } $v1_arrayOfStructs_sig = array(array($xmlrpcInt, $xmlrpcArray)); @@ -441,7 +441,7 @@ function v1_arrayOfStructs($m) } } - return new xmlrpcresp(new xmlrpcval($numcurly, "int")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($numcurly, "int")); } $v1_easyStruct_sig = array(array($xmlrpcInt, $xmlrpcStruct)); @@ -454,7 +454,7 @@ function v1_easyStruct($m) $curly = $sno->structmem("curly"); $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval(); - return new xmlrpcresp(new xmlrpcval($num, "int")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($num, "int")); } $v1_echoStruct_sig = array(array($xmlrpcStruct, $xmlrpcStruct)); @@ -463,7 +463,7 @@ function v1_echoStruct($m) { $sno = $m->getParam(0); - return new xmlrpcresp($sno); + return new PhpXmlRpc\Response($sno); } $v1_manyTypes_sig = array(array( @@ -474,7 +474,7 @@ function v1_echoStruct($m) $v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.'; function v1_manyTypes($m) { - return new xmlrpcresp(new xmlrpcval(array( + return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( $m->getParam(0), $m->getParam(1), $m->getParam(2), @@ -494,7 +494,7 @@ function v1_moderateSizeArrayCheck($m) $first = $ar->arraymem(0); $last = $ar->arraymem($sz - 1); - return new xmlrpcresp(new xmlrpcval($first->scalarval() . + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($first->scalarval() . $last->scalarval(), "string")); } @@ -505,10 +505,10 @@ function v1_simpleStructReturn($m) $sno = $m->getParam(0); $v = $sno->scalarval(); - return new xmlrpcresp(new xmlrpcval(array( - "times10" => new xmlrpcval($v * 10, "int"), - "times100" => new xmlrpcval($v * 100, "int"), - "times1000" => new xmlrpcval($v * 1000, "int"),), + return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( + "times10" => new PhpXmlRpc\Value($v * 10, "int"), + "times100" => new PhpXmlRpc\Value($v * 100, "int"), + "times1000" => new PhpXmlRpc\Value($v * 1000, "int"),), "struct" )); } @@ -526,7 +526,7 @@ function v1_nestedStruct($m) $larry = $fools->structmem("larry"); $moe = $fools->structmem("moe"); - return new xmlrpcresp(new xmlrpcval($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); + return new PhpXmlRpc\Response(new PhpXmlRpc\Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); } $v1_countTheEntities_sig = array(array($xmlrpcStruct, $xmlrpcString)); @@ -563,12 +563,12 @@ function v1_countTheEntities($m) } } - return new xmlrpcresp(new xmlrpcval(array( - "ctLeftAngleBrackets" => new xmlrpcval($lt, "int"), - "ctRightAngleBrackets" => new xmlrpcval($gt, "int"), - "ctAmpersands" => new xmlrpcval($amp, "int"), - "ctApostrophes" => new xmlrpcval($ap, "int"), - "ctQuotes" => new xmlrpcval($qu, "int"),), + return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( + "ctLeftAngleBrackets" => new PhpXmlRpc\Value($lt, "int"), + "ctRightAngleBrackets" => new PhpXmlRpc\Value($gt, "int"), + "ctAmpersands" => new PhpXmlRpc\Value($amp, "int"), + "ctApostrophes" => new PhpXmlRpc\Value($ap, "int"), + "ctQuotes" => new PhpXmlRpc\Value($qu, "int"),), "struct" )); } @@ -613,7 +613,7 @@ function i_echoParam($m) { $s = $m->getParam(0); - return new xmlrpcresp($s); + return new PhpXmlRpc\Response($s); } function i_echoString($m) @@ -684,7 +684,7 @@ function i_whichToolkit($m) "toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'], ); - return new xmlrpcresp(php_xmlrpc_encode($ret)); + return new PhpXmlRpc\Response(php_xmlrpc_encode($ret)); } $o = new xmlrpc_server_methods_container(); @@ -874,7 +874,7 @@ function i_whichToolkit($m) $a['examples.php4.getStateName'] = $findstate5_sig; } -$s = new xmlrpc_server($a, false); +$s = new PhpXmlRpc\Server($a, false); $s->setdebug(3); $s->compress_response = true; diff --git a/demo/vardemo.php b/demo/vardemo.php index 0b542e74..4f91deb1 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -6,43 +6,43 @@ include_once __DIR__ . "/../lib/xmlrpc.inc"; -$f = new xmlrpcmsg('examples.getStateName'); +$f = new PhpXmlRpc\Request('examples.getStateName'); print "

Testing value serialization

\n"; -$v = new xmlrpcval(23, "int"); +$v = new PhpXmlRpc\Value(23, "int"); print "
" . htmlentities($v->serialize()) . "
"; -$v = new xmlrpcval("What are you saying? >> << &&"); +$v = new PhpXmlRpc\Value("What are you saying? >> << &&"); print "
" . htmlentities($v->serialize()) . "
"; -$v = new xmlrpcval(array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean'),), +$v = new PhpXmlRpc\Value(array( + new PhpXmlRpc\Value("ABCDEFHIJ"), + new PhpXmlRpc\Value(1234, 'int'), + new PhpXmlRpc\Value(1, 'boolean'),), "array" ); print "
" . htmlentities($v->serialize()) . "
"; -$v = new xmlrpcval( +$v = new PhpXmlRpc\Value( array( - "thearray" => new xmlrpcval( + "thearray" => new PhpXmlRpc\Value( array( - new xmlrpcval("ABCDEFHIJ"), - new xmlrpcval(1234, 'int'), - new xmlrpcval(1, 'boolean'), - new xmlrpcval(0, 'boolean'), - new xmlrpcval(true, 'boolean'), - new xmlrpcval(false, 'boolean'), + 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 xmlrpcval(23, 'int'), - "thestring" => new xmlrpcval("foobarwhizz"), - "thestruct" => new xmlrpcval( + "theint" => new PhpXmlRpc\Value(23, 'int'), + "thestring" => new PhpXmlRpc\Value("foobarwhizz"), + "thestruct" => new PhpXmlRpc\Value( array( - "one" => new xmlrpcval(1, 'int'), - "two" => new xmlrpcval(2, 'int'), + "one" => new PhpXmlRpc\Value(1, 'int'), + "two" => new PhpXmlRpc\Value(2, 'int'), ), "struct" ), @@ -52,11 +52,11 @@ print "
" . htmlentities($v->serialize()) . "
"; -$w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array"); +$w = new PhpXmlRpc\Value(array($v, new PhpXmlRpc\Value("That was the struct!")), "array"); print "
" . htmlentities($w->serialize()) . "
"; -$w = new xmlrpcval("Mary had a little lamb, +$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. @@ -70,7 +70,7 @@ print "
Value of base64 string is: '" . $w->scalarval() . "'
"; $f->method(''); -$f->addParam(new xmlrpcval("41", "int")); +$f->addParam(new PhpXmlRpc\Value("41", "int")); print "

Testing request serialization

\n"; $op = $f->serialize(); From a566be29a44b1bb08941e81ff1f97eaf4ae10963 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 23 Mar 2015 00:48:50 +0000 Subject: [PATCH 101/228] Move deprecated methods into the compatibility classes, out of the main library classes --- lib/xmlrpc.inc | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ lib/xmlrpcs.inc | 9 +++++++ src/Request.php | 12 +-------- src/Server.php | 10 -------- src/Value.php | 51 +------------------------------------- 5 files changed, 76 insertions(+), 71 deletions(-) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 8f081279..51b175d7 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -62,10 +62,75 @@ PhpXmlRpc\PhpXmlRpc::exportGlobals(); 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 '' . $this->serializedata($typ, $val) . "\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; + } + } class xmlrpcmsg extends PhpXmlRpc\Request { + /** + * Kept the old name even if Request class was renamed, for compatibility. + * @deprecated + * + * @return string + */ + public function kindOf() + { + return 'msg'; + } } class xmlrpcresp extends PhpXmlRpc\Response diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.inc index 7daf1c44..761f3e1c 100644 --- a/lib/xmlrpcs.inc +++ b/lib/xmlrpcs.inc @@ -46,6 +46,15 @@ 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 */ diff --git a/src/Request.php b/src/Request.php index a136bb32..77567abf 100644 --- a/src/Request.php +++ b/src/Request.php @@ -43,16 +43,6 @@ public function xml_footer() return ''; } - /** - * Kept the old name even if class was renamed, for compatibility. - * - * @return string - */ - private function kindOf() - { - return 'msg'; - } - public function createPayload($charset_encoding = '') { if ($charset_encoding != '') { @@ -297,7 +287,7 @@ private function parseResponseHeaders(&$data, $headers_processed = false) } $data = substr($data, $bd); - + if ($this->debug && count($this->httpResponse['headers'])) { $msg = ''; foreach ($this->httpResponse['headers'] as $header => $value) { diff --git a/src/Server.php b/src/Server.php index e1035d3d..7d345aa2 100644 --- a/src/Server.php +++ b/src/Server.php @@ -699,16 +699,6 @@ protected function xml_header($charset_encoding = '') } } - /** - * A debugging routine: just echoes back the input packet as a string value - * DEPRECATED! - */ - public function echoInput() - { - $r = new Response(new Value("'Aha said I: '" . file_get_contents('php://input'), 'string')); - print $r->serialize(); - } - /* Functions that implement system.XXX methods of xmlrpc servers */ public function getSystemDispatchMap() diff --git a/src/Value.php b/src/Value.php index e47e954b..0f39a672 100644 --- a/src/Value.php +++ b/src/Value.php @@ -229,7 +229,7 @@ public function kindOf() } } - private function serializedata($typ, $val, $charset_encoding = '') + protected function serializedata($typ, $val, $charset_encoding = '') { $rs = ''; @@ -339,20 +339,6 @@ public function serialize($charset_encoding = '') //} } - // DEPRECATED - 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 '' . $this->serializedata($typ, $val) . "\n"; - //} - } - /** * Checks whether a struct member with a given name is present. * Works only on xmlrpcvals of type struct. @@ -397,41 +383,6 @@ public function structeach() return each($this->me['struct']); } - // 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; - } - /** * Returns the value of a scalar xmlrpcval. * From 9ff27b2483717ec728dda6a9045d2146e85bde86 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 24 Mar 2015 13:51:49 +0000 Subject: [PATCH 102/228] Refactoring ongoing: move http headers parsing away from response into http class; CamelCase everything; move proxy server and demo server to new api --- demo/server/proxy.php | 40 ++++---- demo/server/server.php | 2 +- lib/xmlrpc.inc | 5 +- src/Helper/Charset.php | 4 +- src/Helper/Http.php | 205 +++++++++++++++++++++++++++++++++++++++- src/Request.php | 208 ++--------------------------------------- src/Response.php | 37 ++++---- src/Server.php | 2 +- src/Value.php | 17 ++-- 9 files changed, 263 insertions(+), 257 deletions(-) diff --git a/demo/server/proxy.php b/demo/server/proxy.php index 64ad4598..4f860de1 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -8,28 +8,30 @@ * @copyright (C) 2006-2015 G. Giunta * @license code licensed under the BSD License: see file license.txt */ -include_once __DIR__ . "/../../vendor/autoload.php"; -include_once __DIR__ . "/../../lib/xmlrpc.inc"; -include_once __DIR__ . "/../../lib/xmlrpcs.inc"; +include_once __DIR__ . "/../../src/Autoloader.php"; +PhpXmlRpc\Autoloader::register(); /** * Forward an xmlrpc request to another server, and return to client the response received. * - * @param xmlrpcmsg $m (see method docs below for a description of the expected parameters) + * @param PhpXmlRpc\Request $req (see method docs below for a description of the expected parameters) * - * @return xmlrpcresp + * @return PhpXmlRpc\Response */ -function forward_request($m) +function forward_request($req) { + $encoder = new \PhpXmlRpc\Encoder(); + // create client $timeout = 0; - $url = php_xmlrpc_decode($m->getParam(0)); - $c = new PhpXmlRpc\Client($url); - if ($m->getNumParams() > 3) { + $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 = php_xmlrpc_decode($m->getParam(3)); + $options = $encoder->decode($req->getParam(3)); foreach ($options as $key => $val) { switch ($key) { case 'Cookie': @@ -37,13 +39,13 @@ function forward_request($m) case 'Credentials': break; case 'RequestCompression': - $c->setRequestCompression($val); + $client->setRequestCompression($val); break; case 'SSLVerifyHost': - $c->setSSLVerifyHost($val); + $client->setSSLVerifyHost($val); break; case 'SSLVerifyPeer': - $c->setSSLVerifyPeer($val); + $client->setSSLVerifyPeer($val); break; case 'Timeout': $timeout = (integer)$val; @@ -56,17 +58,17 @@ function forward_request($m) /// @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... - $method = php_xmlrpc_decode($m->getParam(1)); - $pars = $m->getParam(2); - $m = new PhpXmlRpc\Request($method); + $reqethod = $encoder->decode($req->getParam(1)); + $pars = $req->getParam(2); + $req = new PhpXmlRpc\Request($reqethod); for ($i = 0; $i < $pars->arraySize(); $i++) { - $m->addParam($pars->arraymem($i)); + $req->addParam($pars->arraymem($i)); } // add debug info into response we give back to caller - xmlrpc_debugmsg("Sending to server $url the payload: " . $m->serialize()); + PhpXmlRpc\Server::xmlrpc_debugmsg("Sending to server $url the payload: " . $req->serialize()); - return $c->send($m, $timeout); + return $client->send($req, $timeout); } // run the server diff --git a/demo/server/server.php b/demo/server/server.php index eefaa385..03bbab5c 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -141,7 +141,7 @@ function inner_findstate($stateno) $findstate5_sig = wrap_php_function('xmlrpc_server_methods_container::findstate'); -$obj = new PhpXmlRpc\Server_methods_container(); +$obj = new xmlrpc_server_methods_container(); $findstate4_sig = wrap_php_function(array($obj, 'findstate')); $addtwo_sig = array(array($xmlrpcInt, $xmlrpcInt, $xmlrpcInt)); diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 51b175d7..01323fe7 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -143,9 +143,10 @@ 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()->encode_entitites($data, $srcEncoding, $destEncoding); + return PhpXmlRpc\Helper\Charset::instance()->encodeEntitites($data, $srcEncoding, $destEncoding); } function iso8601_encode($timeT, $utc=0) @@ -160,7 +161,7 @@ function iso8601_decode($iDate, $utc=0) function decode_chunked($buffer) { - return PhpXmlRpc\Helper\Http::decode_chunked($buffer); + return PhpXmlRpc\Helper\Http::decodeChunked($buffer); } function php_xmlrpc_decode($xmlrpcVal, $options=array()) diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index 6d5eb6a2..b23b5c5f 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -87,7 +87,7 @@ private function __construct() * * @return string */ - public function encode_entities($data, $src_encoding = '', $dest_encoding = '') + public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') { if ($src_encoding == '') { // lame, but we know no better... @@ -218,7 +218,7 @@ public function encode_entities($data, $src_encoding = '', $dest_encoding = '') * * @return bool */ - public function is_valid_charset($encoding, $validList) + public function isValidCharset($encoding, $validList) { if (is_string($validList)) { $validList = explode(',', $validList); diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 02bfd578..09be1f3a 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -2,10 +2,12 @@ namespace PhpXmlRpc\Helper; +use PhpXmlRpc\PhpXmlRpc; + class Http { /** - * decode a string that is encoded w/ "chunked" transfer encoding + * Decode a string that is encoded w/ "chunked" transfer encoding * as defined in rfc2068 par. 19.4.6 * code shamelessly stolen from nusoap library by Dietrich Ayala. * @@ -13,7 +15,7 @@ class Http * * @return string */ - public static function decode_chunked($buffer) + public static function decodeChunked($buffer) { // length := 0 $length = 0; @@ -57,4 +59,203 @@ public static function decode_chunked($buffer) 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) { + $header_name = 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'][$header_name] + /// instead of replacing it for those... + if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') { + if ($header_name == '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'][$header_name])) { + $httpResponse['headers'][$header_name] .= ', ' . trim($cookie); + } else { + $httpResponse['headers'][$header_name] = 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'][$header_name] = trim($arr[1]); + } + } elseif (isset($header_name)) { + /// @todo version1 cookies might span multiple lines, thus breaking the parsing above + $httpResponse['headers'][$header_name] .= ' ' . trim($line); + } + } + + $data = substr($data, $bd); + + if ($debug && count($httpResponse['headers'])) { + $msg = ''; + foreach ($httpResponse['headers'] as $header => $value) { + $msg .= "HEADER: $header: $value\n"; + } + foreach ($httpResponse['cookies'] as $header => $value) { + $msg .= "COOKIE: $header={$value['value']}\n"; + } + $this->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) { + $this->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) { + $this->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; + } + + /** + * Echoes a debug message, taking care of escaping it when not in console mode + * + * @param string $message + */ + protected function debugMessage($message) + { + if (PHP_SAPI != 'cli') { + print "
\n".htmlentities($message)."\n
"; + } + else { + print "\n$message\n"; + } + } } diff --git a/src/Request.php b/src/Request.php index 77567abf..17aae840 100644 --- a/src/Request.php +++ b/src/Request.php @@ -153,201 +153,9 @@ public function parseResponseFile($fp) while ($data = fread($fp, 32768)) { $ipd .= $data; } - //fclose($fp); return $this->parseResponse($ipd); } - /** - * Parses HTTP headers and separates them from data. - * - * @return null|Response null on success, or a Response on error - */ - private function parseResponseHeaders(&$data, $headers_processed = false) - { - $this->httpResponse['headers'] = array(); - $this->httpResponse['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'); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)'); - - return $r; - } - } - - // 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); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['http_error'], PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')'); - - return $r; - } - - // 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) { - $header_name = 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'][$header_name] - /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') { - if ($header_name == '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($this->httpResponse['headers'][$header_name])) { - $this->httpResponse['headers'][$header_name] .= ', ' . trim($cookie); - } else { - $this->httpResponse['headers'][$header_name] = 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; - $this->httpResponse['cookies'][$tag] = array(); - $this->httpResponse['cookies'][$cookiename]['value'] = urldecode($val); - } else { - if ($tag != 'value') { - $this->httpResponse['cookies'][$cookiename][$tag] = $val; - } - } - } - } - } else { - $this->httpResponse['headers'][$header_name] = trim($arr[1]); - } - } elseif (isset($header_name)) { - /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $this->httpResponse['headers'][$header_name] .= ' ' . trim($line); - } - } - - $data = substr($data, $bd); - - if ($this->debug && count($this->httpResponse['headers'])) { - $msg = ''; - foreach ($this->httpResponse['headers'] as $header => $value) { - $msg .= "HEADER: $header: $value\n"; - } - foreach ($this->httpResponse['cookies'] as $header => $value) { - $msg .= "COOKIE: $header={$value['value']}\n"; - } - $this->debugMessage($msg); - } - - // if CURL was used for the call, http headers have been processed, - // and dechunking + reinflating have been carried out - if (!$headers_processed) { - // Decode chunked encoding sent by http 1.1 servers - if (isset($this->httpResponse['headers']['transfer-encoding']) && $this->httpResponse['headers']['transfer-encoding'] == 'chunked') { - if (!$data = Http::decode_chunked($data)) { - error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server'); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['dechunk_fail'], PhpXmlRpc::$xmlrpcstr['dechunk_fail']); - - return $r; - } - } - - // Decode gzip-compressed stuff - // code shamelessly inspired from nusoap library by Dietrich Ayala - if (isset($this->httpResponse['headers']['content-encoding'])) { - $this->httpResponse['headers']['content-encoding'] = str_replace('x-', '', $this->httpResponse['headers']['content-encoding']); - if ($this->httpResponse['headers']['content-encoding'] == 'deflate' || $this->httpResponse['headers']['content-encoding'] == 'gzip') { - // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzinflate')) { - if ($this->httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { - $data = $degzdata; - if ($this->debug) { - $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); - } - } elseif ($this->httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { - $data = $degzdata; - if ($this->debug) { - $this->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'); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['decompress_fail'], PhpXmlRpc::$xmlrpcstr['decompress_fail']); - - return $r; - } - } else { - error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['cannot_decompress'], PhpXmlRpc::$xmlrpcstr['cannot_decompress']); - - return $r; - } - } - } - } // end of 'if needed, de-chunk, re-inflate response' - - return; - } - /** * Parse the xmlrpc response contained in the string $data and return a Response object. * @@ -364,22 +172,20 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty $this->debugMessage("---GOT---\n$data\n---END---"); } - $this->httpResponse = array(); - $this->httpResponse['raw_data'] = $data; - $this->httpResponse['headers'] = array(); - $this->httpResponse['cookies'] = array(); + $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array()); if ($data == '') { error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.'); - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']); - - return $r; + 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') { - $r = $this->parseResponseHeaders($data, $headers_processed); - if ($r) { + $httpParser = new Http(); + try { + $this->httpResponse = $httpParser->parseResponseHeaders($data, $headers_processed, $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; diff --git a/src/Response.php b/src/Response.php index efadfb57..54e8db4a 100644 --- a/src/Response.php +++ b/src/Response.php @@ -8,7 +8,7 @@ class Response { /// @todo: do these need to be public? public $val = 0; - public $valtyp; + public $valType; public $errno = 0; public $errstr = ''; public $payload; @@ -19,25 +19,25 @@ class Response /** * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) - * @param integer $fcode set it to anything but 0 to create an error response - * @param string $fstr the error string, in case of an error response - * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml' + * @param integer $fCode set it to anything but 0 to create an error response + * @param string $fString the error string, in case of an error response + * @param string $valType either 'xmlrpcvals', 'phpvals' or 'xml' * - * @todo add check that $val / $fcode / $fstr is of 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 xmlrpcval 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, $fstr = '', $valtyp = '') + public function __construct($val, $fCode = 0, $fString = '', $valType = '') { - if ($fcode != 0) { + if ($fCode != 0) { // error response - $this->errno = $fcode; - $this->errstr = $fstr; - //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later. + $this->errno = $fCode; + $this->errstr = $fString; + //$this->errstr = htmlspecialchars($fString); // XXX: encoding probably shouldn't be done here; fix later. } else { // successful response $this->val = $val; - if ($valtyp == '') { + 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'; @@ -48,7 +48,7 @@ public function __construct($val, $fcode = 0, $fstr = '', $valtyp = '') } } else { // user declares type of resp value: believe him - $this->valtyp = $valtyp; + $this->valtyp = $valType; } } } @@ -102,14 +102,14 @@ public function cookies() /** * Returns xml representation of the response. XML prologue not included. * - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed * * @return string the xml representation of the response */ - public function serialize($charset_encoding = '') + public function serialize($charsetEncoding = '') { - if ($charset_encoding != '') { - $this->content_type = 'text/xml; charset=' . $charset_encoding; + if ($charsetEncoding != '') { + $this->content_type = 'text/xml; charset=' . $charsetEncoding; } else { $this->content_type = 'text/xml'; } @@ -121,11 +121,10 @@ public function serialize($charset_encoding = '') if ($this->errno) { // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients // by xml-encoding non ascii chars - $charsetEncoder = $result .= "\n" . "\nfaultCode\n" . $this->errno . "\n\n\nfaultString\n" . - Charset::instance()->encode_entities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n\n" . + Charset::instance()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n\n" . "
\n
\n"; } else { if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) { @@ -139,7 +138,7 @@ public function serialize($charset_encoding = '') } } else { $result .= "\n\n" . - $this->val->serialize($charset_encoding) . + $this->val->serialize($charsetEncoding) . "\n"; } } diff --git a/src/Server.php b/src/Server.php index 7d345aa2..3a8f5583 100644 --- a/src/Server.php +++ b/src/Server.php @@ -160,7 +160,7 @@ public function serializeDebug($charset_encoding = '') $out .= "\n"; } if (static::$_xmlrpc_debuginfo != '') { - $out .= "\n"; + $out .= "\n"; // NB: a better solution MIGHT be to use CDATA, but we need to insert it // into return payload AFTER the beginning tag //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n"; diff --git a/src/Value.php b/src/Value.php index 0f39a672..b9d34fe9 100644 --- a/src/Value.php +++ b/src/Value.php @@ -42,8 +42,8 @@ class Value */ public function __construct($val = -1, $type = '') { - /// @todo: optimization creep - do not call addXX, do it all inline. - /// downside: booleans will not be coerced anymore + // optimization creep - do not call addXX, do it all inline. + // downside: booleans will not be coerced anymore if ($val !== -1 || $type != '') { // optimization creep: inlined all work done by constructor switch ($type) { @@ -73,7 +73,8 @@ public function __construct($val = -1, $type = '') default: error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)"); } - /*if($type=='') + /* was: + if($type=='') { $type='string'; } @@ -107,7 +108,7 @@ public function addScalar($val, $type = 'string') $typeof = static::$xmlrpcTypes[$type]; } - if ($typeof != 1) { + if ($typeof !== 1) { error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)"); return 0; @@ -135,10 +136,6 @@ public function addScalar($val, $type = 'string') return 0; case 2: // we're adding a scalar value to an array here - //$ar=$this->me['array']; - //$ar[]=new Value($val, $type); - //$this->me['array']=$ar; - // Faster (?) avoid all the costly array-copy-by-val done here... $this->me['array'][] = new Value($val, $type); return 1; @@ -249,7 +246,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') 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()->encode_entities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . ""; + $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . ""; break; case static::$xmlrpcInt: case static::$xmlrpcI4: @@ -297,7 +294,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') } $charsetEncoder = Charset::instance(); foreach ($val as $key2 => $val2) { - $rs .= '' . $charsetEncoder->encode_entities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n"; + $rs .= '' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n"; //$rs.=$this->serializeval($val2); $rs .= $val2->serialize($charset_encoding); $rs .= "\n"; From c0e827c303b8228e64d461a9719ada6eaef7c61a Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 24 Mar 2015 13:58:33 +0000 Subject: [PATCH 103/228] When serialize() is invoked on a response and its payload can not be serialized, an exception is thrown instead of ending all execution --- src/Response.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 54e8db4a..626fd64f 100644 --- a/src/Response.php +++ b/src/Response.php @@ -105,6 +105,8 @@ public function cookies() * @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 = '') { @@ -134,7 +136,7 @@ public function serialize($charsetEncoding = '') "\n
"; } else { /// @todo try to build something serializable? - die('cannot serialize xmlrpc response objects whose content is native php values'); + throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values'); } } else { $result .= "\n\n" . From 47583a0bae1367386da12aba498862932333c30d Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 24 Mar 2015 13:59:20 +0000 Subject: [PATCH 104/228] Whitespace: add terminating LF to .inc files --- lib/xmlrpc.inc | 2 +- lib/xmlrpc_wrappers.inc | 2 +- lib/xmlrpcs.inc | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 01323fe7..9a9a589f 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -189,4 +189,4 @@ function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null) function is_valid_charset($encoding, $validList) { return PhpXmlRpc\Helper\Charset::instance()->is_valid_charset($encoding, $validList); -} \ No newline at end of file +} diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc index 90949346..180656e5 100644 --- a/lib/xmlrpc_wrappers.inc +++ b/lib/xmlrpc_wrappers.inc @@ -46,4 +46,4 @@ function wrap_xmlrpc_server($client, $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); return $wrapper->wrap_xmlrpc_server($client, $extraOptions); -} \ No newline at end of file +} diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.inc index 761f3e1c..aa6a2422 100644 --- a/lib/xmlrpcs.inc +++ b/lib/xmlrpcs.inc @@ -62,4 +62,4 @@ class xmlrpc_server extends PhpXmlRpc\Server function xmlrpc_debugmsg($m) { PhpXmlRpc\Server::xmlrpc_debugmsg($m); -} \ No newline at end of file +} From ad1cc0dd94daaa32323299a260f9f7413afe8230 Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 26 Mar 2015 10:45:39 +0000 Subject: [PATCH 105/228] Fix wrapping class and demo file --- demo/client/wrap.php | 2 +- src/Wrapper.php | 68 +++++++++++++++++++++++--------------------- 2 files changed, 37 insertions(+), 33 deletions(-) diff --git a/demo/client/wrap.php b/demo/client/wrap.php index 13ffabb4..f1a7e005 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -18,7 +18,7 @@ $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 "

Server methods list could not be retrieved: error '" . htmlspecialchars($r->faultString()) . "'

\n"; + echo "

Server methods list could not be retrieved: error {$resp->faultCode()} '" . htmlspecialchars($resp->faultString()) . "'

\n"; } else { $testCase = ''; $wrapper = new PhpXmlRpc\Wrapper(); diff --git a/src/Wrapper.php b/src/Wrapper.php index a710fddd..36851d68 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -147,6 +147,7 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = { $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true; $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc'; + $namespace = '\\PhpXmlRpc\\'; $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'] ? '@' : ''; @@ -294,7 +295,8 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = } // start building of PHP code to be eval'd - $innercode = ''; + + $innercode = "\$encoder = new {$namespace}Encoder();\n"; $i = 0; $parsvariations = array(); $pars = array(); @@ -312,9 +314,9 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = } $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"; + $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->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"; + $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; } $pars[] = "\$p$i"; @@ -342,7 +344,7 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = // 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, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode; + "if (\$paramcount < $minpars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode; } else { $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode; } @@ -374,16 +376,16 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = $psigs[] = $psig; } $innercode .= "\$np = true;\n"; - $innercode .= "if (\$np) return new {$prefix}resp(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n"; + $innercode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n"; //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; - $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n"; + $innercode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) { - $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));"; + $innercode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));"; } else { if ($encode_php_objects) { - $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n"; + $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; } else { - $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n"; + $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; } } // shall we exclude functions returning by ref? @@ -442,7 +444,7 @@ public function wrap_php_class($classname, $extra_options = array()) if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))) ) { - $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); + $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extra_options); if ($methodwrap) { $result[$methodwrap['function']] = $methodwrap['function']; } @@ -515,6 +517,7 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti $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'; + $namespace = '\\PhpXmlRpc\\'; if (isset($extra_options['return_on_fault'])) { $decode_fault = true; $fault_response = $extra_options['return_on_fault']; @@ -524,9 +527,9 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti } $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0; - $msgclass = $prefix . 'msg'; - $valclass = $prefix . 'val'; - $decodefunc = 'php_' . $prefix . '_decode'; + $msgclass = $namespace . 'Request'; + $valclass = $namespace . 'Value'; + $decodefunc = 'new ' . $namespace . 'Encoder()->decode'; $msg = new $msgclass('system.methodSignature'); $msg->addparam(new $valclass($methodname)); @@ -578,8 +581,7 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti $results = $this->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); - + $fault_response, $namespace); //print_r($code); if ($buildit) { $allOK = 0; @@ -624,10 +626,11 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) $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'; + $namespace = '\\PhpXmlRpc\\'; - $msgclass = $prefix . 'msg'; + $msgclass = $namespace . 'Request'; //$valclass = $prefix.'val'; - $decodefunc = 'php_' . $prefix . '_decode'; + $decodefunc = 'new ' . $namespace . 'Encoder()->decode'; $msg = new $msgclass('system.listMethods'); $response = $client->send($msg, $timeout, $protocol); @@ -658,9 +661,9 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) /// @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 .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix); - $source .= "\$this->client =& \$client;\n}\n\n"; + $source .= "function __construct()\n{\n"; + $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix, $namespace); + $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, @@ -671,7 +674,7 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) 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); + $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts); if ($methodwrap) { if (!$buildit) { $source .= $methodwrap['docstring']; @@ -712,12 +715,12 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) protected 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 = '') + $fault_response = '', $namespace = '\\PhpXmlRpc\\') { $code = "function $xmlrpcfuncname ("; if ($client_copy_mode < 2) { // client copy mode 0 or 1 == partial / full client copy in emitted code - $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix); + $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix, $namespace); $innercode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { @@ -725,7 +728,7 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp $innercode = ''; $this_ = 'this->'; } - $innercode .= "\$msg = new {$prefix}msg('$methodname');\n"; + $innercode .= "\$msg = new {$namespace}Request('$methodname');\n"; if ($mdesc != '') { // take care that PHP comment is not terminated unwillingly by method description @@ -735,6 +738,7 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp } // param parsing + $innercode .= "\$encoder = new {$namespace}Encoder();\n"; $plist = array(); $pcount = count($msig); for ($i = 1; $i < $pcount; $i++) { @@ -744,12 +748,12 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp $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"; + $innercode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n"; } else { if ($encode_php_objects) { - $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n"; + $innercode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n"; } else { - $innercode .= "\$p$i = php_{$prefix}_encode(\$p$i);\n"; + $innercode .= "\$p$i = \$encoder->encode(\$p$i);\n"; } } $innercode .= "\$msg->addparam(\$p$i);\n"; @@ -760,7 +764,7 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp $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 ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$prefix}resp obj instance if call fails)\n*/\n"; + $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n"; if ($decode_fault) { @@ -773,9 +777,9 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp $respcode = '$res'; } if ($decode_php_objects) { - $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));"; + $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 php_{$prefix}_decode(\$res->value());"; + $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value());"; } $code = $code . $plist . ") {\n" . $innercode . "\n}\n"; @@ -788,9 +792,9 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp * Take care that no full checking of input parameters is done to ensure that * valid php code is emitted. */ - protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc') + protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) { - $code = "\$client = new {$prefix}_client('" . str_replace("'", "\'", $client->path) . + $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) . "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n"; // copy all client fields to the client that will be generated runtime From 7181e95b7ed0c8bb02169d0c1c0e4b5ab1bf7893 Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 26 Mar 2015 10:47:02 +0000 Subject: [PATCH 106/228] Aesthetic changes --- doc/highlight.php | 4 ++-- src/Client.php | 12 +++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/doc/highlight.php b/doc/highlight.php index 9f44b2cd..750261bd 100644 --- a/doc/highlight.php +++ b/doc/highlight.php @@ -19,11 +19,11 @@ function highlight($file) if ($code[strlen($code) - 1] == "\n") { $code = substr($code, 0, -1); } -//var_dump($code); + $code = str_replace(array('>', '<'), array('>', '<'), $code); $code = highlight_string('<?php 
', '', $code); -//echo($code); + $out = $out . substr($content, $last, $start + strlen($starttag) - $last) . $code . $endtag; $last = $end + strlen($endtag); } diff --git a/src/Client.php b/src/Client.php index ce1d6a5c..4331c4cf 100644 --- a/src/Client.php +++ b/src/Client.php @@ -5,16 +5,19 @@ class Client { /// @todo: do these need to be public? - public $path; + public $method = 'http'; public $server; public $port = 0; - public $method = 'http'; + public $path; + public $errno; public $errstr; public $debug = 0; + public $username = ''; public $password = ''; public $authtype = 1; + public $cert = ''; public $certpass = ''; public $cacert = ''; @@ -24,15 +27,18 @@ class Client public $verifypeer = true; public $verifyhost = 2; public $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT - public $no_multicall = false; + public $proxy = ''; public $proxyport = 0; public $proxy_user = ''; public $proxy_pass = ''; public $proxy_authtype = 1; + public $cookies = array(); public $extracurlopts = array(); + public $no_multicall = false; + /** * List of http compression methods accepted by the client for responses. * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib. From 5c1aaa6fbc49d3c0532da7358a688ab442b861ce Mon Sep 17 00:00:00 2001 From: gggeek Date: Thu, 26 Mar 2015 12:37:52 +0000 Subject: [PATCH 107/228] Oops last commit --- src/Wrapper.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Wrapper.php b/src/Wrapper.php index 36851d68..c182c7f5 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -529,7 +529,7 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti $msgclass = $namespace . 'Request'; $valclass = $namespace . 'Value'; - $decodefunc = 'new ' . $namespace . 'Encoder()->decode'; + $decoderClass = $namespace . 'Encoder'; $msg = new $msgclass('system.methodSignature'); $msg->addparam(new $valclass($methodname)); @@ -542,7 +542,8 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti } else { $msig = $response->value(); if ($client->return_type != 'phpvals') { - $msig = $decodefunc($msig); + $decoder = new $decoderClass(); + $msig = $decoder->decode($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); @@ -630,7 +631,7 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) $msgclass = $namespace . 'Request'; //$valclass = $prefix.'val'; - $decodefunc = 'new ' . $namespace . 'Encoder()->decode'; + $decoderClass = $namespace . 'Encoder'; $msg = new $msgclass('system.listMethods'); $response = $client->send($msg, $timeout, $protocol); @@ -641,7 +642,8 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) } else { $mlist = $response->value(); if ($client->return_type != 'phpvals') { - $mlist = $decodefunc($mlist); + $decoder = new $decoderClass(); + $mlist = $decoder->decode($mlist); } if (!is_array($mlist) || !count($mlist)) { error_log('XML-RPC: could not retrieve meaningful method list from remote server'); From 9ffe753899c3103deb271908e0be352e29aa770e Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 27 Mar 2015 08:51:29 +0000 Subject: [PATCH 108/228] Add tests for the demo files not to have fatal errors --- composer.json | 3 +- tests/1ParsingBugsTest.php | 15 +++- tests/5DemofilesTest.php | 154 +++++++++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 tests/5DemofilesTest.php diff --git a/composer.json b/composer.json index bae04ba9..51130cb2 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,8 @@ "require-dev": { "phpunit/phpunit": ">=4.0.0", "phpunit/phpunit-selenium": "*", - "codeclimate/php-test-reporter": "dev-master" + "codeclimate/php-test-reporter": "dev-master", + "ext-curl": "*" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index db03a478..0868a918 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -14,6 +14,13 @@ public function testMinusOneString() $this->assertEquals($u->scalarval(), $v->scalarval()); } + public function testMinusOneInt() + { + $v = new xmlrpcval(-1); + $u = new xmlrpcval(-1, 'string'); + $this->assertEquals($u->scalarval(), $v->scalarval()); + } + public function testUnicodeInMemberName() { $str = "G" . chr(252) . "nter, El" . chr(232) . "ne"; @@ -403,19 +410,19 @@ public function testUTF8Response() { $s = new xmlrpcmsg('dummy'); $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . 'userid311127 -dateCreated20011126T09:17:52content' . utf8_encode('') . 'postid7414222 +dateCreated20011126T09:17:52content' . utf8_encode('������') . 'postid7414222
'; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("", $v); + $this->assertEquals("������", $v); $f = 'userid311127 -dateCreated20011126T09:17:52content' . utf8_encode('') . 'postid7414222 +dateCreated20011126T09:17:52content' . utf8_encode('������') . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("", $v); + $this->assertEquals("������", $v); } public function testUTF8IntString() diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php new file mode 100644 index 00000000..be97eeb1 --- /dev/null +++ b/tests/5DemofilesTest.php @@ -0,0 +1,154 @@ +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(); + + $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'] ); + } + + protected function request($file, $method = 'GET', $payload = '') + { + $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'); + } + $page = curl_exec($ch); + curl_close($ch); + + $this->assertNotFalse($page); + $this->assertNotContains('Fatal error', $page); + + return $page; + } + + public function testAgeSort() + { + $page = $this->request('client/agesort.php'); + } + + public function testClient() + { + $page = $this->request('client/client.php'); + + // we could test many more calls to the client demo, but the upstream server is gone anyway... + + $page = $this->request('client/client.php', 'POST', array('stateno' => '1')); + } + + public function testComment() + { + $page = $this->request('client/comment.php'); + $page = $this->request('client/client.php', 'POST', array('storyid' => '1')); + } + + public function testIntrospect() + { + $page = $this->request('client/introspect.php'); + } + + public function testMail() + { + $page = $this->request('client/mail.php'); + $page = $this->request('client/client.php', 'POST', array( + 'server' => '', + "mailto" => '', + "mailsub" => '', + "mailmsg" => '', + "mailfrom" => '', + "mailcc" => '', + "mailbcc" => '', + )); + } + + public function testSimpleCall() + { + $page = $this->request('client/simple_call.php'); + } + + public function testWhich() + { + $page = $this->request('client/which.php'); + } + + public function testWrap() + { + $page = $this->request('client/wrap.php'); + } + + public function testZopeTest() + { + $page = $this->request('client/zopetest.php'); + } + + public function testDiscussServer() + { + $page = $this->request('server/discuss.php'); + $this->assertContains('faultCode', $page); + $this->assertContains('105', $page); + } + + public function testProxyServer() + { + $page = $this->request('server/proxy.php'); + $this->assertContains('faultCode', $page); + $this->assertContains('105', $page); + } +} From d70eea288e0fe7d0721285e3712cafd7c56ecabe Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 14:22:13 +0100 Subject: [PATCH 109/228] Stricter tests for demo files --- tests/5DemofilesTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index be97eeb1..48b8489b 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -75,6 +75,7 @@ protected function request($file, $method = 'GET', $payload = '') $this->assertNotFalse($page); $this->assertNotContains('Fatal error', $page); + $this->assertNotContains('Notice:', $page); return $page; } From 8f01888ce85ef2e3748b236e55bbab62a363c2a1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 14:39:11 +0100 Subject: [PATCH 110/228] Update code comments: remove old class names --- src/Client.php | 2 +- src/Encoder.php | 12 ++++++------ src/Helper/Charset.php | 2 +- src/Helper/XMLParser.php | 4 ++-- src/Request.php | 2 +- src/Response.php | 6 +++--- src/Server.php | 8 ++++---- src/Value.php | 34 ++++++++++++++++++---------------- src/Wrapper.php | 6 +++--- 9 files changed, 39 insertions(+), 37 deletions(-) diff --git a/src/Client.php b/src/Client.php index 4331c4cf..5fe3f02e 100644 --- a/src/Client.php +++ b/src/Client.php @@ -892,7 +892,7 @@ public function multicall($msgs, $timeout = 0, $method = '', $fallback = true) /** * Attempt to boxcar $msgs via system.multicall. - * Returns either an array of xmlrpcreponses, an xmlrpc error response + * Returns either an array of xmlrpc reponses, an xmlrpc error response * or false (when received response does not respect valid multicall syntax). */ private function _try_multicall($msgs, $timeout, $method) diff --git a/src/Encoder.php b/src/Encoder.php index e192d6bb..8c639581 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -7,7 +7,7 @@ class Encoder { /** - * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types. + * Takes an xmlrpc value in object format and translates it into native PHP types. * * Works with xmlrpc requests objects as input, too. * @@ -53,7 +53,7 @@ public function decode($xmlrpc_val, $options = array()) } if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') { // we return a Datetime object instead of a string - // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes, + // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes, // we cater to all 3 cases here $out = $xmlrpc_val->scalarval(); if (is_string($out)) { @@ -82,7 +82,7 @@ public function decode($xmlrpc_val, $options = array()) $xmlrpc_val->structreset(); // 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 xmlrpcval instead of + // 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) && $xmlrpc_val->_php_class != '' && class_exists($xmlrpc_val->_php_class) @@ -114,7 +114,7 @@ public function decode($xmlrpc_val, $options = array()) /** * Takes native php types and encodes them into xmlrpc PHP object format. - * It will not re-encode xmlrpcval objects. + * 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) @@ -125,7 +125,7 @@ public function decode($xmlrpc_val, $options = array()) * * @author Dan Libby (dan@libby.com) * - * @param mixed $php_val the value to be converted into an xmlrpcval object + * @param mixed $php_val 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 @@ -188,7 +188,7 @@ public function encode($php_val, $options = array()) } $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); if (in_array('encode_php_objs', $options)) { - // let's save original class name into xmlrpcval: + // let's save original class name into xmlrpc value: // might be useful later on... $xmlrpc_val->_php_class = get_class($php_val); } diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index b23b5c5f..cbf00a90 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -118,7 +118,7 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') case 'UTF-8_ISO-8859-1': // NB: this will choke on invalid UTF-8, going most likely beyond EOF $escaped_data = ''; - // be kind to users creating string xmlrpcvals out of different php types + // 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++) { diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index 734ada7e..b26cc189 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -18,8 +18,8 @@ class XMLParser // 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 xmlrpcresp fault (1) - // isf_reason - used for storing xmlrpcresp fault string + // 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 diff --git a/src/Request.php b/src/Request.php index 17aae840..4009a134 100644 --- a/src/Request.php +++ b/src/Request.php @@ -100,7 +100,7 @@ public function serialize($charset_encoding = '') */ public function addParam($param) { - // add check: do not add to self params which are not xmlrpcvals + // 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; diff --git a/src/Response.php b/src/Response.php index 626fd64f..90980ac9 100644 --- a/src/Response.php +++ b/src/Response.php @@ -18,13 +18,13 @@ class Response public $raw_data = ''; /** - * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string) + * @param mixed $val either an xmlrpc value obj, 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 * @param string $fString the error string, in case of an error response * @param string $valType either 'xmlrpcvals', 'phpvals' or 'xml' * * @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 xmlrpcval or a plain + * 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 = '') @@ -76,7 +76,7 @@ public function faultString() /** * Returns the value received by the server. * - * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects + * @return mixed the xmlrpc value object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects */ public function value() { diff --git a/src/Server.php b/src/Server.php index 3a8f5583..ccf6c8c6 100644 --- a/src/Server.php +++ b/src/Server.php @@ -288,7 +288,7 @@ public function add_to_map($methodname, $function, $sig = null, $doc = false, $s /** * Verify type and number of parameters received against a list of known signatures. * - * @param array $in array of either xmlrpcval objects or xmlrpc type definitions + * @param array $in array of either xmlrpc value objects or xmlrpc type definitions * @param array $sig array of known signatures to match against * * @return array @@ -514,7 +514,7 @@ public function parseRequest($data, $req_encoding = '') xml_parser_free($parser); // small layering violation in favor of speed and memory usage: // we should allow the 'execute' method handle this, but in the - // most common scenario (xmlrpcvals type server with some methods + // most common scenario (xmlrpc values type server with some methods // registered as phpvals) that would mean a useless encode+decode pass if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type']) && ($this->dmap[$xmlRpcParser->_xh['method']]['parameters_type'] == 'phpvals'))) { if ($this->debug > 1) { @@ -788,7 +788,7 @@ public static function _xmlrpcs_listMethods($server, $m = null) // if called in public static function _xmlrpcs_methodSignature($server, $m) { - // let accept as parameter both an xmlrpcval or string + // let accept as parameter both an xmlrpc value or string if (is_object($m)) { $methName = $m->getParam(0); $methName = $methName->scalarval(); @@ -825,7 +825,7 @@ public static function _xmlrpcs_methodSignature($server, $m) public static function _xmlrpcs_methodHelp($server, $m) { - // let accept as parameter both an xmlrpcval or string + // let accept as parameter both an xmlrpc value or string if (is_object($m)) { $methName = $m->getParam(0); $methName = $methName->scalarval(); diff --git a/src/Value.php b/src/Value.php index b9d34fe9..1ea6b9e2 100644 --- a/src/Value.php +++ b/src/Value.php @@ -37,6 +37,8 @@ class Value public $_php_class = null; /** + * Build an xmlrpc value + * * @param mixed $val * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed */ @@ -94,7 +96,7 @@ public function __construct($val = -1, $type = '') } /** - * Add a single php value to an (unitialized) xmlrpcval. + * Add a single php value to an (unitialized) xmlrpc value. * * @param mixed $val * @param string $type @@ -149,13 +151,13 @@ public function addScalar($val, $type = 'string') } /** - * Add an array of xmlrpcval objects to an xmlrpcval. + * Add an array of xmlrpc values objects to an xmlrpc value. * * @param Value[] $vals * * @return int 1 or 0 on failure * - * @todo add some checking for $vals to be an array of xmlrpcvals? + * @todo add some checking for $vals to be an array of xmlrpc values? */ public function addArray($vals) { @@ -177,7 +179,7 @@ public function addArray($vals) } /** - * Add an array of named xmlrpcval objects to an xmlrpcval. + * Add an array of named xmlrpc value objects to an xmlrpc value. * * @param Value[] $vals * @@ -281,7 +283,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') break; default: // no standard type value should arrive here, but provide a possibility - // for xmlrpcvals of unknown type... + // for xmlrpc values of unknown type... $rs .= "<${typ}>${val}"; } break; @@ -326,7 +328,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') */ public function serialize($charset_encoding = '') { - // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals... + // add check? slower, but helps to avoid recursion in serializing broken xmlrpc values... //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval'))) //{ reset($this->me); @@ -338,7 +340,7 @@ public function serialize($charset_encoding = '') /** * Checks whether a struct member with a given name is present. - * Works only on xmlrpcvals of type struct. + * Works only on xmlrpc values of type struct. * * @param string $m the name of the struct member to be looked up * @@ -350,7 +352,7 @@ public function structmemexists($m) } /** - * Returns the value of a given struct member (an xmlrpcval object in itself). + * 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 $m the name of the struct member to be looked up @@ -363,7 +365,7 @@ public function structmem($m) } /** - * Reset internal pointer for xmlrpcvals of type struct. + * Reset internal pointer for xmlrpc values of type struct. */ public function structreset() { @@ -371,9 +373,9 @@ public function structreset() } /** - * Return next member element for xmlrpcvals of type struct. + * Return next member element for xmlrpc values of type struct. * - * @return xmlrpcval + * @return Value */ public function structeach() { @@ -381,7 +383,7 @@ public function structeach() } /** - * Returns the value of a scalar xmlrpcval. + * Returns the value of a scalar xmlrpc value. * * @return mixed */ @@ -394,7 +396,7 @@ public function scalarval() } /** - * Returns the type of the xmlrpcval. + * Returns the type of the xmlrpc value. * For integers, 'int' is always returned in place of 'i4'. * * @return string @@ -411,7 +413,7 @@ public function scalartyp() } /** - * Returns the m-th member of an xmlrpcval of struct type. + * Returns the m-th member of an xmlrpc value of struct type. * * @param integer $m the index of the value to be retrieved (zero based) * @@ -423,7 +425,7 @@ public function arraymem($m) } /** - * Returns the number of members in an xmlrpcval of array type. + * Returns the number of members in an xmlrpc value of array type. * * @return integer */ @@ -433,7 +435,7 @@ public function arraysize() } /** - * Returns the number of members in an xmlrpcval of struct type. + * Returns the number of members in an xmlrpc value of struct type. * * @return integer */ diff --git a/src/Wrapper.php b/src/Wrapper.php index c182c7f5..fa32781e 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -96,7 +96,7 @@ public function xmlrpc_2_php_type($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 + * 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, @@ -417,7 +417,7 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = /** * Given a user-defined PHP class or php object, map its methods onto a list of - * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server + * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server * object and called from remote clients (as well as their corresponding signature info). * * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class @@ -749,7 +749,7 @@ protected function build_remote_method_wrapper_code($client, $methodname, $xmlrp 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 + // only build directly xmlrpc values when type is known and scalar $innercode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n"; } else { if ($encode_php_objects) { From c8a412d48733f671db6ba149659b816c2e14fd3a Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 15:35:48 +0100 Subject: [PATCH 111/228] Move debugger to new api and add basic unit tests for it --- debugger/action.php | 54 +++++++-------- debugger/common.php | 2 + debugger/controller.php | 145 +++++++++------------------------------ debugger/index.html | 11 --- src/Wrapper.php | 2 +- tests/5DemofilesTest.php | 3 + tests/6DebuggerTest.php | 102 +++++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 151 deletions(-) delete mode 100644 debugger/index.html create mode 100644 tests/6DebuggerTest.php diff --git a/debugger/action.php b/debugger/action.php index 2e5e4c56..f77c8761 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -91,31 +91,33 @@ 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); } - include 'xmlrpc.inc'; 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 = 'jsonrpc_client'; - $msgclass = 'jsonrpcmsg'; - $protoname = 'JSONRPC'; + $clientClass = 'PhpJsRpc\client'; + $requestClass = 'PhpJsRpc\request'; + $protoName = 'JSONRPC'; } else { - $clientclass = 'xmlrpc_client'; - $msgclass = 'xmlrpcmsg'; - $protoname = 'XMLRPC'; + $clientClass = 'PhpXmlRpc\client'; + $requestClass = 'PhpXmlRpc\Request'; + $protoName = 'XMLRPC'; } if ($port != "") { - $client = new $clientclass($path, $host, $port); + $client = new $clientClass($path, $host, $port); $server = "$host:$port$path"; } else { - $client = new $clientclass($path, $host); + $client = new $clientClass($path, $host); $server = "$host$path"; } if ($protocol == 2) { @@ -189,30 +191,24 @@ $msg = array(); switch ($action) { - - case 'wrap': - @include 'xmlrpc_wrappers.inc'; - if (!function_exists('build_remote_method_wrapper_code')) { - die('Error: to enable creation of method stubs the xmlrpc_wrappers.inc file is needed'); - } // fall thru intentionally case 'describe': case 'wrap': - $msg[0] = new $msgclass('system.methodHelp', array(), $id); - $msg[0]->addparam(new xmlrpcval($method)); - $msg[1] = new $msgclass('system.methodSignature', array(), $id + 1); - $msg[1]->addparam(new xmlrpcval($method)); + $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 $msgclass('system.listMethods', array(), $id); + $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 $msgclass($method, array(), $id); + $msg[0] = new $requestClass($method, array(), $id); // hack! build xml payload by hand if ($wstype == 1) { $msg[0]->payload = "{\n" . @@ -256,7 +252,7 @@ $time = (float)$mtime[0] + (float)$mtime[1]; foreach ($msg as $message) { // catch errors: for older xmlrpc libs, send does not return by ref - @$response = &$client->send($message, $timeout, $httpprotocol); + @$response = $client->send($message, $timeout, $httpprotocol); $resp[] = $response; if (!$response || $response->faultCode()) { break; @@ -272,14 +268,14 @@ if ($response->faultCode()) { // call failed! echo out error msg! //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; - echo "

$protoname call FAILED!

\n"; + echo "

$protoName call FAILED!

\n"; echo "

Fault code: [" . htmlspecialchars($response->faultCode()) . "] Reason: '" . htmlspecialchars($response->faultString()) . "'

\n"; echo(strftime("%d/%b/%Y:%H:%M:%S\n")); } else { // call succeeded: parse results //echo '

'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

'; - printf("

%s call(s) OK (%.2f secs.)

\n", $protoname, $time); + printf("

%s call(s) OK (%.2f secs.)

\n", $protoName, $time); echo(strftime("%d/%b/%Y:%H:%M:%S\n")); switch ($action) { @@ -324,7 +320,7 @@ ""); //echo("\n"); - // generate lo scheletro per il method payload per eventuali test + // generate the skeleton for method payload per possible tests //$methodpayload="\n".$rec->scalarval()."\n\n\n\n"; /*echo ("
". @@ -388,7 +384,7 @@ echo 'Unknown'; } echo ''; - //bottone per testare questo metodo + // button to test this method //$payload="\n$method\n\n$payload\n"; echo "" . "" . @@ -462,7 +458,8 @@ echo "Error: signature unknown\n"; } else { $mdesc = $r1->scalarval(); - $msig = php_xmlrpc_decode($r2); + $encoder = new PhpXmlRpc\Encoder(); + $msig = $encoder->decode($r2); $msig = $msig[$methodsig]; $proto = $protocol == 2 ? 'https' : $protocol == 1 ? 'http11' : ''; if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression && @@ -478,7 +475,8 @@ $prefix = 'xmlrpc'; } //$code = wrap_xmlrpc_method($client, $method, $methodsig, 0, $proto, '', $opts); - $code = build_remote_method_wrapper_code($client, $method, str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc, $timeout, $proto, $opts, $prefix); + $wrapper = new PhpXmlRpc\Wrapper(); + $code = $wrapper->build_remote_method_wrapper_code($client, $method, str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc, $timeout, $proto, $opts, $prefix); //if ($code) //{ echo "
\n"; diff --git a/debugger/common.php b/debugger/common.php index 642326ab..e8ad64cc 100644 --- a/debugger/common.php +++ b/debugger/common.php @@ -4,6 +4,8 @@ * @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 */ diff --git a/debugger/controller.php b/debugger/controller.php index d5c86109..6051f92b 100644 --- a/debugger/controller.php +++ b/debugger/controller.php @@ -18,8 +18,8 @@ } // relative path to the visual xmlrpc editing dialog -$editorpath = '../../javascript/debugger/'; -$editorlibs = '../../javascript/lib/'; +$editorpath = '../../phpjsrpc/debugger/'; +$editorlibs = '../../phpjsrpc/lib/'; ?> @@ -224,15 +224,12 @@ function switchFormMethod() { echo ' document.forms[2].submit();'; } ?>">

XMLRPC - +
/ -
- JSONRPC Debugger (based on the PHP-XMLRPC library) +
+ JSONRPC Debugger (based on the PHP-XMLRPC library)

-
+ @@ -250,19 +247,10 @@ function switchFormMethod() {
- - - - + + + +

Action

List available methods onclick="switchaction();"/>Describe method onclick="switchaction();"/>Execute method onclick="switchaction();"/>Generate stub for method call onclick="switchaction();"/>List available methods onclick="switchaction();"/>Describe method onclick="switchaction();"/>Execute method onclick="switchaction();"/>Generate stub for method call onclick="switchaction();"/>
@@ -273,13 +261,10 @@ function switchFormMethod() { Name: Payload:
-
- - Msg id: + + Msg id: @@ -290,38 +275,18 @@ function switchFormMethod() {

Client options

Show debug info: Timeout: - + Protocol: @@ -332,18 +297,9 @@ function switchFormMethod() { Type @@ -351,23 +307,12 @@ function switchFormMethod() { SSL: Verify Host's CN: Verify Cert: - /> + /> CA Cert file: @@ -384,44 +329,22 @@ function switchFormMethod() { COMPRESSION: Request: Response: COOKIES: - + Format: 'cookie1=value1, cookie2=value2' diff --git a/debugger/index.html b/debugger/index.html deleted file mode 100644 index 87c75b92..00000000 --- a/debugger/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - -XMLRPC Debugger - - - - - - \ No newline at end of file diff --git a/src/Wrapper.php b/src/Wrapper.php index fa32781e..c5d6c474 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -714,7 +714,7 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) * valid php code is emitted. * Note: real spaghetti code follows... */ - protected function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname, + public 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 = '', $namespace = '\\PhpXmlRpc\\') diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index 48b8489b..8f790d3b 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -70,6 +70,9 @@ protected function request($file, $method = 'GET', $payload = '') { 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); diff --git a/tests/6DebuggerTest.php b/tests/6DebuggerTest.php new file mode 100644 index 00000000..6291fefb --- /dev/null +++ b/tests/6DebuggerTest.php @@ -0,0 +1,102 @@ +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(); + + $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'] ); + } + + protected function request($file, $method = 'GET', $payload = '') + { + $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); + $this->assertNotContains('Fatal error', $page); + $this->assertNotContains('Notice:', $page); + + return $page; + } + + 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'); + } +} From 8e7f7c3cd2daa0c63b3b54b83caad271e1feb31c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 15:46:02 +0100 Subject: [PATCH 112/228] Fix 2 tests --- debugger/action.php | 6 +++--- tests/1ParsingBugsTest.php | 7 ++++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index f77c8761..69f66e0c 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -502,7 +502,7 @@ // no action taken yet: give some instructions on debugger usage ?> -

Instructions on usage of the debugger:

+

Instructions on usage of the debugger

  1. Run a 'list available methods' action against desired server
  2. If list of methods appears, click on 'describe method' for desired method
  3. @@ -516,13 +516,13 @@ } ?> -

    Example:

    +

    Example

    Server Address: phpxmlrpc.sourceforge.net
    Path: /server.php

    -

    Notice:

    +

    Notice

    all usernames and passwords entered on the above form will be written to the web server logs of this server. Use with care.

    diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 0868a918..949130f2 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -11,13 +11,18 @@ public function testMinusOneString() { $v = new xmlrpcval('-1'); $u = new xmlrpcval('-1', 'string'); + $t = new xmlrpcval(-1, 'string'); $this->assertEquals($u->scalarval(), $v->scalarval()); + $this->assertEquals($t->scalarval(), $v->scalarval()); } + /** + * This looks funny, and we might call it a bug. But we strive for 100 backwards compat... + */ public function testMinusOneInt() { $v = new xmlrpcval(-1); - $u = new xmlrpcval(-1, 'string'); + $u = new xmlrpcval(); $this->assertEquals($u->scalarval(), $v->scalarval()); } From 4a81986352f7d0759116e6172bb1c92b356430a1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 16:57:01 +0100 Subject: [PATCH 113/228] CamelCase everywhere! --- src/Client.php | 365 +++++++++++++++++++++++++------------------- src/Encoder.php | 138 ++++++++--------- src/Request.php | 69 ++++----- src/Server.php | 134 ++++++++-------- src/Value.php | 52 +++---- src/Wrapper.php | 394 ++++++++++++++++++++++++------------------------ 6 files changed, 609 insertions(+), 543 deletions(-) diff --git a/src/Client.php b/src/Client.php index 5fe3f02e..a13c31bb 100644 --- a/src/Client.php +++ b/src/Client.php @@ -167,27 +167,27 @@ public function setCredentials($u, $p, $t = 1) * Add a client-side https certificate. * * @param string $cert - * @param string $certpass + * @param string $certPass */ - public function setCertificate($cert, $certpass) + public function setCertificate($cert, $certPass) { $this->cert = $cert; - $this->certpass = $certpass; + $this->certpass = $certPass; } /** * Add a CA certificate to verify server with (see man page about * CURLOPT_CAINFO for more details). * - * @param string $cacert certificate file name (or dir holding certificates) - * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false + * @param string $caCert certificate file name (or dir holding certificates) + * @param bool $isDir set to true to indicate cacert is a dir. defaults to false */ - public function setCaCertificate($cacert, $is_dir = false) + public function setCaCertificate($caCert, $isDir = false) { - if ($is_dir) { - $this->cacertdir = $cacert; + if ($isDir) { + $this->cacertdir = $caCert; } else { - $this->cacert = $cacert; + $this->cacert = $caCert; } } @@ -197,12 +197,12 @@ public function setCaCertificate($cacert, $is_dir = false) * Thanks to Daniel Convissor. * * @param string $key The name of a file containing a private SSL key - * @param string $keypass The secret password needed to use the private SSL key + * @param string $keyPass The secret password needed to use the private SSL key */ - public function setKey($key, $keypass) + public function setKey($key, $keyPass) { $this->key = $key; - $this->keypass = $keypass; + $this->keypass = $keyPass; } /** @@ -238,19 +238,19 @@ public function setSSLVersion($i) /** * Set proxy info. * - * @param string $proxyhost - * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS - * @param string $proxyusername Leave blank if proxy has public access - * @param string $proxypassword Leave blank if proxy has public access - * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy + * @param string $proxyHost + * @param string $proxyPort Defaults to 8080 for HTTP and 443 for HTTPS + * @param string $proxyUsername Leave blank if proxy has public access + * @param string $proxyPassword Leave blank if proxy has public access + * @param int $proxyAuthType set to constant CURLAUTH_NTLM to use NTLM auth with proxy */ - public function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + public function setProxy($proxyHost, $proxyPort, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1) { - $this->proxy = $proxyhost; - $this->proxyport = $proxyport; - $this->proxy_user = $proxyusername; - $this->proxy_pass = $proxypassword; - $this->proxy_authtype = $proxyauthtype; + $this->proxy = $proxyHost; + $this->proxyport = $proxyPort; + $this->proxy_user = $proxyUsername; + $this->proxy_pass = $proxyPassword; + $this->proxy_authtype = $proxyAuthType; } /** @@ -259,16 +259,16 @@ public function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypass * http headers to xmlrpc requests. It is up to the xmlrpc server to return * compressed responses when receiving such requests. * - * @param string $compmethod either 'gzip', 'deflate', 'any' or '' + * @param string $compMethod either 'gzip', 'deflate', 'any' or '' */ - public function setAcceptedCompression($compmethod) + public function setAcceptedCompression($compMethod) { - if ($compmethod == 'any') { + if ($compMethod == 'any') { $this->accepted_compression = array('gzip', 'deflate'); - } elseif ($compmethod == false) { + } elseif ($compMethod == false) { $this->accepted_compression = array(); } else { - $this->accepted_compression = array($compmethod); + $this->accepted_compression = array($compMethod); } } @@ -277,11 +277,11 @@ public function setAcceptedCompression($compmethod) * Take care when sending compressed requests: servers might not support them * (and automatic fallback to uncompressed requests is not yet implemented). * - * @param string $compmethod either 'gzip', 'deflate' or '' + * @param string $compMethod either 'gzip', 'deflate' or '' */ - public function setRequestCompression($compmethod) + public function setRequestCompression($compMethod) { - $this->request_compression = $compmethod; + $this->request_compression = $compMethod; } /** @@ -324,22 +324,24 @@ public function SetCurlOptions($options) /** * Set user-agent string that will be used by this client instance * in http headers sent to the server. + * + * @param string $agentString */ - public function SetUserAgent($agentstring) + public function SetUserAgent($agentString) { - $this->user_agent = $agentstring; + $this->user_agent = $agentString; } /** * Send an xmlrpc request. * - * @param Request|Request[]|string $msg The Request object, or an array of requests for using multicall, or the complete xml representation of a request + * @param Request|Request[]|string $req The Request object, or an array of requests for using multicall, or the complete xml representation of a request * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used * * @return Response */ - public function send($msg, $timeout = 0, $method = '') + public function send($req, $timeout = 0, $method = '') { // if user does not specify http protocol, use native method of this client // (i.e. method set during call to constructor) @@ -347,23 +349,23 @@ public function send($msg, $timeout = 0, $method = '') $method = $this->method; } - if (is_array($msg)) { + if (is_array($req)) { // $msg is an array of Requests - $r = $this->multicall($msg, $timeout, $method); + $r = $this->multicall($req, $timeout, $method); return $r; - } elseif (is_string($msg)) { + } elseif (is_string($req)) { $n = new Request(''); - $n->payload = $msg; - $msg = $n; + $n->payload = $req; + $req = $n; } // where msg is a Request - $msg->debug = $this->debug; + $req->debug = $this->debug; if ($method == 'https') { $r = $this->sendPayloadHTTPS( - $msg, + $req, $this->server, $this->port, $timeout, @@ -386,7 +388,7 @@ public function send($msg, $timeout = 0, $method = '') ); } elseif ($method == 'http11') { $r = $this->sendPayloadCURL( - $msg, + $req, $this->server, $this->port, $timeout, @@ -407,7 +409,7 @@ public function send($msg, $timeout = 0, $method = '') ); } else { $r = $this->sendPayloadHTTP10( - $msg, + $req, $this->server, $this->port, $timeout, @@ -425,96 +427,111 @@ public function send($msg, $timeout = 0, $method = '') return $r; } - private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, - $username = '', $password = '', $authtype = 1, $proxyhost = '', - $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1) + /** + * @param Request $req + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @return Response + */ + protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, + $username = '', $password = '', $authType = 1, $proxyHost = '', + $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1) { if ($port == 0) { $port = 80; } // Only create the payload if it was not created previously - if (empty($msg->payload)) { - $msg->createPayload($this->request_charset_encoding); + if (empty($req->payload)) { + $req->createPayload($this->request_charset_encoding); } - $payload = $msg->payload; + $payload = $req->payload; // Deflate request body and set appropriate request headers if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { if ($this->request_compression == 'gzip') { $a = @gzencode($payload); if ($a) { $payload = $a; - $encoding_hdr = "Content-Encoding: gzip\r\n"; + $encodingHdr = "Content-Encoding: gzip\r\n"; } } else { $a = @gzcompress($payload); if ($a) { $payload = $a; - $encoding_hdr = "Content-Encoding: deflate\r\n"; + $encodingHdr = "Content-Encoding: deflate\r\n"; } } } else { - $encoding_hdr = ''; + $encodingHdr = ''; } // thanks to Grant Rauscher for this $credentials = ''; if ($username != '') { $credentials = 'Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n"; - if ($authtype != 1) { + if ($authType != 1) { error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported with HTTP 1.0'); } } - $accepted_encoding = ''; + $acceptedEncoding = ''; if (is_array($this->accepted_compression) && count($this->accepted_compression)) { - $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; + $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n"; } - $proxy_credentials = ''; - if ($proxyhost) { - if ($proxyport == 0) { - $proxyport = 8080; + $proxyCredentials = ''; + if ($proxyHost) { + if ($proxyPort == 0) { + $proxyPort = 8080; } - $connectserver = $proxyhost; - $connectport = $proxyport; + $connectServer = $proxyHost; + $connectPort = $proxyPort; $uri = 'http://' . $server . ':' . $port . $this->path; - if ($proxyusername != '') { - if ($proxyauthtype != 1) { + if ($proxyUsername != '') { + if ($proxyAuthType != 1) { error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported with HTTP 1.0'); } - $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername . ':' . $proxypassword) . "\r\n"; + $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n"; } } else { - $connectserver = $server; - $connectport = $port; + $connectServer = $server; + $connectPort = $port; $uri = $this->path; } // Cookie generation, as per rfc2965 (version 1 cookies) or // netscape's rules (version 0 cookies) - $cookieheader = ''; + $cookieHeader = ''; if (count($this->cookies)) { $version = ''; foreach ($this->cookies as $name => $cookie) { if ($cookie['version']) { $version = ' $Version="' . $cookie['version'] . '";'; - $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";'; + $cookieHeader .= ' ' . $name . '="' . $cookie['value'] . '";'; if ($cookie['path']) { - $cookieheader .= ' $Path="' . $cookie['path'] . '";'; + $cookieHeader .= ' $Path="' . $cookie['path'] . '";'; } if ($cookie['domain']) { - $cookieheader .= ' $Domain="' . $cookie['domain'] . '";'; + $cookieHeader .= ' $Domain="' . $cookie['domain'] . '";'; } if ($cookie['port']) { - $cookieheader .= ' $Port="' . $cookie['port'] . '";'; + $cookieHeader .= ' $Port="' . $cookie['port'] . '";'; } } else { - $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";"; + $cookieHeader .= ' ' . $name . '=' . $cookie['value'] . ";"; } } - $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n"; + $cookieHeader = 'Cookie:' . $version . substr($cookieHeader, 0, -1) . "\r\n"; } // omit port if 80 @@ -524,12 +541,12 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, 'User-Agent: ' . $this->user_agent . "\r\n" . 'Host: ' . $server . $port . "\r\n" . $credentials . - $proxy_credentials . - $accepted_encoding . - $encoding_hdr . + $proxyCredentials . + $acceptedEncoding . + $encodingHdr . 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" . - $cookieheader . - 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " . + $cookieHeader . + 'Content-Type: ' . $req->content_type . "\r\nContent-Length: " . strlen($payload) . "\r\n\r\n" . $payload; @@ -538,9 +555,9 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, } if ($timeout > 0) { - $fp = @fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout); + $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr, $timeout); } else { - $fp = @fsockopen($connectserver, $connectport, $this->errno, $this->errstr); + $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr); } if ($fp) { if ($timeout > 0 && function_exists('stream_set_timeout')) { @@ -572,47 +589,87 @@ private function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, $ipd .= fread($fp, 32768); } while (!feof($fp)); fclose($fp); - $r = $msg->parseResponse($ipd, false, $this->return_type); + $r = $req->parseResponse($ipd, false, $this->return_type); return $r; } - private function sendPayloadHTTPS($msg, $server, $port, $timeout = 0, $username = '', - $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', - $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, - $keepalive = false, $key = '', $keypass = '', $sslversion = 0) + /** + * @param Request $req + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $cert + * @param string $certPass + * @param string $caCert + * @param string $caCertDir + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @param bool $keepAlive + * @param string $key + * @param string $keyPass + * @param int $sslVersion + * @return Response + */ + protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $username = '', + $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', + $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, + $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0) { - $r = $this->sendPayloadCURL($msg, $server, $port, $timeout, $username, - $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport, - $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass, $sslversion); - - return $r; + return $this->sendPayloadCURL($req, $server, $port, $timeout, $username, + $password, $authType, $cert, $certPass, $caCert, $caCertDir, $proxyHost, $proxyPort, + $proxyUsername, $proxyPassword, $proxyAuthType, 'https', $keepAlive, $key, $keyPass, $sslVersion); } /** * Contributed by Justin Miller * Requires curl to be built into PHP * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! + * + * @param Request $msg + * @param string $server + * @param int $port + * @param int $timeout + * @param string $username + * @param string $password + * @param int $authType + * @param string $cert + * @param string $certPass + * @param string $caCert + * @param string $caCertDir + * @param string $proxyHost + * @param int $proxyPort + * @param string $proxyUsername + * @param string $proxyPassword + * @param int $proxyAuthType + * @param string $method + * @param bool $keepAlive + * @param string $key + * @param string $keyPass + * @param int $sslVersion + * @return Response */ - private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '', - $password = '', $authtype = 1, $cert = '', $certpass = '', $cacert = '', $cacertdir = '', - $proxyhost = '', $proxyport = 0, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1, $method = 'https', - $keepalive = false, $key = '', $keypass = '', $sslversion = 0) + protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '', + $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', + $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', + $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0) { if (!function_exists('curl_init')) { $this->errstr = 'CURL unavailable on this install'; - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); - - return $r; + return new Response(0, PhpXmlRpc::$xmlrpcerr['no_curl'], PhpXmlRpc::$xmlrpcstr['no_curl']); } if ($method == 'https') { if (($info = curl_version()) && ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))) ) { $this->errstr = 'SSL unavailable on this install'; - $r = new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); - - return $r; + return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']); } } @@ -636,17 +693,17 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = $a = @gzencode($payload); if ($a) { $payload = $a; - $encoding_hdr = 'Content-Encoding: gzip'; + $encodingHdr = 'Content-Encoding: gzip'; } } else { $a = @gzcompress($payload); if ($a) { $payload = $a; - $encoding_hdr = 'Content-Encoding: deflate'; + $encodingHdr = 'Content-Encoding: deflate'; } } } else { - $encoding_hdr = ''; + $encodingHdr = ''; } if ($this->debug > 1) { @@ -655,9 +712,9 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = flush(); } - if (!$keepalive || !$this->xmlrpc_curl_handle) { + if (!$keepAlive || !$this->xmlrpc_curl_handle) { $curl = curl_init($method . '://' . $server . ':' . $port . $this->path); - if ($keepalive) { + if ($keepAlive) { $this->xmlrpc_curl_handle = $curl; } } else { @@ -694,12 +751,12 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = // extra headers $headers = array('Content-Type: ' . $msg->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); // if no keepalive is wanted, let the server know it in advance - if (!$keepalive) { + if (!$keepAlive) { $headers[] = 'Connection: close'; } // request compression header - if ($encoding_hdr) { - $headers[] = $encoding_hdr; + if ($encodingHdr) { + $headers[] = $encodingHdr; } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -711,8 +768,8 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = if ($username && $password) { curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password); if (defined('CURLOPT_HTTPAUTH')) { - curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype); - } elseif ($authtype != 1) { + curl_setopt($curl, CURLOPT_HTTPAUTH, $authType); + } elseif ($authType != 1) { error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth is supported by the current PHP/curl install'); } } @@ -723,44 +780,43 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = curl_setopt($curl, CURLOPT_SSLCERT, $cert); } // set cert password - if ($certpass) { - curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass); + if ($certPass) { + curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certPass); } // whether to verify remote host's cert curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer); // set ca certificates file/dir - if ($cacert) { - curl_setopt($curl, CURLOPT_CAINFO, $cacert); + if ($caCert) { + curl_setopt($curl, CURLOPT_CAINFO, $caCert); } - if ($cacertdir) { - curl_setopt($curl, CURLOPT_CAPATH, $cacertdir); + if ($caCertDir) { + curl_setopt($curl, CURLOPT_CAPATH, $caCertDir); } // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?) if ($key) { curl_setopt($curl, CURLOPT_SSLKEY, $key); } // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?) - if ($keypass) { - curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass); + if ($keyPass) { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keyPass); } // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost); // allow usage of different SSL versions - curl_setopt($curl, CURLOPT_SSLVERSION, $sslversion); + curl_setopt($curl, CURLOPT_SSLVERSION, $sslVersion); } // proxy info - if ($proxyhost) { - if ($proxyport == 0) { - $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080 + if ($proxyHost) { + if ($proxyPort == 0) { + $proxyPort = 8080; // NB: even for HTTPS, local connection is on port 8080 } - curl_setopt($curl, CURLOPT_PROXY, $proxyhost . ':' . $proxyport); - //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport); - if ($proxyusername) { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername . ':' . $proxypassword); + curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort); + if ($proxyUsername) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUsername . ':' . $proxyPassword); if (defined('CURLOPT_PROXYAUTH')) { - curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype); - } elseif ($proxyauthtype != 1) { + curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyAuthType); + } elseif ($proxyAuthType != 1) { error_log('XML-RPC: ' . __METHOD__ . ': warning. Only Basic auth to proxy is supported by the current PHP/curl install'); } } @@ -770,11 +826,11 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = // the following code does not honour 'expires', 'path' and 'domain' cookie attributes // set to client obj the the user... if (count($this->cookies)) { - $cookieheader = ''; + $cookieHeader = ''; foreach ($this->cookies as $name => $cookie) { - $cookieheader .= $name . '=' . $cookie['value'] . '; '; + $cookieHeader .= $name . '=' . $cookie['value'] . '; '; } - curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2)); + curl_setopt($curl, CURLOPT_COOKIE, substr($cookieHeader, 0, -2)); } foreach ($this->extracurlopts as $opt => $val) { @@ -801,16 +857,16 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = $this->errstr = 'no response'; $resp = new Response(0, PhpXmlRpc::$xmlrpcerr['curl_fail'], PhpXmlRpc::$xmlrpcstr['curl_fail'] . ': ' . curl_error($curl)); curl_close($curl); - if ($keepalive) { + if ($keepAlive) { $this->xmlrpc_curl_handle = null; } } else { - if (!$keepalive) { + if (!$keepAlive) { curl_close($curl); } $resp = $msg->parseResponse($result, true, $this->return_type); // if we got back a 302, we can not reuse the curl handle for later calls - if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepalive) { + if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) { curl_close($curl); $this->xmlrpc_curl_handle = null; } @@ -834,20 +890,20 @@ private function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = * NB: trying to shoehorn extra functionality into existing syntax has resulted * in pretty much convoluted code... * - * @param Request[] $msgs an array of Request objects + * @param Request[] $reqs an array of Request objects * @param integer $timeout connection timeout (in seconds) * @param string $method the http protocol variant to be used * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted * * @return array */ - public function multicall($msgs, $timeout = 0, $method = '', $fallback = true) + public function multicall($reqs, $timeout = 0, $method = '', $fallback = true) { if ($method == '') { $method = $this->method; } if (!$this->no_multicall) { - $results = $this->_try_multicall($msgs, $timeout, $method); + $results = $this->_try_multicall($reqs, $timeout, $method); if (is_array($results)) { // System.multicall succeeded return $results; @@ -875,14 +931,14 @@ public function multicall($msgs, $timeout = 0, $method = '', $fallback = true) if ($fallback) { // system.multicall is (probably) unsupported by server: // emulate multicall via multiple requests - foreach ($msgs as $msg) { - $results[] = $this->send($msg, $timeout, $method); + foreach ($reqs as $req) { + $results[] = $this->send($req, $timeout, $method); } } else { // user does NOT want to fallback on many single calls: // since we should always return an array of responses, // return an array with the same error repeated n times - foreach ($msgs as $msg) { + foreach ($reqs as $req) { $results[] = $result; } } @@ -891,29 +947,34 @@ public function multicall($msgs, $timeout = 0, $method = '', $fallback = true) } /** - * Attempt to boxcar $msgs via system.multicall. + * Attempt to boxcar $reqs via system.multicall. * Returns either an array of xmlrpc reponses, an xmlrpc error response * or false (when received response does not respect valid multicall syntax). + * + * @param Request[] $reqs + * @param int $timeout + * @param string $method + * @return array|bool|mixed|Response */ - private function _try_multicall($msgs, $timeout, $method) + private function _try_multicall($reqs, $timeout, $method) { // Construct multicall request $calls = array(); - foreach ($msgs as $msg) { - $call['methodName'] = new Value($msg->method(), 'string'); - $numParams = $msg->getNumParams(); + foreach ($reqs as $req) { + $call['methodName'] = new Value($req->method(), 'string'); + $numParams = $req->getNumParams(); $params = array(); for ($i = 0; $i < $numParams; $i++) { - $params[$i] = $msg->getParam($i); + $params[$i] = $req->getParam($i); } $call['params'] = new Value($params, 'array'); $calls[] = new Value($call, 'struct'); } - $multicall = new Request('system.multicall'); - $multicall->addParam(new Value($calls, 'array')); + $multiCall = new Request('system.multicall'); + $multiCall->addParam(new Value($calls, 'array')); // Attempt RPC call - $result = $this->send($multicall, $timeout, $method); + $result = $this->send($multiCall, $timeout, $method); if ($result->faultCode() != 0) { // call to system.multicall failed @@ -932,7 +993,7 @@ private function _try_multicall($msgs, $timeout, $method) return false; // bad return type from system.multicall } $numRets = count($rets); - if ($numRets != count($msgs)) { + if ($numRets != count($reqs)) { return false; // wrong number of return values. } @@ -976,7 +1037,7 @@ private function _try_multicall($msgs, $timeout, $method) return false; // bad return type from system.multicall } $numRets = $rets->arraysize(); - if ($numRets != count($msgs)) { + if ($numRets != count($reqs)) { return false; // wrong number of return values. } diff --git a/src/Encoder.php b/src/Encoder.php index 8c639581..f7238891 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -23,39 +23,39 @@ class Encoder * * @author Dan Libby (dan@libby.com) * - * @param Value|Request $xmlrpc_val + * @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($xmlrpc_val, $options = array()) + public function decode($xmlrpcVal, $options = array()) { - switch ($xmlrpc_val->kindOf()) { + switch ($xmlrpcVal->kindOf()) { case 'scalar': if (in_array('extension_api', $options)) { - reset($xmlrpc_val->me); - list($typ, $val) = each($xmlrpc_val->me); + reset($xmlrpcVal->me); + list($typ, $val) = each($xmlrpcVal->me); switch ($typ) { case 'dateTime.iso8601': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->type = 'datetime'; - $xmlrpc_val->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val); + $xmlrpcVal->scalar = $val; + $xmlrpcVal->type = 'datetime'; + $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val); - return $xmlrpc_val; + return $xmlrpcVal; case 'base64': - $xmlrpc_val->scalar = $val; - $xmlrpc_val->type = $typ; + $xmlrpcVal->scalar = $val; + $xmlrpcVal->type = $typ; - return $xmlrpc_val; + return $xmlrpcVal; default: - return $xmlrpc_val->scalarval(); + return $xmlrpcVal->scalarval(); } } - if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601') { + 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 = $xmlrpc_val->scalarval(); + $out = $xmlrpcVal->scalarval(); if (is_string($out)) { $out = strtotime($out); } @@ -69,43 +69,43 @@ public function decode($xmlrpc_val, $options = array()) } } - return $xmlrpc_val->scalarval(); + return $xmlrpcVal->scalarval(); case 'array': - $size = $xmlrpc_val->arraysize(); + $size = $xmlrpcVal->arraysize(); $arr = array(); for ($i = 0; $i < $size; $i++) { - $arr[] = $this->decode($xmlrpc_val->arraymem($i), $options); + $arr[] = $this->decode($xmlrpcVal->arraymem($i), $options); } return $arr; case 'struct': - $xmlrpc_val->structreset(); + $xmlrpcVal->structreset(); // 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) && $xmlrpc_val->_php_class != '' - && class_exists($xmlrpc_val->_php_class) + if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != '' + && class_exists($xmlrpcVal->_php_class) ) { - $obj = @new $xmlrpc_val->_php_class(); - while (list($key, $value) = $xmlrpc_val->structeach()) { + $obj = @new $xmlrpcVal->_php_class(); + while (list($key, $value) = $xmlrpcVal->structeach()) { $obj->$key = $this->decode($value, $options); } return $obj; } else { $arr = array(); - while (list($key, $value) = $xmlrpc_val->structeach()) { + while (list($key, $value) = $xmlrpcVal->structeach()) { $arr[$key] = $this->decode($value, $options); } return $arr; } case 'msg': - $paramcount = $xmlrpc_val->getNumParams(); + $paramCount = $xmlrpcVal->getNumParams(); $arr = array(); - for ($i = 0; $i < $paramcount; $i++) { - $arr[] = $this->decode($xmlrpc_val->getParam($i)); + for ($i = 0; $i < $paramCount; $i++) { + $arr[] = $this->decode($xmlrpcVal->getParam($i)); } return $arr; @@ -130,39 +130,39 @@ public function decode($xmlrpc_val, $options = array()) * * @return \PhpXmlrpc\Value */ - public function encode($php_val, $options = array()) + public function encode($phpVal, $options = array()) { - $type = gettype($php_val); + $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}$/', $php_val)) { - $xmlrpc_val = new Value($php_val, Value::$xmlrpcDateTime); + 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 { - $xmlrpc_val = new Value($php_val, Value::$xmlrpcString); + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString); } break; case 'integer': - $xmlrpc_val = new Value($php_val, Value::$xmlrpcInt); + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt); break; case 'double': - $xmlrpc_val = new Value($php_val, Value::$xmlrpcDouble); + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble); break; // // Add support for encoding/decoding of booleans, since they are supported in PHP case 'boolean': - $xmlrpc_val = new Value($php_val, Value::$xmlrpcBoolean); + $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean); break; // 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($php_val), range(0, count($php_val)-1)); + // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1)); // but execution time skyrockets! $j = 0; $arr = array(); $ko = false; - foreach ($php_val as $key => $val) { + foreach ($phpVal as $key => $val) { $arr[$key] = $this->encode($val, $options); if (!$ko && $key !== $j) { $ko = true; @@ -170,67 +170,67 @@ public function encode($php_val, $options = array()) $j++; } if ($ko) { - $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); + $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct); } else { - $xmlrpc_val = new Value($arr, Value::$xmlrpcArray); + $xmlrpcVal = new Value($arr, Value::$xmlrpcArray); } break; case 'object': - if (is_a($php_val, 'PhpXmlRpc\Value')) { - $xmlrpc_val = $php_val; - } elseif (is_a($php_val, 'DateTime')) { - $xmlrpc_val = new Value($php_val->format('Ymd\TH:i:s'), Value::$xmlrpcStruct); + 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($php_val); - while (list($k, $v) = each($php_val)) { + reset($phpVal); + while (list($k, $v) = each($phpVal)) { $arr[$k] = $this->encode($v, $options); } - $xmlrpc_val = new Value($arr, Value::$xmlrpcStruct); + $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... - $xmlrpc_val->_php_class = get_class($php_val); + $xmlrpcVal->_php_class = get_class($phpVal); } } break; case 'NULL': if (in_array('extension_api', $options)) { - $xmlrpc_val = new Value('', Value::$xmlrpcString); + $xmlrpcVal = new Value('', Value::$xmlrpcString); } elseif (in_array('null_extension', $options)) { - $xmlrpc_val = new Value('', Value::$xmlrpcNull); + $xmlrpcVal = new Value('', Value::$xmlrpcNull); } else { - $xmlrpc_val = new Value(); + $xmlrpcVal = new Value(); } break; case 'resource': if (in_array('extension_api', $options)) { - $xmlrpc_val = new Value((int)$php_val, Value::$xmlrpcInt); + $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt); } else { - $xmlrpc_val = new Value(); + $xmlrpcVal = new Value(); } // catch "user function", "unknown type" default: // giancarlo pinerolo // it has to return // an empty object in case, not a boolean. - $xmlrpc_val = new Value(); + $xmlrpcVal = new Value(); break; } - return $xmlrpc_val; + 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 $xml_val + * @param string $xmlVal * @param array $options * * @return mixed false on error, or an instance of either Value, Request or Response */ - public function decode_xml($xml_val, $options = array()) + public function decode_xml($xmlVal, $options = array()) { /// @todo 'guestimate' encoding @@ -250,7 +250,7 @@ public function decode_xml($xml_val, $options = array()) 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, $xml_val, 1)) { + 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)); @@ -300,14 +300,14 @@ public function decode_xml($xml_val, $options = array()) * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers, * which will be most probably using UTF-8 anyway... * - * @param string $httpheader the http Content-type header - * @param string $xmlchunk xml content buffer - * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled) + * @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) * @return string * * @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 guess_encoding($httpheader = '', $xmlchunk = '', $encoding_prefs = null) + public static function guess_encoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null) { // discussion: see http://www.yale.edu/pclt/encoding/ // 1 - test if encoding is specified in HTTP HEADERS @@ -325,7 +325,7 @@ public static function guess_encoding($httpheader = '', $xmlchunk = '', $encodin /// @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)) { + if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) { return strtoupper(trim($matches[1], " \t\"")); } @@ -336,11 +336,11 @@ public static function guess_encoding($httpheader = '', $xmlchunk = '', $encodin // 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)) { + 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)) { + } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) { return 'UTF-16'; - } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk)) { + } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) { return 'UTF-8'; } @@ -350,17 +350,17 @@ public static function guess_encoding($httpheader = '', $xmlchunk = '', $encodin // 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)) { + $xmlChunk, $matches)) { return strtoupper(substr($matches[2], 1, -1)); } // 4 - if mbstring is available, let it do the guesswork // NB: we favour finding an encoding that is compatible with what we can process if (extension_loaded('mbstring')) { - if ($encoding_prefs) { - $enc = mb_detect_encoding($xmlchunk, $encoding_prefs); + if ($encodingPrefs) { + $enc = mb_detect_encoding($xmlChunk, $encodingPrefs); } else { - $enc = mb_detect_encoding($xmlchunk); + $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 diff --git a/src/Request.php b/src/Request.php index 4009a134..12cbf688 100644 --- a/src/Request.php +++ b/src/Request.php @@ -29,10 +29,10 @@ public function __construct($methodName, $params = array()) } } - public function xml_header($charset_encoding = '') + public function xml_header($charsetEncoding = '') { - if ($charset_encoding != '') { - return "\n\n"; + if ($charsetEncoding != '') { + return "\n\n"; } else { return "\n\n"; } @@ -43,18 +43,18 @@ public function xml_footer() return ''; } - public function createPayload($charset_encoding = '') + public function createPayload($charsetEncoding = '') { - if ($charset_encoding != '') { - $this->content_type = 'text/xml; charset=' . $charset_encoding; + if ($charsetEncoding != '') { + $this->content_type = 'text/xml; charset=' . $charsetEncoding; } else { $this->content_type = 'text/xml'; } - $this->payload = $this->xml_header($charset_encoding); + $this->payload = $this->xml_header($charsetEncoding); $this->payload .= '' . $this->methodname . "\n"; $this->payload .= "\n"; foreach ($this->params as $p) { - $this->payload .= "\n" . $p->serialize($charset_encoding) . + $this->payload .= "\n" . $p->serialize($charsetEncoding) . "\n"; } $this->payload .= "\n"; @@ -80,13 +80,13 @@ public function method($methodName = '') /** * Returns xml representation of the message. XML prologue included. * - * @param string $charset_encoding + * @param string $charsetEncoding * * @return string the xml representation of the message, xml prologue included */ - public function serialize($charset_encoding = '') + public function serialize($charsetEncoding = '') { - $this->createPayload($charset_encoding); + $this->createPayload($charsetEncoding); return $this->payload; } @@ -160,12 +160,12 @@ public function parseResponseFile($fp) * Parse the xmlrpc response contained in the string $data and return a Response object. * * @param string $data the xmlrpc response, eventually including http headers - * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding - * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals' + * @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 = '', $headers_processed = false, $return_type = 'xmlrpcvals') + public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals') { if ($this->debug) { // by maHo, replaced htmlspecialchars with htmlentities @@ -183,7 +183,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty if (substr($data, 0, 4) == 'HTTP') { $httpParser = new Http(); try { - $this->httpResponse = $httpParser->parseResponseHeaders($data, $headers_processed, $this->debug); + $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 @@ -217,7 +217,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty } // if user wants back raw xml, give it to him - if ($return_type == 'xml') { + if ($returnType == 'xml') { $r = new Response($data, 0, '', 'xml'); $r->hdrs = $this->httpResponse['headers']; $r->_cookies = $this->httpResponse['cookies']; @@ -256,7 +256,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty $xmlRpcParser = new XMLParser(); xml_set_object($parser, $xmlRpcParser); - if ($return_type == 'phpvals') { + if ($returnType == 'phpvals') { xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast'); } else { xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee'); @@ -269,17 +269,17 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty if (!xml_parse($parser, $data, count($data))) { // thanks to Peter Kocks if ((xml_get_current_line_number($parser)) == 1) { - $errstr = 'XML error at line 1, check URL'; + $errStr = 'XML error at line 1, check URL'; } else { - $errstr = sprintf('XML error: %s at line %d, column %d', + $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 . ')'); + 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; + print $errStr; } $r->hdrs = $this->httpResponse['headers']; $r->_cookies = $this->httpResponse['cookies']; @@ -299,7 +299,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty } // third error check: parsing of the response has somehow gone boink. // NB: shall we omit this check, since we trust the parsing code? - elseif ($return_type == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) { + 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 @@ -318,24 +318,24 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty if ($xmlRpcParser->_xh['isf']) { /// @todo we should test here if server sent an int and a string, /// and/or coerce them into such... - if ($return_type == 'xmlrpcvals') { - $errno_v = $v->structmem('faultCode'); - $errstr_v = $v->structmem('faultString'); - $errno = $errno_v->scalarval(); - $errstr = $errstr_v->scalarval(); + if ($returnType == 'xmlrpcvals') { + $errNo_v = $v->structmem('faultCode'); + $errStr_v = $v->structmem('faultString'); + $errNo = $errNo_v->scalarval(); + $errStr = $errStr_v->scalarval(); } else { - $errno = $v['faultCode']; - $errstr = $v['faultString']; + $errNo = $v['faultCode']; + $errStr = $v['faultString']; } - if ($errno == 0) { + if ($errNo == 0) { // FAULT returned, errno needs to reflect that - $errno = -1; + $errNo = -1; } - $r = new Response(0, $errno, $errstr); + $r = new Response(0, $errNo, $errStr); } else { - $r = new Response($v, 0, '', $return_type); + $r = new Response($v, 0, '', $returnType); } } @@ -350,6 +350,7 @@ public function parseResponse($data = '', $headers_processed = false, $return_ty * Echoes a debug message, taking care of escaping it when not in console mode * * @param string $message + * @param bool $encodeEntities when false, escapes using htmlspecialchars instead of htmlentities */ protected function debugMessage($message, $encodeEntities = true) { diff --git a/src/Server.php b/src/Server.php index ccf6c8c6..ec9ebb44 100644 --- a/src/Server.php +++ b/src/Server.php @@ -71,10 +71,10 @@ class Server public static $_xmlrpcs_prev_ehandler = ''; /** - * @param array $dispmap the dispatch map with definition of exposed services + * @param array $dispatchMap the dispatch map with definition of exposed services * @param boolean $servicenow set to false to prevent the server from running upon construction */ - public function __construct($dispMap = null, $serviceNow = true) + public function __construct($dispatchMap = null, $serviceNow = true) { // if ZLIB is enabled, let the server by default accept compressed requests, // and compress responses sent to clients that support them @@ -95,8 +95,8 @@ public function __construct($dispMap = null, $serviceNow = true) * instead, you can use the class add_to_map() function * to add functions manually (borrowed from SOAPX4) */ - if ($dispMap) { - $this->dmap = $dispMap; + if ($dispatchMap) { + $this->dmap = $dispatchMap; if ($serviceNow) { $this->service(); } @@ -106,7 +106,7 @@ public function __construct($dispMap = null, $serviceNow = true) /** * Set debug level of server. * - * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments) + * @param integer $level debug lvl: determines info added to xmlrpc responses (as xml comments) * 0 = no debug info, * 1 = msgs set from user with debugmsg(), * 2 = add complete xmlrpc request (headers and body), @@ -117,9 +117,9 @@ public function __construct($dispMap = null, $serviceNow = true) * execution anymore, but just end up logged in the xmlrpc response) * Note that info added at level 2 and 3 will be base64 encoded */ - public function setDebug($in) + public function setDebug($level) { - $this->debug = $in; + $this->debug = $level; } /** @@ -128,27 +128,27 @@ public function setDebug($in) * Note that for best compatibility, the debug string should be encoded using * the PhpXmlRpc::$xmlrpc_internalencoding character set. * - * @param string $m + * @param string $msg * @access public */ - public static function xmlrpc_debugmsg($m) + public static function xmlrpc_debugmsg($msg) { - static::$_xmlrpc_debuginfo .= $m . "\n"; + static::$_xmlrpc_debuginfo .= $msg . "\n"; } - public static function error_occurred($m) + public static function error_occurred($msg) { - static::$_xmlrpcs_occurred_errors .= $m . "\n"; + static::$_xmlrpcs_occurred_errors .= $msg . "\n"; } /** * Return a string with the serialized representation of all debug info. * - * @param string $charset_encoding the target charset encoding for the serialization + * @param string $charsetEncoding the target charset encoding for the serialization * * @return string an XML comment (or two) */ - public function serializeDebug($charset_encoding = '') + public function serializeDebug($charsetEncoding = '') { // Tough encoding problem: which internal charset should we assume for debug info? // It might contain a copy of raw data received from client, ie with unknown encoding, @@ -160,7 +160,7 @@ public function serializeDebug($charset_encoding = '') $out .= "\n"; } if (static::$_xmlrpc_debuginfo != '') { - $out .= "\n"; + $out .= "\n"; // NB: a better solution MIGHT be to use CDATA, but we need to insert it // into return payload AFTER the beginning tag //$out .= "', ']_]_>', static::$_xmlrpc_debuginfo) . "\n]]>\n"; @@ -173,16 +173,16 @@ public function serializeDebug($charset_encoding = '') * Execute the xmlrpc request, printing the response. * * @param string $data the request body. If null, the http POST request will be examined - * @param bool $return_payload When true, return the response but do not echo it or any http header + * @param bool $returnPayload When true, return the response but do not echo it or any http header * * @return Response the response object (usually not used by caller...) */ - public function service($data = null, $return_payload = false) + public function service($data = null, $returnPayload = false) { if ($data === null) { $data = file_get_contents('php://input'); } - $raw_data = $data; + $rawData = $data; // reset internal debug info $this->debug_info = ''; @@ -192,32 +192,32 @@ public function service($data = null, $return_payload = false) $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); } - $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding); + $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding); if (!$r) { - $r = $this->parseRequest($data, $req_charset); + $r = $this->parseRequest($data, $reqCharset); } // save full body of request into response, for more debugging usages - $r->raw_data = $raw_data; + $r->raw_data = $rawData; if ($this->debug > 2 && static::$_xmlrpcs_occurred_errors) { $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" . static::$_xmlrpcs_occurred_errors . "+++END+++"); } - $payload = $this->xml_header($resp_charset); + $payload = $this->xml_header($respCharset); if ($this->debug > 0) { - $payload = $payload . $this->serializeDebug($resp_charset); + $payload = $payload . $this->serializeDebug($respCharset); } // G. Giunta 2006-01-27: do not create response serialization if it has // already happened. Helps building json magic if (empty($r->payload)) { - $r->serialize($resp_charset); + $r->serialize($respCharset); } $payload = $payload . $r->payload; - if ($return_payload) { + if ($returnPayload) { return $payload; } @@ -232,15 +232,15 @@ public function service($data = null, $return_payload = false) // http compression of output: only // if we can do it, and we want to do it, and client asked us to, // and php ini settings do not force it already - $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); - if ($this->compress_response && function_exists('gzencode') && $resp_encoding != '' - && $php_no_self_compress + $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler'); + if ($this->compress_response && function_exists('gzencode') && $respEncoding != '' + && $phpNoSelfCompress ) { - if (strpos($resp_encoding, 'gzip') !== false) { + if (strpos($respEncoding, 'gzip') !== false) { $payload = gzencode($payload); header("Content-Encoding: gzip"); header("Vary: Accept-Encoding"); - } elseif (strpos($resp_encoding, 'deflate') !== false) { + } elseif (strpos($respEncoding, 'deflate') !== false) { $payload = gzcompress($payload); header("Content-Encoding: deflate"); header("Vary: Accept-Encoding"); @@ -249,7 +249,7 @@ public function service($data = null, $return_payload = false) // do not output content-length header if php is compressing output for us: // it will mess up measurements - if ($php_no_self_compress) { + if ($phpNoSelfCompress) { header('Content-Length: ' . (int)strlen($payload)); } } else { @@ -265,23 +265,23 @@ public function service($data = null, $return_payload = false) /** * Add a method to the dispatch map. * - * @param string $methodname the name with which the method will be made available + * @param string $methodName the name with which the method will be made available * @param string $function the php function that will get invoked * @param array $sig the array of valid method signatures * @param string $doc method documentation - * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type) + * @param array $sigDoc the array of valid method signatures docs (one string per param, one for return type) */ - public function add_to_map($methodname, $function, $sig = null, $doc = false, $sigdoc = false) + public function add_to_map($methodName, $function, $sig = null, $doc = false, $sigDoc = false) { - $this->dmap[$methodname] = array( + $this->dmap[$methodName] = array( 'function' => $function, 'docstring' => $doc, ); if ($sig) { - $this->dmap[$methodname]['signature'] = $sig; + $this->dmap[$methodName]['signature'] = $sig; } - if ($sigdoc) { - $this->dmap[$methodname]['signature_docs'] = $sigdoc; + if ($sigDoc) { + $this->dmap[$methodName]['signature_docs'] = $sigDoc; } } @@ -342,7 +342,7 @@ protected function verifySignature($in, $sig) * * @return mixed null on success or a Response */ - protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression) + protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$resp_compression) { // check if $_SERVER is populated: it might have been disabled via ini file // (this is true even when in CLI mode) @@ -397,7 +397,7 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, // check if client specified accepted charsets, and if we know how to fulfill // the request if ($this->response_charset_encoding == 'auto') { - $resp_encoding = ''; + $respEncoding = ''; if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) { // here we should check if we can match the client-requested encoding // with the encodings we know we can generate. @@ -408,17 +408,17 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, foreach ($known_charsets as $charset) { foreach ($client_accepted_charsets as $accepted) { if (strpos($accepted, $charset) === 0) { - $resp_encoding = $charset; + $respEncoding = $charset; break; } } - if ($resp_encoding) { + if ($respEncoding) { break; } } } } else { - $resp_encoding = $this->response_charset_encoding; + $respEncoding = $this->response_charset_encoding; } if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { @@ -429,7 +429,7 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, // 'guestimate' request encoding /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? - $req_encoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $reqEncoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', $data); return; @@ -440,11 +440,11 @@ protected function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, * php function registered with the server. * * @param string $data the xml request - * @param string $req_encoding (optional) the charset encoding of the xml request + * @param string $reqEncoding (optional) the charset encoding of the xml request * * @return Response */ - public function parseRequest($data, $req_encoding = '') + public function parseRequest($data, $reqEncoding = '') { // 2005/05/07 commented and moved into caller function code //if($data=='') @@ -457,19 +457,19 @@ public function parseRequest($data, $req_encoding = '') //$data = xmlrpc_html_entity_xlate($data); // decompose incoming XML into request structure - if ($req_encoding != '') { - if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + if ($reqEncoding != '') { + if (!in_array($reqEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { // the following code might be better for mb_string enabled installs, but // makes the lib about 200% slower... - //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + //if (!is_valid_charset($reqEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $req_encoding); - $req_encoding = PhpXmlRpc::$xmlrpc_defencoding; + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding); + $reqEncoding = PhpXmlRpc::$xmlrpc_defencoding; } /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, // the encoding is not UTF8 and there are non-ascii chars in the text... /// @todo use an empty string for php 5 ??? - $parser = xml_parser_create($req_encoding); + $parser = xml_parser_create($reqEncoding); } else { $parser = xml_parser_create(); } @@ -544,11 +544,11 @@ public function parseRequest($data, $req_encoding = '') * * @param mixed $m either a Request obj or a method name * @param array $params array with method parameters as php types (if m is method name only) - * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) + * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only) * * @return Response */ - protected function execute($m, $params = null, $paramtypes = null) + protected function execute($m, $params = null, $paramTypes = null) { if (is_object($m)) { $methName = $m->method(); @@ -569,9 +569,9 @@ protected function execute($m, $params = null, $paramtypes = null) if (isset($dmap[$methName]['signature'])) { $sig = $dmap[$methName]['signature']; if (is_object($m)) { - list($ok, $errstr) = $this->verifySignature($m, $sig); + list($ok, $errStr) = $this->verifySignature($m, $sig); } else { - list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); + list($ok, $errStr) = $this->verifySignature($paramTypes, $sig); } if (!$ok) { // Didn't match. @@ -690,10 +690,10 @@ protected function debugmsg($string) $this->debug_info .= $string . "\n"; } - protected function xml_header($charset_encoding = '') + protected function xml_header($charsetEncoding = '') { - if ($charset_encoding != '') { - return "\n"; + if ($charsetEncoding != '') { + return "\n"; } else { return "\n"; } @@ -978,33 +978,33 @@ public static function _xmlrpcs_multicall($server, $m) * * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors. */ - public static function _xmlrpcs_errorHandler($errcode, $errstring, $filename = null, $lineno = null, $context = null) + public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = null, $lineNo = null, $context = null) { // obey the @ protocol if (error_reporting() == 0) { return; } - //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING) - if ($errcode != E_STRICT) { - \PhpXmlRpc\Server::error_occurred($errstring); + //if($errCode != E_NOTICE && $errCode != E_WARNING && $errCode != E_USER_NOTICE && $errCode != E_USER_WARNING) + if ($errCode != E_STRICT) { + \PhpXmlRpc\Server::error_occurred($errString); } // Try to avoid as much as possible disruption to the previous error handling // mechanism in place if ($GLOBALS['_xmlrpcs_prev_ehandler'] == '') { // The previous error handler was the default: all we should do is log error // to the default error log (if level high enough) - if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode)) { - error_log($errstring); + if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) { + error_log($errString); } } else { // Pass control on to previous error handler, trying to avoid loops... if ($GLOBALS['_xmlrpcs_prev_ehandler'] != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) { if (is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) { // the following works both with static class methods and plain object methods as error handler - call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context)); + call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errCode, $errString, $filename, $lineNo, $context)); } else { - $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context); + $GLOBALS['_xmlrpcs_prev_ehandler']($errCode, $errString, $filename, $lineno, $context); } } } diff --git a/src/Value.php b/src/Value.php index 1ea6b9e2..1e5f1bf2 100644 --- a/src/Value.php +++ b/src/Value.php @@ -105,12 +105,12 @@ public function __construct($val = -1, $type = '') */ public function addScalar($val, $type = 'string') { - $typeof = null; + $typeOf = null; if (isset(static::$xmlrpcTypes[$type])) { - $typeof = static::$xmlrpcTypes[$type]; + $typeOf = static::$xmlrpcTypes[$type]; } - if ($typeof !== 1) { + if ($typeOf !== 1) { error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)"); return 0; @@ -144,7 +144,7 @@ public function addScalar($val, $type = 'string') default: // a scalar, so set the value and remember we're scalar $this->me[$type] = $val; - $this->mytype = $typeof; + $this->mytype = $typeOf; return 1; } @@ -153,22 +153,22 @@ public function addScalar($val, $type = 'string') /** * Add an array of xmlrpc values objects to an xmlrpc value. * - * @param Value[] $vals + * @param Value[] $values * * @return int 1 or 0 on failure * - * @todo add some checking for $vals to be an array of xmlrpc values? + * @todo add some checking for $values to be an array of xmlrpc values? */ - public function addArray($vals) + public function addArray($values) { if ($this->mytype == 0) { $this->mytype = static::$xmlrpcTypes['array']; - $this->me['array'] = $vals; + $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'], $vals); + $this->me['array'] = array_merge($this->me['array'], $values); return 1; } else { @@ -181,22 +181,22 @@ public function addArray($vals) /** * Add an array of named xmlrpc value objects to an xmlrpc value. * - * @param Value[] $vals + * @param Value[] $values * * @return int 1 or 0 on failure * - * @todo add some checking for $vals to be an array? + * @todo add some checking for $values to be an array? */ - public function addStruct($vals) + public function addStruct($values) { if ($this->mytype == 0) { $this->mytype = static::$xmlrpcTypes['struct']; - $this->me['struct'] = $vals; + $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'], $vals); + $this->me['struct'] = array_merge($this->me['struct'], $values); return 1; } else { @@ -322,11 +322,11 @@ protected function serializedata($typ, $val, $charset_encoding = '') /** * Returns xml representation of the value. XML prologue not included. * - * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed + * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed * * @return string */ - public function serialize($charset_encoding = '') + public function serialize($charsetEncoding = '') { // add check? slower, but helps to avoid recursion in serializing broken xmlrpc values... //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval'))) @@ -334,7 +334,7 @@ public function serialize($charset_encoding = '') reset($this->me); list($typ, $val) = each($this->me); - return '' . $this->serializedata($typ, $val, $charset_encoding) . "\n"; + return '' . $this->serializedata($typ, $val, $charsetEncoding) . "\n"; //} } @@ -342,26 +342,26 @@ public function serialize($charset_encoding = '') * Checks whether a struct member with a given name is present. * Works only on xmlrpc values of type struct. * - * @param string $m the name of the struct member to be looked up + * @param string $key the name of the struct member to be looked up * * @return boolean */ - public function structmemexists($m) + public function structmemexists($key) { - return array_key_exists($m, $this->me['struct']); + 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 $m the name of the struct member to be looked up + * @param string $key the name of the struct member to be looked up * * @return Value */ - public function structmem($m) + public function structmem($key) { - return $this->me['struct'][$m]; + return $this->me['struct'][$key]; } /** @@ -415,13 +415,13 @@ public function scalartyp() /** * Returns the m-th member of an xmlrpc value of struct type. * - * @param integer $m the index of the value to be retrieved (zero based) + * @param integer $key the index of the value to be retrieved (zero based) * * @return Value */ - public function arraymem($m) + public function arraymem($key) { - return $this->me['array'][$m]; + return $this->me['array'][$key]; } /** diff --git a/src/Wrapper.php b/src/Wrapper.php index c5d6c474..be3cdb8e 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -9,7 +9,7 @@ /** * PHP-XMLRPC "wrapper" class. - * Generate stubs to transparently access xmlrpc methods as php functions and viceversa. + * Generate stubs to transparently access xmlrpc methods as php functions and vice-versa. * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies. * * @todo separate introspection from code generation for func-2-method wrapping @@ -26,13 +26,13 @@ class Wrapper * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs * for php arrays always return array, even though arrays sometimes serialize as json structs. * - * @param string $phptype + * @param string $phpType * * @return string */ - public function php_2_xmlrpc_type($phptype) + public function php_2_xmlrpc_type($phpType) { - switch (strtolower($phptype)) { + switch (strtolower($phpType)) { case 'string': return Value::$xmlrpcString; case 'integer': @@ -49,11 +49,11 @@ public function php_2_xmlrpc_type($phptype) return Value::$xmlrpcStruct; case Value::$xmlrpcBase64: case Value::$xmlrpcStruct: - return strtolower($phptype); + return strtolower($phpType); case 'resource': return ''; default: - if (class_exists($phptype)) { + if (class_exists($phpType)) { return Value::$xmlrpcStruct; } else { // unknown: might be any 'extended' xmlrpc type @@ -65,13 +65,13 @@ public function php_2_xmlrpc_type($phptype) /** * Given a string defining a phpxmlrpc type return corresponding php type. * - * @param string $xmlrpctype + * @param string $xmlrpcType * * @return string */ - public function xmlrpc_2_php_type($xmlrpctype) + public function xmlrpc_2_php_type($xmlrpcType) { - switch (strtolower($xmlrpctype)) { + switch (strtolower($xmlrpcType)) { case 'base64': case 'datetime.iso8601': case 'string': @@ -90,7 +90,7 @@ public function xmlrpc_2_php_type($xmlrpctype) case 'null': default: // unknown: might be any xmlrpc type - return strtolower($xmlrpctype); + return strtolower($xmlrpcType); } } @@ -123,9 +123,9 @@ public function xmlrpc_2_php_type($xmlrpctype) * php functions (ie. functions not expecting a single Request 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') and array('class', 'methodname') are ok too - * @param string $newfuncname (optional) name for function to be created - * @param array $extra_options (optional) array of options for conversion. valid values include: + * @param string $funcName the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too + * @param string $newFuncName (optional) name for function to be created + * @param array $extraOptions (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 --- @@ -140,98 +140,97 @@ public function xmlrpc_2_php_type($xmlrpctype) * @todo add some trigger_errors / error_log when returning false? * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value... * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? - * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster + * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance? */ - public function wrap_php_function($funcname, $newfuncname = '', $extra_options = array()) + public function wrap_php_function($funcName, $newFuncName = '', $extraOptions = array()) { - $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true; - $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc'; + $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; - $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'] ? '@' : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; - $exists = false; - if (is_string($funcname) && strpos($funcname, '::') !== false) { - $funcname = explode('::', $funcname); + if (is_string($funcName) && strpos($funcName, '::') !== false) { + $funcName = explode('::', $funcName); } - if (is_array($funcname)) { - if (count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0]))) { + if (is_array($funcName)) { + if (count($funcName) < 2 || (!is_string($funcName[0]) && !is_object($funcName[0]))) { error_log('XML-RPC: syntax for function to be wrapped is wrong'); return false; } - if (is_string($funcname[0])) { - $plainfuncname = implode('::', $funcname); - } elseif (is_object($funcname[0])) { - $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1]; + if (is_string($funcName[0])) { + $plainFuncName = implode('::', $funcName); + } elseif (is_object($funcName[0])) { + $plainFuncName = get_class($funcName[0]) . '->' . $funcName[1]; } - $exists = method_exists($funcname[0], $funcname[1]); + $exists = method_exists($funcName[0], $funcName[1]); } else { - $plainfuncname = $funcname; - $exists = function_exists($funcname); + $plainFuncName = $funcName; + $exists = function_exists($funcName); } if (!$exists) { - error_log('XML-RPC: function to be wrapped is not defined: ' . $plainfuncname); + error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName); return false; } else { // determine name of new php function - if ($newfuncname == '') { - if (is_array($funcname)) { - if (is_string($funcname[0])) { - $xmlrpcfuncname = "{$prefix}_" . implode('_', $funcname); + if ($newFuncName == '') { + if (is_array($funcName)) { + if (is_string($funcName[0])) { + $xmlrpcFuncName = "{$prefix}_" . implode('_', $funcName); } else { - $xmlrpcfuncname = "{$prefix}_" . get_class($funcname[0]) . '_' . $funcname[1]; + $xmlrpcFuncName = "{$prefix}_" . get_class($funcName[0]) . '_' . $funcName[1]; } } else { - $xmlrpcfuncname = "{$prefix}_$funcname"; + $xmlrpcFuncName = "{$prefix}_$funcName"; } } else { - $xmlrpcfuncname = $newfuncname; + $xmlrpcFuncName = $newFuncName; } - while ($buildit && function_exists($xmlrpcfuncname)) { - $xmlrpcfuncname .= 'x'; + while ($buildIt && function_exists($xmlrpcFuncName)) { + $xmlrpcFuncName .= 'x'; } // start to introspect PHP code - if (is_array($funcname)) { - $func = new \ReflectionMethod($funcname[0], $funcname[1]); + if (is_array($funcName)) { + $func = new \ReflectionMethod($funcName[0], $funcName[1]); if ($func->isPrivate()) { - error_log('XML-RPC: method to be wrapped is private: ' . $plainfuncname); + error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); return false; } if ($func->isProtected()) { - error_log('XML-RPC: method to be wrapped is protected: ' . $plainfuncname); + error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); return false; } if ($func->isConstructor()) { - error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainfuncname); + error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); return false; } if ($func->isDestructor()) { - error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainfuncname); + error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); return false; } if ($func->isAbstract()) { - error_log('XML-RPC: method to be wrapped is abstract: ' . $plainfuncname); + error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); return false; } /// @todo add more checks for static vs. nonstatic? } else { - $func = new \ReflectionFunction($funcname); + $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: ' . $plainfuncname); + error_log('XML-RPC: function to be wrapped is internal: ' . $plainFuncName); return false; } @@ -287,20 +286,20 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = // execute introspection of actual function prototype $params = array(); $i = 0; - foreach ($func->getParameters() as $paramobj) { + foreach ($func->getParameters() as $paramObj) { $params[$i] = array(); - $params[$i]['name'] = '$' . $paramobj->getName(); - $params[$i]['isoptional'] = $paramobj->isOptional(); + $params[$i]['name'] = '$' . $paramObj->getName(); + $params[$i]['isoptional'] = $paramObj->isOptional(); $i++; } // start building of PHP code to be eval'd - $innercode = "\$encoder = new {$namespace}Encoder();\n"; + $innerCode = "\$encoder = new {$namespace}Encoder();\n"; $i = 0; - $parsvariations = array(); + $parsVariations = array(); $pars = array(); - $pnum = count($params); + $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! @@ -309,107 +308,107 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = if ($param['isoptional']) { // this particular parameter is optional. save as valid previous list of parameters - $innercode .= "if (\$paramcount > $i) {\n"; - $parsvariations[] = $pars; + $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 = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; + $innerCode .= "\$p$i = \$msg->getParam($i);\n"; + if ($decodePhpObjects) { + $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; } else { - $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; + $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; } $pars[] = "\$p$i"; $i++; if ($param['isoptional']) { - $innercode .= "}\n"; + $innerCode .= "}\n"; } - if ($i == $pnum) { + if ($i == $pNum) { // last allowed parameters combination - $parsvariations[] = $pars; + $parsVariations[] = $pars; } } $sigs = array(); - $psigs = array(); - if (count($parsvariations) == 0) { + $pSigs = array(); + if (count($parsVariations) == 0) { // only known good synopsis = no parameters - $parsvariations[] = array(); - $minpars = 0; + $parsVariations[] = array(); + $minPars = 0; } else { - $minpars = count($parsvariations[0]); + $minPars = count($parsVariations[0]); } - if ($minpars) { + 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 {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innercode; + $innerCode = "\$paramcount = \$msg->getNumParams();\n" . + "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innerCode; } else { - $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode; + $innerCode = "\$paramcount = \$msg->getNumParams();\n" . $innerCode; } - $innercode .= "\$np = false;\n"; + $innerCode .= "\$np = false;\n"; // since there are no closures in php, if we are given an object instance, // we store a pointer to it in a global var... - if (is_array($funcname) && is_object($funcname[0])) { - $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] = &$funcname[0]; - $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n"; - $realfuncname = '$obj->' . $funcname[1]; + if (is_array($funcName) && is_object($funcName[0])) { + $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcFuncName] = &$funcName[0]; + $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcFuncName'];\n"; + $realFuncName = '$obj->' . $funcName[1]; } else { - $realfuncname = $plainfuncname; + $realFuncName = $plainFuncName; } - foreach ($parsvariations as $pars) { - $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n"; + foreach ($parsVariations as $pars) { + $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n"; // build a 'generic' signature (only use an appropriate return type) $sig = array($returns); - $psig = array($returnsDocs); + $pSig = array($returnsDocs); for ($i = 0; $i < count($pars); $i++) { if (isset($paramDocs[$i]['type'])) { $sig[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']); } else { $sig[] = Value::$xmlrpcValue; } - $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : ''; + $pSig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : ''; } $sigs[] = $sig; - $psigs[] = $psig; + $pSigs[] = $pSig; } - $innercode .= "\$np = true;\n"; - $innercode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n"; - //$innercode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; - $innercode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; + $innerCode .= "\$np = true;\n"; + $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n"; + //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; + $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) { - $innercode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));"; + $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));"; } else { - if ($encode_php_objects) { - $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; + if ($encodePhpObjects) { + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; } else { - $innercode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; } } // shall we exclude functions returning by ref? // if($func->returnsReference()) // return false; - $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}"; + $code = "function $xmlrpcFuncName(\$msg) {\n" . $innerCode . "}\n}"; //print_r($code); - if ($buildit) { + if ($buildIt) { $allOK = 0; eval($code . '$allOK=1;'); // alternative - //$xmlrpcfuncname = create_function('$m', $innercode); + //$xmlrpcFuncName = create_function('$m', $innerCode); if (!$allOK) { - error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap php function ' . $plainfuncname); + error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap php function ' . $plainFuncName); return false; } } - /// @todo examine if $paramDocs matches $parsvariations and build array for + /// @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); + $ret = array('function' => $xmlrpcFuncName, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $pSigs, 'source' => $code); return $ret; } @@ -421,7 +420,7 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = * object and called from remote clients (as well as their corresponding signature info). * * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class - * @param array $extra_options see the docs for wrap_php_method for more options + * @param array $extraOptions see the docs for wrap_php_method for more options * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance * * @return array or false on failure @@ -429,10 +428,10 @@ public function wrap_php_function($funcname, $newfuncname = '', $extra_options = * @todo get_class_methods will return both static and non-static methods. * we have to differentiate the action, depending on wheter we recived a class name or object */ - public function wrap_php_class($classname, $extra_options = array()) + public function wrap_php_class($classname, $extraOptions = array()) { - $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; - $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; + $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + $methodtype = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; $result = array(); $mlist = get_class_methods($classname); @@ -444,7 +443,7 @@ public function wrap_php_class($classname, $extra_options = array()) if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))) ) { - $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extra_options); + $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extraOptions); if ($methodwrap) { $result[$methodwrap['function']] = $methodwrap['function']; } @@ -480,8 +479,8 @@ public function wrap_php_class($classname, $extra_options = array()) * for debugging purposes. * * @param 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 options include + * @param string $methodName the xmlrpc method to be mapped to a php function + * @param array $extraOptions array of options that specify conversion details. valid options 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' @@ -494,49 +493,49 @@ public function wrap_php_class($classname, $extra_options = array()) * * @return string the name of the generated php function (or false) - OR AN ARRAY... */ - public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $timeout = 0, $protocol = '', $newfuncname = '') + public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 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 options) - we really love backward compat, don't we? - if (!is_array($extra_options)) { - $signum = $extra_options; - $extra_options = array(); + if (!is_array($extraOptions)) { + $signum = $extraOptions; + $extraOptions = 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'] : ''; + $signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['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; + //$encodePhpObjects = in_array('encode_php_objects', $extraOptions); + //$verbatimClientCopy = in_array('simple_client_copy', $extraOptions) ? 1 : + // in_array('build_class_code', $extraOptions) ? 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; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... - $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'; + $simple_client_copy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; + $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; - if (isset($extra_options['return_on_fault'])) { + if (isset($extraOptions['return_on_fault'])) { $decode_fault = true; - $fault_response = $extra_options['return_on_fault']; + $fault_response = $extraOptions['return_on_fault']; } else { $decode_fault = false; $fault_response = ''; } - $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0; + $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; $msgclass = $namespace . 'Request'; $valclass = $namespace . 'Value'; $decoderClass = $namespace . 'Encoder'; $msg = new $msgclass('system.methodSignature'); - $msg->addparam(new $valclass($methodname)); + $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); + error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName); return false; } else { @@ -546,30 +545,30 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti $msig = $decoder->decode($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); + 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; + 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); + $xmlrpcFuncName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $methodName); } - while ($buildit && function_exists($xmlrpcfuncname)) { - $xmlrpcfuncname .= 'x'; + 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) { + if (!$buildIt) { $msg = new $msgclass('system.methodHelp'); - $msg->addparam(new $valclass($methodname)); + $msg->addparam(new $valclass($methodName)); $response = $client->send($msg, $timeout, $protocol); if (!$response->faultCode()) { $mdesc = $response->value(); @@ -579,25 +578,25 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti } } - $results = $this->build_remote_method_wrapper_code($client, $methodname, - $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy, - $prefix, $decode_php_objects, $encode_php_objects, $decode_fault, + $results = $this->build_remote_method_wrapper_code($client, $methodName, + $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simple_client_copy, + $prefix, $decodePhpObjects, $encodePhpObjects, $decode_fault, $fault_response, $namespace); //print_r($code); - if ($buildit) { + if ($buildIt) { $allOK = 0; eval($results['source'] . '$allOK=1;'); // alternative - //$xmlrpcfuncname = create_function('$m', $innercode); + //$xmlrpcFuncName = create_function('$m', $innerCode); if ($allOK) { - return $xmlrpcfuncname; + return $xmlrpcFuncName; } else { - error_log('XML-RPC: could not create function ' . $xmlrpcfuncname . ' to wrap remote method ' . $methodname); + error_log('XML-RPC: could not create function ' . $xmlrpcFuncName . ' to wrap remote method ' . $methodName); return false; } } else { - $results['function'] = $xmlrpcfuncname; + $results['function'] = $xmlrpcFuncName; return $results; } @@ -611,22 +610,22 @@ public function wrap_xmlrpc_method($client, $methodname, $extra_options = 0, $ti * For more details see wrap_xmlrpc_method. * * @param Client $client the client obj all set to query the desired server - * @param array $extra_options list of options for wrapped code + * @param array $extraOptions 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) */ - public function wrap_xmlrpc_server($client, $extra_options = array()) + public function wrap_xmlrpc_server($client, $extraOptions = 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'; + $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + //$signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $newclassname = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true; + $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; $msgclass = $namespace . 'Request'; @@ -652,24 +651,24 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) } else { // pick a suitable name for the new function, avoiding collisions if ($newclassname != '') { - $xmlrpcclassname = $newclassname; + $xmlrpcClassName = $newclassname; } else { - $xmlrpcclassname = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), array('_', ''), $client->server) . '_client'; } - while ($buildit && class_exists($xmlrpcclassname)) { - $xmlrpcclassname .= 'x'; + 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 = "class $xmlrpcClassName\n{\nvar \$client;\n\n"; $source .= "function __construct()\n{\n"; - $source .= $this->build_client_wrapper_code($client, $verbatim_client_copy, $prefix, $namespace); + $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); $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, + 'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix, + 'decode_php_objs' => $decodePhpObjects, ); /// @todo build javadoc for class definition, too foreach ($mlist as $mname) { @@ -678,7 +677,7 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) array('_', ''), $mname); $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts); if ($methodwrap) { - if (!$buildit) { + if (!$buildIt) { $source .= $methodwrap['docstring']; } $source .= $methodwrap['source'] . "\n"; @@ -688,20 +687,20 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) } } $source .= "}\n"; - if ($buildit) { + if ($buildIt) { $allOK = 0; eval($source . '$allOK=1;'); // alternative - //$xmlrpcfuncname = create_function('$m', $innercode); + //$xmlrpcFuncName = create_function('$m', $innerCode); if ($allOK) { - return $xmlrpcclassname; + return $xmlrpcClassName; } else { - error_log('XML-RPC: could not create class ' . $xmlrpcclassname . ' to wrap remote server ' . $client->server); + 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' => ''); + return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => ''); } } } @@ -714,33 +713,33 @@ public function wrap_xmlrpc_server($client, $extra_options = array()) * valid php code is emitted. * Note: real spaghetti code follows... */ - public function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname, + public 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, + $decodePhpObjects = false, $encodePhpObjects = false, $decode_fault = false, $fault_response = '', $namespace = '\\PhpXmlRpc\\') { - $code = "function $xmlrpcfuncname ("; + $code = "function $xmlrpcFuncName ("; if ($client_copy_mode < 2) { // client copy mode 0 or 1 == partial / full client copy in emitted code - $innercode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix, $namespace); - $innercode .= "\$client->setDebug(\$debug);\n"; + $innerCode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix, $namespace); + $innerCode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { // client copy mode 2 == no client copy in emitted code - $innercode = ''; + $innerCode = ''; $this_ = 'this->'; } - $innercode .= "\$msg = new {$namespace}Request('$methodname');\n"; + $innerCode .= "\$msg = 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"; + $mdesc = "/**\nFunction $xmlrpcFuncName\n"; } // param parsing - $innercode .= "\$encoder = new {$namespace}Encoder();\n"; + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; $plist = array(); $pcount = count($msig); for ($i = 1; $i < $pcount; $i++) { @@ -750,15 +749,15 @@ public function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfu $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"; + $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$ptype');\n"; } else { - if ($encode_php_objects) { - $innercode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n"; + if ($encodePhpObjects) { + $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n"; } else { - $innercode .= "\$p$i = \$encoder->encode(\$p$i);\n"; + $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n"; } } - $innercode .= "\$msg->addparam(\$p$i);\n"; + $innerCode .= "\$msg->addparam(\$p$i);\n"; $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n"; } if ($client_copy_mode < 2) { @@ -768,23 +767,23 @@ public function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfu $plist = implode(', ', $plist); $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; - $innercode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\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) . "')"; + $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $fault_response) . "')"; } else { - $respcode = var_export($fault_response, true); + $respCode = var_export($fault_response, true); } } else { - $respcode = '$res'; + $respCode = '$res'; } - if ($decode_php_objects) { - $innercode .= "if (\$res->faultcode()) return $respcode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));"; + 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());"; + $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());"; } - $code = $code . $plist . ") {\n" . $innercode . "\n}\n"; + $code = $code . $plist . ") {\n" . $innerCode . "\n}\n"; return array('source' => $code, 'docstring' => $mdesc); } @@ -793,15 +792,20 @@ public function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfu * 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. + * @param Client $client + * @param bool $verbatimClientCopy + * @param string $prefix + * @param string $namespace + * @return string */ - protected function build_client_wrapper_code($client, $verbatim_client_copy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) + protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) { $code = "\$client = new {$namespace}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) { + if ($verbatimClientCopy) { foreach ($client as $fld => $val) { if ($fld != 'debug' && $fld != 'return_type') { $val = var_export($val, true); From 779732528b1a39798fbebc2443ea8f2e0b562e3f Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 17:13:43 +0100 Subject: [PATCH 114/228] More CamelCase --- src/Request.php | 12 ++++++------ src/Server.php | 28 ++++++++++++++-------------- src/Value.php | 10 +++++----- src/Wrapper.php | 36 ++++++++++++++++++------------------ 4 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/Request.php b/src/Request.php index 12cbf688..9192b81e 100644 --- a/src/Request.php +++ b/src/Request.php @@ -227,19 +227,19 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType } // try to 'guestimate' the character encoding of the received response - $resp_encoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data); + $respEncoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data); // if response charset encoding is not known / supported, try to use // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { + if (!in_array($respEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { // the following code might be better for mb_string enabled installs, but // makes the lib about 200% slower... - //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) + //if (!is_valid_charset($respEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $resp_encoding); - $resp_encoding = PhpXmlRpc::$xmlrpc_defencoding; + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding); + $respEncoding = PhpXmlRpc::$xmlrpc_defencoding; } - $parser = xml_parser_create($resp_encoding); + $parser = xml_parser_create($respEncoding); 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. diff --git a/src/Server.php b/src/Server.php index ec9ebb44..113ead4f 100644 --- a/src/Server.php +++ b/src/Server.php @@ -342,7 +342,7 @@ protected function verifySignature($in, $sig) * * @return mixed null on success or a Response */ - protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$resp_compression) + protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression) { // check if $_SERVER is populated: it might have been disabled via ini file // (this is true even when in CLI mode) @@ -360,22 +360,22 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ } if (isset($_SERVER['HTTP_CONTENT_ENCODING'])) { - $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); + $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']); } else { - $content_encoding = ''; + $contentEncoding = ''; } // check if request body has been compressed and decompress it - if ($content_encoding != '' && strlen($data)) { - if ($content_encoding == 'deflate' || $content_encoding == 'gzip') { + if ($contentEncoding != '' && strlen($data)) { + if ($contentEncoding == 'deflate' || $contentEncoding == 'gzip') { // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression)) { - if ($content_encoding == 'deflate' && $degzdata = @gzuncompress($data)) { + if (function_exists('gzinflate') && in_array($contentEncoding, $this->accepted_compression)) { + if ($contentEncoding == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; if ($this->debug > 1) { $this->debugmsg("\n+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++"); } - } elseif ($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { + } elseif ($contentEncoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; if ($this->debug > 1) { $this->debugmsg("+++INFLATED REQUEST+++[" . strlen($data) . " chars]+++\n" . $data . "\n+++END+++"); @@ -402,11 +402,11 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ // here we should check if we can match the client-requested encoding // with the encodings we know we can generate. /// @todo we should parse q=0.x preferences instead of getting first charset specified... - $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); + $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET'])); // Give preference to internal encoding - $known_charsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII'); - foreach ($known_charsets as $charset) { - foreach ($client_accepted_charsets as $accepted) { + $knownCharsets = array(PhpXmlRpc::$xmlrpc_internalencoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII'); + foreach ($knownCharsets as $charset) { + foreach ($clientAcceptedCharsets as $accepted) { if (strpos($accepted, $charset) === 0) { $respEncoding = $charset; break; @@ -422,9 +422,9 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ } if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { - $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING']; + $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING']; } else { - $resp_compression = ''; + $respCompression = ''; } // 'guestimate' request encoding diff --git a/src/Value.php b/src/Value.php index 1e5f1bf2..0d963b53 100644 --- a/src/Value.php +++ b/src/Value.php @@ -228,7 +228,7 @@ public function kindOf() } } - protected function serializedata($typ, $val, $charset_encoding = '') + protected function serializedata($typ, $val, $charsetEncoding = '') { $rs = ''; @@ -248,7 +248,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') 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, $charset_encoding) . ""; + $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . ""; break; case static::$xmlrpcInt: case static::$xmlrpcI4: @@ -296,9 +296,9 @@ protected function serializedata($typ, $val, $charset_encoding = '') } $charsetEncoder = Charset::instance(); foreach ($val as $key2 => $val2) { - $rs .= '' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charset_encoding) . "\n"; + $rs .= '' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n"; //$rs.=$this->serializeval($val2); - $rs .= $val2->serialize($charset_encoding); + $rs .= $val2->serialize($charsetEncoding); $rs .= "\n"; } $rs .= ''; @@ -308,7 +308,7 @@ protected function serializedata($typ, $val, $charset_encoding = '') $rs .= "\n\n"; foreach ($val as $element) { //$rs.=$this->serializeval($val[$i]); - $rs .= $element->serialize($charset_encoding); + $rs .= $element->serialize($charsetEncoding); } $rs .= "\n"; break; diff --git a/src/Wrapper.php b/src/Wrapper.php index be3cdb8e..71abda58 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -513,16 +513,16 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... - $simple_client_copy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; + $simpleClientCopy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; if (isset($extraOptions['return_on_fault'])) { - $decode_fault = true; - $fault_response = $extraOptions['return_on_fault']; + $decodeFault = true; + $faultResponse = $extraOptions['return_on_fault']; } else { - $decode_fault = false; - $fault_response = ''; + $decodeFault = false; + $faultResponse = ''; } $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; @@ -579,9 +579,9 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim } $results = $this->build_remote_method_wrapper_code($client, $methodName, - $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simple_client_copy, - $prefix, $decodePhpObjects, $encodePhpObjects, $decode_fault, - $fault_response, $namespace); + $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simpleClientCopy, + $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, + $faultResponse, $namespace); //print_r($code); if ($buildIt) { $allOK = 0; @@ -714,14 +714,14 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) * Note: real spaghetti code follows... */ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, - $msig, $mdesc = '', $timeout = 0, $protocol = '', $client_copy_mode = 0, $prefix = 'xmlrpc', - $decodePhpObjects = false, $encodePhpObjects = false, $decode_fault = false, - $fault_response = '', $namespace = '\\PhpXmlRpc\\') + $msig, $mdesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc', + $decodePhpObjects = false, $encodePhpObjects = false, $decdoeFault = false, + $faultResponse = '', $namespace = '\\PhpXmlRpc\\') { $code = "function $xmlrpcFuncName ("; - if ($client_copy_mode < 2) { + if ($clientCopyMode < 2) { // client copy mode 0 or 1 == partial / full client copy in emitted code - $innerCode = $this->build_client_wrapper_code($client, $client_copy_mode, $prefix, $namespace); + $innerCode = $this->build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace); $innerCode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { @@ -760,7 +760,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $innerCode .= "\$msg->addparam(\$p$i);\n"; $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n"; } - if ($client_copy_mode < 2) { + 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"; } @@ -768,11 +768,11 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response 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) . "')"; + if ($decdoeFault) { + 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($fault_response, true); + $respCode = var_export($faultResponse, true); } } else { $respCode = '$res'; From b081e4541f5728a5f18d15832f0b72e2e133aad2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 17:25:52 +0100 Subject: [PATCH 115/228] One more round of CamelCase --- src/Encoder.php | 2 +- src/Helper/Charset.php | 64 ++++++++++++++++++++-------------------- src/Helper/Http.php | 50 +++++++++++++++---------------- src/Helper/XMLParser.php | 30 +++++++++---------- 4 files changed, 73 insertions(+), 73 deletions(-) diff --git a/src/Encoder.php b/src/Encoder.php index f7238891..636ef359 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -125,7 +125,7 @@ public function decode($xmlrpcVal, $options = array()) * * @author Dan Libby (dan@libby.com) * - * @param mixed $php_val the value to be converted into an xmlrpc value object + * @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 diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index cbf00a90..d7670a13 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -82,27 +82,27 @@ private function __construct() * @todo make usage of iconv() or recode_string() or mb_string() where available * * @param string $data - * @param string $src_encoding - * @param string $dest_encoding + * @param string $srcEncoding + * @param string $destEncoding * * @return string */ - public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') + public function encodeEntities($data, $srcEncoding = '', $destEncoding = '') { - if ($src_encoding == '') { + if ($srcEncoding == '') { // lame, but we know no better... - $src_encoding = PhpXmlRpc::$xmlrpc_internalencoding; + $srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding; } - switch (strtoupper($src_encoding . '_' . $dest_encoding)) { + switch (strtoupper($srcEncoding . '_' . $destEncoding)) { case 'ISO-8859-1_': case 'ISO-8859-1_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escaped_data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData); break; case 'ISO-8859-1_UTF-8': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = utf8_encode($escaped_data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = utf8_encode($escapedData); break; case 'ISO-8859-1_ISO-8859-1': case 'US-ASCII_US-ASCII': @@ -111,13 +111,13 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') case 'US-ASCII_ISO-8859-1': case 'UTF-8_UTF-8': //case 'CP1252_CP1252': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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 - $escaped_data = ''; + $escapedData = ''; // be kind to users creating string xmlrpc values out of different php types $data = (string)$data; $ns = strlen($data); @@ -129,22 +129,22 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') /// @todo shall we replace this with a (supposedly) faster str_replace? switch ($ii) { case 34: - $escaped_data .= '"'; + $escapedData .= '"'; break; case 38: - $escaped_data .= '&'; + $escapedData .= '&'; break; case 39: - $escaped_data .= '''; + $escapedData .= '''; break; case 60: - $escaped_data .= '<'; + $escapedData .= '<'; break; case 62: - $escaped_data .= '>'; + $escapedData .= '>'; break; default: - $escaped_data .= $ch; + $escapedData .= $ch; } // switch } //2 11 110bbbbb 10bbbbbb (2047) elseif ($ii >> 5 == 6) { @@ -153,7 +153,7 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') $b2 = ($ii & 63); $ii = ($b1 * 64) + $b2; $ent = sprintf('&#%d;', $ii); - $escaped_data .= $ent; + $escapedData .= $ent; $nn += 1; } //3 16 1110bbbb 10bbbbbb 10bbbbbb elseif ($ii >> 4 == 14) { @@ -164,7 +164,7 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') $b3 = ($ii & 63); $ii = ((($b1 * 64) + $b2) * 64) + $b3; $ent = sprintf('&#%d;', $ii); - $escaped_data .= $ent; + $escapedData .= $ent; $nn += 2; } //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb elseif ($ii >> 3 == 30) { @@ -177,7 +177,7 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') $b4 = ($ii & 63); $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4; $ent = sprintf('&#%d;', $ii); - $escaped_data .= $ent; + $escapedData .= $ent; $nn += 3; } } @@ -185,28 +185,28 @@ public function encodeEntities($data, $src_encoding = '', $dest_encoding = '') /* case 'CP1252_': case 'CP1252_US-ASCII': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); - $escaped_data = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escaped_data); - $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them) - $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); - $escaped_data = utf8_encode($escaped_data); + $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData); + $escapedData = utf8_encode($escapedData); break; case 'CP1252_ISO-8859-1': - $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); + $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $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... - $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data); + $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData); break; */ default: - $escaped_data = ''; - error_log("Converting from $src_encoding to $dest_encoding: not supported..."); + $escapedData = ''; + error_log("Converting from $srcEncoding to $destEncoding: not supported..."); } - return $escaped_data; + return $escapedData; } /** diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 09be1f3a..141cfe40 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -23,16 +23,16 @@ public static function decodeChunked($buffer) // 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); - $chunk_size = hexdec(trim($temp)); - $chunkstart = $chunkend; - while ($chunk_size > 0) { - $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size); + $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); + if ($chunkEnd == false) { + $chunk = substr($buffer, $chunkStart); // append chunk-data to entity-body $new .= $chunk; $length += strlen($chunk); @@ -40,21 +40,21 @@ public static function decodeChunked($buffer) } // read chunk-data and crlf - $chunk = substr($buffer, $chunkstart, $chunkend - $chunkstart); + $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; + $chunkStart = $chunkEnd + 2; - $chunkend = strpos($buffer, "\r\n", $chunkstart) + 2; - if ($chunkend == false) { + $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); - $chunk_size = hexdec(trim($temp)); - $chunkstart = $chunkend; + $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart); + $chunkSize = hexdec(trim($temp)); + $chunkStart = $chunkEnd; } return $new; @@ -138,13 +138,13 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 // take care of multi-line headers and cookies $arr = explode(':', $line, 2); if (count($arr) > 1) { - $header_name = strtolower(trim($arr[0])); + $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'][$header_name] + /// We should add content to $xmlrpc->_xh['headers'][$headerName] /// instead of replacing it for those... - if ($header_name == 'set-cookie' || $header_name == 'set-cookie2') { - if ($header_name == 'set-cookie2') { + 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]); @@ -154,10 +154,10 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 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'][$header_name])) { - $httpResponse['headers'][$header_name] .= ', ' . trim($cookie); + if (isset($httpResponse['headers'][$headerName])) { + $httpResponse['headers'][$headerName] .= ', ' . trim($cookie); } else { - $httpResponse['headers'][$header_name] = trim($cookie); + $httpResponse['headers'][$headerName] = trim($cookie); } // parse cookie attributes, in case user wants to correctly honour them // feature creep: only allow rfc-compliant cookie attributes? @@ -180,11 +180,11 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 } } } else { - $httpResponse['headers'][$header_name] = trim($arr[1]); + $httpResponse['headers'][$headerName] = trim($arr[1]); } - } elseif (isset($header_name)) { + } elseif (isset($headerName)) { /// @todo version1 cookies might span multiple lines, thus breaking the parsing above - $httpResponse['headers'][$header_name] .= ' ' . trim($line); + $httpResponse['headers'][$headerName] .= ' ' . trim($line); } } diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index b26cc189..91b686a7 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -61,7 +61,7 @@ class XMLParser /** * xml parser handler function for opening element tags. */ - public function xmlrpc_se($parser, $name, $attrs, $accept_single_vals = false) + public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false) { // if invalid xmlrpc already detected, skip all processing if ($this->_xh['isf'] < 2) { @@ -71,7 +71,7 @@ public function xmlrpc_se($parser, $name, $attrs, $accept_single_vals = false) /// there is only a single top level element in xml anyway if (count($this->_xh['stack']) == 0) { if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && ( - $name != 'VALUE' && !$accept_single_vals) + $name != 'VALUE' && !$acceptSingleVals) ) { $this->_xh['isf'] = 2; $this->_xh['isf_reason'] = 'missing top level xmlrpc element'; @@ -126,15 +126,15 @@ public function xmlrpc_se($parser, $name, $attrs, $accept_single_vals = false) return; } // create an empty array to hold child values, and push it onto appropriate stack - $cur_val = array(); - $cur_val['values'] = array(); - $cur_val['type'] = $name; + $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'])) { - $cur_val['php_class'] = $attrs['PHP_CLASS']; + $curVal['php_class'] = $attrs['PHP_CLASS']; } - $this->_xh['valuestack'][] = $cur_val; + $this->_xh['valuestack'][] = $curVal; $this->_xh['vt'] = 'data'; // be prepared for a data element next break; case 'DATA': @@ -209,14 +209,14 @@ public function xmlrpc_se_any($parser, $name, $attrs) /** * xml parser handler function for close element tags. */ - public function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) + 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 == $curr_elem. + // we do not have to check for $name == $currElem. // we also checked for proper nesting at start of elements... - $curr_elem = array_pop($this->_xh['stack']); + $currElem = array_pop($this->_xh['stack']); switch ($name) { case 'VALUE': @@ -226,7 +226,7 @@ public function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) $this->_xh['vt'] = Value::$xmlrpcString; } - if ($rebuild_xmlrpcvals) { + 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 @@ -342,11 +342,11 @@ public function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true) case 'STRUCT': case 'ARRAY': // fetch out of stack array of values, and promote it to current value - $curr_val = array_pop($this->_xh['valuestack']); - $this->_xh['value'] = $curr_val['values']; + $currVal = array_pop($this->_xh['valuestack']); + $this->_xh['value'] = $currVal['values']; $this->_xh['vt'] = strtolower($name); - if (isset($curr_val['php_class'])) { - $this->_xh['php_class'] = $curr_val['php_class']; + if (isset($currVal['php_class'])) { + $this->_xh['php_class'] = $currVal['php_class']; } break; case 'PARAM': From 9277512c28da1762073b77787f4ed282a575d057 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 29 Mar 2015 17:41:10 +0100 Subject: [PATCH 116/228] Add one more test of the debugger --- tests/6DebuggerTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/6DebuggerTest.php b/tests/6DebuggerTest.php index 6291fefb..f0021808 100644 --- a/tests/6DebuggerTest.php +++ b/tests/6DebuggerTest.php @@ -83,6 +83,11 @@ protected function request($file, $method = 'GET', $payload = '') return $page; } + public function testIndex() + { + $page = $this->request('index.php'); + } + public function testController() { $page = $this->request('controller.php'); From 428236a8cdb916da4a33cf57ef90739b70af994e Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 3 Apr 2015 00:48:56 +0100 Subject: [PATCH 117/228] Fix autoloader to work with helper classes on linux --- src/Autoloader.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Autoloader.php b/src/Autoloader.php index b03b1cb3..77ba30f6 100644 --- a/src/Autoloader.php +++ b/src/Autoloader.php @@ -29,7 +29,7 @@ public static function autoload($class) return; } - if (is_file($file = __DIR__ . str_replace('PhpXmlRpc\\', '/', $class).'.php')) { + if (is_file($file = __DIR__ . str_replace(array('PhpXmlRpc\\', '\\'), '/', $class).'.php')) { require $file; } } From 87bfdaa02fe2f9bc52980682812786074a40ecc5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 3 Apr 2015 01:06:53 +0100 Subject: [PATCH 118/228] Try fixing test case for hhvm --- tests/5DemofilesTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index 8f790d3b..4e790533 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -146,13 +146,13 @@ public function testDiscussServer() { $page = $this->request('server/discuss.php'); $this->assertContains('faultCode', $page); - $this->assertContains('105', $page); + $this->assertRegexp('#10(5|3)#', $page); } public function testProxyServer() { $page = $this->request('server/proxy.php'); $this->assertContains('faultCode', $page); - $this->assertContains('105', $page); + $this->assertRegexp('#10(5|3)#', $page); } } From 5be54109b83d6a77f3a2804e7520db9662c53002 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 6 Apr 2015 21:12:18 +0100 Subject: [PATCH 119/228] Increase backwards compatibility with version 3: make ALL global vars available which were there before --- lib/xmlrpc.inc | 19 ++++++++++++++++++- src/Helper/Charset.php | 21 +++++++++++++++++++++ src/Helper/XMLParser.php | 1 + src/PhpXmlRpc.php | 15 +++++++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 9a9a589f..15722798 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -36,7 +36,7 @@ /****************************************************************************** * - *** DEPRECATED *** + * *** DEPRECATED *** * * This file is only used to insure backwards compatibility * with the API of the library <= rev. 3 @@ -55,9 +55,26 @@ include_once(__DIR__.'/../src/Helper/Charset.php'); include_once(__DIR__.'/../src/Helper/Http.php'); include_once(__DIR__.'/../src/Helper/XMLParser.php'); + /* Expose the global variables which used to be defined */ 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 diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index d7670a13..5225c593 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -237,4 +237,25 @@ public function isValidCharset($encoding, $validList) 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); + } + } } diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index 91b686a7..e11d233d 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -439,4 +439,5 @@ public function xmlrpc_dh($parser, $data) return true; } + } diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index dff38967..7de98c07 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -95,10 +95,25 @@ public static function exportGlobals() $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'); } /** From 420d30fce6c2dafe7eac8bc7ff13dd17da908652 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 7 Apr 2015 00:20:13 +0100 Subject: [PATCH 120/228] Move very old release announcements to the NEWS file --- NEWS | 186 ++++++++++++++++++++++++++++++++++++++++---- doc/announce1_0.txt | 29 ------- doc/announce1_1.txt | 34 -------- doc/announce1b6.txt | 23 ------ doc/announce1b7.txt | 29 ------- doc/announce1b8.txt | 33 -------- doc/announce1b9.txt | 28 ------- 7 files changed, 173 insertions(+), 189 deletions(-) delete mode 100644 doc/announce1_0.txt delete mode 100644 doc/announce1_1.txt delete mode 100644 doc/announce1b6.txt delete mode 100644 doc/announce1b7.txt delete mode 100644 doc/announce1b8.txt delete mode 100644 doc/announce1b9.txt diff --git a/NEWS b/NEWS index fc174fb8..61e0fc0b 100644 --- a/NEWS +++ b/NEWS @@ -1,39 +1,42 @@ -XML-RPC for PHP version 4.0.0 - 201X/Y/Z +XML-RPC for PHP version 4.0.0 - 2015/Y/Z 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. -PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. +The minimum required php version has been increased to 5.3, even though we strongly urge you to use +more recent versions. -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. All php classes have been renamed and moved to separate files. Class autoloading can now be done in accord with the PSR-4 standard. 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 * improved: all php code is now formatted according to the PSR-2 standard -* improved: this release 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: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds +* improved: debug messages are not html-escaped any more when executing from the command line + +* 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 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: debug messages are not html-escaped any more when executing from the command line - -* improved: a specific option allow 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 Travis) +* improved: the testsuite has basic checks for the debugger and demo files XML-RPC for PHP version 3.0.0 - 2014/6/15 @@ -382,3 +385,160 @@ 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 +. + + +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 + and 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 . + + +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 . + + +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 . + + +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 . diff --git a/doc/announce1_0.txt b/doc/announce1_0.txt deleted file mode 100644 index a45b1821..00000000 --- a/doc/announce1_0.txt +++ /dev/null @@ -1,29 +0,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 -. diff --git a/doc/announce1_1.txt b/doc/announce1_1.txt deleted file mode 100644 index db0a9fde..00000000 --- a/doc/announce1_1.txt +++ /dev/null @@ -1,34 +0,0 @@ -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 relase. 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 runnning PHP5). - -Notheworthy 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 malfprmed 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/ diff --git a/doc/announce1b6.txt b/doc/announce1b6.txt deleted file mode 100644 index 30c1d10e..00000000 --- a/doc/announce1b6.txt +++ /dev/null @@ -1,23 +0,0 @@ - -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 . diff --git a/doc/announce1b7.txt b/doc/announce1b7.txt deleted file mode 100644 index aceea29f..00000000 --- a/doc/announce1b7.txt +++ /dev/null @@ -1,29 +0,0 @@ - -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 . diff --git a/doc/announce1b8.txt b/doc/announce1b8.txt deleted file mode 100644 index d4db3812..00000000 --- a/doc/announce1b8.txt +++ /dev/null @@ -1,33 +0,0 @@ - -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 . diff --git a/doc/announce1b9.txt b/doc/announce1b9.txt deleted file mode 100644 index ad43a4ed..00000000 --- a/doc/announce1b9.txt +++ /dev/null @@ -1,28 +0,0 @@ - -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 - and 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 . From 8ef5517baf3fd7da0dd84bb3f0f7525d93567103 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 7 Apr 2015 00:42:55 +0100 Subject: [PATCH 121/228] Move more docs to markdown format --- INSTALL => INSTALL.md | 9 ++++++--- README.md | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) rename INSTALL => INSTALL.md (92%) diff --git a/INSTALL b/INSTALL.md similarity index 92% rename from INSTALL rename to INSTALL.md index b016c13b..19d96abc 100644 --- a/INSTALL +++ b/INSTALL.md @@ -4,8 +4,10 @@ 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 + +* 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, @@ -57,7 +59,8 @@ Installation of the library is quite easy: 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) + 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. diff --git a/README.md b/README.md index 81c27b13..f611c959 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ A php library for building xml-rpc clients and servers. Installation ------------ -Installation instructions are in the INSTALL file. +Installation instructions are in the [INSTALL.md](INSTALL.md) file. Docs ---- From 17fed094dda896d83c2ab45eea5f03ca5c5491aa Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 7 Apr 2015 12:03:03 +0100 Subject: [PATCH 122/228] Add a new test for verify_compat.php, refactor some test classes --- tests/5DemofilesTest.php | 74 +---------------------------------- tests/6DebuggerTest.php | 74 +---------------------------------- tests/7ExtraTest.php | 21 ++++++++++ tests/LocalFileTestCase.php | 77 +++++++++++++++++++++++++++++++++++++ tests/parse_args.php | 2 +- 5 files changed, 103 insertions(+), 145 deletions(-) create mode 100644 tests/7ExtraTest.php create mode 100644 tests/LocalFileTestCase.php diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index 4e790533..63708fee 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -1,46 +1,9 @@ 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(); @@ -50,39 +13,6 @@ public function setUp() $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); } - protected function request($file, $method = 'GET', $payload = '') - { - $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); - $this->assertNotContains('Fatal error', $page); - $this->assertNotContains('Notice:', $page); - - return $page; - } - public function testAgeSort() { $page = $this->request('client/agesort.php'); diff --git a/tests/6DebuggerTest.php b/tests/6DebuggerTest.php index f0021808..db0e850c 100644 --- a/tests/6DebuggerTest.php +++ b/tests/6DebuggerTest.php @@ -1,46 +1,9 @@ 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(); @@ -50,39 +13,6 @@ public function setUp() $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] ); } - protected function request($file, $method = 'GET', $payload = '') - { - $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); - $this->assertNotContains('Fatal error', $page); - $this->assertNotContains('Notice:', $page); - - return $page; - } - public function testIndex() { $page = $this->request('index.php'); diff --git a/tests/7ExtraTest.php b/tests/7ExtraTest.php new file mode 100644 index 00000000..ff2d056d --- /dev/null +++ b/tests/7ExtraTest.php @@ -0,0 +1,21 @@ +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'); + } +} \ No newline at end of file diff --git a/tests/LocalFileTestCase.php b/tests/LocalFileTestCase.php new file mode 100644 index 00000000..688e0df5 --- /dev/null +++ b/tests/LocalFileTestCase.php @@ -0,0 +1,77 @@ +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 = '') + { + $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); + $this->assertNotContains('Fatal error', $page); + $this->assertNotContains('Notice:', $page); + + return $page; + } + +} diff --git a/tests/parse_args.php b/tests/parse_args.php index b2e438ea..6660b9e8 100644 --- a/tests/parse_args.php +++ b/tests/parse_args.php @@ -1,7 +1,7 @@ Date: Tue, 7 Apr 2015 12:06:09 +0100 Subject: [PATCH 123/228] Improve indentation of readme file for readability when viewed non-transformed --- INSTALL.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 19d96abc..8d77e7c9 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -19,19 +19,19 @@ Installation instructions Installation of the library is quite easy: -1. Via Composer (highly recommended): +1. Via Composer (highly recommended): - 1. Install composer if you don't have it already present on your system. + 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. + 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. + 3. Open a terminal and use Composer to grab the library. $ composer require phpxmlrpc/phpxmlrpc:4.0 - 4. Write your code. + 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: @@ -48,21 +48,21 @@ Installation of the library is quite easy: $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, + 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 +2. Via manual download and autoload configuration - 1. copy the contents of the src/ folder to any location required by your + 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 + 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. + 3. Write your code. // File example: script.php @@ -75,7 +75,7 @@ Installation of the library is quite easy: $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, + 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. From e6515c749fc5b792992926ce243caec277465b29 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 7 Apr 2015 12:06:48 +0100 Subject: [PATCH 124/228] Whitespace and comments fixes --- src/PhpXmlRpc.php | 2 +- src/Value.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 7de98c07..5705b2fd 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -97,7 +97,7 @@ public static function exportGlobals() // 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; diff --git a/src/Value.php b/src/Value.php index 0d963b53..f544fa58 100644 --- a/src/Value.php +++ b/src/Value.php @@ -31,7 +31,7 @@ class Value "null" => 1, ); - /// @todo: does these need to be public? + /// @todo: do these need to be public? public $me = array(); public $mytype = 0; public $_php_class = null; From da824472c0045c183f40792b8c760c11d024005d Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 10 Apr 2015 12:05:42 +0100 Subject: [PATCH 125/228] Fix: debugger has problems with latin-1 characters in payload --- NEWS | 2 ++ debugger/action.php | 8 +++----- debugger/common.php | 4 ++++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/NEWS b/NEWS index 61e0fc0b..ee0d49a8 100644 --- a/NEWS +++ b/NEWS @@ -38,6 +38,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: the testsuite has basic checks for the debugger and demo files +* fixed: the debugger would fail sending a request with ISO-8859-1 payload + XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/debugger/action.php b/debugger/action.php index 69f66e0c..0345798e 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -226,7 +226,7 @@ } } } else { - $msg[0]->payload = $msg[0]->xml_header() . + $msg[0]->payload = $msg[0]->xml_header($inputcharset) . '' . $method . "\n" . $payload . "\n" . $msg[0]->xml_footer(); @@ -248,8 +248,7 @@ echo '

    Debug info:

    '; } /// @todo use ob_start instead $resp = array(); - $mtime = explode(' ', microtime()); - $time = (float)$mtime[0] + (float)$mtime[1]; + $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); @@ -258,8 +257,7 @@ break; } } - $mtime = explode(' ', microtime()); - $time = (float)$mtime[0] + (float)$mtime[1] - $time; + $time = microtime(true) - $time; if ($debug) { echo "
    \n"; } diff --git a/debugger/common.php b/debugger/common.php index e8ad64cc..ecd09cf2 100644 --- a/debugger/common.php +++ b/debugger/common.php @@ -24,8 +24,12 @@ function stripslashes_deep($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; + /// @todo detect encoding, eg from from http headers? + // mb_detect_encoding(urldecode($_SERVER['...']), $preferredEncodings); } // recover input parameters From 7ef47445e3dc236ef5fea0d3ea5bd0492a83d2a2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 11 Apr 2015 23:44:39 +0100 Subject: [PATCH 126/228] Fix server and client: support LATIN-1 requests/responses where the charset declaration is in the xml prologue instead of http headers; reintroduce guess_encoding --- composer.json | 6 +- lib/xmlrpc.inc | 1 + src/Encoder.php | 107 ++++++++---------------------------- src/Helper/XMLParser.php | 115 +++++++++++++++++++++++++++++++++++++++ src/Request.php | 31 +++++++---- src/Server.php | 43 +++++++-------- 6 files changed, 182 insertions(+), 121 deletions(-) diff --git a/composer.json b/composer.json index 51130cb2..62d1129b 100644 --- a/composer.json +++ b/composer.json @@ -12,11 +12,13 @@ "phpunit/phpunit": ">=4.0.0", "phpunit/phpunit-selenium": "*", "codeclimate/php-test-reporter": "dev-master", - "ext-curl": "*" + "ext-curl": "*", + "ext-mbstring": "*" }, "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-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/"} diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 15722798..9106bd67 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -201,6 +201,7 @@ function php_xmlrpc_decode_xml($xmlVal, $options=array()) function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null) { + return PhpXmlRpc\Helper\XMLParser::guessEncoding($httpHeader, $xmlChunk, $encodingPrefs); } function is_valid_charset($encoding, $validList) diff --git a/src/Encoder.php b/src/Encoder.php index 636ef359..2955f44e 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -232,8 +232,29 @@ public function encode($phpVal, $options = array()) */ public function decode_xml($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); + } + } + } + } - /// @todo 'guestimate' encoding $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? @@ -293,88 +314,4 @@ public function decode_xml($xmlVal, $options = array()) } } - /** - * 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 unconforming (legacy?) clients/servers, - * which will be most probably using UTF-8 anyway... - * - * @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) - * @return string - * - * @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 guess_encoding($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 cointrol 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 - // NB: we favour finding an encoding that is compatible with what we can process - if (extension_loaded('mbstring')) { - 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; - } - } } diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index e11d233d..58acdafb 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -440,4 +440,119 @@ public function xmlrpc_dh($parser, $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... + * + * @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) + * @return string + * + * @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 cointrol 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 + // NB: we favour finding an encoding that is compatible with what we can process + if (extension_loaded('mbstring')) { + 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; + } } diff --git a/src/Request.php b/src/Request.php index 9192b81e..e6816a30 100644 --- a/src/Request.php +++ b/src/Request.php @@ -227,19 +227,30 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType } // try to 'guestimate' the character encoding of the received response - $respEncoding = Encoder::guess_encoding(@$this->httpResponse['headers']['content-type'], $data); + $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data); - // if response charset encoding is not known / supported, try to use - // the default encoding and parse the xml anyway, but log a warning... - if (!in_array($respEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { - // 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', 'ISO-8859-1', 'US-ASCII'))) + if ($respEncoding != '') { - error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding); - $respEncoding = PhpXmlRpc::$xmlrpc_defencoding; + // 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($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. diff --git a/src/Server.php b/src/Server.php index 113ead4f..40afa9bd 100644 --- a/src/Server.php +++ b/src/Server.php @@ -429,7 +429,7 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ // 'guestimate' request encoding /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check??? - $reqEncoding = Encoder::guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', + $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '', $data); return; @@ -446,34 +446,29 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ */ public function parseRequest($data, $reqEncoding = '') { - // 2005/05/07 commented and moved into caller function code - //if($data=='') - //{ - // $data=$GLOBALS['HTTP_RAW_POST_DATA']; - //} - - // G. Giunta 2005/02/13: we do NOT expect to receive html entities - // so we do not try to convert them into xml character entities - //$data = xmlrpc_html_entity_xlate($data); - // decompose incoming XML into request structure - if ($reqEncoding != '') { - if (!in_array($reqEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) { - // the following code might be better for mb_string enabled installs, but - // makes the lib about 200% slower... - //if (!is_valid_charset($reqEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) - error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding); - $reqEncoding = PhpXmlRpc::$xmlrpc_defencoding; + if ($reqEncoding != '') { + // 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($reqEncoding, array('UTF-8'))) + if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) { + if ($reqEncoding == 'ISO-8859-1') { + $data = utf8_encode($data); + } + else { + if (extension_loaded('mbstring')) { + $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding); + } else { + error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received request: ' . $reqEncoding); + } + } } - /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue, - // the encoding is not UTF8 and there are non-ascii chars in the text... - /// @todo use an empty string for php 5 ??? - $parser = xml_parser_create($reqEncoding); - } else { - $parser = xml_parser_create(); } + $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 From 98ff9c3b600d0a98a8febe836acdfe4f67e91f53 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 00:09:16 +0100 Subject: [PATCH 127/228] Add test for latest fixes and update NEWS --- NEWS | 8 +++++++- tests/1ParsingBugsTest.php | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index ee0d49a8..d54c51f9 100644 --- a/NEWS +++ b/NEWS @@ -38,7 +38,13 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: the testsuite has basic checks for the debugger and demo files -* fixed: the debugger would fail sending a request with ISO-8859-1 payload +* fixed: the debugger would fail sending a request with ISO-8859-1 payload (it missed the character set declaration) + +* fixed: the server would fail to decode a request with ISO-8859-1 payload and character set declaration in the xml prologue only + +* fixed: the client would fail to decode a response with ISO-8859-1 payload and character set declaration in the xml prologue only + +* fixed: the function decode_xml() would not decode an xml with character set declaration in the xml prologue XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 949130f2..33915cab 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -421,6 +421,7 @@ public function testUTF8Response() $v = $r->value(); $v = $v['content']; $this->assertEquals("������", $v); + $f = 'userid311127 dateCreated20011126T09:17:52content' . utf8_encode('������') . 'postid7414222 '; @@ -428,6 +429,36 @@ public function testUTF8Response() $v = $r->value(); $v = $v['content']; $this->assertEquals("������", $v); + + $r = php_xmlrpc_decode_xml($f); + $v = $r->value(); + $v = $v->structmem('content')->scalarval(); + $this->assertEquals("������", $v); + } + + public function testLatin1Response() + { + $s = new xmlrpcmsg('dummy'); + $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=ISO-8859-1\r\n\r\n" . 'userid311127 +dateCreated20011126T09:17:52content' . '������' . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals("������", $v); + + $f = 'userid311127 +dateCreated20011126T09:17:52content' . '������' . 'postid7414222 +'; + $r = $s->parseResponse($f, false, 'phpvals'); + $v = $r->value(); + $v = $v['content']; + $this->assertEquals("������", $v); + + $r = php_xmlrpc_decode_xml($f); + $v = $r->value(); + $v = $v->structmem('content')->scalarval(); + $this->assertEquals("������", $v); } public function testUTF8IntString() From 6c135b8b143dd39dce4c9e4fdedb51b7a19ea5b2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 00:27:44 +0100 Subject: [PATCH 128/228] One more test dealing with latin-1 --- tests/3LocalhostTest.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 0dce5682..0e34bc8b 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -150,6 +150,19 @@ public function testString() } } + public function testLatin1String() + { + $sendstring = + "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->"; + $f = 'examples.stringecho'. + $sendstring. + ''; + $v = $this->send($f); + if ($v) { + $this->assertEquals($sendstring, $v->scalarval()); + } + } + public function testAddingDoubles() { // note that rounding errors mean we From 58ef35a678d6b26c919245ff83e33e37135bae12 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 00:28:33 +0100 Subject: [PATCH 129/228] Whitespace and comments --- src/Client.php | 2 +- src/Helper/Charset.php | 1 + src/PhpXmlRpc.php | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Client.php b/src/Client.php index a13c31bb..00195af3 100644 --- a/src/Client.php +++ b/src/Client.php @@ -360,7 +360,7 @@ public function send($req, $timeout = 0, $method = '') $req = $n; } - // where msg is a Request + // where req is a Request $req->debug = $this->debug; if ($method == 'https') { diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index 5225c593..b9340414 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -258,4 +258,5 @@ public function getEntities($charset) throw new \Exception('Unsupported charset: ' . $charset); } } + } diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 5705b2fd..deb697a4 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -66,7 +66,7 @@ class PhpXmlRpc // 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 - public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or atleast configurable? + public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or at least configurable? public static $xmlrpcName = "XML-RPC for PHP"; public static $xmlrpcVersion = "4.0.0.beta"; From cea2f82f38206b5aac20b189e0037e4e71fcb347 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 00:49:34 +0100 Subject: [PATCH 130/228] PRS-2 formatting: else and braces --- src/Client.php | 3 +-- src/Encoder.php | 3 +-- src/Helper/Http.php | 3 +-- src/Request.php | 6 ++---- src/Server.php | 3 +-- tests/3LocalhostTest.php | 3 +-- 6 files changed, 7 insertions(+), 14 deletions(-) diff --git a/src/Client.php b/src/Client.php index 00195af3..7473afed 100644 --- a/src/Client.php +++ b/src/Client.php @@ -1081,8 +1081,7 @@ protected function debugMessage($message) { if (PHP_SAPI != 'cli') { print "
    \n".htmlentities($message)."\n
    "; - } - else { + } else { print "\n$message\n"; } // let the client see this now in case http times out... diff --git a/src/Encoder.php b/src/Encoder.php index 2955f44e..e19dada2 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -244,8 +244,7 @@ public function decode_xml($xmlVal, $options = array()) if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) { if ($valEncoding == 'ISO-8859-1') { $xmlVal = utf8_encode($xmlVal); - } - else { + } else { if (extension_loaded('mbstring')) { $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding); } else { diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 141cfe40..2fc7b80a 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -253,8 +253,7 @@ protected function debugMessage($message) { if (PHP_SAPI != 'cli') { print "
    \n".htmlentities($message)."\n
    "; - } - else { + } else { print "\n$message\n"; } } diff --git a/src/Request.php b/src/Request.php index e6816a30..66e723f7 100644 --- a/src/Request.php +++ b/src/Request.php @@ -239,8 +239,7 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) { if ($respEncoding == 'ISO-8859-1') { $data = utf8_encode($data); - } - else { + } else { if (extension_loaded('mbstring')) { $data = mb_convert_encoding($data, 'UTF-8', $respEncoding); } else { @@ -370,8 +369,7 @@ protected function debugMessage($message, $encodeEntities = true) print "
    \n".htmlentities($message)."\n
    "; else print "
    \n".htmlspecialchars($message)."\n
    "; - } - else { + } else { print "\n$message\n"; } } diff --git a/src/Server.php b/src/Server.php index 40afa9bd..8a378c3f 100644 --- a/src/Server.php +++ b/src/Server.php @@ -457,8 +457,7 @@ public function parseRequest($data, $reqEncoding = '') if (!in_array($reqEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) { if ($reqEncoding == 'ISO-8859-1') { $data = utf8_encode($data); - } - else { + } else { if (extension_loaded('mbstring')) { $data = mb_convert_encoding($data, 'UTF-8', $reqEncoding); } else { diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 0e34bc8b..99bb4908 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -107,8 +107,7 @@ protected function send($msg, $errrorcode = 0, $return_response = false) } if (is_array($errrorcode)) { $this->assertContains($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); - } - else { + } else { $this->assertEquals($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); } if (!$r->faultCode()) { From 81ff420c14ca2c24b7e204b1c8ec1405739b88da Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 12:27:00 +0100 Subject: [PATCH 131/228] Always display debug messages even when there's badly encoded chars in them --- NEWS | 3 +++ src/Client.php | 28 +++++----------------- src/Helper/Http.php | 21 ++++------------ src/Helper/Logger.php | 38 +++++++++++++++++++++++++++++ src/PhpXmlRpc.php | 3 ++- src/Request.php | 56 +++++++++++++++---------------------------- 6 files changed, 72 insertions(+), 77 deletions(-) create mode 100644 src/Helper/Logger.php diff --git a/NEWS b/NEWS index d54c51f9..9f0bd696 100644 --- a/NEWS +++ b/NEWS @@ -46,6 +46,9 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * fixed: the function decode_xml() would not decode an xml with character set declaration in the xml prologue +* improved: echo all debug messages even when there are characters in them which php deems in a wrong encoding + (this is visible e.g. in the debugger) + XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/src/Client.php b/src/Client.php index 7473afed..d71ef274 100644 --- a/src/Client.php +++ b/src/Client.php @@ -2,6 +2,8 @@ namespace PhpXmlRpc; +use PhpXmlRpc\Helper\Logger; + class Client { /// @todo: do these need to be public? @@ -551,7 +553,7 @@ protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $payload; if ($this->debug > 1) { - $this->debugMessage("---SENDING---\n$op\n---END---"); + Logger::debugMessage("---SENDING---\n$op\n---END---"); } if ($timeout > 0) { @@ -707,9 +709,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username } if ($this->debug > 1) { - $this->debugMessage("---SENDING---\n$payload\n---END---"); - // let the client see this now in case http times out... - flush(); + Logger::debugMessage("---SENDING---\n$payload\n---END---"); } if (!$keepAlive || !$this->xmlrpc_curl_handle) { @@ -848,7 +848,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username $message .= $name . ': ' . $val . "\n"; } $message .= "---END---"; - $this->debugMessage($message); + Logger::debugMessage($message); } if (!$result) { @@ -987,7 +987,7 @@ private function _try_multicall($reqs, $timeout, $method) if ($this->return_type == 'xml') { return $rets; } elseif ($this->return_type == 'phpvals') { - ///@todo test this code branch... + /// @todo test this code branch... $rets = $result->value(); if (!is_array($rets)) { return false; // bad return type from system.multicall @@ -1071,20 +1071,4 @@ private function _try_multicall($reqs, $timeout, $method) return $response; } } - - /** - * Echoes a debug message, taking care of escaping it when not in console mode - * - * @param string $message - */ - protected function debugMessage($message) - { - if (PHP_SAPI != 'cli') { - print "
    \n".htmlentities($message)."\n
    "; - } else { - print "\n$message\n"; - } - // let the client see this now in case http times out... - flush(); - } } diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 2fc7b80a..0fa3f51b 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -3,6 +3,7 @@ namespace PhpXmlRpc\Helper; use PhpXmlRpc\PhpXmlRpc; +use PhpXmlRpc\Helper\Logger; class Http { @@ -198,7 +199,7 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 foreach ($httpResponse['cookies'] as $header => $value) { $msg .= "COOKIE: $header={$value['value']}\n"; } - $this->debugMessage($msg); + Logger::debugMessage($msg); } // if CURL was used for the call, http headers have been processed, @@ -222,12 +223,12 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; if ($debug) { - $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + Logger::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) { - $this->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + Logger::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'); @@ -243,18 +244,4 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 return $httpResponse; } - - /** - * Echoes a debug message, taking care of escaping it when not in console mode - * - * @param string $message - */ - protected function debugMessage($message) - { - if (PHP_SAPI != 'cli') { - print "
    \n".htmlentities($message)."\n
    "; - } else { - print "\n$message\n"; - } - } } diff --git a/src/Helper/Logger.php b/src/Helper/Logger.php new file mode 100644 index 00000000..cb0ab104 --- /dev/null +++ b/src/Helper/Logger.php @@ -0,0 +1,38 @@ +\n".htmlentities($message, $flags, $encoding)."\n"; + } else { + print "
    \n".htmlentities($message, $flags)."\n
    "; + } + } else { + print "\n$message\n"; + } + + // let the user see this now in case there's a time out later... + flush(); + } +} \ No newline at end of file diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index deb697a4..88b8f703 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -66,7 +66,7 @@ class PhpXmlRpc // 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 - public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8, or at least configurable? + public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8 public static $xmlrpcName = "XML-RPC for PHP"; public static $xmlrpcVersion = "4.0.0.beta"; @@ -136,4 +136,5 @@ public static function importGlobals() } } } + } diff --git a/src/Request.php b/src/Request.php index 66e723f7..6eb76718 100644 --- a/src/Request.php +++ b/src/Request.php @@ -4,6 +4,7 @@ use PhpXmlRpc\Helper\Http; use PhpXmlRpc\Helper\XMLParser; +use PhpXmlRpc\Helper\Logger; class Request { @@ -168,8 +169,7 @@ public function parseResponseFile($fp) public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals') { if ($this->debug) { - // by maHo, replaced htmlspecialchars with htmlentities - $this->debugMessage("---GOT---\n$data\n---END---"); + Logger::debugMessage("---GOT---\n$data\n---END---"); } $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array()); @@ -194,16 +194,6 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType } } - if ($this->debug) { - $start = strpos($data, '', $start); - $comments = substr($data, $start, $end - $start); - $this->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments))) . "\n---END---\n"; - } - } - // be tolerant of extra whitespace in response body $data = trim($data); @@ -216,6 +206,20 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType $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, '', $start); + $comments = substr($data, $start, $end - $start); + Logger::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'); @@ -226,9 +230,6 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType return $r; } - // try to 'guestimate' the character encoding of the received response - $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data); - if ($respEncoding != '') { // Since parsing will fail if charset is not specified in the xml prologue, @@ -317,8 +318,8 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType PhpXmlRpc::$xmlrpcstr['invalid_return']); } else { if ($this->debug) { - $this->debugMessage( - "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---", false + Logger::debugMessage( + "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---" ); } @@ -326,8 +327,7 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType $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... + /// @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->structmem('faultCode'); $errStr_v = $v->structmem('faultString'); @@ -355,22 +355,4 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType return $r; } - - /** - * Echoes a debug message, taking care of escaping it when not in console mode - * - * @param string $message - * @param bool $encodeEntities when false, escapes using htmlspecialchars instead of htmlentities - */ - protected function debugMessage($message, $encodeEntities = true) - { - if (PHP_SAPI != 'cli') { - if ($encodeEntities) - print "
    \n".htmlentities($message)."\n
    "; - else - print "
    \n".htmlspecialchars($message)."\n
    "; - } else { - print "\n$message\n"; - } - } } From 233eeff65a76b725619a681086079043247e7799 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 12:42:22 +0100 Subject: [PATCH 132/228] better name for undefined var used for testing --- demo/server/server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/server/server.php b/demo/server/server.php index 03bbab5c..c88c384a 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -42,7 +42,7 @@ class xmlrpc_server_methods_container */ public function phpwarninggenerator($m) { - $a = $b; // this triggers a warning in E_ALL mode, since $b is undefined + $a = $undefinedVariable; // this triggers a warning in E_ALL mode, since $undefinedVariable is undefined return new PhpXmlRpc\Response(new PhpXmlRpc\Value(1, 'boolean')); } From 20a65226a4dad0def0ed1b34ac37c0a539fb2495 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 12:43:38 +0100 Subject: [PATCH 133/228] Move from static logging calls to a singleton --- src/Client.php | 6 +++--- src/Helper/Http.php | 12 +++++------- src/Helper/Logger.php | 18 +++++++++++++++++- src/Request.php | 6 +++--- 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/src/Client.php b/src/Client.php index d71ef274..79948e86 100644 --- a/src/Client.php +++ b/src/Client.php @@ -553,7 +553,7 @@ protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0, $payload; if ($this->debug > 1) { - Logger::debugMessage("---SENDING---\n$op\n---END---"); + Logger::instance()->debugMessage("---SENDING---\n$op\n---END---"); } if ($timeout > 0) { @@ -709,7 +709,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username } if ($this->debug > 1) { - Logger::debugMessage("---SENDING---\n$payload\n---END---"); + Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---"); } if (!$keepAlive || !$this->xmlrpc_curl_handle) { @@ -848,7 +848,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username $message .= $name . ': ' . $val . "\n"; } $message .= "---END---"; - Logger::debugMessage($message); + Logger::instance()->debugMessage($message); } if (!$result) { diff --git a/src/Helper/Http.php b/src/Helper/Http.php index 0fa3f51b..2faf5833 100644 --- a/src/Helper/Http.php +++ b/src/Helper/Http.php @@ -3,14 +3,12 @@ namespace PhpXmlRpc\Helper; use PhpXmlRpc\PhpXmlRpc; -use PhpXmlRpc\Helper\Logger; class Http { /** - * Decode a string that is encoded w/ "chunked" transfer encoding - * as defined in rfc2068 par. 19.4.6 - * code shamelessly stolen from nusoap library by Dietrich Ayala. + * 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 * @@ -199,7 +197,7 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 foreach ($httpResponse['cookies'] as $header => $value) { $msg .= "COOKIE: $header={$value['value']}\n"; } - Logger::debugMessage($msg); + Logger::instance()->debugMessage($msg); } // if CURL was used for the call, http headers have been processed, @@ -223,12 +221,12 @@ public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0 if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; if ($debug) { - Logger::debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + 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::debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---"); + 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'); diff --git a/src/Helper/Logger.php b/src/Helper/Logger.php index cb0ab104..0194765a 100644 --- a/src/Helper/Logger.php +++ b/src/Helper/Logger.php @@ -11,6 +11,22 @@ class Logger { + protected static $instance = null; + + /** + * This class is singleton, so that later we can move to DI patterns. + * + * @return Charset + */ + 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 @@ -19,7 +35,7 @@ class Logger * @param string $message * @param string $encoding */ - public static function debugMessage($message, $encoding=null) + public function debugMessage($message, $encoding=null) { if (PHP_SAPI != 'cli') { $flags = ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE; diff --git a/src/Request.php b/src/Request.php index 6eb76718..8b367f14 100644 --- a/src/Request.php +++ b/src/Request.php @@ -169,7 +169,7 @@ public function parseResponseFile($fp) public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals') { if ($this->debug) { - Logger::debugMessage("---GOT---\n$data\n---END---"); + Logger::instance()->debugMessage("---GOT---\n$data\n---END---"); } $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array()); @@ -215,7 +215,7 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType $start += strlen('', $start); $comments = substr($data, $start, $end - $start); - Logger::debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . + Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" . str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding); } } @@ -318,7 +318,7 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType PhpXmlRpc::$xmlrpcstr['invalid_return']); } else { if ($this->debug) { - Logger::debugMessage( + Logger::instance()->debugMessage( "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---" ); } From f7815d511de0760616a58cfb3c1161242a216c9d Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 12:44:05 +0100 Subject: [PATCH 134/228] Comments fixing --- src/Helper/Charset.php | 2 +- src/Response.php | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index b9340414..a4064d89 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -110,7 +110,7 @@ public function encodeEntities($data, $srcEncoding = '', $destEncoding = '') case 'US-ASCII_': case 'US-ASCII_ISO-8859-1': case 'UTF-8_UTF-8': - //case 'CP1252_CP1252': + //case 'CP1252_CP1252': $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data); break; case 'UTF-8_': diff --git a/src/Response.php b/src/Response.php index 90980ac9..6ed243ac 100644 --- a/src/Response.php +++ b/src/Response.php @@ -33,7 +33,6 @@ public function __construct($val, $fCode = 0, $fString = '', $valType = '') // error response $this->errno = $fCode; $this->errstr = $fString; - //$this->errstr = htmlspecialchars($fString); // XXX: encoding probably shouldn't be done here; fix later. } else { // successful response $this->val = $val; From 568742e1a2911037c8d164716c138aa2cce74039 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 12:59:05 +0100 Subject: [PATCH 135/228] Make latin-1 tests more ide-proof --- tests/1ParsingBugsTest.php | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 33915cab..e4a3048c 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -413,52 +413,56 @@ public function testUTF8Request() public function testUTF8Response() { + $string = chr(224) . chr(252) . chr(232); + $s = new xmlrpcmsg('dummy'); $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . 'userid311127 -dateCreated20011126T09:17:52content' . utf8_encode('������') . 'postid7414222 +dateCreated20011126T09:17:52content' . utf8_encode($string) . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); $f = 'userid311127 -dateCreated20011126T09:17:52content' . utf8_encode('������') . 'postid7414222 +dateCreated20011126T09:17:52content' . utf8_encode($string) . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); $r = php_xmlrpc_decode_xml($f); $v = $r->value(); $v = $v->structmem('content')->scalarval(); - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); } public function testLatin1Response() { + $string = chr(224) . chr(252) . chr(232); + $s = new xmlrpcmsg('dummy'); $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=ISO-8859-1\r\n\r\n" . 'userid311127 -dateCreated20011126T09:17:52content' . '������' . 'postid7414222 +dateCreated20011126T09:17:52content' . $string . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); $f = 'userid311127 -dateCreated20011126T09:17:52content' . '������' . 'postid7414222 +dateCreated20011126T09:17:52content' . $string . 'postid7414222 '; $r = $s->parseResponse($f, false, 'phpvals'); $v = $r->value(); $v = $v['content']; - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); $r = php_xmlrpc_decode_xml($f); $v = $r->value(); $v = $v->structmem('content')->scalarval(); - $this->assertEquals("������", $v); + $this->assertEquals($string, $v); } public function testUTF8IntString() From 4a15ca01cea275528e059ca31474b927f613837a Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 13:05:28 +0100 Subject: [PATCH 136/228] Minor fix in one charset-related test --- tests/3LocalhostTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 99bb4908..a0e9b2a3 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -152,7 +152,7 @@ public function testString() public function testLatin1String() { $sendstring = - "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->"; + "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne"; $f = 'examples.stringecho'. $sendstring. ''; From 6899594826eeabef7fa3ed8e5b0091cf05497ae4 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 13:11:09 +0100 Subject: [PATCH 137/228] Fix one phpdoc --- src/Helper/Logger.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Helper/Logger.php b/src/Helper/Logger.php index 0194765a..62f7d753 100644 --- a/src/Helper/Logger.php +++ b/src/Helper/Logger.php @@ -16,7 +16,7 @@ class Logger /** * This class is singleton, so that later we can move to DI patterns. * - * @return Charset + * @return Logger */ public static function instance() { From a3b1d45eb2e1fd0712d574a423c6c4af8d512ee1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Apr 2015 13:48:05 +0100 Subject: [PATCH 138/228] Consistent with server, at debug level 1, request will not dump the rebuilt php object to screen; let paring tests echo the xml they use, as http tests do --- NEWS | 2 ++ src/Client.php | 2 +- src/Request.php | 12 +++++++++- tests/1ParsingBugsTest.php | 45 +++++++++++++++++++++++++------------- 4 files changed, 44 insertions(+), 17 deletions(-) diff --git a/NEWS b/NEWS index 9f0bd696..b2c5fb32 100644 --- a/NEWS +++ b/NEWS @@ -49,6 +49,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: echo all debug messages even when there are characters in them which php deems in a wrong encoding (this is visible e.g. in the debugger) +* improved: at debug level 1, the rebuilt php objects are not dumped to screen (server-side already did that) + XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/src/Client.php b/src/Client.php index 79948e86..d3f75408 100644 --- a/src/Client.php +++ b/src/Client.php @@ -363,7 +363,7 @@ public function send($req, $timeout = 0, $method = '') } // where req is a Request - $req->debug = $this->debug; + $req->setDebug($this->debug); if ($method == 'https') { $r = $this->sendPayloadHTTPS( diff --git a/src/Request.php b/src/Request.php index 8b367f14..7d5a8a0c 100644 --- a/src/Request.php +++ b/src/Request.php @@ -317,7 +317,7 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return']); } else { - if ($this->debug) { + if ($this->debug > 1) { Logger::instance()->debugMessage( "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---" ); @@ -355,4 +355,14 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType return $r; } + + /** + * 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; + } } diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index e4a3048c..4bbccba0 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -7,6 +7,22 @@ class ParsingBugsTests extends PHPUnit_Framework_TestCase { + public $args = array(); + + public function setUp() + { + $this->args = argParser::getArgs(); + } + + protected function newMsg($methodName, $params = array()) + { + $msg = new xmlrpcmsg($methodName, $params); + if ($this->args['DEBUG']) { + $msg->setDebug($this->args['DEBUG']); + } + return $msg; + } + public function testMinusOneString() { $v = new xmlrpcval('-1'); @@ -32,7 +48,7 @@ public function testUnicodeInMemberName() $v = array($str => new xmlrpcval(1)); $r = new xmlrpcresp(new xmlrpcval($v, 'struct')); $r = $r->serialize(); - $m = new xmlrpcmsg('dummy'); + $m = $this->newMsg('dummy'); $r = $m->parseResponse($r); $v = $r->value(); $this->assertEquals($v->structmemexists($str), true); @@ -62,7 +78,7 @@ public function testUnicodeInErrorString() '); - $m = new xmlrpcmsg('dummy'); + $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); @@ -70,7 +86,7 @@ public function testUnicodeInErrorString() public function testValidNumbers() { - $m = new xmlrpcmsg('dummy'); + $m = $this->newMsg('dummy'); $fp = ' @@ -193,8 +209,7 @@ public function testBrokenRequests() public function testBrokenResponses() { - $m = new xmlrpcmsg('dummy'); - //$m->debug = 1; + $m = $this->newMsg('dummy'); // omitting the 'params' tag: no more tolerated by the lib... $f = ' @@ -226,7 +241,7 @@ public function testBrokenResponses() public function testBuggyHttp() { - $s = new xmlrpcmsg('dummy'); + $s = $this->newMsg('dummy'); $f = 'HTTP/1.1 100 Welcome to the jungle HTTP/1.0 200 OK @@ -253,7 +268,7 @@ public function testBuggyHttp() public function testStringBug() { - $s = new xmlrpcmsg('dummy'); + $s = $this->newMsg('dummy'); $f = ' \n"; - for ($i = 0; $i < $max; $i++) { - $rec = $sno->arraymem($i); - if ($rec->kindOf() != "struct") { - $err = "Found non-struct in array at element $i"; - break; - } - // extract name and age from struct - $n = $rec->structmem("name"); - $a = $rec->structmem("age"); - // $n and $a are xmlrpcvals, - // so get the scalarval from them - $agar[$n->scalarval()] = $a->scalarval(); + $max = $sno->arraysize(); + PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements"); + for ($i = 0; $i < $max; $i++) { + $rec = $sno->arraymem($i); + if ($rec->kindOf() != "struct") { + $err = "Found non-struct in array at element $i"; + break; } + // extract name and age from struct + $n = $rec->structmem("name"); + $a = $rec->structmem("age"); + // $n and $a are xmlrpcvals, + // so get the scalarval from them + $agar[$n->scalarval()] = $a->scalarval(); + } - $agesorter_arr = $agar; - // hack, must make global as uksort() won't - // allow us to pass any other auxilliary information - uksort($agesorter_arr, agesorter_compare); - $outAr = array(); - while (list($key, $val) = each($agesorter_arr)) { - // recreate each struct element - $outAr[] = new PhpXmlRpc\Value(array("name" => new PhpXmlRpc\Value($key), - "age" => new PhpXmlRpc\Value($val, "int"),), "struct"); - } - // add this array to the output value - $v->addArray($outAr); - } else { - $err = "Must be one parameter, an array of structs"; + $agesorter_arr = $agar; + // hack, must make global as uksort() won't + // allow us to pass any other auxiliary information + uksort($agesorter_arr, 'agesorter_compare'); + $outAr = array(); + while (list($key, $val) = each($agesorter_arr)) { + // recreate each struct element + $outAr[] = new Value(array("name" => new Value($key), + "age" => new Value($val, "int"),), "struct"); } + // add this array to the output value + $v->addArray($outAr); if ($err) { - return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); } else { return new PhpXmlRpc\Response($v); } @@ -315,13 +301,13 @@ function agesorter($m) // signature and instructions, place these in the dispatch // map -$mail_send_sig = array(array( - $xmlrpcBoolean, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString, $xmlrpcString, - $xmlrpcString, $xmlrpcString, +$mailsend_sig = array(array( + Value::$xmlrpcBoolean, Value::$xmlrpcString, Value::$xmlrpcString, + Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString, + Value::$xmlrpcString, Value::$xmlrpcString, )); -$mail_send_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
    +$mailsend_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
    recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.
    subject is a string, the subject of the message.
    sender is a string, it\'s the email address of the person sending the message. This string can not be @@ -332,9 +318,8 @@ function agesorter($m) // 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 mail_send($m) +function mailSend($m) { - global $xmlrpcerruser, $xmlrpcBoolean; $err = ""; $mTo = $m->getParam(0); @@ -378,19 +363,20 @@ function mail_send($m) } if ($err) { - return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); } else { - return new PhpXmlRpc\Response(new PhpXmlRpc\Value("true", $xmlrpcBoolean)); + return new PhpXmlRpc\Response(new Value("true", Value::$xmlrpcBoolean)); } } -$getallheaders_sig = array(array($xmlrpcStruct)); +$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($m) { - global $xmlrpcerruser; + $encoder = new PhpXmlRpc\Encoder(); + if (function_exists('getallheaders')) { - return new PhpXmlRpc\Response(php_xmlrpc_encode(getallheaders())); + return new PhpXmlRpc\Response($encoder->encode(getallheaders())); } else { $headers = array(); // IIS: poor man's version of getallheaders @@ -401,50 +387,52 @@ function getallheaders_xmlrpc($m) } } - return new PhpXmlRpc\Response(php_xmlrpc_encode($headers)); + return new PhpXmlRpc\Response($encoder->encode($headers)); } } -$setcookies_sig = array(array($xmlrpcInt, $xmlrpcStruct)); +$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($m) +function setCookies($m) { + $encoder = new PhpXmlRpc\Encoder(); $m = $m->getParam(0); while (list($name, $value) = $m->structeach()) { - $cookiedesc = php_xmlrpc_decode($value); - setcookie($name, @$cookiedesc['value'], @$cookiedesc['expires'], @$cookiedesc['path'], @$cookiedesc['domain'], @$cookiedesc['secure']); + $cookieDesc = $encoder->decode($value); + setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']); } - return new PhpXmlRpc\Response(new PhpXmlRpc\Value(1, 'int')); + return new PhpXmlRpc\Response(new Value(1, 'int')); } -$getcookies_sig = array(array($xmlrpcStruct)); +$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($m) +function getCookies($m) { - return new PhpXmlRpc\Response(php_xmlrpc_encode($_COOKIE)); + $encoder = new PhpXmlRpc\Encoder(); + return new PhpXmlRpc\Response($encoder->encode($_COOKIE)); } -$v1_arrayOfStructs_sig = array(array($xmlrpcInt, $xmlrpcArray)); +$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 s. Your handler must add all the struct elements named curly and return the result.'; function v1_arrayOfStructs($m) { $sno = $m->getParam(0); - $numcurly = 0; + $numCurly = 0; for ($i = 0; $i < $sno->arraysize(); $i++) { $str = $sno->arraymem($i); $str->structreset(); while (list($key, $val) = $str->structeach()) { if ($key == "curly") { - $numcurly += $val->scalarval(); + $numCurly += $val->scalarval(); } } } - return new PhpXmlRpc\Response(new PhpXmlRpc\Value($numcurly, "int")); + return new PhpXmlRpc\Response(new Value($numCurly, "int")); } -$v1_easyStruct_sig = array(array($xmlrpcInt, $xmlrpcStruct)); +$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 <i4>s. Your handler must add the three numbers and return the result.'; function v1_easyStruct($m) { @@ -454,10 +442,10 @@ function v1_easyStruct($m) $curly = $sno->structmem("curly"); $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval(); - return new PhpXmlRpc\Response(new PhpXmlRpc\Value($num, "int")); + return new PhpXmlRpc\Response(new Value($num, "int")); } -$v1_echoStruct_sig = array(array($xmlrpcStruct, $xmlrpcStruct)); +$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($m) { @@ -467,14 +455,14 @@ function v1_echoStruct($m) } $v1_manyTypes_sig = array(array( - $xmlrpcArray, $xmlrpcInt, $xmlrpcBoolean, - $xmlrpcString, $xmlrpcDouble, $xmlrpcDateTime, - $xmlrpcBase64, + 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($m) { - return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( + return new PhpXmlRpc\Response(new Value(array( $m->getParam(0), $m->getParam(1), $m->getParam(2), @@ -485,7 +473,7 @@ function v1_manyTypes($m) )); } -$v1_moderateSizeArrayCheck_sig = array(array($xmlrpcString, $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($m) { @@ -494,26 +482,26 @@ function v1_moderateSizeArrayCheck($m) $first = $ar->arraymem(0); $last = $ar->arraymem($sz - 1); - return new PhpXmlRpc\Response(new PhpXmlRpc\Value($first->scalarval() . + return new PhpXmlRpc\Response(new Value($first->scalarval() . $last->scalarval(), "string")); } -$v1_simpleStructReturn_sig = array(array($xmlrpcStruct, $xmlrpcInt)); +$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($m) { $sno = $m->getParam(0); $v = $sno->scalarval(); - return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( - "times10" => new PhpXmlRpc\Value($v * 10, "int"), - "times100" => new PhpXmlRpc\Value($v * 100, "int"), - "times1000" => new PhpXmlRpc\Value($v * 1000, "int"),), + return new PhpXmlRpc\Response(new Value(array( + "times10" => new Value($v * 10, "int"), + "times100" => new Value($v * 100, "int"), + "times1000" => new Value($v * 1000, "int"),), "struct" )); } -$v1_nestedStruct_sig = array(array($xmlrpcInt, $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 <i4>s. Your handler must add the three numbers and return the result.'; function v1_nestedStruct($m) { @@ -526,10 +514,10 @@ function v1_nestedStruct($m) $larry = $fools->structmem("larry"); $moe = $fools->structmem("moe"); - return new PhpXmlRpc\Response(new PhpXmlRpc\Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); + return new PhpXmlRpc\Response(new Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), "int")); } -$v1_countTheEntities_sig = array(array($xmlrpcStruct, $xmlrpcString)); +$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 <, >, & \' and ".
    Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; function v1_countTheEntities($m) { @@ -563,12 +551,12 @@ function v1_countTheEntities($m) } } - return new PhpXmlRpc\Response(new PhpXmlRpc\Value(array( - "ctLeftAngleBrackets" => new PhpXmlRpc\Value($lt, "int"), - "ctRightAngleBrackets" => new PhpXmlRpc\Value($gt, "int"), - "ctAmpersands" => new PhpXmlRpc\Value($amp, "int"), - "ctApostrophes" => new PhpXmlRpc\Value($ap, "int"), - "ctQuotes" => new PhpXmlRpc\Value($qu, "int"),), + return new PhpXmlRpc\Response(new Value(array( + "ctLeftAngleBrackets" => new Value($lt, "int"), + "ctRightAngleBrackets" => new Value($gt, "int"), + "ctAmpersands" => new Value($amp, "int"), + "ctApostrophes" => new Value($ap, "int"), + "ctQuotes" => new Value($qu, "int"),), "struct" )); } @@ -576,37 +564,37 @@ function v1_countTheEntities($m) // trivial interop tests // http://www.xmlrpc.com/stories/storyReader$1636 -$i_echoString_sig = array(array($xmlrpcString, $xmlrpcString)); +$i_echoString_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); $i_echoString_doc = "Echoes string."; -$i_echoStringArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoStringArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); $i_echoStringArray_doc = "Echoes string array."; -$i_echoInteger_sig = array(array($xmlrpcInt, $xmlrpcInt)); +$i_echoInteger_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt)); $i_echoInteger_doc = "Echoes integer."; -$i_echoIntegerArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoIntegerArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); $i_echoIntegerArray_doc = "Echoes integer array."; -$i_echoFloat_sig = array(array($xmlrpcDouble, $xmlrpcDouble)); +$i_echoFloat_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble)); $i_echoFloat_doc = "Echoes float."; -$i_echoFloatArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$i_echoFloatArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); $i_echoFloatArray_doc = "Echoes float array."; -$i_echoStruct_sig = array(array($xmlrpcStruct, $xmlrpcStruct)); +$i_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct)); $i_echoStruct_doc = "Echoes struct."; -$i_echoStructArray_sig = array(array($xmlrpcArray, $xmlrpcArray)); +$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($xmlrpcValue, $xmlrpcValue)); +$i_echoValue_sig = array(array(Value::$xmlrpcValue, Value::$xmlrpcValue)); -$i_echoBase64_sig = array(array($xmlrpcBase64, $xmlrpcBase64)); +$i_echoBase64_sig = array(array(Value::$xmlrpcBase64, Value::$xmlrpcBase64)); $i_echoBase64_doc = "Echoes base64."; -$i_echoDate_sig = array(array($xmlrpcDateTime, $xmlrpcDateTime)); +$i_echoDate_sig = array(array(Value::$xmlrpcDateTime, Value::$xmlrpcDateTime)); $i_echoDate_doc = "Echoes dateTime."; function i_echoParam($m) @@ -671,69 +659,72 @@ function i_echoDate($m) return i_echoParam($m); } -$i_whichToolkit_sig = array(array($xmlrpcStruct)); +$i_whichToolkit_sig = array(array(Value::$xmlrpcStruct)); $i_whichToolkit_doc = "Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem."; function i_whichToolkit($m) { - global $xmlrpcName, $xmlrpcVersion, $SERVER_SOFTWARE; + global $SERVER_SOFTWARE; $ret = array( "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/", - "toolkitName" => $xmlrpcName, - "toolkitVersion" => $xmlrpcVersion, + "toolkitName" => PhpXmlRpc\PhpXmlRpc::$xmlrpcName, + "toolkitVersion" => PhpXmlRpc\PhpXmlRpc::$xmlrpcVersion, "toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'], ); - return new PhpXmlRpc\Response(php_xmlrpc_encode($ret)); + $encoder = new PhpXmlRpc\Encoder(); + return new PhpXmlRpc\Response($encoder->encode($ret)); } -$o = new xmlrpc_server_methods_container(); -$a = array( +$object = new xmlrpcServerMethodsContainer(); +$signatures = array( "examples.getStateName" => array( - "function" => "findstate", + "function" => "findState", "signature" => $findstate_sig, "docstring" => $findstate_doc, ), "examples.sortByAge" => array( - "function" => "agesorter", + "function" => "ageSorter", "signature" => $agesorter_sig, "docstring" => $agesorter_doc, ), "examples.addtwo" => array( - "function" => "addtwo", + "function" => "addTwo", "signature" => $addtwo_sig, "docstring" => $addtwo_doc, ), "examples.addtwodouble" => array( - "function" => "addtwodouble", + "function" => "addTwoDouble", "signature" => $addtwodouble_sig, "docstring" => $addtwodouble_doc, ), "examples.stringecho" => array( - "function" => "stringecho", + "function" => "stringEcho", "signature" => $stringecho_sig, "docstring" => $stringecho_doc, ), "examples.echo" => array( - "function" => "echoback", + "function" => "echoBack", "signature" => $echoback_sig, "docstring" => $echoback_doc, ), "examples.decode64" => array( - "function" => "echosixtyfour", + "function" => "echoSixtyFour", "signature" => $echosixtyfour_sig, "docstring" => $echosixtyfour_doc, ), "examples.invertBooleans" => array( - "function" => "bitflipper", + "function" => "bitFlipper", "signature" => $bitflipper_sig, "docstring" => $bitflipper_doc, ), + // signature omitted on purpose "examples.generatePHPWarning" => array( - "function" => array($o, "phpwarninggenerator"), + "function" => array($object, "phpWarningGenerator"), ), + // signature omitted on purpose "examples.raiseException" => array( - "function" => array($o, "exceptiongenerator"), + "function" => array($object, "exceptionGenerator"), ), "examples.getallheaders" => array( "function" => 'getallheaders_xmlrpc', @@ -741,19 +732,19 @@ function i_whichToolkit($m) "docstring" => $getallheaders_doc, ), "examples.setcookies" => array( - "function" => 'setcookies', + "function" => 'setCookies', "signature" => $setcookies_sig, "docstring" => $setcookies_doc, ), "examples.getcookies" => array( - "function" => 'getcookies', + "function" => 'getCookies', "signature" => $getcookies_sig, "docstring" => $getcookies_doc, ), "mail.send" => array( - "function" => "mail_send", - "signature" => $mail_send_sig, - "docstring" => $mail_send_doc, + "function" => "mailSend", + "signature" => $mailsend_sig, + "docstring" => $mailsend_doc, ), "validator1.arrayOfStructsTest" => array( "function" => "v1_arrayOfStructs", @@ -858,22 +849,22 @@ function i_whichToolkit($m) ); if ($findstate2_sig) { - $a['examples.php.getStateName'] = $findstate2_sig; + $signatures['examples.php.getStateName'] = $findstate2_sig; } if ($findstate3_sig) { - $a['examples.php2.getStateName'] = $findstate3_sig; + $signatures['examples.php2.getStateName'] = $findstate3_sig; } if ($findstate4_sig) { - $a['examples.php3.getStateName'] = $findstate4_sig; + $signatures['examples.php3.getStateName'] = $findstate4_sig; } if ($findstate5_sig) { - $a['examples.php4.getStateName'] = $findstate5_sig; + $signatures['examples.php4.getStateName'] = $findstate5_sig; } -$s = new PhpXmlRpc\Server($a, false); +$s = new PhpXmlRpc\Server($signatures, false); $s->setdebug(3); $s->compress_response = true; From 5165658f984c1112f1f29e9663d5c334e71bdc98 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 18 Apr 2015 00:21:22 +0100 Subject: [PATCH 149/228] For travis tests, use the version of phpunit which we install via composer, instead of the system one (might fix autoloading pbl for Logger) --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 94eef7b1..cb7fce80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,7 @@ before_script: 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 - 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 + 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 From 7f511cb14b813295a06c5f4d82b1e2d9a27fb571 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 18 Apr 2015 00:34:23 +0100 Subject: [PATCH 150/228] Remove legacy code from vardemo demo file --- demo/vardemo.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/demo/vardemo.php b/demo/vardemo.php index 4f91deb1..d24d04ec 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -2,11 +2,10 @@ xmlrpc Testing value serialization\n"; @@ -69,25 +68,26 @@ print "
    " . htmlentities($w->serialize()) . "
    "; print "
    Value of base64 string is: '" . $w->scalarval() . "'
    "; -$f->method(''); -$f->addParam(new PhpXmlRpc\Value("41", "int")); +$req->method(''); +$req->addParam(new PhpXmlRpc\Value("41", "int")); print "

    Testing request serialization

    \n"; -$op = $f->serialize(); +$op = $req->serialize(); print "
    " . htmlentities($op) . "
    "; print "

    Testing ISO date format

    \n";
     
     $t = time();
    -$date = iso8601_encode($t);
    +$date = PhpXmlRpc\Helper\Date::iso8601_encode($t);
     print "Now is $t --> $date\n";
    -print "Or in UTC, that is " . iso8601_encode($t, 1) . "\n";
    -$tb = iso8601_decode($date);
    +print "Or in UTC, that is " . PhpXmlRpc\Helper\Date::iso8601_encode($t, 1) . "\n";
    +$tb = PhpXmlRpc\Helper\Date::iso8601_decode($date);
     print "That is to say $date --> $tb\n";
    -print "Which comes out at " . iso8601_encode($tb) . "\n";
    -print "Which was the time in UTC at " . iso8601_decode($date, 1) . "\n";
    +print "Which comes out at " . PhpXmlRpc\Helper\Date::iso8601_encode($tb) . "\n";
    +print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601_decode($date, 1) . "\n";
     
     print "
    \n"; + ?> From d8b819265ed2783764352484e2ea1bf71eb93f94 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 18 Apr 2015 00:38:14 +0100 Subject: [PATCH 151/228] Terminate files with a NL to appease sensiolabs --- demo/server/server.php | 2 +- src/Autoloader.php | 2 +- src/Helper/Logger.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index e6b4bb4d..93585bf8 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -883,4 +883,4 @@ function i_whichToolkit($m) // 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"; -} \ No newline at end of file +} diff --git a/src/Autoloader.php b/src/Autoloader.php index 77ba30f6..40ec2190 100644 --- a/src/Autoloader.php +++ b/src/Autoloader.php @@ -33,4 +33,4 @@ public static function autoload($class) require $file; } } -} \ No newline at end of file +} diff --git a/src/Helper/Logger.php b/src/Helper/Logger.php index 0bf6a201..77e0e149 100644 --- a/src/Helper/Logger.php +++ b/src/Helper/Logger.php @@ -49,4 +49,4 @@ public function debugMessage($message, $encoding=null) // let the user see this now in case there's a time out later... flush(); } -} \ No newline at end of file +} From b19b4df8cca4856106ed6d19c9fec5d3e2fdcab3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 18 Apr 2015 01:40:26 +0100 Subject: [PATCH 152/228] Make the debugger tolerate latin-1 characters in all fields, not just method payload --- debugger/action.php | 111 +++++++++++++++++++++------------------- debugger/controller.php | 31 ++++++----- 2 files changed, 74 insertions(+), 68 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index 7bb07f50..c8184296 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -239,7 +239,7 @@ // Before calling execute, echo out brief description of action taken + date and time ??? // this gives good user feedback for long-running methods... - echo '

    ' . htmlspecialchars($actionname) . ' on server ' . htmlspecialchars($server) . " ...

    \n"; + echo '

    ' . htmlspecialchars($actionname, ENT_COMPAT, $inputcharset) . ' on server ' . htmlspecialchars($server, ENT_COMPAT, $inputcharset) . " ...

    \n"; flush(); $response = null; @@ -265,14 +265,14 @@ if ($response) { if ($response->faultCode()) { // call failed! echo out error msg! - //echo '

    '.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

    '; + //echo '

    '.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'

    '; echo "

    $protoName call FAILED!

    \n"; - echo "

    Fault code: [" . htmlspecialchars($response->faultCode()) . - "] Reason: '" . htmlspecialchars($response->faultString()) . "'

    \n"; + echo "

    Fault code: [" . htmlspecialchars($response->faultCode(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + "] Reason: '" . htmlspecialchars($response->faultString(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "'

    \n"; echo(strftime("%d/%b/%Y:%H:%M:%S\n")); } else { // call succeeded: parse results - //echo '

    '.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'

    '; + //echo '

    '.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'

    '; printf("

    %s call(s) OK (%.2f secs.)

    \n", $protoName, $time); echo(strftime("%d/%b/%Y:%H:%M:%S\n")); @@ -291,27 +291,27 @@ } else { $class = ' class="evenrow"'; } - echo("" . htmlspecialchars($rec->scalarval()) . "" . - "" . - "" . - "" . - "" . + echo("" . htmlspecialchars($rec->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "" . + "" . + "" . + "" . + "" . "" . - "" . - "" . + "" . + "" . "" . "" . "" . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . "" . - "" . + "" . "" . - "" . - "scalarval() . "\" />" . + "" . + "scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "\" />" . "" . "" . "" . @@ -341,8 +341,8 @@ $r2 = $resp[1]->value(); echo "\n"; - echo "\n\n\n\n"; - $desc = htmlspecialchars($r1->scalarval()); + echo "\n\n\n\n"; + $desc = htmlspecialchars($r1->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($desc == "") { $desc = "-"; } @@ -362,13 +362,16 @@ $x = $r2->arraymem($i); if ($x->kindOf() == "array") { $ret = $x->arraymem(0); - echo "OUT: " . htmlspecialchars($ret->scalarval()) . "
    IN: ("; + echo "OUT: " . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "
    IN: ("; if ($x->arraysize() > 1) { for ($k = 1; $k < $x->arraysize(); $k++) { $y = $x->arraymem($k); - echo $y->scalarval(); + echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($wstype != 1) { - $payload = $payload . '<' . htmlspecialchars($y->scalarval()) . '>scalarval()) . ">\n"; + $payload = $payload . '<' . + htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + '>scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + ">\n"; } $alt_payload .= $y->scalarval(); if ($k < $x->arraysize() - 1) { @@ -385,28 +388,28 @@ // button to test this method //$payload="\n$method\n\n$payload\n"; echo "" . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . - "" . - "" . + "" . + "" . "" . "" . "" . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . "" . - "" . + "" . "" . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . ""; if ($wstype != 1) { @@ -415,29 +418,29 @@ echo "\n"; echo "
    " . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . - "" . - "" . + "" . + "" . "" . "" . "" . - "" . - "" . - "" . - "" . + "" . + "" . + "" . + "" . "" . "" . - "" . + "" . "" . - "" . - "" . + "" . + "" . "" . - "" . - "" . + "" . + "" . "" . "" . "" . diff --git a/debugger/controller.php b/debugger/controller.php index 6051f92b..e58d2a44 100644 --- a/debugger/controller.php +++ b/debugger/controller.php @@ -12,6 +12,9 @@ * @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'; @@ -235,12 +238,12 @@ function switchFormMethod() {
    - + - - +
    Method" . htmlspecialchars($method) . "  
    Method" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "  

    Target server

    Address: Port: + Path:
    @@ -253,18 +256,18 @@ function switchFormMethod() { Generate stub for method call onclick="switchaction();"/> - + - + - - + + @@ -292,9 +295,9 @@ function switchFormMethod() { - + - + - + - + - + - + @@ -344,7 +347,7 @@ function switchFormMethod() { - +

    Method

    Name: Payload:
    Msg id: Msg id:
    AUTH: Username: Pwd: Type Verify Cert: /> CA Cert file:
    PROXY: Server: Proxy user: Proxy pwd:
    COMPRESSION:
    COOKIES: Format: 'cookie1=value1, cookie2=value2'
    From 85f6c5ecb5094c17aa7a0134006534a8b8387274 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 18 Apr 2015 02:06:44 +0100 Subject: [PATCH 153/228] fix: the client can now successfully call methods using ISO-8859-1 or UTF-8 characters in their name --- NEWS | 11 ++++--- demo/server/server.php | 30 ++++++++++++------ src/Request.php | 5 +-- tests/3LocalhostTest.php | 66 ++++++++++++++++++++++++++-------------- 4 files changed, 74 insertions(+), 38 deletions(-) diff --git a/NEWS b/NEWS index 6d869187..e1045d38 100644 --- a/NEWS +++ b/NEWS @@ -38,13 +38,16 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: the testsuite has basic checks for the debugger and demo files -* fixed: the debugger would fail sending a request with ISO-8859-1 payload (it missed the character set declaration) +* 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 server would fail to decode a request with ISO-8859-1 payload and character set declaration in the xml prologue only +* 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 prologue 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 prologue +* 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 * improved: echo all debug messages even when there are characters in them which php deems in a wrong encoding (this is visible e.g. in the debugger) diff --git a/demo/server/server.php b/demo/server/server.php index 93585bf8..88938d4c 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -86,6 +86,7 @@ public static function findState($s) function findState($m) { global $stateNames; + $err = ""; // get the first param $sno = $m->getParam(0); @@ -122,6 +123,7 @@ function findState($m) function inner_findstate($stateNo) { global $stateNames; + if (isset($stateNames[$stateNo - 1])) { return $stateNames[$stateNo - 1]; } else { @@ -166,10 +168,7 @@ function addTwoDouble($m) function stringEcho($m) { // just sends back a string - $s = $m->getParam(0); - $v = $s->scalarval(); - - return new PhpXmlRpc\Response(new Value($s->scalarval())); + return new PhpXmlRpc\Response(new Value($m->getParam(0)->scalarval())); } $echoback_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); @@ -186,9 +185,8 @@ function echoBack($m) $echosixtyfour_doc = 'Accepts a base64 parameter and returns it decoded as a string'; function echoSixtyFour($m) { - // accepts an encoded value, but sends it back - // as a normal string. this is to test base64 encoding - // is working as expected + // Accepts an encoded value, but sends it back as a normal string. + // This is to test that base64 encoding is working as expected $incoming = $m->getParam(0); return new PhpXmlRpc\Response(new Value($incoming->scalarval(), "string")); @@ -306,7 +304,6 @@ function ageSorter($m) Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString, )); - $mailsend_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)
    recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.
    subject is a string, the subject of the message.
    @@ -719,13 +716,26 @@ function i_whichToolkit($m) "docstring" => $bitflipper_doc, ), // signature omitted on purpose - "examples.generatePHPWarning" => array( + "tests.generatePHPWarning" => array( "function" => array($object, "phpWarningGenerator"), ), // signature omitted on purpose - "examples.raiseException" => array( + "tests.raiseException" => array( "function" => array($object, "exceptionGenerator"), ), + /* + // Greek word 'kosme'. NB: NOT a valid ISO8859 string! + // 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, diff --git a/src/Request.php b/src/Request.php index 7d5a8a0c..df899e3b 100644 --- a/src/Request.php +++ b/src/Request.php @@ -2,9 +2,10 @@ namespace PhpXmlRpc; +use PhpXmlRpc\Helper\Charset; use PhpXmlRpc\Helper\Http; -use PhpXmlRpc\Helper\XMLParser; use PhpXmlRpc\Helper\Logger; +use PhpXmlRpc\Helper\XMLParser; class Request { @@ -52,7 +53,7 @@ public function createPayload($charsetEncoding = '') $this->content_type = 'text/xml'; } $this->payload = $this->xml_header($charsetEncoding); - $this->payload .= '' . $this->methodname . "\n"; + $this->payload .= '' . Charset::instance()->encodeEntities($this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n"; $this->payload .= "\n"; foreach ($this->params as $p) { $this->payload .= "\n" . $p->serialize($charsetEncoding) . diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index e73bf61f..e6cc42d4 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -108,7 +108,7 @@ protected function tearDown() } } - protected function send($msg, $errrorcode = 0, $return_response = false) + protected function send($msg, $errorCode = 0, $returnResponse = false) { if ($this->collectCodeCoverageInformation) { $this->client->setCookie('PHPUNIT_SELENIUM_TEST_ID', $this->testId); @@ -119,13 +119,13 @@ protected function send($msg, $errrorcode = 0, $return_response = false) if (is_array($r)) { return $r; } - if (is_array($errrorcode)) { - $this->assertContains($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + if (is_array($errorCode)) { + $this->assertContains($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); } else { - $this->assertEquals($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + $this->assertEquals($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); } if (!$r->faultCode()) { - if ($return_response) { + if ($returnResponse) { return $r; } else { return $r->value(); @@ -137,7 +137,7 @@ protected function send($msg, $errrorcode = 0, $return_response = false) public function testString() { - $sendstring = "here are 3 \"entities\": < > & " . + $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]. " . @@ -147,35 +147,57 @@ public function testString() "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: -->"; $f = new xmlrpcmsg('examples.stringecho', array( - new xmlrpcval($sendstring, 'string'), + new xmlrpcval($sendString, 'string'), )); $v = $this->send($f); 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); + $l1 = strlen($sendString); $l2 = strlen($v->scalarval()); if ($l1 == $l2) { - $this->assertEquals($sendstring, $v->scalarval()); + $this->assertEquals($sendString, $v->scalarval()); } else { - $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendstring), $v->scalarval()); + $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval()); } } } public function testLatin1String() { - $sendstring = + $sendString = "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne"; $f = 'examples.stringecho'. - $sendstring. + $sendString. ''; $v = $this->send($f); if ($v) { - $this->assertEquals($sendstring, $v->scalarval()); + $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() + { + $f = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array( + new xmlrpcval('hello') + )); + $v = $this->send($f); + if ($v) { + $this->assertEquals('hello', $v->scalarval()); + } + }*/ + public function testAddingDoubles() { // note that rounding errors mean we @@ -250,7 +272,7 @@ public function testBoolean() public function testBase64() { - $sendstring = 'Mary had a little lamb, + $sendString = 'Mary had a little lamb, Whose fleece was white as snow, And everywhere that Mary went the lamb was sure to go. @@ -260,14 +282,14 @@ public function testBase64() Ten thousand volts went down its back And turned it into nylon'; $f = new xmlrpcmsg('examples.decode64', array( - new xmlrpcval($sendstring, 'base64'), + new xmlrpcval($sendString, 'base64'), )); $v = $this->send($f); if ($v) { - if (strlen($sendstring) == strlen($v->scalarval())) { - $this->assertEquals($sendstring, $v->scalarval()); + 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()); + $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval()); } } } @@ -290,9 +312,9 @@ public function testDateTime() public function testCountEntities() { - $sendstring = "h'fd>onc>>l>>rw&bpu>q>esend($f); if ($v) { @@ -491,7 +513,7 @@ public function testClientMulticall3() public function testCatchWarnings() { - $f = new xmlrpcmsg('examples.generatePHPWarning', array( + $f = new xmlrpcmsg('tests.generatePHPWarning', array( new xmlrpcval('whatever', 'string'), )); $v = $this->send($f); @@ -502,7 +524,7 @@ public function testCatchWarnings() public function testCatchExceptions() { - $f = new xmlrpcmsg('examples.raiseException', array( + $f = new xmlrpcmsg('tests.raiseException', array( new xmlrpcval('whatever', 'string'), )); $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); From 9c35037a23ea6491bdf710260e8958902fc07605 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 19:42:13 +0100 Subject: [PATCH 154/228] Fix: encoder needs the kindOf method on requests --- lib/xmlrpc.inc | 10 ---------- src/Request.php | 10 ++++++++++ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 9106bd67..2bcead01 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -138,16 +138,6 @@ class xmlrpcval extends PhpXmlRpc\Value class xmlrpcmsg extends PhpXmlRpc\Request { - /** - * Kept the old name even if Request class was renamed, for compatibility. - * @deprecated - * - * @return string - */ - public function kindOf() - { - return 'msg'; - } } class xmlrpcresp extends PhpXmlRpc\Response diff --git a/src/Request.php b/src/Request.php index df899e3b..2c479408 100644 --- a/src/Request.php +++ b/src/Request.php @@ -357,6 +357,16 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType 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. * From 4e8ba3e1d1a411856c639ebcf93a45fe065cd794 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 19:42:57 +0100 Subject: [PATCH 155/228] Remove legacy api usage from comment.php --- demo/server/discuss.php | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/demo/server/discuss.php b/demo/server/discuss.php index 2a137e8e..b6b46599 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -2,23 +2,22 @@ include_once __DIR__ . "/../../vendor/autoload.php"; -include_once __DIR__ . "/../../lib/xmlrpc.inc"; -include_once __DIR__ . "/../../lib/xmlrpcs.inc"; +use PhpXmlRpc\Value; -$addcomment_sig = array(array($xmlrpcInt, $xmlrpcString, $xmlrpcString, $xmlrpcString)); +$addComment_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString)); -$addcomment_doc = 'Adds a comment to an item. The first parameter +$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($m) +function addComment($m) { - global $xmlrpcerruser; $err = ""; // since validation has already been carried out for us, // we know we got exactly 3 string values - $n = php_xmlrpc_decode($m); + $encoder = new PhpXmlRpc\Encoder(); + $n = $encoder->decode($m); $msgID = $n[0]; $name = $n[1]; $comment = $n[2]; @@ -42,7 +41,7 @@ function addcomment($m) } // if we generated an error, create an error return response if ($err) { - return new PhpXmlRpc\Response(0, $xmlrpcerruser, $err); + return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); } else { // otherwise, we create the right response // with the state name @@ -50,15 +49,14 @@ function addcomment($m) } } -$getcomments_sig = array(array($xmlrpcArray, $xmlrpcString)); +$getComments_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcString)); -$getcomments_doc = 'Returns an array of comments for a given ID, which +$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($m) +function getComments($m) { - global $xmlrpcerruser; $err = ""; $ra = array(); $msgID = php_xmlrpc_decode($m->getParam(0)); @@ -80,23 +78,24 @@ function getcomments($m) } // if we generated an error, create an error return response if ($err) { - return new PhpXmlRpc\Response(0, $xmlrpcerruser, $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(php_xmlrpc_encode($ra)); + $encoder = new PhpXmlRpc\Encoder(); + return new PhpXmlRpc\Response($encoder->encode($ra)); } } $s = new PhpXmlRpc\Server(array( "discuss.addComment" => array( - "function" => "addcomment", - "signature" => $addcomment_sig, - "docstring" => $addcomment_doc, + "function" => "addComment", + "signature" => $addComment_sig, + "docstring" => $addComment_doc, ), "discuss.getComments" => array( - "function" => "getcomments", - "signature" => $getcomments_sig, - "docstring" => $getcomments_doc, + "function" => "getComments", + "signature" => $getComments_sig, + "docstring" => $getComments_doc, ), )); From 21597f4011977e682392aec4ad391a54bbf99212 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 19:48:03 +0100 Subject: [PATCH 156/228] Comments and whitespace in discuss.php --- demo/server/discuss.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/demo/server/discuss.php b/demo/server/discuss.php index b6b46599..ac65209b 100644 --- a/demo/server/discuss.php +++ b/demo/server/discuss.php @@ -11,13 +11,13 @@ is the comment itself. Returns the number of comments against that ID.'; -function addComment($m) +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($m); + $n = $encoder->decode($req); $msgID = $n[0]; $name = $n[1]; $comment = $n[2]; @@ -44,7 +44,6 @@ function addComment($m) 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 PhpXmlRpc\Value($count, "int")); } } @@ -55,11 +54,12 @@ function addComment($m) is the sole argument. Each array item is a struct containing name and comment text.'; -function getComments($m) +function getComments($req) { $err = ""; $ra = array(); - $msgID = php_xmlrpc_decode($m->getParam(0)); + $encoder = new PhpXmlRpc\Encoder(); + $msgID = $encoder->decode($req->getParam(0)); $dbh = dba_open("/tmp/comments.db", "r", "db2"); if ($dbh) { $countID = "${msgID}_count"; @@ -81,13 +81,11 @@ function getComments($m) return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err); } else { // otherwise, we create the right response - // with the state name - $encoder = new PhpXmlRpc\Encoder(); return new PhpXmlRpc\Response($encoder->encode($ra)); } } -$s = new PhpXmlRpc\Server(array( +$srv = new PhpXmlRpc\Server(array( "discuss.addComment" => array( "function" => "addComment", "signature" => $addComment_sig, From 5282cf295c80ee4acfdde505e7122d050e574596 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 21:22:22 +0100 Subject: [PATCH 157/228] Set default internal charset to UTF8 and change tests accordingly; add function has_encoding() from lib ver. 3.0.1; fixed one missing autoload in xmlrpc.inc; proper usage of actual and expected in all tests --- NEWS | 5 ++++- demo/server/server.php | 9 ++++----- lib/xmlrpc.inc | 9 ++++++++- src/PhpXmlRpc.php | 5 +++-- tests/1ParsingBugsTest.php | 8 ++++---- tests/3LocalhostTest.php | 26 ++++++++++++-------------- tests/4LocalhostMultiTest.php | 3 ++- 7 files changed, 37 insertions(+), 28 deletions(-) diff --git a/NEWS b/NEWS index e1045d38..7f2c2614 100644 --- a/NEWS +++ b/NEWS @@ -17,6 +17,9 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. 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 encoding delivered from the library to your code is now utf8. + It can be changed at anytime setting a value to PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding + * improved: all php code is now formatted according to the PSR-2 standard * improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https @@ -49,7 +52,7 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * fixed: the client can now successfully call methods using ISO-8859-1 or UTF-8 characters in their name -* improved: echo all debug messages even when there are characters in them which php deems in a wrong encoding +* improved: echo all debug messages even when there are characters in them which php deems to be in a wrong encoding (this is visible e.g. in the debugger) * changed: debug info handling diff --git a/demo/server/server.php b/demo/server/server.php index 88938d4c..aa604b85 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -723,19 +723,18 @@ function i_whichToolkit($m) "tests.raiseException" => array( "function" => array($object, "exceptionGenerator"), ), - /* // Greek word 'kosme'. NB: NOT a valid ISO8859 string! - // We can only register this when setting internal encoding to UTF-8, or it will break system.listMethods + // 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( + ), + /*"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, diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 2bcead01..450e881f 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -50,13 +50,15 @@ 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/Date.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 */ @@ -194,6 +196,11 @@ 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()->is_valid_charset($encoding, $validList); diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 88b8f703..84597e6b 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -65,8 +65,9 @@ class PhpXmlRpc // 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 - public static $xmlrpc_internalencoding = "ISO-8859-1"; // TODO: maybe this would be better as UTF-8 + // 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.0.0.beta"; diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 6a6a3f99..06fb36ac 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -40,8 +40,8 @@ public function testMinusOneString() $v = new xmlrpcval('-1'); $u = new xmlrpcval('-1', 'string'); $t = new xmlrpcval(-1, 'string'); - $this->assertEquals($u->scalarval(), $v->scalarval()); - $this->assertEquals($t->scalarval(), $v->scalarval()); + $this->assertEquals($v->scalarval(), $u->scalarval()); + $this->assertEquals($v->scalarval(), $t->scalarval()); } /** @@ -49,8 +49,8 @@ public function testMinusOneString() */ public function testMinusOneInt() { - $v = new xmlrpcval(-1); $u = new xmlrpcval(); + $v = new xmlrpcval(-1); $this->assertEquals($u->scalarval(), $v->scalarval()); } @@ -63,7 +63,7 @@ public function testUnicodeInMemberName() $m = $this->newMsg('dummy'); $r = $m->parseResponse($r); $v = $r->value(); - $this->assertEquals($v->structmemexists($str), true); + $this->assertEquals(true, $v->structmemexists($str)); } public function testUnicodeInErrorString() diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index e6cc42d4..b782319f 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -122,7 +122,7 @@ protected function send($msg, $errorCode = 0, $returnResponse = false) if (is_array($errorCode)) { $this->assertContains($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); } else { - $this->assertEquals($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + $this->assertEquals($errorCode, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); } if (!$r->faultCode()) { if ($returnResponse) { @@ -176,7 +176,7 @@ public function testLatin1String() } } - public function testLatin1Method() + /*public function testLatin1Method() { $f = new xmlrpcmsg("tests.iso88591methodname." . chr(224) . chr(252) . chr(232), array( new xmlrpcval('hello') @@ -185,10 +185,11 @@ public function testLatin1Method() if ($v) { $this->assertEquals('hello', $v->scalarval()); } - } + }*/ - /*public function testUtf8Method() + public function testUtf8Method() { + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8'; $f = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array( new xmlrpcval('hello') )); @@ -196,7 +197,8 @@ public function testLatin1Method() if ($v) { $this->assertEquals('hello', $v->scalarval()); } - }*/ + PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; + } public function testAddingDoubles() { @@ -247,9 +249,7 @@ public function testBoolean() new xmlrpcval(true, 'boolean'), new xmlrpcval(false, 'boolean'), new xmlrpcval(1, 'boolean'), - new xmlrpcval(0, 'boolean'), - //new xmlrpcval('true', 'boolean'), - //new xmlrpcval('false', 'boolean') + new xmlrpcval(0, 'boolean') ), 'array' ),)); @@ -518,7 +518,7 @@ public function testCatchWarnings() )); $v = $this->send($f); if ($v) { - $this->assertEquals($v->scalarval(), true); + $this->assertEquals(true, $v->scalarval()); } } @@ -547,7 +547,6 @@ public function testCodeInjectionServerSide() $f = new xmlrpcmsg('system.MethodHelp'); $f->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; $v = $this->send($f); - //$v = $r->faultCode(); if ($v) { $this->assertEquals(0, $v->structsize()); } @@ -661,7 +660,7 @@ public function testSetCookies() $cookies[$cookie] = (string)$cookies[$cookie]; } $r = $this->client->send($f, $this->timeout, $this->method); - $this->assertEquals($r->faultCode(), 0, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); + $this->assertEquals(0, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString()); if (!$r->faultCode()) { $v = $r->value(); $v = php_xmlrpc_decode($v); @@ -672,7 +671,7 @@ public function testSetCookies() } // on IIS and Apache getallheaders returns something slightly different... - $this->assertEquals($v, $cookies); + $this->assertEquals($cookies, $v); } } @@ -683,9 +682,8 @@ public function testSendTwiceSameMsg() )); $v1 = $this->send($f); $v2 = $this->send($f); - //$v = $r->faultCode(); if ($v1 && $v2) { - $this->assertEquals($v2, $v1); + $this->assertEquals($v1, $v2); } } } diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 51a89332..5ef6a3cf 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -15,9 +15,10 @@ class LocalhostMultiTest extends LocalhostTest */ function _runtests() { + $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method'); foreach(get_class_methods('LocalhostTest') as $method) { - if(strpos($method, 'test') === 0 && $method != 'testHttps' && $method != 'testCatchExceptions') + if(strpos($method, 'test') === 0 && !in_array($method, $unsafeMethods)) { if (!isset(self::$failed_tests[$method])) $this->$method(); From f68bfa1c150747d2118e4b2c4f193b00a56dedb1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 22:59:55 +0100 Subject: [PATCH 158/228] Make debugger use utf8 by default --- NEWS | 8 +++++--- debugger/action.php | 4 ++++ debugger/common.php | 5 +++-- debugger/controller.php | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/NEWS b/NEWS index 7f2c2614..50624738 100644 --- a/NEWS +++ b/NEWS @@ -41,9 +41,6 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: the testsuite has basic checks for the debugger and demo files -* 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 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 @@ -52,6 +49,11 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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 + +* 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 (this is visible e.g. in the debugger) diff --git a/debugger/action.php b/debugger/action.php index c8184296..3e22c692 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -8,6 +8,9 @@ * @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'); + ?> @@ -529,6 +532,7 @@

    Changelog

      +
    • 2015-04-19: fix problems with LATIN-1 characters in payload
    • 2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id
    • 2006-06-26: support building php code stub for calling remote methods
    • 2006-05-25: better support for long running queries; check for no-curl installs
    • diff --git a/debugger/common.php b/debugger/common.php index ea389a65..4026d607 100644 --- a/debugger/common.php +++ b/debugger/common.php @@ -28,10 +28,11 @@ function stripslashes_deep($value) $inputcharset = mb_detect_encoding(urldecode($_SERVER['REQUEST_URI']), $preferredEncodings); if (isset($_GET['usepost']) && $_GET['usepost'] === 'true') { $_GET = $_POST; - /// @bug this is not a perfect detection method - it will fail if eg. a latin1 character is in the method name - $inputcharset = mb_detect_encoding(urldecode(isset($_GET['methodpayload'])) ? $_GET['methodpayload'] : '', $preferredEncodings); + $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; diff --git a/debugger/controller.php b/debugger/controller.php index e58d2a44..2fd43070 100644 --- a/debugger/controller.php +++ b/debugger/controller.php @@ -13,7 +13,7 @@ **/ // 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'); +header('Content-Type: text/html; charset=utf-8'); include __DIR__ . '/common.php'; if ($action == '') { From eb00ccc94d22b89172a7dedff973da779875b9f3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 19 Apr 2015 23:03:43 +0100 Subject: [PATCH 159/228] Test if we can get faster tests for hhvm --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cb7fce80..efe4af90 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ after_failure: - cat apache_error.log - cat apache_access.log - cat /var/log/hhvm/error.log - - php -i + - if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then php -i; fi after_script: # Upload code-coverage to Scrutinizer From 0edbdbaa43d40da250ab8b9b548ce764a7ae884e Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 01:10:46 +0100 Subject: [PATCH 160/228] Add pakefile as replacement for makefile --- .gitignore | 2 +- composer.json | 3 +- pakefile.php | 189 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 pakefile.php diff --git a/.gitignore b/.gitignore index 70c1a68e..1305331a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,4 @@ composer.phar composer.lock /vendor/* /tests/coverage/* - +/build/* diff --git a/composer.json b/composer.json index 62d1129b..788aa993 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "phpunit/phpunit-selenium": "*", "codeclimate/php-test-reporter": "dev-master", "ext-curl": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "indeyets/pake": "~1.99" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", diff --git a/pakefile.php b/pakefile.php new file mode 100644 index 00000000..2ae9e357 --- /dev/null +++ b/pakefile.php @@ -0,0 +1,189 @@ + 1) + self::$sourceBranch = $args[1]; + + pake_echo('---'.self::$libVersion.'---'); + } +} + +} + +namespace { + +use PhpXmlRpc\Builder; + +function run_default($task=null, $args=array(), $cliOpts=array()) +{ + echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag]\n"; + echo "\n"; + echo " Run 'pake help' to list all pake options\n"; + echo " Run 'pake -T' to list all available tasks\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(); + $targetBranch = 'php53'; + + // 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::sourceRepo()) { + 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::sourceRepo(), Builder::workspaceDir()); + } + + $repo->checkout($targetBranch); +} + +/** + * 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()) +{ +} + +/** + * Generates documentation in all formats + */ +function run_doc($task=null, $args=array(), $cliOpts=array()) +{ + pake_echo('TBD...'); +} + +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 + 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 = '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); + } + } +} + +/** + * Cleans up the 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'); +pake_task('build', 'getopts', 'init', 'doc'); +pake_task('dist', 'getopts', 'init', 'build', 'clean-dist'); +pake_task('clean-dist', 'getopts'); +pake_task('clean', 'getopts'); + +} From 62fa838f6c3bababe376b75684d29c699f1fce31 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 02:32:42 +0100 Subject: [PATCH 161/228] Add generation of docs to pakefile --- Makefile | 125 ----------------------------------- NEWS | 2 + composer.json | 3 +- doc/Makefile | 80 ---------------------- doc/convert.php | 61 ----------------- doc/custom.fo.xsl | 2 +- doc/highlight.php | 43 ------------ pakefile.php | 164 +++++++++++++++++++++++++++++++++++++++++++--- 8 files changed, 160 insertions(+), 320 deletions(-) delete mode 100644 Makefile delete mode 100644 doc/Makefile delete mode 100644 doc/convert.php delete mode 100644 doc/highlight.php diff --git a/Makefile b/Makefile deleted file mode 100644 index c6d49850..00000000 --- a/Makefile +++ /dev/null @@ -1,125 +0,0 @@ -# Makefile for phpxmlrpc library - -### USER EDITABLE VARS - can be passed as command-line options ### - -# path to PHP executable, preferably CLI version -PHP=php - -# path were xmlrpc lib files will be copied to -PHPINCLUDEDIR=/usr/local/lib/php - -# mkdir is a thorny beast under windows: make sure we can not use the cmd version, running eg. "make MKDIR=mkdir.exe" -MKDIR=mkdir - -#find too -FIND=find - -DOS2UNIX=dos2unix - -#### DO NOT TOUCH FROM HERE ONWARDS ### - -# recover version number from code -# thanks to Firman Pribadi for unix command line help -# on unix shells lasts char should be \\2/g ) -export VERSION=$(shell grep -E "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g ) - -LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc \ - src/*.php src/Helper/*.php - -EXTRAFILES=extras/test.pl \ - extras/test.py \ - extras/rsakey.pem \ - extras/workspace.testPhpServer.fttb - -DEMOFILES=demo/vardemo.php \ - demo/demo1.xml \ - demo/demo2.xml \ - demo/demo3.xml - -DEMOSFILES=demo/server/discuss.php \ - demo/server/server.php \ - demo/server/proxy.php - -DEMOCFILES=demo/client/agesort.php \ - demo/client/client.php \ - demo/client/comment.php \ - demo/client/introspect.php \ - demo/client/mail.php \ - demo/client/simple_call.php \ - demo/client/which.php \ - demo/client/wrap.php \ - demo/client/zopetest.php - -TESTFILES=test/testsuite.php \ - tests/benchmark.php \ - tests/parse_args.php \ - test/InvalidHostTest.php \ - test/LocalHostTest.php \ - test/ParsingBugsTest.php \ - tests/verify_compat.php - -INFOFILES=Changelog \ - Makefile \ - NEWS \ - README - -DEBUGGERFILES=debugger/index.php \ - debugger/action.php \ - debugger/common.php \ - debugger/controller.php - - -all: install - -install: - cp ${LIBFILES} ${PHPINCLUDEDIR} - @echo Lib files have been copied to ${PHPINCLUDEDIR} - cd doc && $(MAKE) install - -test: - cd test && ${PHP} -q testsuite.php - - -### the following targets are to be used for library development ### - -# make tag target: tag existing working copy as release in git. -tag: - git tag v${VERSION} - git push origin --tags - -dist: xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz - -xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz: ${LIBFILES} ${DEBUGGERFILES} ${INFOFILES} ${TESTFILES} ${EXTRAFILES} ${DEMOFILES} ${DEMOSFILES} ${DEMOCFILES} - @echo ---${VERSION}--- - rm -rf xmlrpc-${VERSION} - ${MKDIR} xmlrpc-${VERSION} - ${MKDIR} xmlrpc-${VERSION}/demo - ${MKDIR} xmlrpc-${VERSION}/demo/client - ${MKDIR} xmlrpc-${VERSION}/demo/server - ${MKDIR} xmlrpc-${VERSION}/test - ${MKDIR} xmlrpc-${VERSION}/test/PHPUnit - ${MKDIR} xmlrpc-${VERSION}/extras - ${MKDIR} xmlrpc-${VERSION}/lib - ${MKDIR} xmlrpc-${VERSION}/debugger - cp --parents ${DEMOFILES} xmlrpc-${VERSION} - cp --parents ${DEMOCFILES} xmlrpc-${VERSION} - cp --parents ${DEMOSFILES} xmlrpc-${VERSION} - cp --parents ${TESTFILES} xmlrpc-${VERSION} - cp --parents ${EXTRAFILES} xmlrpc-${VERSION} - cp --parents ${LIBFILES} xmlrpc-${VERSION} - cp --parents ${DEBUGGERFILES} xmlrpc-${VERSION} - cp ${INFOFILES} xmlrpc-${VERSION} - cd doc && $(MAKE) dist -# on unix shells last char should be \; - ${FIND} xmlrpc-${VERSION} -type f ! -name "*.fttb" ! -name "*.pdf" ! -name "*.gif" -exec ${DOS2UNIX} ; - -rm xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz - tar -cvf xmlrpc-${VERSION}.tar xmlrpc-${VERSION} - gzip xmlrpc-${VERSION}.tar - zip -r xmlrpc-${VERSION}.zip xmlrpc-${VERSION} - -doc: - cd doc && $(MAKE) doc - -clean: - rm -rf xmlrpc-${VERSION} xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz - cd doc && $(MAKE) clean diff --git a/NEWS b/NEWS index 50624738..bba59f7d 100644 --- a/NEWS +++ b/NEWS @@ -62,6 +62,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. - 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 + XML-RPC for PHP version 3.0.0 - 2014/6/15 diff --git a/composer.json b/composer.json index 788aa993..8a6f29fb 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,8 @@ "codeclimate/php-test-reporter": "dev-master", "ext-curl": "*", "ext-mbstring": "*", - "indeyets/pake": "~1.99" + "indeyets/pake": "~1.99", + "phpdocumentor/phpdocumentor": "2.*" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", diff --git a/doc/Makefile b/doc/Makefile deleted file mode 100644 index 5a77386a..00000000 --- a/doc/Makefile +++ /dev/null @@ -1,80 +0,0 @@ - -### USER EDITABLE VARS ### - -WEB=/var/www/xmlrpc/doc - -MKDIR=mkdir - -PHP=php - -FOP=fop - -PHPDOC=phpdoc - - -#### DO NOT TOUCH FROM HERE ONWARDS ### - -install: - ${MKDIR} -p ${WEB} - cp *.html ${WEB} - cp *.css ${WEB} - cp *.gif ${WEB} - @echo HTML version of the manual has been installed to ${WEB} - - -### the following targets are to be used for library development ### - -doc: out/index.html xmlrpc_php.pdf javadoc-out/index.html - -# tools currently used in building docs: php 5 with xsl extension, apache fop, phpdocumentor -# alternatives include doxygen, jade, saxon, xsltproc etc... - -out/index.html xmlrpc_php.pdf: xmlrpc_php.xml - -${MKDIR} out -# 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 -# -# custom php script that does the xslt magic - ${PHP} convert.php xmlrpc_php.xml custom.xsl out/ -# post process html files to highlight php code samples - ${PHP} highlight.php out -# convert to fo and then to pdf using apache fop - ${PHP} convert.php xmlrpc_php.xml custom.fo.xsl xmlrpc_php.fo.xml - ${FOP} xmlrpc_php.fo.xml xmlrpc_php.pdf -# -rm xmlrpc_php.fo.xml - -javadoc-out/index.html: ../lib/xmlrpc.inc ../lib/xmlrpcs.inc ../lib/xmlrpc_wrappers.inc -# generate docs out of javadoc via doxygen -# doxygen phpxmlrpc.dox -# -# generate docs out of javadoc via phpdocumentor - ${PHP} ${PHPDOC} -f ../lib/xmlrpc.inc,../lib/xmlrpcs.inc,../lib/xmlrpc_wrappers.inc -t javadoc-out --title PHP-XMLRPC - -rm -rf javadoc-out/phpdoc-cache-* - -dist: doc - ${MKDIR} -p ../xmlrpc-${VERSION}/doc - -cp out/*.html ../xmlrpc-${VERSION}/doc - -cp out/*.css ../xmlrpc-${VERSION}/doc - -cp out/*.gif ../xmlrpc-${VERSION}/doc - -cp out/*.pdf ../xmlrpc-${VERSION}/doc - cp xmlrpc_php.xml ../xmlrpc-${VERSION}/doc - cp xmlrpc_php.pdf ../xmlrpc-${VERSION}/doc - cp Makefile ../xmlrpc-${VERSION}/doc - -clean: - -rm -f out/*.html - -rm -rf javadoc-out - -rm xmlrpc_php.fo.xml - -rm xmlrpc_php.pdf diff --git a/doc/convert.php b/doc/convert.php deleted file mode 100644 index a7e08cbc..00000000 --- a/doc/convert.php +++ /dev/null @@ -1,61 +0,0 @@ -load($doc); -$xsl = new DOMDocument(); -$xsl->load($xss); - -// Configure the transformer -$proc = 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')) { - $proc->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); - } else { - $proc->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE); - } -} -$proc->importStyleSheet($xsl); // attach the xsl rules - -//if ($_SERVER['argc'] >= 4) -//{ -if (is_dir($_SERVER['argv'][3])) { - if (!$proc->setParameter('', 'base.dir', realpath($_SERVER['argv'][3]))) { - echo "setting param base.dir KO\n"; - } -} else { - //echo "{$_SERVER['argv'][3]} is not a dir\n"; -} -//} - -$out = $proc->transformToXML($xml); -if (!is_dir($_SERVER['argv'][3])) { - file_put_contents($_SERVER['argv'][3], $out); -} - -echo "OK\n"; diff --git a/doc/custom.fo.xsl b/doc/custom.fo.xsl index 1fe0ddac..1ba937c1 100644 --- a/doc/custom.fo.xsl +++ b/doc/custom.fo.xsl @@ -12,7 +12,7 @@ - + diff --git a/doc/highlight.php b/doc/highlight.php deleted file mode 100644 index 750261bd..00000000 --- a/doc/highlight.php +++ /dev/null @@ -1,43 +0,0 @@ -'; - $endtag = ''; - - $content = file_get_contents($file); - $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('>', '<'), array('>', '<'), $code); - $code = highlight_string('<?php 
      ', '', $code); - - $out = $out . substr($content, $last, $start + strlen($starttag) - $last) . $code . $endtag; - $last = $end + strlen($endtag); - } - $out .= substr($content, $last, strlen($content)); - - return $out; -} - -$dir = $argv[1]; - -$files = scandir($dir); -foreach ($files as $file) { - if (substr($file, -5, 5) == '.html') { - $out = highlight($dir . '/' . $file); - file_put_contents($dir . '/' . $file, $out); - } -} diff --git a/pakefile.php b/pakefile.php index 2ae9e357..5b7386ba 100644 --- a/pakefile.php +++ b/pakefile.php @@ -3,7 +3,8 @@ * Makefile for phpxmlrpc library. * To be used with the Pake tool: https://github.com/indeyets/pake/wiki * - * @todo allow user to specify location for zip command + * @copyright (c) 2015 G. Giunta + * * @todo allow user to specify release number and tag/branch to use */ @@ -11,9 +12,14 @@ class Builder { - protected static $buildDir = 'build/'; + protected static $buildDir = 'build'; protected static $libVersion; protected static $sourceBranch = 'master'; + protected static $tools = array( + 'zip' => 'zip', + 'fop' => 'fop', + 'php' => 'php' + ); public static function libVersion() { @@ -27,13 +33,13 @@ public static function buildDir() public static function workspaceDir() { - return self::buildDir().'workspace'; + 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(); + return self::buildDir().'/xmlrpc-'.self::libVersion(); } /// these will be generated in BuildDir @@ -59,7 +65,96 @@ public static function getOpts($args=array(), $cliOpts=array()) if (count($args) > 1) self::$sourceBranch = $args[1]; - pake_echo('---'.self::$libVersion.'---'); + foreach (self::$tools as $name => $binary) { + if (isset($cliOpts[$name])) { + self::$tools[$name] = $cliOpts[$name]; + } + } + + //pake_echo('---'.self::$libVersion.'---'); + } + + public static function tool($name) + { + return self::$tools[$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 = '
      ';
      +        $endTag = '
      '; + + //$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('>', '<'), array('>', '<'), $code); + $code = highlight_string('<?php 
      ', '', $code); + + $out = $out . substr($content, $last, $start + strlen($startTag) - $last) . $code . $endTag; + $last = $end + strlen($endTag); + } + $out .= substr($content, $last, strlen($content)); + + return $out; } } @@ -71,10 +166,14 @@ public static function getOpts($args=array(), $cliOpts=array()) function run_default($task=null, $args=array(), $cliOpts=array()) { - echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag]\n"; + 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 all available tasks\n"; + echo " Task options:\n"; + echo " --php=\$php"; + echo " --fop=\$fop"; + echo " --zip=\$zip"; } function run_getopts($task=null, $args=array(), $cliOpts=array()) @@ -118,12 +217,56 @@ function run_build($task=null, $args=array(), $cliOpts=array()) { } +function run_clean_doc() +{ + pake_remove_dir(Builder::workspaceDir().'/doc/out'); + pake_remove_dir(Builder::workspaceDir().'/doc/javadoc-out'); +} + /** * Generates documentation in all formats */ function run_doc($task=null, $args=array(), $cliOpts=array()) { - pake_echo('TBD...'); + $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/javadoc-out --title PHP-XMLRPC'); + + # 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 + + pake_mkdirs($docDir.'/out'); + + // HTML files from docbook + + Builder::applyXslt($docDir.'/xmlrpc_php.xml', $docDir.'/custom.xsl', $docDir.'/out/'); + // post process html files to highlight php code samples + foreach(pakeFinder::type('file')->name('*.html')->in($docDir) 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.'/xmlrpc_php.xml', $docDir.'/custom.fo.xsl', $docDir.'/xmlrpc_php.fo.xml'); + $cmd = Builder::tool('fop'); + pake_sh("$cmd $docDir/xmlrpc_php.fo.xml $docDir/xmlrpc_php.pdf"); + unlink($docDir.'/xmlrpc_php.fo.xml'); } function run_clean_dist() @@ -148,11 +291,12 @@ function run_dist($task=null, $args=array(), $cliOpts=array()) // 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 = 'zip'; + $cmd = Builder::tool('zip'); $extra = '-9 -r'; pake_sh("$cmd $distFile $extra ".basename(Builder::distDir())); } @@ -164,6 +308,7 @@ function run_dist($task=null, $args=array(), $cliOpts=array()) rename($pharFile, $distFile); } } + chdir($cwd); } /** @@ -180,9 +325,10 @@ function run_clean($task=null, $args=array(), $cliOpts=array()) // internal task: parse cli options pake_task('getopts'); pake_task('init', 'getopts'); -pake_task('doc', 'getopts', 'init'); +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', 'getopts'); From b6bd997767fed557f15f052c9f188d54e8dc2656 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 02:33:24 +0100 Subject: [PATCH 162/228] More readme tags to display on github --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f611c959..b0d323b4 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,3 @@ -[![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) - XMLRPC for PHP ============== A php library for building xml-rpc clients and servers. @@ -18,3 +14,12 @@ Use of this software is subject to the terms in doc/index.html SSL-certificate --------------- The passphrase for the rsakey.pem certificate is 'test'. + + +[![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) +[![License](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/license)](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) From 3f58e3cf14f75d513f08242d0535411ba1af2f4a Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 02:36:19 +0100 Subject: [PATCH 163/228] Install the docbook xslts via composer for doc generation --- composer.json | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 8a6f29fb..58c3d40b 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ "ext-curl": "*", "ext-mbstring": "*", "indeyets/pake": "~1.99", - "phpdocumentor/phpdocumentor": "2.*" + "phpdocumentor/phpdocumentor": "2.*", + "docbook/docbook-xsl": "~1.78" }, "suggest": { "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...", @@ -24,5 +25,18 @@ }, "autoload": { "psr-4": {"PhpXmlRpc\\": "src/"} - } + }, + "repositories": [ + { + "type": "package", + "package": { + "name": "docbook/docbook-xsl", + "version": "1.78.1", + "dist": { + "url": "http://sourceforge.net/projects/docbook/files/docbook-xsl/1.78.1/docbook-xsl-1.78.1.zip/download", + "type": "zip" + } + } + } + ] } From 52d0fcaf30f8185b1bf3e069eb065264bffb26f5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 02:50:07 +0100 Subject: [PATCH 164/228] Remove gitignore from docs dir, as we now build in a separate directory --- doc/.gitignore | 4 ---- pakefile.php | 1 + 2 files changed, 1 insertion(+), 4 deletions(-) delete mode 100644 doc/.gitignore diff --git a/doc/.gitignore b/doc/.gitignore deleted file mode 100644 index bace1405..00000000 --- a/doc/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -out/ -javadoc-out/ -xmlrpc_php.pdf -xmlrpc_php.fo.xml diff --git a/pakefile.php b/pakefile.php index 5b7386ba..6866f58f 100644 --- a/pakefile.php +++ b/pakefile.php @@ -6,6 +6,7 @@ * @copyright (c) 2015 G. Giunta * * @todo allow user to specify release number and tag/branch to use + * @todo !important allow user to specify location of docbook xslt instead of the one installed via composer */ namespace PhpXmlRpc { From 101184f00f6c8cf8487cab10f05af7ec6914222e Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 21:49:08 +0100 Subject: [PATCH 165/228] Restructure the documentation folder; add more options to makefile --- README.md | 5 +- doc/{ => build}/custom.fo.xsl | 204 +++++++++--------- doc/{ => build}/custom.xsl | 2 +- doc/custom.dsl | 25 --- .../css-docbook}/COPYING | 34 +-- .../css-docbook}/CREDITS | 20 +- .../css-docbook}/core.css | 0 .../css-docbook}/db-bindings.xml | 62 +++--- .../css-docbook}/driver.css | 0 .../css-docbook}/l10n.css | 0 .../css-docbook}/l10n/de.css | 0 .../css-docbook}/l10n/en.css | 0 .../css-docbook}/l10n/es.css | 0 .../css-docbook}/l10n/pl.css | 0 .../css-docbook}/mozilla.css | 0 .../css-docbook}/opera.css | 0 .../css-docbook}/styles.css | 0 .../css-docbook}/tables.css | 0 .../css-docbook}/xmlrpc.css | 0 doc/{ => manual/images}/debugger.gif | Bin doc/{ => manual/images}/progxmlrpc.s.gif | Bin .../phpxmlrpc_manual.xml} | 6 +- pakefile.php | 75 ++++--- 23 files changed, 216 insertions(+), 217 deletions(-) rename doc/{ => build}/custom.fo.xsl (93%) rename doc/{ => build}/custom.xsl (97%) delete mode 100644 doc/custom.dsl rename doc/{docbook-css => manual/css-docbook}/COPYING (98%) rename doc/{docbook-css => manual/css-docbook}/CREDITS (95%) rename doc/{docbook-css => manual/css-docbook}/core.css (100%) rename doc/{docbook-css => manual/css-docbook}/db-bindings.xml (96%) rename doc/{docbook-css => manual/css-docbook}/driver.css (100%) rename doc/{docbook-css => manual/css-docbook}/l10n.css (100%) rename doc/{docbook-css => manual/css-docbook}/l10n/de.css (100%) rename doc/{docbook-css => manual/css-docbook}/l10n/en.css (100%) rename doc/{docbook-css => manual/css-docbook}/l10n/es.css (100%) rename doc/{docbook-css => manual/css-docbook}/l10n/pl.css (100%) rename doc/{docbook-css => manual/css-docbook}/mozilla.css (100%) rename doc/{docbook-css => manual/css-docbook}/opera.css (100%) rename doc/{docbook-css => manual/css-docbook}/styles.css (100%) rename doc/{docbook-css => manual/css-docbook}/tables.css (100%) rename doc/{docbook-css => manual/css-docbook}/xmlrpc.css (100%) rename doc/{ => manual/images}/debugger.gif (100%) rename doc/{ => manual/images}/progxmlrpc.s.gif (100%) rename doc/{xmlrpc_php.xml => manual/phpxmlrpc_manual.xml} (99%) diff --git a/README.md b/README.md index b0d323b4..dfc96311 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,9 @@ Installation instructions are in the [INSTALL.md](INSTALL.md) file. Docs ---- -The manual, in HTML and pdf versions, can be found in the doc/ directory. -Use of this software is subject to the terms in doc/index.html +The manual can be found in the doc/manual directory, in HTML and PDF versions for release tarballs and Docbook always. + +Use of this software is subject to the terms in the [license.txt](license.txt) file SSL-certificate --------------- diff --git a/doc/custom.fo.xsl b/doc/build/custom.fo.xsl similarity index 93% rename from doc/custom.fo.xsl rename to doc/build/custom.fo.xsl index 1ba937c1..b1964c0c 100644 --- a/doc/custom.fo.xsl +++ b/doc/build/custom.fo.xsl @@ -1,103 +1,103 @@ - - - - - - - - - - -1 -no -ansi -0 -1 -php -A4 -1 - - - 80% - - - - - - - - - - - - - - - - - - - - - - - - - - - ( void ) - - - ( ) - - - - - - ( ... ) - - - - - - - ( - - - - - - - - - - - , - - - ) - - - - - - - - - - - - = - - - - + + + + + + + + + + +1 +no +ansi +0 +1 +php +A4 +1 + + + 80% + + + + + + + + + + + + + + + + + + + + + + + + + + + ( void ) + + + ( ) + + + + + + ( ... ) + + + + + + + ( + + + + + + + + + + + , + + + ) + + + + + + + + + + + + = + + + + \ No newline at end of file diff --git a/doc/custom.xsl b/doc/build/custom.xsl similarity index 97% rename from doc/custom.xsl rename to doc/build/custom.xsl index f648887a..aed8d5eb 100644 --- a/doc/custom.xsl +++ b/doc/build/custom.xsl @@ -15,7 +15,7 @@ - + diff --git a/doc/custom.dsl b/doc/custom.dsl deleted file mode 100644 index b3b35ce7..00000000 --- a/doc/custom.dsl +++ /dev/null @@ -1,25 +0,0 @@ - -]> - - - - - -(define %link-mailto-url% - "edd@usefulinc.com") - -(define %html-ext% - ".html") - -(define %use-id-as-filename% - #t) - -(define %root-filename% - "index") - - - - - - diff --git a/doc/docbook-css/COPYING b/doc/manual/css-docbook/COPYING similarity index 98% rename from doc/docbook-css/COPYING rename to doc/manual/css-docbook/COPYING index d199ddcd..735dca1d 100644 --- a/doc/docbook-css/COPYING +++ b/doc/manual/css-docbook/COPYING @@ -1,17 +1,17 @@ -Copyright (c) 2004 David Holroyd, and contributors. - -Permission to use, copy, modify and distribute this software and its -documentation for any purpose and without fee is hereby granted in -perpetuity, provided that the above copyright notice appear in all -copies, and that both the copyright notice and this permission notice -appear in supporting documentation. The contributors make no -representations about the suitability of this software for any -purpose. It is provided "as is" without express or implied warranty. - -THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER -RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +Copyright (c) 2004 David Holroyd, and contributors. + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted in +perpetuity, provided that the above copyright notice appear in all +copies, and that both the copyright notice and this permission notice +appear in supporting documentation. The contributors make no +representations about the suitability of this software for any +purpose. It is provided "as is" without express or implied warranty. + +THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER +RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/doc/docbook-css/CREDITS b/doc/manual/css-docbook/CREDITS similarity index 95% rename from doc/docbook-css/CREDITS rename to doc/manual/css-docbook/CREDITS index 08d96c57..cbc51ee7 100644 --- a/doc/docbook-css/CREDITS +++ b/doc/manual/css-docbook/CREDITS @@ -1,10 +1,10 @@ -This stylesheet was writen by David Holroyd, with patches, suggestions, -translations, and other help from these people: - - David Leppik - Martin Gautier - Asia Magiera - Federico Koessler - Katie McSweenie - -Many thanks to all of them! +This stylesheet was writen by David Holroyd, with patches, suggestions, +translations, and other help from these people: + + David Leppik + Martin Gautier + Asia Magiera + Federico Koessler + Katie McSweenie + +Many thanks to all of them! diff --git a/doc/docbook-css/core.css b/doc/manual/css-docbook/core.css similarity index 100% rename from doc/docbook-css/core.css rename to doc/manual/css-docbook/core.css diff --git a/doc/docbook-css/db-bindings.xml b/doc/manual/css-docbook/db-bindings.xml similarity index 96% rename from doc/docbook-css/db-bindings.xml rename to doc/manual/css-docbook/db-bindings.xml index cb575fd3..f3c0059e 100644 --- a/doc/docbook-css/db-bindings.xml +++ b/doc/manual/css-docbook/db-bindings.xml @@ -1,31 +1,31 @@ - - - - - - - - - - - - - - - - - - var img = document.getAnonymousNodes(this)[0]; - var file = this.getAttribute("fileref"); - // HACK: using img.src=file 'inline' doesn't seem to work - // but it does when called from a setTimeout() - var f = function() { img.src = file; } - setTimeout(f, 0); - - - - + + + + + + + + + + + + + + + + + + var img = document.getAnonymousNodes(this)[0]; + var file = this.getAttribute("fileref"); + // HACK: using img.src=file 'inline' doesn't seem to work + // but it does when called from a setTimeout() + var f = function() { img.src = file; } + setTimeout(f, 0); + + + + diff --git a/doc/docbook-css/driver.css b/doc/manual/css-docbook/driver.css similarity index 100% rename from doc/docbook-css/driver.css rename to doc/manual/css-docbook/driver.css diff --git a/doc/docbook-css/l10n.css b/doc/manual/css-docbook/l10n.css similarity index 100% rename from doc/docbook-css/l10n.css rename to doc/manual/css-docbook/l10n.css diff --git a/doc/docbook-css/l10n/de.css b/doc/manual/css-docbook/l10n/de.css similarity index 100% rename from doc/docbook-css/l10n/de.css rename to doc/manual/css-docbook/l10n/de.css diff --git a/doc/docbook-css/l10n/en.css b/doc/manual/css-docbook/l10n/en.css similarity index 100% rename from doc/docbook-css/l10n/en.css rename to doc/manual/css-docbook/l10n/en.css diff --git a/doc/docbook-css/l10n/es.css b/doc/manual/css-docbook/l10n/es.css similarity index 100% rename from doc/docbook-css/l10n/es.css rename to doc/manual/css-docbook/l10n/es.css diff --git a/doc/docbook-css/l10n/pl.css b/doc/manual/css-docbook/l10n/pl.css similarity index 100% rename from doc/docbook-css/l10n/pl.css rename to doc/manual/css-docbook/l10n/pl.css diff --git a/doc/docbook-css/mozilla.css b/doc/manual/css-docbook/mozilla.css similarity index 100% rename from doc/docbook-css/mozilla.css rename to doc/manual/css-docbook/mozilla.css diff --git a/doc/docbook-css/opera.css b/doc/manual/css-docbook/opera.css similarity index 100% rename from doc/docbook-css/opera.css rename to doc/manual/css-docbook/opera.css diff --git a/doc/docbook-css/styles.css b/doc/manual/css-docbook/styles.css similarity index 100% rename from doc/docbook-css/styles.css rename to doc/manual/css-docbook/styles.css diff --git a/doc/docbook-css/tables.css b/doc/manual/css-docbook/tables.css similarity index 100% rename from doc/docbook-css/tables.css rename to doc/manual/css-docbook/tables.css diff --git a/doc/docbook-css/xmlrpc.css b/doc/manual/css-docbook/xmlrpc.css similarity index 100% rename from doc/docbook-css/xmlrpc.css rename to doc/manual/css-docbook/xmlrpc.css diff --git a/doc/debugger.gif b/doc/manual/images/debugger.gif similarity index 100% rename from doc/debugger.gif rename to doc/manual/images/debugger.gif diff --git a/doc/progxmlrpc.s.gif b/doc/manual/images/progxmlrpc.s.gif similarity index 100% rename from doc/progxmlrpc.s.gif rename to doc/manual/images/progxmlrpc.s.gif diff --git a/doc/xmlrpc_php.xml b/doc/manual/phpxmlrpc_manual.xml similarity index 99% rename from doc/xmlrpc_php.xml rename to doc/manual/phpxmlrpc_manual.xml index 363f8a73..5c69ba7e 100644 --- a/doc/xmlrpc_php.xml +++ b/doc/manual/phpxmlrpc_manual.xml @@ -1,5 +1,5 @@ - + - + diff --git a/doc/build/custom.xsl b/doc/build/custom.xsl index aed8d5eb..c96cf558 100644 --- a/doc/build/custom.xsl +++ b/doc/build/custom.xsl @@ -15,7 +15,7 @@ - + diff --git a/pakefile.php b/pakefile.php index 09f060f3..35a33013 100644 --- a/pakefile.php +++ b/pakefile.php @@ -283,7 +283,7 @@ function run_doc($task=null, $args=array(), $cliOpts=array()) // 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/phpxmlrpc_manual.fo.xml $docDir/phpxmlrpc_manual.pdf"); + pake_sh("$cmd $docDir/manual/phpxmlrpc_manual.fo.xml $docDir/manual/phpxmlrpc_manual.pdf"); unlink($docDir.'/manual/phpxmlrpc_manual.fo.xml'); } From 228f56e3bb4f5457507d67eeebb0e525d4817d2d Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 22:01:29 +0100 Subject: [PATCH 167/228] one more doc build fix --- doc/build/custom.xsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/build/custom.xsl b/doc/build/custom.xsl index c96cf558..5d704ecd 100644 --- a/doc/build/custom.xsl +++ b/doc/build/custom.xsl @@ -15,7 +15,7 @@ - + From e1923b6d55b69e592b2fba8ce0f097751416823e Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 27 Apr 2015 22:41:03 +0100 Subject: [PATCH 168/228] try again fixing xsl paths for docs --- doc/build/custom.fo.xsl | 2 +- doc/build/custom.xsl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/build/custom.fo.xsl b/doc/build/custom.fo.xsl index 0d73049a..b1964c0c 100644 --- a/doc/build/custom.fo.xsl +++ b/doc/build/custom.fo.xsl @@ -12,7 +12,7 @@ - + diff --git a/doc/build/custom.xsl b/doc/build/custom.xsl index 5d704ecd..c96cf558 100644 --- a/doc/build/custom.xsl +++ b/doc/build/custom.xsl @@ -15,7 +15,7 @@ - + From f140ea8aba41c3628c0e5e729d072729d3353558 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 29 Apr 2015 00:20:41 +0100 Subject: [PATCH 169/228] Move to asciidoc as principal documentation format --- doc/manual/css-docbook/COPYING | 17 - doc/manual/css-docbook/CREDITS | 10 - doc/manual/css-docbook/core.css | 70 - doc/manual/css-docbook/db-bindings.xml | 31 - doc/manual/css-docbook/driver.css | 31 - doc/manual/css-docbook/l10n.css | 24 - doc/manual/css-docbook/l10n/de.css | 37 - doc/manual/css-docbook/l10n/en.css | 48 - doc/manual/css-docbook/l10n/es.css | 39 - doc/manual/css-docbook/l10n/pl.css | 44 - doc/manual/css-docbook/mozilla.css | 44 - doc/manual/css-docbook/opera.css | 33 - doc/manual/css-docbook/styles.css | 641 ---- doc/manual/css-docbook/tables.css | 59 - doc/manual/css-docbook/xmlrpc.css | 42 - doc/manual/phpxmlrpc_manual.adoc | 3117 +++++++++++++++++ doc/manual/phpxmlrpc_manual.xml | 4274 ------------------------ pakefile.php | 49 +- 18 files changed, 3148 insertions(+), 5462 deletions(-) delete mode 100644 doc/manual/css-docbook/COPYING delete mode 100644 doc/manual/css-docbook/CREDITS delete mode 100644 doc/manual/css-docbook/core.css delete mode 100644 doc/manual/css-docbook/db-bindings.xml delete mode 100644 doc/manual/css-docbook/driver.css delete mode 100644 doc/manual/css-docbook/l10n.css delete mode 100644 doc/manual/css-docbook/l10n/de.css delete mode 100644 doc/manual/css-docbook/l10n/en.css delete mode 100644 doc/manual/css-docbook/l10n/es.css delete mode 100644 doc/manual/css-docbook/l10n/pl.css delete mode 100644 doc/manual/css-docbook/mozilla.css delete mode 100644 doc/manual/css-docbook/opera.css delete mode 100644 doc/manual/css-docbook/styles.css delete mode 100644 doc/manual/css-docbook/tables.css delete mode 100644 doc/manual/css-docbook/xmlrpc.css create mode 100644 doc/manual/phpxmlrpc_manual.adoc delete mode 100644 doc/manual/phpxmlrpc_manual.xml diff --git a/doc/manual/css-docbook/COPYING b/doc/manual/css-docbook/COPYING deleted file mode 100644 index 735dca1d..00000000 --- a/doc/manual/css-docbook/COPYING +++ /dev/null @@ -1,17 +0,0 @@ -Copyright (c) 2004 David Holroyd, and contributors. - -Permission to use, copy, modify and distribute this software and its -documentation for any purpose and without fee is hereby granted in -perpetuity, provided that the above copyright notice appear in all -copies, and that both the copyright notice and this permission notice -appear in supporting documentation. The contributors make no -representations about the suitability of this software for any -purpose. It is provided "as is" without express or implied warranty. - -THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER -RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/doc/manual/css-docbook/CREDITS b/doc/manual/css-docbook/CREDITS deleted file mode 100644 index cbc51ee7..00000000 --- a/doc/manual/css-docbook/CREDITS +++ /dev/null @@ -1,10 +0,0 @@ -This stylesheet was writen by David Holroyd, with patches, suggestions, -translations, and other help from these people: - - David Leppik - Martin Gautier - Asia Magiera - Federico Koessler - Katie McSweenie - -Many thanks to all of them! diff --git a/doc/manual/css-docbook/core.css b/doc/manual/css-docbook/core.css deleted file mode 100644 index d9d4ba02..00000000 --- a/doc/manual/css-docbook/core.css +++ /dev/null @@ -1,70 +0,0 @@ -/* - * core.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -/* Generated 2002-12-12 */ -abbrev, accel, acronym, action, application, artpagenums, authorinitials, -bibliocoverage, biblioid, bibliomisc, bibliorelation, bibliosource, citation, -citebiblioid, citerefentry, citetitle, city, classname, co, command, -computeroutput, constant, coref, country, database, date, email, emphasis, -envar, errorcode, errorname, errortext, errortype, exceptionname, fax, -filename, firstname, firstterm, funcdef, funcparams, function, group, -guibutton, guiicon, guilabel, guimenu, guimenuitem, guisubmenu, hardware, -honorific, initializer, inlineequation, inlinegraphic, inlinemediaobject, -interface, interfacename, invpartnumber, isbn, issn, keycap, keycode, -keycombo, keysym, lineage, lineannotation, link, literal, markup, medialabel, -member, menuchoice, methodname, methodparam, modifier, mousebutton, olink, -ooclass, ooexception, oointerface, option, optional, orgdiv, orgname, -otheraddr, othername, pagenums, paramdef, parameter, phone, phrase, pob, -postcode, productname, productnumber, prompt, property, pubdate, pubsnumber, -quote, refpurpose, replaceable, returnvalue, revnumber, seriesvolnums, -sgmltag, shortcut, state, street, structfield, structname, subscript, -superscript, surname, symbol, systemitem, token, trademark, type, ulink, -userinput, varname, volumenum, wordasword, year { - display:inline; -} - -abstract, ackno, address, answer, appendix, article, attribution, authorblurb, -bibliodiv, biblioentry, bibliography, bibliomixed, bibliomset, biblioset, -blockquote, book, callout, calloutlist, caption, caution, chapter, -cmdsynopsis, colophon, constraintdef, dedication, epigraph, equation, example, -figure, formalpara, glossary, glossdef, glossdiv, glossentry, glosslist, -graphic, graphicco, highlights, imagedata, imageobjectco, important, index, -indexdiv, indexentry, informalequation, informalexample, informalfigure, -informaltable, itemizedlist, legalnotice, listitem, lot, lotentry, -mediaobject, mediaobjectco, msg, msgentry, msgexplan, msgmain, msgset, note, -orderedlist, para, part, partintro, personblurb, preface, primaryie, -printhistory, procedure, productionset, programlistingco, qandadiv, qandaentry, -qandaset, question, refentry, refentrytitle, reference, refnamediv, refsect1, -refsect2, refsect3, refsection, refsynopsisdiv, revhistory, screenco, -screenshot, secondaryie, sect2, sect3, sect4, sect5, section, seealsoie, seeie, -set, setindex, sidebar, simpara, simplemsgentry, simplesect, step, substeps, -subtitle, synopfragment, synopfragmentref, table, term, tertiaryie, tip, -title, toc, tocback, tocchap, tocentry, tocfront, toclevel1, toclevel2, -toclevel3, toclevel4, toclevel5, tocpart, variablelist, varlistentry, warning, -sect1 { - display:block; -} - -appendixinfo, area, areaset, areaspec, articleinfo, bibliographyinfo, -blockinfo, bookinfo, chapterinfo, colspec, glossaryinfo, indexinfo, indexterm, -itermset, modespec, objectinfo, partinfo, prefaceinfo, primary, refentryinfo, -referenceinfo, refmeta, refsect1info, refsect2info, refsect3info, -refsectioninfo, refsynopsisdivinfo, screeninfo, secondary, sect1info, -sect2info, sect3info, sect4info, sect5info, sectioninfo, see, seealso, -setindexinfo, setinfo, sidebarinfo, spanspec, tertiary { - display:none; -} - -classsynopsisinfo, funcsynopsisinfo, literallayout, programlisting, screen, -synopsis { - white-space:pre; - font-family:monospace; - display:block; -} diff --git a/doc/manual/css-docbook/db-bindings.xml b/doc/manual/css-docbook/db-bindings.xml deleted file mode 100644 index f3c0059e..00000000 --- a/doc/manual/css-docbook/db-bindings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - var img = document.getAnonymousNodes(this)[0]; - var file = this.getAttribute("fileref"); - // HACK: using img.src=file 'inline' doesn't seem to work - // but it does when called from a setTimeout() - var f = function() { img.src = file; } - setTimeout(f, 0); - - - - diff --git a/doc/manual/css-docbook/driver.css b/doc/manual/css-docbook/driver.css deleted file mode 100644 index 1e7a2de7..00000000 --- a/doc/manual/css-docbook/driver.css +++ /dev/null @@ -1,31 +0,0 @@ -/* - * driver.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - * - * This is the 'driver' file of the stylesheet. It imports all the major - * stylesheet components. If you want to make use of this stylesheet in your - * XML document (e.g. for display in a web browser), include a line like this - * at the top of the XML file (replacing with the version number): - * - * /driver.css" type="text/css"?> - * - * If you want to customise the stylesheet, a customisation layer can be - * created by simply witing a new CSS file, and including a declaration to - * import this file at the top. The customisation layer can then override any - * of the existing stylesheet rules, or create new ones. - */ - -/* add xmlrpc css customizations... */ -@import "xmlrpc.css"; - -@import "core.css"; -@import "tables.css"; -@import "styles.css"; -@import "l10n.css"; -@import "mozilla.css"; -@import "opera.css"; diff --git a/doc/manual/css-docbook/l10n.css b/doc/manual/css-docbook/l10n.css deleted file mode 100644 index caeaa03b..00000000 --- a/doc/manual/css-docbook/l10n.css +++ /dev/null @@ -1,24 +0,0 @@ -/* - * i10n.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - * - * This file deals with localisation ('l10n') of CSS generated content by - * delegating to each of the locale-specific files in the l10n directory. - */ - - -/* - * 'en' doesn't specify 'lang()' selectors, so its settings will be the - * default where no localisation is available for a particular language. - * It must come first; other lauguages override it. - */ -@import "l10n/en.css"; - -@import "l10n/pl.css"; -@import "l10n/de.css"; -@import "l10n/es.css"; diff --git a/doc/manual/css-docbook/l10n/de.css b/doc/manual/css-docbook/l10n/de.css deleted file mode 100644 index 261be583..00000000 --- a/doc/manual/css-docbook/l10n/de.css +++ /dev/null @@ -1,37 +0,0 @@ -@charset "utf-8"; -/* - * l10n/de.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -question:lang(de):before { - content: "F: "; -} -answer:lang(de):before { - content: "A: "; -} - -example > title:lang(de):before { - content: "Beispiel: "; -} - -warning:lang(de):before { - content: "Warnung: "; -} -caution:lang(de):before { - content: "Achtung: "; -} -important:lang(de):before { - content: "Wichtig: "; -} -tip:lang(de):before { - content: "Hinweis: "; -} -note:lang(de):before { - content: "Erläuterung: "; -} diff --git a/doc/manual/css-docbook/l10n/en.css b/doc/manual/css-docbook/l10n/en.css deleted file mode 100644 index 497e5f52..00000000 --- a/doc/manual/css-docbook/l10n/en.css +++ /dev/null @@ -1,48 +0,0 @@ -@charset "utf-8"; -/* - * l10n/en.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -/* Generated content for English documents */ - -question:before { - content: "Q: "; -} -answer:before { - content: "A: "; -} - -example > title:before { - content: "Example: "; -} - -quote { - quotes: "“" "”"; -} -quote quote { - quotes: "‘" "’"; -} - -/* Admonitions */ - -warning:before { - content: "Warning: "; -} -caution:before { - content: "Caution: "; -} -important:before { - content: "Important: "; -} -tip:before { - content: "Tip: "; -} -note:before { - content: "Note: "; -} diff --git a/doc/manual/css-docbook/l10n/es.css b/doc/manual/css-docbook/l10n/es.css deleted file mode 100644 index 9b435fd7..00000000 --- a/doc/manual/css-docbook/l10n/es.css +++ /dev/null @@ -1,39 +0,0 @@ -@charset "utf-8"; -/* - * l10n/es.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -question:lang(es):before { - content: "P: "; -} -answer:lang(es):before { - content: "R: "; -} - -example > title:lang(es):before { - content: "Ejemplo: "; -} - - -warning:lang(es):before { - content: "Aviso: "; -} -caution:lang(es):before { - content: "Atención: "; -} -important:lang(es):before { - content: "Importante: "; -} -tip:lang(es):before { - content: "Consejo: "; -} -note:lang(es):before { - content: "Nota: "; -} - diff --git a/doc/manual/css-docbook/l10n/pl.css b/doc/manual/css-docbook/l10n/pl.css deleted file mode 100644 index 7e3504f1..00000000 --- a/doc/manual/css-docbook/l10n/pl.css +++ /dev/null @@ -1,44 +0,0 @@ -@charset "utf-8"; -/* - * l10n/pl.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -question:lang(pl):before { - content: "P: "; -} -answer:lang(pl):before { - content: "O: "; -} - -example > title:lang(pl):before { - content: "Przykład: "; -} - -:lang(pl) > quote { - quotes: "„" "”"; -} -:lang(pl) > quote quote { - quotes: "«" "»"; -} - -warning:lang(pl):before { - content: "Ostrzeżenie: "; -} -caution:lang(pl):before { - content: "Uwaga: "; -} -important:lang(pl):before { - content: "Ważne: "; -} -tip:lang(pl):before { - content: "Pomoc: "; -} -note:lang(pl):before { - content: "Notatka: "; -} diff --git a/doc/manual/css-docbook/mozilla.css b/doc/manual/css-docbook/mozilla.css deleted file mode 100644 index 4f15519f..00000000 --- a/doc/manual/css-docbook/mozilla.css +++ /dev/null @@ -1,44 +0,0 @@ -/* - * mozilla.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - * - * This file contains CSS specific to mozilla.org's Gecko rendering engine. - * - * Some of the rules here will take effect even if you aren't using a Mozilla- - * based browser. - */ - - -/* make s clickable */ -ulink { - -moz-binding:url('db-bindings.xml#ulink'); - cursor: pointer; - -moz-user-focus: normal; -} - -ulink:active { - color: red; -} - -ulink:focus { - -moz-outline: 1px dotted invert; -} - -imagedata { - -moz-binding:url('db-bindings.xml#image'); -} - - -guimenu, guimenuitem, guisubmenu { - font: menu; -} - -orderedlist, itemizedlist, procedure { - /* this seems to be required to make auto-numbering work */ - -moz-counter-reset: -html-counter 0; -} diff --git a/doc/manual/css-docbook/opera.css b/doc/manual/css-docbook/opera.css deleted file mode 100644 index a00a7c2a..00000000 --- a/doc/manual/css-docbook/opera.css +++ /dev/null @@ -1,33 +0,0 @@ -/* - * opera.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - * - * This file contains CSS specific to the Opera browser. - */ - -/* - * Discovered -o-link from, - * http://groups.google.com/groups?q=opera+styles+xml&start=10&hl=en&lr=&ie=UTF-8&newwindow=1&selm=opr6pgr0tgicz8n2%40news.opera.com&rnum=18 - */ -ulink { - -o-link: attr(url); - -o-link-source: current; -} - -/* - * Given the above rule, it makes sense to have this here too, though it's - * not Opera-specific - */ -ulink:focus { - outline: 1px dotted invert; -} - -/* this was in the example I found, but it doesn't achive much */ -imagedata { - -o-replace: attr(fileref) -} diff --git a/doc/manual/css-docbook/styles.css b/doc/manual/css-docbook/styles.css deleted file mode 100644 index fae29b72..00000000 --- a/doc/manual/css-docbook/styles.css +++ /dev/null @@ -1,641 +0,0 @@ -/* - * styles.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - */ - -/* - * CSS2 styling for DocBook XML - * - * To be included in the cascade _after_ core.css. Defines styling that can't - * be generated mechanically from another source. - */ - -/* - * TODO: - * - * - do I remember correctly that be hidden for screen media? - */ - - -article, book { - margin:.5em; -} -title, subtitle { - font-family:sans-serif; -} -title { - font-weight:bolder; - margin-bottom:.5em; -} - -/* - * Sectioning elements that may contain paragraph-level elements get left/right - * margins - */ -section>*, chapter>*, bibliography>*, appendix>*, glossary>*, preface>*, -dedication>*, colophon>*, sect1>*, sect2>*, sect3>*, sect4>*, sect5>*, -bibliodiv>* { - margin-left:10%; - margin-right:10%; -} - -/* - * Give admonitions bigger margins, to set them more apart from the main - * flow of text. - */ -warning, caution, important, tip, note { - margin-left: 15%; - margin-right: 15%; -} - -/* - * Remove any margin defined be the previous rule when the child in question - * is a section or title. Titles should be allowed to take up the maximum - * available width, as they're usually is larger type. Sections must not - * be given margins because, the *contents* of the section will alreay have - * them; we don't want to recursively increase margins with the nesting depth - * of the document. - */ -section, title, sect1, sect2, sect3, sect4, sect5, bibliodiv { - margin-left:0; - margin-right:0; -} - -book>title, article>title { - font-size:xx-large; - text-align:center; - border-bottom-style:solid; -} - -appendix>title, bibliography>title, chapter>title, colophon>title, dedication>title, glossary>title, part>title, preface>title { - font-size:xx-large; - text-align:center; -} - -section>title, sect1>title, bibliodiv>title { - font-size:xx-large; -} - -section>section>title, sect2>title { - font-size:x-large; - margin-left:5%; -} - -section>section>section>title, sect3>title { - font-size:large; - margin-left:7.5%; -} - -section>section>section>section>title, sect4>title { - font-size:large; - margin-left:10%; -} - -section>section>section>section>section>title, sect5>title { - font-size:inherit; - margin-left:10%; -} - -biblioentry > title { - display: inline; -} - -/* Give vertical spacing between compoments of the document */ - -*+section, *+chapter, *+bibliography, *+bibliodiv, *+appendix, *+glossary { - margin-top: 3em; -} -section>*+section { - margin-top: 2em; -} -section>section>*+section { - margin-top: 1em; -} - - -/* - * Give paragraph-level elements some leading space when they aren't the first - * item in their containing block. - */ -*+para, *+formalpara, *+blockquote, *+glossentry, *+table, *+variablelist, -*+example, *+informalexample, *+programlisting, *+cmdsynopsis, -*+orderedlist, *+itemizedlist, *+figure, -*>warning, *>caution, *>important, *>tip, *>note { - margin-top:.5em; -} - - -/* - * BiblioEntry blocks need a bit more space, since they may contain multiple - * paragraphs, and so need greater-than-paragraph spacing to make it clear - * which gap is the end just of a paragraph, and which gap is the end of the - * entry - */ -*+biblioentry { - margin-top: 1em; -} - -/* - * REVISIT: I think this is the proper way; but deson't work in Firefox 0.8 - -formalpara > title { - display: run-in; -} - - * Make all children of formalpara inline, instead... - */ - -formalpara > * { - display: inline; -} - -formalpara > title:after { - content: "."; -} - -para, formalpara { - text-align: justify; -} - -quote:before { - content: open-quote; -} - -quote:after { - content: close-quote; -} - -question, answer { - margin-top:.5em; - display:list-item; -} - -question>para, answer>para { - display:inline; -} - -/* see language specific files for content */ -question:before { - display:marker; - font-weight:bolder; -} -answer:before { - display:marker; - font-weight: bolder; -} - -emphasis { - font-style:italic; -} -emphasis[role="strong"] { - font-weight:bolder; -} -emphasis[role="bold"] { - font-weight:bolder; - font-style:inherit; -} -emphasis[role="underline"] { - text-decoration:underline; - font-style:inherit; -} -emphasis[role="strikethrough"] { - text-decoration:line-through; - font-style:inherit; -} -emphasis>emphasis { - font-weight:bolder; -} - -foreignphrase, wordasword, productname { - font-style:italic; -} - -replaceable { - font-style:italic; -} - -sgmltag[class="starttag"]:before, sgmltag[class="emptytag"]:before { - content: "<"; -} - -sgmltag[class="starttag"]:after, sgmltag[class="endtag"]:after { - content: ">"; -} - -sgmltag[class="endtag"]:before { - content: ""; -} - -sgmltag[class="attvalue"]:before, sgmltag[class="attvalue"]:after { - content: '"'; -} - -sgmltag[class="genentity"]:before { - content: "&"; -} -sgmltag[class="genentity"]:after { - content: ";"; -} - -sgmltag[class="sgmlcomment"]:before { - content: ""; -} - -sgmltag[class="xmlpi"]:before { - content: ""; -} - - -application, keycap, guimenu, guimenuitem, guisubmenu { - font-family: sans-serif; -} - -/* - * ensure there's some whitespace between elements of an author's name - */ -author>* + *:before { - content: " "; -} - -/* give keycaps a '3D' shaded look */ -keycap { - padding-left: .2em; - padding-right: .2em; - border-style: solid; - border-top-width: 2px; - border-left-width: 3px; - border-right-width: 3px; - border-bottom-width: 4px; - border-top-color: #eeeecc; - border-left-color: #eeeecc; - border-right-color: #999977; - border-bottom-color: #999977; - background-color: #ddddbb; - /* All these borders may interfere with text on the line bellow. Make - the text a little smaller to try and 'pull up' the bottom edge, */ - font-size: smaller; -} - -keycombo>keycap+keycap:before { - /* FIXME: this appears inside the second keycap's 3D boarder, but - * ideally, we'd like it to appear inbetween the two keycaps */ - content: "-"; -} - -menuchoice>guimenu+guimenuitem:before, -menuchoice>guimenuitem+guimenuitem:before, -menuchoice>guimenuitem+guisubmenu:before { - /*content: "->";*/ - /* a 'proper' left-arrow character */ - content: "\2192"; -} - -guibutton { - border: 2px outset #dddddd; - background-color: #dddddd; -/* - border: 2px solid; - border-top-color: #eeeeee; - border-left-color: #eeeeee; - border-right-color: #999999; - border-bottom-color: #999999; - background-color: #dddddd; -*/} - - -/* render link-like elements per HTML's normal styling */ -link, ulink, email { - /* When ulink contains no body text, the url should be rendered - * at this point in the document. Can't see how to do this with CSS */ - color:#0000ff; - text-decoration:underline; -} - -/*ulink:after { - content: " <" attr(url) ">"; -}*/ - -email:before { - content: "<"; -} -email:after { - content: ">"; -} - -citation:before { - content: "["; -} -citation:after { - content: "]"; -} - -xref:after { - /* simple symbol - content: "#" attr(linkend);*/ - /* 'section' symbol */ - content: "\00a7" attr(linkend); - color:#0000ff; - text-decoration: underline; -} - -blockquote { - padding-left:3em; - padding-bottom: 1em; -} - -blockquote>attribution { - text-align:right; - font-style: italic; -} -blockquote>attribution:after { - /* I've tried various things to position the attribution after the - * other blockquote content (e.g. relative/absolute positioning), but - * none of the things I tried produced satisfactory results (e.g. the - * attribution appears at the bottom of the containing block, but it - * overlaps preceeding content). */ - content:":" -} -blockquote>para:before { - content: open-quote; -} -blockquote>para:after { - content: no-close-quote; -} -blockquote>para:last-child:after { - content: close-quote; -} - -/* lists */ - -itemizedlist { - padding-left: 1em; - list-style-type: disc; -} - -listitem+listitem { - padding-top: .5em; -} - -/* 2 deep nested lists */ -itemizedlist itemizedlist { - list-style-type: circle; -} - -/* 3 or more deep nested lists */ -itemizedlist itemizedlist itemizedlist { - list-style-type: square; -} - - -itemizedlist>listitem { - display:list-item; -} - -orderedlist { - padding-left: 1.5em; - list-style-type: decimal; -} - -orderedlist>listitem { - display:list-item; -} - -/* - * We've got no way of properly implementing call-out lists with CSS, so just - * present as a list of bullet points. - */ -calloutlist { - padding-left: 1em; - list-style-type: disc; -} -calloutlist>callout { - display:list-item; -} - - - -/* - * The list of possible mark names is not defined by Docbook, but "opencircle" - * and "bullet" are used in T.D.G. example - */ -itemizedlist[mark="opencircle"], listitem[override="opencircle"] { - list-style-type: circle; -} - -itemizedlist[mark="bullet"], listitem[override="bullet"] { - list-style-type: disc; -} - - -varlistentry>listitem { - margin-left: 2em; -} -varlistentry+varlistentry { - margin-top: .5em; -} - -simplelist[type=horiz] { - display: block; -} - -simplelist[type=inline]>member+member:before { - /* typically, we end up with unwanted whitespace before the comma - * (i.e. whitespace between elements). I see no way of - * suppressing this with CSS. - * TODO: try a combination of :after and :first-child instead to - * avoid the above issue */ - content: ", "; -} - -cmdsynopsis, code, command, computeroutput, envar, filename, keycode, keysym, -literal, option, parameter, sgmltag, systemitem { - font-family: monospace; -} - -filename[class=directory]:after { - content: "/"; -} - -/* TODO: Are these specific to 'en' locales or not? */ -trademark:after { - content: "\2122" -} -trademark[class="copyright"]:after { - content: "\A9" -} -trademark[class="registered"]:after { - content: "\AE" -} -trademark[class="service"]:after { - content: "\2120" -} - -example, informalexample, programlisting { - background-color:#dddddd; - padding: .5em; - border: 1px dashed black; -} - - -example programlisting, informalexample programlisting { - background-color: none; - padding: 0; - border: none; -} - -/* admonitions */ - -warning, caution, tip, note, important { - border: 1px dashed gray; - padding: .5em; -} - -/* Have admonition titles appear inline with generated content ("Note:" etc.) */ -warning>title, caution>title, tip>title, note>title, important>title { - display: inline; - -} - -warning:before, caution:before, tip:before, note:before, important:before { - /* Match the style of */ - font-weight: bolder; - font-family: sans-serif; -} - -/* FIXME: background colours are cheezy :S ... */ -/* see language specific css for content: */ -warning:before { - background-color: red; -} -caution:before { - background-color: yellow; -} -tip:before { - background-color: #aaaddd; -} -note:before { - background-color: #dddddd; -} -important:before { - background-color: plum; -} - -/* Tables */ - -thead > row > entry { - /* FIXME: will under-rule every row in the <thead>, not just the last - * (I tried adding this style to <thead> itself, but this doesn't - * appear to work in combination with display:table-header-group, as - * defined in tables.css) */ - border-bottom: 2px solid black; -} - -thead { - font-weight: bolder; -} - -entry { - padding: .2em; -} - - -/* Footnotes */ - - -/* - * Attempt to display footnotes on-mouseover. This may well break if a - * footnote element has multiple children (I think the children will end up - * stacked on top of each other). - */ - -footnote { - position: relative; - cursor: help; -} -footnote:hover { -} -footnote>* { - display: none; - z-index: 100; -} -footnote:hover>* { - display: block; - position: fixed; - border: 2px dotted black; - background-color: #ffeeaa; - padding: .5em; - left: 0px; - bottom: 0px; -} -footnote:before { - content: "?"; - background-color: #ffeeaa; - border: 2px dotted black; - font-size: smaller; -} - - -/* - -Attempting to format <footnote> as a sitebar, floating it to the right. -Sometimes works for footnotes in the 'main body' of some text, but works badly -when the containing block is, for instance, a table cell. - -footnote:before { - content: "*"; - display: block; - border: 2px dotted black; -} - -footnote>* { - display: block; - float: right; - border: 2px dotted black; - padding: .5em; - width: 25%; - top: -1em; -} - -footnote>*:before { - content: "*Footnote"; - display: block; - font-weight: bold; - font-family: sans-serif; -} -*/ - -glossentry>glossterm { - font-weight: bolder; - font-style: italic; -} - - -userinput { - font-weight: bolder; -} - -figure { - text-align: center; -} - -imageobject { - display: block; -} - -mediaobject>textobject { - font-size: smaller; -} diff --git a/doc/manual/css-docbook/tables.css b/doc/manual/css-docbook/tables.css deleted file mode 100644 index da148a38..00000000 --- a/doc/manual/css-docbook/tables.css +++ /dev/null @@ -1,59 +0,0 @@ -/* - * tables.css - * - * Copyright (c) 2004 David Holroyd, and contributors - * See the file 'COPYING' for terms of use - * - * Part of the Docbook-CSS stylesheet - * http://www.badgers-in-foil.co.uk/projects/docbook-css/ - * - */ - -tgroup { - display: table; -} - -row { - display: table-row; -} - -thead { - display: table-header-group; -} - -tbody { - display: table-row-group; -} - -entry, entrytbl { - display: table-cell; -} - -entry[valign=top] { - vertical-align: top; -} -entry[valign=bottom] { - vertical-align: bottom; -} - -/* - * CSS can't generate the indended formatting for segmented lists, so we turn - * them into tables instead. - * - * TODO: seems to break formatting when nested in a table entry - */ -segmentedlist { - display: table; -} - -seglistitem { - display: table-row; -} - -seg, segtitle { - display: table-cell; -} - -segmentedlist>title { - display: table-caption; -} diff --git a/doc/manual/css-docbook/xmlrpc.css b/doc/manual/css-docbook/xmlrpc.css deleted file mode 100644 index 08425ef9..00000000 --- a/doc/manual/css-docbook/xmlrpc.css +++ /dev/null @@ -1,42 +0,0 @@ -funcsynopsis>* { - margin-left:10%; - margin-right:10%; -} - -funcprototype { - display: block; - text-align: justify; - font-family:monospace; -} - -funcprototype:after { - content:");"; -} - -funcdef:after { - content:"("; -} - -paramdef type:after { - content:" "; -} - -funcdef function { - font-weight:bold; -} - -paramdef initializer:before -{ - content:" = "; -} - -paramdef:after -{ - content:","; -} - -/* remove the extra comma after the last paramdef of a funcprotoype */ -paramdef:last-child:after -{ - content:""; -} diff --git a/doc/manual/phpxmlrpc_manual.adoc b/doc/manual/phpxmlrpc_manual.adoc new file mode 100644 index 00000000..1480b402 --- /dev/null +++ b/doc/manual/phpxmlrpc_manual.adoc @@ -0,0 +1,3117 @@ += XML-RPC for PHP +:revision: 4.0.0 +:keywords: xml, rpc, xmlrpc, webservices, http +:toc: left +:imagesdir: images + +[preface] +== Introduction + +XML-RPC is a format devised by link:$$http://www.userland.com/$$[Userland Software] for achieving + remote procedure call via XML using HTTP as the transport. XML-RPC has its + own web site, link:$$http://www.xmlrpc.com/$$[www.xmlrpc.com] + +This collection of PHP classes provides a framework for writing + XML-RPC clients and servers in PHP. + +Main goals of the project are ease of use, flexibility and + completeness. + +The original author is Edd Dumbill of link:$$http://usefulinc.com/$$[Useful Information Company]. As of the + 1.0 stable release, the project was opened to wider involvement and moved + to link:$$http://phpxmlrpc.sourceforge.net/$$[SourceForge]; later, to link:$$https://github.com/gggeek/phpxmlrpc$$[Github] + +A list of XML-RPC implementations for other languages such as Perl + and Python can be found on the link:$$http://www.xmlrpc.com/$$[www.xmlrpc.com] site. + +=== Acknowledgements + +Daniel E. Baumann + +James Bercegay + +Leon Blackwell + +Stephane Bortzmeyer + +Daniel Convissor + +Geoffrey T. Dairiki + +Stefan Esser + +James Flemer + +Ernst de Haan + +Tom Knight + +Axel Kollmorgen + +Peter Kocks + +Daniel Krippner + +{empty}S. Kuip + +{empty}A. Lambert + +Frederic Lecointre + +Dan Libby + +Arnaud Limbourg + +Ernest MacDougal Campbell III + +Lukasz Mach + +Kjartan Mannes + +Ben Margolin + +Nicolay Mausz + +Justin Miller + +Jan Pfeifer + +Giancarlo Pinerolo + +Peter Russel + +Jean-Jacques Sarton + +Viliam Simko + +Idan Sofer + +Douglas Squirrel + +Heiko Stübner + +Anatoly Techtonik + +Tommaso Trani + +Eric van der Vlist + +Christian Wenz + +Jim Winstead + +Przemyslaw Wroblewski + +Bruno Zanetti Melotti + + +[[requirements]] +== System Requirements + +The library has been designed with goals of scalability and backward + compatibility. As such, it supports a wide range of PHP installs. Note + that not all features of the lib are available in every + configuration. + +The __minimum supported__ PHP version is + 5.3. + +If you wish to use HTTPS or HTTP 1.1 to communicate with remote + servers, you need the "curl" extension compiled into your PHP + installation. + +The "xmlrpc" native extension is not required to be compiled into + your PHP installation, but if it is, there will be no interference with + the operation of this library. + + +[[manifest]] +== Files in the distribution + +lib/xmlrpc.inc:: + the XML-RPC classes. include() this in + your PHP files to use the classes. + +lib/xmlrpcs.inc:: + the XML-RPC server class. include() this + in addition to xmlrpc.inc to get server functionality + +lib/xmlrpc_wrappers.php:: + helper functions to "automagically" convert plain php + functions to xmlrpc services and vice versa + +demo/server/proxy.php:: + a sample server implementing xmlrpc proxy + functionality. + +demo/server/server.php:: + a sample server hosting various demo functions, as well as a + full suite of functions used for interoperability testing. It is + used by testsuite.php (see below) for unit testing the library, and + is not to be copied literally into your production servers + +demo/client/client.php, demo/client/agesort.php, + demo/client/which.php:: + client code to exercise some of the functions in server.php, + including the interopEchoTests.whichToolkit + method. + +demo/client/wrap.php:: + client code to illustrate 'wrapping' of remote methods into + php functions. + +demo/client/introspect.php:: + client code to illustrate usage of introspection capabilities + offered by server.php. + +demo/client/mail.php:: + client code to illustrate usage of an xmlrpc-to-email gateway + using Dave Winer's XML-RPC server at userland.com. + +demo/client/zopetest.php:: + example client code that queries an xmlrpc server built in + Zope. + +demo/vardemo.php:: + examples of how to construct xmlrpcval types + +demo/demo1.xml, demo/demo2.xml, demo/demo3.xml:: + XML-RPC responses captured in a file for testing purposes (you + can use these to test the + xmlrpcmsg->parseResponse() method). + +demo/server/discuss.php, + demo/client/comment.php:: + Software used in the PHP chapter of <<jellyfish>> to provide a comment server and allow the + attachment of comments to stories from Meerkat's data store. + +test/testsuite.php, test/parse_args.php:: + A unit test suite for this software package. If you do + development on this software, please consider submitting tests for + this suite. + +test/benchmark.php:: + A (very limited) benchmarking suite for this software package. + If you do development on this software, please consider submitting + benchmarks for this suite. + +test/phpunit.php, test/PHPUnit/*.php:: + An (incomplete) version PEAR's unit test framework for PHP. + The complete package can be found at link:$$http://pear.php.net/package/PHPUnit$$[http://pear.php.net/package/PHPUnit] + +test/verify_compat.php:: + Script designed to help the user to verify the level of + compatibility of the library with the current php install + +extras/test.pl, extras/test.py:: + Perl and Python programs to exercise server.php to test that + some of the methods work. + +extras/workspace.testPhpServer.fttb:: + Frontier scripts to exercise the demo server. Thanks to Dave + Winer for permission to include these. See link:$$http://www.xmlrpc.com/discuss/msgReader$853$$[Dave's announcement of these.] + +extras/rsakey.pem:: + A test certificate key for the SSL support, which can be used + to generate dummy certificates. It has the passphrase "test." + + +[[bugs]] + +== Known bugs and limitations + +This started out as a bare framework. Many "nice" bits haven't been + put in yet. Specifically, very little type validation or coercion has been + put in. PHP being a loosely-typed language, this is going to have to be + done explicitly (in other words: you can call a lot of library functions + passing them arguments of the wrong type and receive an error message only + much further down the code, where it will be difficult to + understand). + +dateTime.iso8601 is supported opaquely. It can't be done natively as + the XML-RPC specification explicitly forbids passing of timezone + specifiers in ISO8601 format dates. You can, however, use the <<iso8601encode>> and <<iso8601decode>> functions + to do the encoding and decoding for you. + +Very little HTTP response checking is performed (e.g. HTTP redirects + are not followed and the Content-Length HTTP header, mandated by the + xml-rpc spec, is not validated); cookie support still involves quite a bit + of coding on the part of the user. + +If a specific character set encoding other than US-ASCII, ISO-8859-1 + or UTF-8 is received in the HTTP header or XML prologue of xml-rpc request + or response messages then it will be ignored for the moment, and the + content will be parsed as if it had been encoded using the charset defined + by <<xmlrpc-defencoding>> + +Support for receiving from servers version 1 cookies (i.e. + conforming to RFC 2965) is quite incomplete, and might cause unforeseen + errors. + + +[[support]] + +== Support + + +=== Online Support + +XML-RPC for PHP is offered "as-is" without any warranty or + commitment to support. However, informal advice and help is available + via the XML-RPC for PHP website and mailing list and from + XML-RPC.com. + +* The __XML-RPC for PHP__ development is hosted + on link:$$https://github.com/gggeek/phpxmlrpc$$[github.com/gggeek/phpxmlrpc]. + Bugs, feature requests and patches can be posted to the link:$$https://github.com/gggeek/phpxmlrpc/issues$$[project's website]. + +* The __PHP XML-RPC interest mailing list__ is + run by the author. More details link:$$http://lists.gnomehack.com/mailman/listinfo/phpxmlrpc$$[can be found here]. + +* For more general XML-RPC questions, there is a Yahoo! Groups + link:$$http://groups.yahoo.com/group/xml-rpc/$$[XML-RPC mailing list]. + +* The link:$$http://www.xmlrpc.com/discuss$$[XML-RPC.com] discussion + group is a useful place to get help with using XML-RPC. This group + is also gatewayed into the Yahoo! Groups mailing list. + +[[jellyfish]] + +=== The Jellyfish Book + +image::progxmlrpc.s.gif[The Jellyfish Book] +Together with Simon St.Laurent and Joe + Johnston, Edd Dumbill wrote a book on XML-RPC for O'Reilly and + Associates on XML-RPC. It features a rather fetching jellyfish on the + cover. + +Complete details of the book are link:$$http://www.oreilly.com/catalog/progxmlrpc/$$[available from O'Reilly's web site.] + +Edd is responsible for the chapter on PHP, which includes a worked + example of creating a forum server, and hooking it up the O'Reilly's + link:$$http://meerkat.oreillynet.com/$$[Meerkat] service in + order to allow commenting on news stories from around the Web. + +If you've benefited from the effort that has been put into writing + this software, then please consider buying the book! + + +[[apidocs]] + +== Class documentation + +[[xmlrpcval]] + +=== xmlrpcval + +This is where a lot of the hard work gets done. This class enables + the creation and encapsulation of values for XML-RPC. + +Ensure you've read the XML-RPC spec at link:$$http://www.xmlrpc.com/stories/storyReader$7$$[http://www.xmlrpc.com/stories/storyReader$7] + before reading on as it will make things clearer. + +The xmlrpcval class can store arbitrarily + complicated values using the following types: ++i4 int boolean string double dateTime.iso8601 base64 array struct++ + ++null++. You should refer to the link:$$http://www.xmlrpc.com/spec$$[spec] for more information on + what each of these types mean. + +==== Notes on types + +===== int + +The type i4 is accepted as a synonym + for int when creating xmlrpcval objects. The + xml parsing code will always convert i4 to + int: int is regarded + by this implementation as the canonical name for this type. + +===== base64 + +Base 64 encoding is performed transparently to the caller when + using this type. Decoding is also transparent. Therefore you ought + to consider it as a "binary" data type, for use when you want to + pass data that is not 7-bit clean. + +===== boolean + +The php values ++true++ and + ++1++ map to ++true++. All other + values (including the empty string) are converted to + ++false++. + +===== string + +Characters <, >, ', ", &, are encoded using their + entity reference as &lt; &gt; &apos; &quot; and + &amp; All other characters outside of the ASCII range are + encoded using their character reference representation (e.g. + &#200 for é). The XML-RPC spec recommends only encoding + ++< &++ but this implementation goes further, + for reasons explained by link:$$http://www.w3.org/TR/REC-xml#syntax$$[the XML 1.0 recommendation]. In particular, using character reference + representation has the advantage of producing XML that is valid + independently of the charset encoding assumed. + +===== null + +There is no support for encoding ++null++ + values in the XML-RPC spec, but at least a couple of extensions (and + many toolkits) do support it. Before using ++null++ + values in your messages, make sure that the responding party accepts + them, and uses the same encoding convention (see ...). + +[[xmlrpcval-creation]] + +==== Creation + +The constructor is the normal way to create an + xmlrpcval. The constructor can take these + forms: + +xmlrpcvalnew + xmlrpcval xmlrpcvalnew + xmlrpcval string $stringVal xmlrpcvalnew + xmlrpcval mixed $scalarVal string$scalartyp xmlrpcvalnew + xmlrpcval array $arrayVal string $arraytyp The first constructor creates an empty value, which must be + altered using the methods addScalar, + addArray or addStruct before + it can be used. + +The second constructor creates a simple string value. + +The third constructor is used to create a scalar value. The + second parameter must be a name of an XML-RPC type. Valid types are: + "++int++", "++boolean++", + "++string++", "++double++", + "++dateTime.iso8601++", "++base64++" or + "null". + +Examples: + +[source, php] +---- + +$myInt = new xmlrpcval(1267, "int"); +$myString = new xmlrpcval("Hello, World!", "string"); +$myBool = new xmlrpcval(1, "boolean"); +$myString2 = new xmlrpcval(1.24, "string"); // note: this will serialize a php float value as xmlrpc string + +---- + +The fourth constructor form can be used to compose complex + XML-RPC values. The first argument is either a simple array in the + case of an XML-RPC array or an associative + array in the case of a struct. The elements of + the array __must be xmlrpcval objects themselves__. + +The second parameter must be either "++array++" + or "++struct++". + +Examples: + +[source, php] +---- + +$myArray = new xmlrpcval( + array( + new xmlrpcval("Tom"), + new xmlrpcval("Dick"), + new xmlrpcval("Harry") + ), + "array"); + +// recursive struct +$myStruct = new xmlrpcval( + array( + "name" => new xmlrpcval("Tom", "string"), + "age" => new xmlrpcval(34, "int"), + "address" => new xmlrpcval( + array( + "street" => new xmlrpcval("Fifht Ave", "string"), + "city" => new xmlrpcval("NY", "string") + ), + "struct") + ), + "struct"); + +---- + +See the file ++vardemo.php++ in this distribution + for more examples. + +[[xmlrpcval-methods]] + +==== Methods + +===== addScalar + +int addScalarstring$stringValintaddScalarmixed$scalarValstring$scalartypIf $val is an empty + xmlrpcval this method makes it a scalar + value, and sets that value. + +If $val is already a scalar value, then + no more scalars can be added and ++0++ is + returned. + +If $val is an xmlrpcval of type array, + the php value $scalarval is added as its last + element. + +If all went OK, ++1++ is returned, otherwise + ++0++. + +===== addArray + +intaddArrayarray$arrayValThe argument is a simple (numerically indexed) array. The + elements of the array __must be xmlrpcval objects themselves__. + +Turns an empty xmlrpcval into an + array with contents as specified by + $arrayVal. + +If $val is an xmlrpcval of type array, + the elements of $arrayVal are appended to the + existing ones. + +See the fourth constructor form for more information. + +If all went OK, ++1++ is returned, otherwise + ++0++. + +===== addStruct + +int addStructarray$assocArrayValThe argument is an associative array. The elements of the + array __must be xmlrpcval objects themselves__. + +Turns an empty xmlrpcval into a + struct with contents as specified by + $assocArrayVal. + +If $val is an xmlrpcval of type struct, + the elements of $arrayVal are merged with the + existing ones. + +See the fourth constructor form for more information. + +If all went OK, ++1++ is returned, otherwise + ++0++. + +===== kindOf + +string kindOf Returns a string containing "struct", "array" or "scalar" + describing the base type of the value. If it returns "undef" it + means that the value hasn't been initialised. + +===== serialize + +string serialize Returns a string containing the XML-RPC representation of this + value. + + +===== scalarVal + +mixed scalarVal If $val->kindOf() == "scalar", this + method returns the actual PHP-language value of the scalar (base 64 + decoding is automatically handled here). + +===== scalarTyp + +string scalarTyp If $val->kindOf() == "scalar", this + method returns a string denoting the type of the scalar. As + mentioned before, ++i4++ is always coerced to + ++int++. + +===== arrayMem + +xmlrpcval arrayMem int $n If $val->kindOf() == "array", returns + the $nth element in the array represented by + the value $val. The value returned is an + xmlrpcval object. + +[source, php] +---- + +// iterating over values of an array object +for ($i = 0; $i < $val->arraySize(); $i++) +{ + $v = $val->arrayMem($i); + echo "Element $i of the array is of type ".$v->kindOf(); +} + +---- + +===== arraySize + +int arraySize If $val is an + array, returns the number of elements in that + array. + +===== structMem + +xmlrpcval structMem string $memberName If $val->kindOf() == "struct", returns + the element called $memberName from the + struct represented by the value $val. The + value returned is an xmlrpcval object. + +===== structEach + +array structEach Returns the next (key, value) pair from the struct, when + $val is a struct. + $value is an xmlrpcval itself. See also <<structreset>>. + +[source, php] +---- + +// iterating over all values of a struct object +$val->structreset(); +while (list($key, $v) = $val->structEach()) +{ + echo "Element $key of the struct is of type ".$v->kindOf(); +} + +---- + +[[structreset]] + +===== structReset + +void structReset Resets the internal pointer for + structEach() to the beginning of the struct, + where $val is a struct. + +[[structmemexists]] + +===== structMemExists + +bool structMemExsists string $memberName Returns TRUE or + FALSE depending on whether a member of the + given name exists in the struct. + +[[xmlrpcmsg]] + +=== xmlrpcmsg + +This class provides a representation for a request to an XML-RPC + server. A client sends an xmlrpcmsg to a server, + and receives back an xmlrpcresp (see <<xmlrpc-client-send>>). + +==== Creation + +The constructor takes the following forms: + +xmlrpcmsgnew + xmlrpcmsgstring$methodNamearray$parameterArraynullWhere methodName is a string indicating + the name of the method you wish to invoke, and + parameterArray is a simple php + Array of xmlrpcval + objects. Here's an example message to the __US state name__ server: + +[source, php] +---- + +$msg = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int"))); + +---- + +This example requests the name of state number 23. For more + information on xmlrpcval objects, see <<xmlrpcval>>. + +Note that the parameterArray parameter is + optional and can be omitted for methods that take no input parameters + or if you plan to add parameters one by one. + +==== Methods + + +===== addParam + +bool addParam xmlrpcval $xmlrpcVal Adds the xmlrpcval + xmlrpcVal to the parameter list for this + method call. Returns TRUE or FALSE on error. + +===== getNumParams + +int getNumParams Returns the number of parameters attached to this + message. + +===== getParam + +xmlrpcval getParam int $n Gets the nth parameter in the message + (with the index zero-based). Use this method in server + implementations to retrieve the values sent by the client. + +===== method + +string method string method string $methNameGets or sets the method contained in the XML-RPC + message. + +===== parseResponse + +xmlrpcresp parseResponsestring $xmlString Given an incoming XML-RPC server response contained in the + string $xmlString, this method constructs an + xmlrpcresp response object and returns it, + setting error codes as appropriate (see <<xmlrpc-client-send>>). + +This method processes any HTTP/MIME headers it finds. + +===== parseResponseFile + +xmlrpcresp parseResponseFile file handle + resource$fileHandleGiven an incoming XML-RPC server response on the open file + handle fileHandle, this method reads all the + data it finds and passes it to + parseResponse. + +This method is useful to construct responses from pre-prepared + files (see files ++demo1.xml, demo2.xml, demo3.xml++ + in this distribution). It processes any HTTP headers it finds, and + does not close the file handle. + +===== serialize + +string + serializeReturns the an XML string representing the XML-RPC + message. + +[[xmlrpc-client]] + +=== xmlrpc_client + +This is the basic class used to represent a client of an XML-RPC + server. + +==== Creation + +The constructor accepts one of two possible syntaxes: + +xmlrpc_clientnew + xmlrpc_clientstring$server_urlxmlrpc_clientnew + xmlrpc_clientstring$server_pathstring$server_hostnameint$server_port80string$transport'http'Here are a couple of usage examples of the first form: + + +[source, php] +---- + +$client = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); +$another_client = new xmlrpc_client("https://james:bond@secret.service.com:443/xmlrpcserver?agent=007"); + +---- + +The second syntax does not allow to express a username and + password to be used for basic HTTP authorization as in the second + example above, but instead it allows to choose whether xmlrpc calls + will be made using the HTTP 1.0 or 1.1 protocol. + +Here's another example client set up to query Userland's XML-RPC + server at __betty.userland.com__: + +[source, php] +---- + +$client = new xmlrpc_client("/RPC2", "betty.userland.com", 80); + +---- + +The server_port parameter is optional, + and if omitted will default to 80 when using HTTP and 443 when using + HTTPS (see the <<xmlrpc-client-send>> method + below). + +The transport parameter is optional, and + if omitted will default to 'http'. Allowed values are either + 'http', 'https' or + 'http11'. Its value can be overridden with every call + to the send method. See the + send method below for more details about the + meaning of the different values. + + +==== Methods + +This class supports the following methods. + +[[xmlrpc-client-send]] + +===== send + +This method takes the forms: + +xmlrpcresp send xmlrpcmsg $xmlrpc_message int $timeout string $transport array sendarray $xmlrpc_messages int $timeout string $transportxmlrpcrespsendstring$xml_payloadint$timeoutstring$transportWhere xmlrpc_message is an instance of + xmlrpcmsg (see <<xmlrpcmsg>>), + and response is an instance of + xmlrpcresp (see <<xmlrpcresp>>). + +If xmlrpc_messages is an array of + message instances, ++responses++ will be an array of + response instances. The client will try to make use of a single + ++system.multicall++ xml-rpc method call to forward to the + server all the messages in a single HTTP round trip, unless + ++$$$client->no_multicall$$++ has been previously set to + ++TRUE++ (see the multicall method below), in which case + many consecutive xmlrpc requests will be sent. + +The third syntax allows to build by hand (or any other means) + a complete xmlrpc request message, and send it to the server. + xml_payload should be a string containing the + complete xml representation of the request. It is e.g. useful when, + for maximal speed of execution, the request is serialized into a + string using the native php xmlrpc functions (see link:$$http://www.php.net/xmlrpc$$[the php manual on xmlrpc]). + +The timeout is optional, and will be + set to ++0++ (wait for platform-specific predefined + timeout) if omitted. This timeout value is passed to + fsockopen(). It is also used for detecting + server timeouts during communication (i.e. if the server does not + send anything to the client for timeout + seconds, the connection will be closed). + +The transport parameter is optional, + and if omitted will default to the transport set using instance + creator or 'http' if omitted. The only other valid values are + 'https', which will use an SSL HTTP connection to connect to the + remote server, and 'http11'. Note that your PHP must have the "curl" + extension compiled in order to use both these features. Note that + when using SSL you should normally set your port number to 443, + unless the SSL server you are contacting runs at any other + port. + +In addition to low-level errors, the XML-RPC server you were + querying may return an error in the + xmlrpcresp object. See <<xmlrpcresp>> for details of how to handle these + errors. + +[[multicall]] + +===== multiCall + +This method takes the form: + +array multiCall array $messages int $timeout string $transport bool $fallback This method is used to boxcar many method calls in a single + xml-rpc request. It will try first to make use of the + ++system.multicall++ xml-rpc method call, and fall back to + executing many separate requests if the server returns any + error. + +msgs is an array of + xmlrpcmsg objects (see <<xmlrpcmsg>>), and response is an + array of xmlrpcresp objects (see <<xmlrpcresp>>). + +The timeout and + transport parameters are optional, and behave + as in the send method above. + +The fallback parameter is optional, and + defaults to TRUE. When set to + FALSE it will prevent the client to try using + many single method calls in case of failure of the first multicall + request. It should be set only when the server is known to support + the multicall extension. + +===== setAcceptedCompression + +void setAcceptedCompression string $compressionmethod This method defines whether the client will accept compressed + xml payload forming the bodies of the xmlrpc responses received from + servers. Note that enabling reception of compressed responses merely + adds some standard http headers to xmlrpc requests. It is up to the + xmlrpc server to return compressed responses when receiving such + requests. Allowed values for + compressionmethod are: 'gzip', 'deflate', + 'any' or null (with any meaning either gzip or deflate). + +This requires the "zlib" extension to be enabled in your php + install. If it is, by default xmlrpc_client + instances will enable reception of compressed content. + +===== setCaCertificate + +voidsetCaCertificatestring$certificatebool$is_dirThis method sets an optional certificate to be used in + SSL-enabled communication to validate a remote server with (when the + server_method is set to 'https' in the + client's construction or in the send method and + SetSSLVerifypeer has been set to + TRUE). + +The certificate parameter must be the + filename of a PEM formatted certificate, or a directory containing + multiple certificate files. The is_dir + parameter defaults to FALSE, set it to + TRUE to specify that + certificate indicates a directory instead of + a single file. + +This requires the "curl" extension to be compiled into your + installation of PHP. For more details see the man page for the + curl_setopt function. + + +===== setCertificate + +voidsetCertificatestring$certificatestring$passphraseThis method sets the optional certificate and passphrase used + in SSL-enabled communication with a remote server (when the + server_method is set to 'https' in the + client's construction or in the send method). + +The certificate parameter must be the + filename of a PEM formatted certificate. The + passphrase parameter must contain the + password required to use the certificate. + +This requires the "curl" extension to be compiled into your + installation of PHP. For more details see the man page for the + curl_setopt function. + +Note: to retrieve information about the client certificate on + the server side, you will need to look into the environment + variables which are set up by the webserver. Different webservers + will typically set up different variables. + +===== setCookie + +void setCookiestring $name string $value string $path string $domain int $portThis method sets a cookie that will be sent to the xmlrpc + server along with every further request (useful e.g. for keeping + session info outside of the xml-rpc payload). + +$value is optional, and defaults to + null. + +$path, $domain and $port are optional, + and will be omitted from the cookie header if unspecified. Note that + setting any of these values will turn the cookie into a 'version 1' + cookie, that might not be fully supported by the server (see RFC2965 + for more details). + +===== setCredentials + +voidsetCredentialsstring$usernamestring$passwordint$authtypeThis method sets the username and password for authorizing the + client to a server. With the default (HTTP) transport, this + information is used for HTTP Basic authorization. Note that username + and password can also be set using the class constructor. With HTTP + 1.1 and HTTPS transport, NTLM and Digest authentication protocols + are also supported. To enable them use the constants + CURLAUTH_DIGEST and + CURLAUTH_NTLM as values for the authtype + parameter. + + +===== setCurlOptions + +voidsetCurlOptionsarray$optionsThis method allows to directly set any desired + option to manipulate the usage of the cURL client (when in cURL + mode). It can be used eg. to explicitly bind to an outgoing ip + address when the server is multihomed + + +===== setDebug + +void setDebugint$debugLvldebugLvl is either ++0, 1++ or 2 depending on whether you require the client to + print debugging information to the browser. The default is not to + output this information (0). + +The debugging information at level 1includes the raw data + returned from the XML-RPC server it was querying (including bot HTTP + headers and the full XML payload), and the PHP value the client + attempts to create to represent the value returned by the server. At + level2, the complete payload of the xmlrpc request is also printed, + before being sent t the server. + +This option can be very useful when debugging servers as it + allows you to see exactly what the client sends and the server + returns. + + +===== setKey + +voidsetKeyint$keyint$keypassThis method sets the optional certificate key and passphrase + used in SSL-enabled communication with a remote server (when the + transport is set to 'https' in the client's + construction or in the send method). + +This requires the "curl" extension to be compiled into your + installation of PHP. For more details see the man page for the + curl_setopt function. + + +===== setProxy + +voidsetProxystring$proxyhostint$proxyportstring$proxyusernamestring$proxypasswordint$authtypeThis method enables calling servers via an HTTP proxy. The + proxyusername, + proxypassword and authtype + parameters are optional. Authtype defaults to + CURLAUTH_BASIC (Basic authentication protocol); + the only other valid value is the constant + CURLAUTH_NTLM, and has effect only when the + client uses the HTTP 1.1 protocol. + +NB: CURL versions before 7.11.10 cannot use a proxy to + communicate with https servers. + + +===== setRequestCompression + +voidsetRequestCompressionstring$compressionmethodThis method defines whether the xml payload forming the + request body will be sent to the server in compressed format, as per + the HTTP specification. This is particularly useful for large + request parameters and over slow network connections. Allowed values + for compressionmethod are: 'gzip', 'deflate', + 'any' or null (with any meaning either gzip or deflate). Note that + there is no automatic fallback mechanism in place for errors due to + servers not supporting receiving compressed request bodies, so make + sure that the particular server you are querying does accept + compressed requests before turning it on. + +This requires the "zlib" extension to be enabled in your php + install. + + +===== setSSLVerifyHost + +voidsetSSLVerifyHostint$iThis method defines whether connections made to XML-RPC + backends via HTTPS should verify the remote host's SSL certificate's + common name (CN). By default, only the existence of a CN is checked. + $i should be an + integer value; 0 to not check the CN at all, 1 to merely check for + its existence, and 2 to check that the CN on the certificate matches + the hostname that is being connected to. + + +===== setSSLVerifyPeer + +voidsetSSLVerifyPeerbool$iThis method defines whether connections made to XML-RPC + backends via HTTPS should verify the remote host's SSL certificate, + and cause the connection to fail if the cert verification fails. + $i should be a boolean + value. Default value: TRUE. To specify custom + SSL certificates to validate the server with, use the + setCaCertificate method. + + +===== setUserAgent + +voidUseragentstring$useragentThis method sets a custom user-agent that will be + used by the client in the http headers sent with the request. The + default value is built using the library name and version + constants. + + +==== Variables + +NB: direct manipulation of these variables is only recommended + for advanced users. + + +===== no_multicall + +This member variable determines whether the multicall() method + will try to take advantage of the system.multicall xmlrpc method to + dispatch to the server an array of requests in a single http + roundtrip or simply execute many consecutive http calls. Defaults to + FALSE, but it will be enabled automatically on the first failure of + execution of system.multicall. + + +===== request_charset_encoding + +This is the charset encoding that will be used for serializing + request sent by the client. + +If defaults to NULL, which means using US-ASCII and encoding + all characters outside of the ASCII range using their xml character + entity representation (this has the benefit that line end characters + will not be mangled in the transfer, a CR-LF will be preserved as + well as a singe LF). + +Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1' + +[[return-type]] + +===== return_type + +This member variable determines whether the value returned + inside an xmlrpcresp object as results of calls to the send() and + multicall() methods will be an xmlrpcval object, a plain php value + or a raw xml string. Allowed values are 'xmlrpcvals' (the default), + 'phpvals' and 'xml'. To allow the user to differentiate between a + correct and a faulty response, fault responses will be returned as + xmlrpcresp objects in any case. Note that the 'phpvals' setting will + yield faster execution times, but some of the information from the + original response will be lost. It will be e.g. impossible to tell + whether a particular php string value was sent by the server as an + xmlrpc string or base64 value. + +Example usage: + + +[source, php] +---- + +$client = new xmlrpc_client("phpxmlrpc.sourceforge.net/server.php"); +$client->return_type = 'phpvals'; +$message = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int"))); +$resp = $client->send($message); +if ($resp->faultCode()) echo 'KO. Error: '.$resp->faultString(); else echo 'OK: got '.$resp->value(); + +---- + +For more details about usage of the 'xml' value, see Appendix + A. + +[[xmlrpcresp]] + +=== xmlrpcresp + +This class is used to contain responses to XML-RPC requests. A + server method handler will construct an + xmlrpcresp and pass it as a return value. This + same value will be returned by the result of an invocation of the + send method of the + xmlrpc_client class. + + +==== Creation + +xmlrpcrespnew + xmlrpcrespxmlrpcval$xmlrpcvalxmlrpcrespnew + xmlrpcresp0int$errcodestring$err_stringThe first syntax is used when execution has happened without + difficulty: $xmlrpcval is an + xmlrpcval value with the result of the method + execution contained in it. Alternatively it can be a string containing + the xml serialization of the single xml-rpc value result of method + execution. + +The second type of constructor is used in case of failure. + errcode and err_string + are used to provide indication of what has gone wrong. See <<xmlrpc-server>> for more information on passing error + codes. + + +==== Methods + + +===== faultCode + +intfaultCodeReturns the integer fault code return from the XML-RPC + response. A zero value indicates success, any other value indicates + a failure response. + + +===== faultString + +stringfaultStringReturns the human readable explanation of the fault indicated + by $resp->faultCode(). + + +===== value + +xmlrpcvalvalueReturns an xmlrpcval object containing + the return value sent 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). + +Note: if the xmlrpcresp instance in question has been created + by an xmlrpc_client object whose + return_type was set to 'phpvals', then a plain + php value will be returned instead of an + xmlrpcval object. If the + return_type was set to 'xml', an xml string will + be returned (see the return_type member var above for more + details). + + +===== serialize + +stringserializeReturns an XML string representation of the response (xml + prologue not included). + +[[xmlrpc-server]] + +=== xmlrpc_server + +The implementation of this class has been kept as simple to use as + possible. The constructor for the server basically does all the work. + Here's a minimal example: + + +[source, php] +---- + + function foo ($xmlrpcmsg) { + ... + return new xmlrpcresp($some_xmlrpc_val); + } + + class bar { + function foobar($xmlrpcmsg) { + ... + return new xmlrpcresp($some_xmlrpc_val); + } + } + + $s = new xmlrpc_server( + array( + "examples.myFunc1" => array("function" => "foo"), + "examples.myFunc2" => array("function" => "bar::foobar"), + )); + +---- + +This performs everything you need to do with a server. The single + constructor argument is an associative array from xmlrpc method names to + php function names. The incoming request is parsed and dispatched to the + relevant php function, which is responsible for returning a + xmlrpcresp object, that will be serialized back + to the caller. + + +==== Method handler functions + +Both php functions and class methods can be registered as xmlrpc + method handlers. + +The synopsis of a method handler function is: + +xmlrpcresp $resp = function (xmlrpcmsg $msg) + +No text should be echoed 'to screen' by the handler function, or + it will break the xml response sent back to the client. This applies + also to error and warning messages that PHP prints to screen unless + the appropriate parameters have been set in the php.in file. Another + way to prevent echoing of errors inside the response and facilitate + debugging is to use the server SetDebug method with debug level 3 (see + ...). Exceptions thrown duting execution of handler functions are + caught by default and a XML-RPC error reponse is generated instead. + This behaviour can be finetuned by usage of the + exception_handling member variable (see + ...). + +Note that if you implement a method with a name prefixed by + ++system.++ the handler function will be invoked by the + server with two parameters, the first being the server itself and the + second being the xmlrpcmsg object. + +The same php function can be registered as handler of multiple + xmlrpc methods. + +Here is a more detailed example of what the handler function + foo may do: + + +[source, php] +---- + + function foo ($xmlrpcmsg) { + global $xmlrpcerruser; // import user errcode base value + + $meth = $xmlrpcmsg->method(); // retrieve method name + $par = $xmlrpcmsg->getParam(0); // retrieve value of first parameter - assumes at least one param received + $val = $par->scalarval(); // decode value of first parameter - assumes it is a scalar value + + ... + + if ($err) { + // this is an error condition + return new xmlrpcresp(0, $xmlrpcerruser+1, // user error 1 + "There's a problem, Captain"); + } else { + // this is a successful value being returned + return new xmlrpcresp(new xmlrpcval("All's fine!", "string")); + } + } + +---- + +See __server.php__ in this distribution for + more examples of how to do this. + +Since release 2.0RC3 there is a new, even simpler way of + registering php functions with the server. See section 5.7 + below + + +==== The dispatch map + +The first argument to the xmlrpc_server + constructor is an array, called the __dispatch map__. + In this array is the information the server needs to service the + XML-RPC methods you define. + +The dispatch map takes the form of an associative array of + associative arrays: the outer array has one entry for each method, the + key being the method name. The corresponding value is another + associative array, which can have the following members: + + +* ++function++ - this + entry is mandatory. It must be either a name of a function in the + global scope which services the XML-RPC method, or an array + containing an instance of an object and a static method name (for + static class methods the 'class::method' syntax is also + supported). + + +* ++signature++ - this + entry is an array containing the possible signatures (see <<signatures>>) for the method. If this entry is present + then the server will check that the correct number and type of + parameters have been sent for this method before dispatching + it. + + +* ++docstring++ - this + entry is a string containing documentation for the method. The + documentation may contain HTML markup. + + +* ++$$signature_docs$$++ - this entry can be used + to provide documentation for the single parameters. It must match + in structure the 'signature' member. By default, only the + documenting_xmlrpc_server class in the + extras package will take advantage of this, since the + "system.methodHelp" protocol does not support documenting method + parameters individually. + + +* ++$$parameters_type$$++ - this entry can be used + when the server is working in 'xmlrpcvals' mode (see ...) to + define one or more entries in the dispatch map as being functions + that follow the 'phpvals' calling convention. The only useful + value is currently the string ++phpvals++. + +Look at the __server.php__ example in the + distribution to see what a dispatch map looks like. + +[[signatures]] + +==== Method signatures + +A signature is a description of a method's return type and its + parameter types. A method may have more than one signature. + +Within a server's dispatch map, each method has an array of + possible signatures. Each signature is an array of types. The first + entry is the return type. For instance, the method +[source, php] +---- +string examples.getStateName(int) + +---- + + has the signature +[source, php] +---- +array($xmlrpcString, $xmlrpcInt) + +---- + + and, assuming that it is the only possible signature for the + method, it might be used like this in server creation: +[source, php] +---- + +$findstate_sig = array(array($xmlrpcString, $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.'; + +$s = new xmlrpc_server( array( + "examples.getStateName" => array( + "function" => "findstate", + "signature" => $findstate_sig, + "docstring" => $findstate_doc + ))); + +---- + + + +Note that method signatures do not allow to check nested + parameters, e.g. the number, names and types of the members of a + struct param cannot be validated. + +If a method that you want to expose has a definite number of + parameters, but each of those parameters could reasonably be of + multiple types, the array of acceptable signatures will easily grow + into a combinatorial explosion. To avoid such a situation, the lib + defines the global var $xmlrpcValue, which can be + used in method signatures as a placeholder for 'any xmlrpc + type': + + +[source, php] +---- + +$echoback_sig = array(array($xmlrpcValue, $xmlrpcValue)); + +$findstate_doc = 'Echoes back to the client the received value, regardless of its type'; + +$s = new xmlrpc_server( array( + "echoBack" => array( + "function" => "echoback", + "signature" => $echoback_sig, // this sig guarantees that the method handler will be called with one and only one parameter + "docstring" => $echoback_doc + ))); + +---- + +Methods system.listMethods, + system.methodHelp, + system.methodSignature and + system.multicall are already defined by the + server, and should not be reimplemented (see Reserved Methods + below). + + +==== Delaying the server response + +You may want to construct the server, but for some reason not + fulfill the request immediately (security verification, for instance). + If you omit to pass to the constructor the dispatch map or pass it a + second argument of ++0++ this will have the desired + effect. You can then use the service() method of + the server class to service the request. For example: + + +[source, php] +---- + +$s = new xmlrpc_server($myDispMap, 0); // second parameter = 0 prevents automatic servicing of request + +// ... some code that does other stuff here + +$s->service(); + +---- + +Note that the service method will print + the complete result payload to screen and send appropriate HTTP + headers back to the client, but also return the response object. This + permits further manipulation of the response, possibly in combination + with output buffering. + +To prevent the server from sending HTTP headers back to the + client, you can pass a second parameter with a value of + ++TRUE++ to the service + method. In this case, the response payload will be returned instead of + the response object. + +Xmlrpc requests retrieved by other means than HTTP POST bodies + can also be processed. For example: + + +[source, php] +---- + +$s = new xmlrpc_server(); // not passing a dispatch map prevents automatic servicing of request + +// ... some code that does other stuff here, including setting dispatch map into server object + +$resp = $s->service($xmlrpc_request_body, true); // parse a variable instead of POST body, retrieve response payload + +// ... some code that does other stuff with xml response $resp here + +---- + + +==== Modifying the server behaviour + +A couple of methods / class variables are available to modify + the behaviour of the server. The only way to take advantage of their + existence is by usage of a delayed server response (see above) + + +===== setDebug() + +This function controls weather the server is going to echo + debugging messages back to the client as comments in response body. + Valid values: 0,1,2,3, with 1 being the default. At level 0, no + debug info is returned to the client. At level 2, the complete + client request is added to the response, as part of the xml + comments. At level 3, a new PHP error handler is set when executing + user functions exposed as server methods, and all non-fatal errors + are trapped and added as comments into the response. + + +===== allow_system_funcs + +Default_value: TRUE. When set to FALSE, disables support for + System.xxx functions in the server. It + might be useful e.g. if you do not wish the server to respond to + requests to System.ListMethods. + + +===== compress_response + +When set to TRUE, enables the server to take advantage of HTTP + compression, otherwise disables it. Responses will be transparently + compressed, but only when an xmlrpc-client declares its support for + compression in the HTTP headers of the request. + +Note that the ZLIB php extension must be installed for this to + work. If it is, compress_response will default to + TRUE. + + +===== exception_handling + +This variable controls the behaviour of the server when an + exception is thrown by a method handler php function. Valid values: + 0,1,2, with 0 being the default. At level 0, the server catches the + exception and return an 'internal error' xmlrpc response; at 1 it + catches the exceptions and return an xmlrpc response with the error + code and error message corresponding to the exception that was + thron; at 2 = the exception is floated to the upper layers in the + code + + +===== response_charset_encoding + +Charset encoding to be used for response (only affects string + values). + +If it can, the server will convert the generated response from + internal_encoding to the intended one. + +Valid values are: a supported xml encoding (only UTF-8 and + ISO-8859-1 at present, unless mbstring is enabled), null (leave + charset unspecified in response and convert output stream to + US_ASCII), 'default' (use xmlrpc library default as specified in + xmlrpc.inc, convert output stream if needed), or 'auto' (use + client-specified charset encoding or same as request if request + headers do not specify it (unless request is US-ASCII: then use + library default anyway). + + +==== Fault reporting + +Fault codes for your servers should start at the value indicated + by the global ++$xmlrpcerruser++ + 1. + +Standard errors returned by the server include: + +++1++ Unknown method:: Returned if the server was asked to dispatch a method it + didn't know about + +++2++ Invalid return payload:: This error is actually generated by the client, not + server, code, but signifies that a server returned something it + couldn't understand. A more detailed error report is sometimes + added onto the end of the phrase above. + +++3++ Incorrect parameters:: This error is generated when the server has signature(s) + defined for a method, and the parameters passed by the client do + not match any of signatures. + +++4++ Can't introspect: method unknown:: This error is generated by the builtin + system.* methods when any kind of + introspection is attempted on a method undefined by the + server. + +++5++ Didn't receive 200 OK from remote server:: This error is generated by the client when a remote server + doesn't return HTTP/1.1 200 OK in response to a request. A more + detailed error report is added onto the end of the phrase + above. + +++6++ No data received from server:: This error is generated by the client when a remote server + returns HTTP/1.1 200 OK in response to a request, but no + response body follows the HTTP headers. + +++7++ No SSL support compiled in:: This error is generated by the client when trying to send + a request with HTTPS and the CURL extension is not available to + PHP. + +++8++ CURL error:: This error is generated by the client when trying to send + a request with HTTPS and the HTTPS communication fails. + +++9-14++ multicall errors:: These errors are generated by the server when something + fails inside a system.multicall request. + +++100-++ XML parse errors:: Returns 100 plus the XML parser error code for the fault + that occurred. The faultString returned + explains where the parse error was in the incoming XML + stream. + + +==== 'New style' servers + +In the same spirit of simplification that inspired the + xmlrpc_client::return_type class variable, a new + class variable has been added to the server class: + functions_parameters_type. When set to 'phpvals', + the functions registered in the server dispatch map will be called + with plain php values as parameters, instead of a single xmlrpcmsg + instance parameter. The return value of those functions is expected to + be a plain php value, too. An example is worth a thousand + words: +[source, php] +---- + + function foo($usr_id, $out_lang='en') { + global $xmlrpcerruser; + + ... + + if ($someErrorCondition) + return new xmlrpcresp(0, $xmlrpcerruser+1, 'DOH!'); + else + return array( + 'name' => 'Joe', + 'age' => 27, + 'picture' => new xmlrpcval(file_get_contents($picOfTheGuy), 'base64') + ); + } + + $s = new xmlrpc_server( + array( + "examples.myFunc" => array( + "function" => "bar::foobar", + "signature" => array( + array($xmlrpcString, $xmlrpcInt), + array($xmlrpcString, $xmlrpcInt, $xmlrpcString) + ) + ) + ), false); + $s->functions_parameters_type = 'phpvals'; + $s->service(); + +---- + +There are a few things to keep in mind when using this + simplified syntax: + +to return an xmlrpc error, the method handler function must + return an instance of xmlrpcresp. The only + other way for the server to know when an error response should be + served to the client is to throw an exception and set the server's + exception_handling memeber var to 1; + +to return a base64 value, the method handler function must + encode it on its own, creating an instance of an xmlrpcval + object; + +the method handler function cannot determine the name of the + xmlrpc method it is serving, unlike standard handler functions that + can retrieve it from the message object; + +when receiving nested parameters, the method handler function + has no way to distinguish a php string that was sent as base64 value + from one that was sent as a string value; + +this has a direct consequence on the support of + system.multicall: a method whose signature contains datetime or base64 + values will not be available to multicall calls; + +last but not least, the direct parsing of xml to php values is + much faster than using xmlrpcvals, and allows the library to handle + much bigger messages without allocating all available server memory or + smashing PHP recursive call stack. + + +[[globalvars]] + +== Global variables + +Many global variables are defined in the xmlrpc.inc file. Some of + those are meant to be used as constants (and modifying their value might + cause unpredictable behaviour), while some others can be modified in your + php scripts to alter the behaviour of the xml-rpc client and + server. + + +=== "Constant" variables + + +==== $xmlrpcerruser + +$xmlrpcerruser800The minimum value for errors reported by user + implemented XML-RPC servers. Error numbers lower than that are + reserved for library usage. + + +==== $xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, $xmlrpcString, $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, $xmlrpcStruct, $xmlrpcValue, $xmlrpcNull + +For convenience the strings representing the XML-RPC types have + been encoded as global variables: +[source, php] +---- + +$xmlrpcI4="i4"; +$xmlrpcInt="int"; +$xmlrpcBoolean="boolean"; +$xmlrpcDouble="double"; +$xmlrpcString="string"; +$xmlrpcDateTime="dateTime.iso8601"; +$xmlrpcBase64="base64"; +$xmlrpcArray="array"; +$xmlrpcStruct="struct"; +$xmlrpcValue="undefined"; +$xmlrpcNull="null"; + +---- + +==== $xmlrpcTypes, $xmlrpc_valid_parents, $xmlrpcerr, $xmlrpcstr, $xmlrpcerrxml, $xmlrpc_backslash, $_xh, $xml_iso88591_Entities, $xmlEntities, $xmlrpcs_capabilities + +Reserved for internal usage. + + +=== Variables whose value can be modified + +[[xmlrpc-defencoding]] + +==== xmlrpc_defencoding + +$xmlrpc_defencoding"UTF8"This variable defines the character set encoding that will be + used by the xml-rpc client and server to decode the received messages, + when a specific charset declaration is not found (in the messages sent + non-ascii chars are always encoded using character references, so that + the produced xml is valid regardless of the charset encoding + assumed). + +Allowed values: ++"UTF8"++, + ++"ISO-8859-1"++, ++"ASCII".++ + +Note that the appropriate RFC actually mandates that XML + received over HTTP without indication of charset encoding be treated + as US-ASCII, but many servers and clients 'in the wild' violate the + standard, and assume the default encoding is UTF-8. + + +==== xmlrpc_internalencoding + +$xmlrpc_internalencoding"ISO-8859-1"This variable defines the character set encoding + that the library uses to transparently encode into valid XML the + xml-rpc values created by the user and to re-encode the received + xml-rpc values when it passes them to the PHP application. It only + affects xml-rpc values of string type. It is a separate value from + xmlrpc_defencoding, allowing e.g. to send/receive xml messages encoded + on-the-wire in US-ASCII and process them as UTF-8. It defaults to the + character set used internally by PHP (unless you are running an + MBString-enabled installation), so you should change it only in + special situations, if e.g. the string values exchanged in the xml-rpc + messages are directly inserted into / fetched from a database + configured to return UTF8 encoded strings to PHP. Example + usage: + +[source, php] +---- + +<?php + +include('xmlrpc.inc'); +$xmlrpc_internalencoding = 'UTF-8'; // this has to be set after the inclusion above +$v = new xmlrpcval('κόσμε'); // This xmlrpc value will be correctly serialized as the greek word 'kosme' + +---- + +==== xmlrpcName + +$xmlrpcName"XML-RPC for PHP"The string representation of the name of the XML-RPC + for PHP library. It is used by the client for building the User-Agent + HTTP header that is sent with every request to the server. You can + change its value if you need to customize the User-Agent + string. + + +==== xmlrpcVersion + +$xmlrpcVersion"2.2"The string representation of the version number of + the XML-RPC for PHP library in use. It is used by the client for + building the User-Agent HTTP header that is sent with every request to + the server. You can change its value if you need to customize the + User-Agent string. + + +==== xmlrpc_null_extension + +When set to TRUE, the lib will enable + support for the <NIL/> (and <EX:NIL/>) xmlrpc value, as + per the extension to the standard proposed here. This means that + <NIL/> and <EX:NIL/> tags received will be parsed as valid + xmlrpc, and the corresponding xmlrpcvals will return "null" for + scalarTyp(). + + +==== xmlrpc_null_apache_encoding + +When set to ++TRUE++, php NULL values encoded + into xmlrpcval objects get serialized using the + ++<EX:NIL/>++ tag instead of + ++<NIL/>++. Please note that both forms are + always accepted as input regardless of the value of this + variable. + + +[[helpers]] + +== Helper functions + +XML-RPC for PHP contains some helper functions which you can use to + make processing of XML-RPC requests easier. + + +=== Date functions + +The XML-RPC specification has this to say on dates: + +[quote] +____ +[[wrap_xmlrpc_method]] +Don't assume a timezone. It should be + specified by the server in its documentation what assumptions it makes + about timezones. +____ + + +Unfortunately, this means that date processing isn't + straightforward. Although XML-RPC uses ISO 8601 format dates, it doesn't + use the timezone specifier. + +We strongly recommend that in every case where you pass dates in + XML-RPC calls, you use UTC (GMT) as your timezone. Most computer + languages include routines for handling GMT times natively, and you + won't have to translate between timezones. + +For more information about dates, see link:$$http://www.uic.edu/year2000/datefmt.html$$[ISO 8601: The Right Format for Dates], which has a handy link to a PDF of the ISO + 8601 specification. Note that XML-RPC uses exactly one of the available + representations: CCYYMMDDTHH:MM:SS. + +[[iso8601encode]] + +==== iso8601_encode + +stringiso8601_encodestring$time_tint$utc0Returns an ISO 8601 formatted date generated from the UNIX + timestamp $time_t, as returned by the PHP + function time(). + +The argument $utc can be omitted, in + which case it defaults to ++0++. If it is set to + ++1++, then the function corrects the time passed in + for UTC. Example: if you're in the GMT-6:00 timezone and set + $utc, you will receive a date representation + six hours ahead of your local time. + +The included demo program __vardemo.php__ + includes a demonstration of this function. + +[[iso8601decode]] + +==== iso8601_decode + +intiso8601_decodestring$isoStringint$utc0Returns a UNIX timestamp from an ISO 8601 encoded time and date + string passed in. If $utc is + ++1++ then $isoString is assumed + to be in the UTC timezone, and thus the result is also UTC: otherwise, + the timezone is assumed to be your local timezone and you receive a + local timestamp. + +[[arrayuse]] + +=== Easy use with nested PHP values + +Dan Libby was kind enough to contribute two helper functions that + make it easier to translate to and from PHP values. This makes it easier + to deal with complex structures. At the moment support is limited to + int, double, string, + array, datetime and struct + datatypes; note also that all PHP arrays are encoded as structs, except + arrays whose keys are integer numbers starting with 0 and incremented by + 1. + +These functions reside in __xmlrpc.inc__. + +[[phpxmlrpcdecode]] + +==== php_xmlrpc_decode + +mixedphp_xmlrpc_decodexmlrpcval$xmlrpc_valarray$optionsarrayphp_xmlrpc_decodexmlrpcmsg$xmlrpcmsg_valstring$optionsReturns a native PHP value corresponding to the values found in + the xmlrpcval $xmlrpc_val, + translated into PHP types. Base-64 and datetime values are + automatically decoded to strings. + +In the second form, returns an array containing the parameters + of the given + xmlrpcmsg_val, decoded + to php types. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + decoding process. At the moment the only valid option are + decode_php_objs and + ++$$dates_as_objects$$++. When the first is set, php + objects that have been converted to xml-rpc structs using the + php_xmlrpc_encode function and a corresponding + encoding option will be converted back into object values instead of + arrays (provided that the class definition is available at + reconstruction time). When the second is set, XML-RPC datetime values + will be converted into native dateTime objects + instead of strings. + +____WARNING__:__ please take + extreme care before enabling the decode_php_objs + option: when php objects are rebuilt from the received xml, their + constructor function will be silently invoked. This means that you are + allowing the remote end to trigger execution of uncontrolled PHP code + on your server, opening the door to code injection exploits. Only + enable this option when you have complete trust of the remote + server/client. + +Example: +[source, php] +---- + +// wrapper to expose an existing php function as xmlrpc method handler +function foo_wrapper($m) +{ + $params = php_xmlrpc_decode($m); + $retval = call_user_func_array('foo', $params); + return new xmlrpcresp(new xmlrpcval($retval)); // foo return value will be serialized as string +} + +$s = new xmlrpc_server(array( + "examples.myFunc1" => array( + "function" => "foo_wrapper", + "signatures" => ... + ))); + +---- + +[[phpxmlrpcencode]] + +==== php_xmlrpc_encode + +xmlrpcvalphp_xmlrpc_encodemixed$phpvalarray$optionsReturns an xmlrpcval object populated with the PHP + values in $phpval. Works recursively on arrays + and objects, encoding numerically indexed php arrays into array-type + xmlrpcval objects and non numerically indexed php arrays into + struct-type xmlrpcval objects. Php objects are encoded into + struct-type xmlrpcvals, excepted for php values that are already + instances of the xmlrpcval class or descendants thereof, which will + not be further encoded. Note that there's no support for encoding php + values into base-64 values. Encoding of date-times is optionally + carried on on php strings with the correct format. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + encoding process. At the moment the only valid options are + encode_php_objs, ++$$null_extension$$++ + and auto_dates. + +The first will enable the creation of 'particular' xmlrpcval + objects out of php objects, that add a "php_class" xml attribute to + their serialized representation. This attribute allows the function + php_xmlrpc_decode to rebuild the native php objects (provided that the + same class definition exists on both sides of the communication). The + second allows to encode php ++NULL++ values to the + ++<NIL/>++ (or + ++<EX:NIL/>++, see ...) tag. The last encodes any + string that matches the ISO8601 format into an XML-RPC + datetime. + +Example: +[source, php] +---- + +// the easy way to build a complex xml-rpc struct, showing nested base64 value and datetime values +$val = php_xmlrpc_encode(array( + 'first struct_element: an int' => 666, + 'second: an array' => array ('apple', 'orange', 'banana'), + 'third: a base64 element' => new xmlrpcval('hello world', 'base64'), + 'fourth: a datetime' => '20060107T01:53:00' + ), array('auto_dates')); + +---- + +==== php_xmlrpc_decode_xml + +xmlrpcval | xmlrpcresp | + xmlrpcmsgphp_xmlrpc_decode_xmlstring$xmlarray$optionsDecodes the xml representation of either an xmlrpc request, + response or single value, returning the corresponding php-xmlrpc + object, or ++FALSE++ in case of an error. + +The options parameter is optional. If + specified, it must consist of an array of options to be enabled in the + decoding process. At the moment, no option is supported. + +Example: +[source, php] +---- + +$text = '<value><array><data><value>Hello world</value></data></array></value>'; +$val = php_xmlrpc_decode_xml($text); +if ($val) echo 'Found a value of type '.$val->kindOf(); else echo 'Found invalid xml'; + +---- + +=== Automatic conversion of php functions into xmlrpc methods (and vice versa) + +For the extremely lazy coder, helper functions have been added + that allow to convert a php function into an xmlrpc method, and a + remotely exposed xmlrpc method into a local php function - or a set of + methods into a php class. Note that these comes with many caveat. + + +==== wrap_xmlrpc_method + +stringwrap_xmlrpc_method$client$methodname$extra_optionsstringwrap_xmlrpc_method$client$methodname$signum$timeout$protocol$funcnameGiven an xmlrpc server and a method name, creates a php wrapper + function that will call the remote method and return results using + native php types for both params and results. The generated php + function will return an xmlrpcresp object for failed xmlrpc + calls. + +The second syntax is deprecated, and is listed here only for + backward compatibility. + +The server must support the + system.methodSignature xmlrpc method call for + this function to work. + +The client param must be a valid + xmlrpc_client object, previously created with the address of the + target xmlrpc server, and to which the preferred communication options + have been set. + +The optional parameters can be passed as array key,value pairs + in the extra_options param. + +The signum optional param has the purpose + of indicating which method signature to use, if the given server + method has multiple signatures (defaults to 0). + +The timeout and + protocol optional params are the same as in the + xmlrpc_client::send() method. + +If set, the optional new_function_name + parameter indicates which name should be used for the generated + function. In case it is not set the function name will be + auto-generated. + +If the ++$$return_source$$++ optional parameter is + set, the function will return the php source code to build the wrapper + function, instead of evaluating it (useful to save the code and use it + later as stand-alone xmlrpc client). + +If the ++$$encode_php_objs$$++ optional parameter is + set, instances of php objects later passed as parameters to the newly + created function will receive a 'special' treatment that allows the + server to rebuild them as php objects instead of simple arrays. Note + that this entails using a "slightly augmented" version of the xmlrpc + protocol (ie. using element attributes), which might not be understood + by xmlrpc servers implemented using other libraries. + +If the ++$$decode_php_objs$$++ optional parameter is + set, instances of php objects that have been appropriately encoded by + the server using a coordinate option will be deserialized as php + objects instead of simple arrays (the same class definition should be + present server side and client side). + +__Note that this might pose a security risk__, + since in order to rebuild the object instances their constructor + method has to be invoked, and this means that the remote server can + trigger execution of unforeseen php code on the client: not really a + code injection, but almost. Please enable this option only when you + trust the remote server. + +In case of an error during generation of the wrapper function, + FALSE is returned, otherwise the name (or source code) of the new + function. + +Known limitations: server must support + system.methodsignature for the wanted xmlrpc + method; for methods that expose multiple signatures, only one can be + picked; for remote calls with 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 base64. + +Note: 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 the parameter + list of the generated php function, useful for debugging + purposes. + +Example usage: + + +[source, php] +---- + +$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); + +$function = wrap_xmlrpc_method($client, 'examples.getStateName'); + +if (!$function) + die('Cannot introspect remote method'); +else { + $stateno = 15; + $statename = $function($a); + if (is_a($statename, 'xmlrpcresp')) // call failed + { + echo 'Call failed: '.$statename->faultCode().'. Calling again with debug on'; + $function($a, true); + } + else + echo "OK, state nr. $stateno is $statename"; +} + +---- + +[[wrap_php_function]] + +==== wrap_php_function + +arraywrap_php_functionstring$funcnamestring$wrapper_function_namearray$extra_optionsGiven 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, and return the appropriate + definition to be added to a server's dispatch map. + +The optional $wrapper_function_name + specifies the name that will be used for the auto-generated + function. + +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 docblock @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: only works for + user-defined functions, not for PHP internal functions (reflection + does not support retrieving number/type of params for those); the + wrapped php function will not be able to programmatically return an + xmlrpc error response. + +If the ++$$return_source$$++ optional parameter is + set, the function will return the php source code to build the wrapper + function, instead of evaluating it (useful to save the code and use it + later in a stand-alone xmlrpc server). It will be in the stored in the + ++source++ member of the returned array. + +If the ++$$suppress_warnings$$++ optional parameter + is set, any runtime warning generated while processing the + user-defined php function will be catched and not be printed in the + generated xml response. + +If the extra_options array contains the + ++$$encode_php_objs$$++ value, wrapped 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 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) + +If the ++$$decode_php_objs$$++ optional parameter is + set, instances of php objects that have been appropriately encoded by + the client using a coordinate option will be deserialized and passed + to the user function as php objects instead of simple arrays (the same + class definition should be present server side and client + side). + +__Note that this might pose a security risk__, + since in order to rebuild the object instances their constructor + method has to be invoked, and this means that the remote client can + trigger execution of unforeseen php code on the server: not really a + code injection, but almost. Please enable this option only when you + trust the remote clients. + +Example usage: + + +[source, php] +---- +/** +* State name from state number decoder. NB: do NOT remove this comment block. +* @param integer $stateno the state number +* @return string the name of the state (or error description) +*/ +function findstate($stateno) +{ + global $stateNames; + if (isset($stateNames[$stateno-1])) + { + return $stateNames[$stateno-1]; + } + else + { + return "I don't have a state for the index '" . $stateno . "'"; + } +} + +// wrap php function, build xmlrpc server +$methods = array(); +$findstate_sig = wrap_php_function('findstate'); +if ($findstate_sig) + $methods['examples.getStateName'] = $findstate_sig; +$srv = new xmlrpc_server($methods); + +---- + +[[deprecated]] + +=== Functions removed from the library + +The following two functions have been deprecated in version 1.1 of + the library, and removed in version 2, in order to avoid conflicts with + the EPI xml-rpc library, which also defines two functions with the same + names. + +To ease the transition to the new naming scheme and avoid breaking + existing implementations, the following scheme has been adopted: + +* If EPI-XMLRPC is not active in the current PHP installation, + the constant ++$$XMLRPC_EPI_ENABLED$$++ will be set to + ++$$'0'$$++ + + +* If EPI-XMLRPC is active in the current PHP installation, the + constant ++$$XMLRPC_EPI_ENABLED$$++ will be set to + ++$$'1'$$++ + + + +The following documentation is kept for historical + reference: + +[[xmlrpcdecode]] + +==== xmlrpc_decode + +mixedx mlrpc_decode xmlrpcval $xmlrpc_val Alias for php_xmlrpc_decode. + +[[xmlrpcencode]] + +==== xmlrpc_encode + +xmlrpcval xmlrpc_encode mixed $phpvalAlias for php_xmlrpc_encode. + +[[debugging]] + +=== Debugging aids + +==== xmlrpc_debugmsg + +void xmlrpc_debugmsgstring$debugstringSends the contents of $debugstring in XML + comments in the server return payload. If a PHP client has debugging + turned on, the user will be able to see server debug + information. + +Use this function in your methods so you can pass back + diagnostic information. It is only available from + __xmlrpcs.inc__. + + +[[reserved]] + +== Reserved methods + +In order to extend the functionality offered by XML-RPC servers + without impacting on the protocol, reserved methods are supported in this + release. + +All methods starting with system. are + considered reserved by the server. PHP for XML-RPC itself provides four + special methods, detailed in this chapter. + +Note that all server objects will automatically respond to clients + querying these methods, unless the property + allow_system_funcs has been set to + false before calling the + service() method. This might pose a security risk + if the server is exposed to public access, e.g. on the internet. + + +=== system.getCapabilities + + +=== system.listMethods + +This method may be used to enumerate the methods implemented by + the XML-RPC server. + +The system.listMethods method requires no + parameters. It returns an array of strings, each of which is the name of + a method implemented by the server. + +[[sysmethodsig]] + +=== system.methodSignature + +This method takes one parameter, the name of a method implemented + by the XML-RPC server. + +It returns an array of possible signatures for this method. A + signature is an array of types. The first of these types is the return + type of the method, the rest are parameters. + +Multiple signatures (i.e. overloading) are permitted: this is the + reason that an array of signatures are returned by this method. + +Signatures themselves are restricted to the top level parameters + expected by a method. For instance if a method expects one array of + structs as a parameter, and it returns a string, its signature is simply + "string, array". If it expects three integers, its signature is "string, + int, int, int". + +For parameters that can be of more than one type, the "undefined" + string is supported. + +If no signature is defined for the method, a not-array value is + returned. Therefore this is the way to test for a non-signature, if + $resp below is the response object from a method + call to system.methodSignature: + +[source, php] +---- + +$v = $resp->value(); +if ($v->kindOf() != "array") { + // then the method did not have a signature defined +} + +---- + +See the __introspect.php__ demo included in this + distribution for an example of using this method. + +[[sysmethhelp]] + +=== system.methodHelp + +This method takes one parameter, the name of a method implemented + by the XML-RPC server. + +It returns a documentation string describing the use of that + method. If no such string is available, an empty string is + returned. + +The documentation string may contain HTML markup. + +=== system.multicall + +This method takes one parameter, an array of 'request' struct + types. Each request struct must contain a + methodName member of type string and a + params member of type array, and corresponds to + the invocation of the corresponding method. + +It returns a response of type array, with each value of the array + being either an error struct (containing the faultCode and faultString + members) or the successful response value of the corresponding single + method call. + + +[[examples]] + +== Examples + +The best examples are to be found in the sample files included with + the distribution. Some are included here. + +[[statename]] + +=== XML-RPC client: state name query + +Code to get the corresponding state name from a number (1-50) from + the demo server available on SourceForge + +[source, php] +---- + + $m = new xmlrpcmsg('examples.getStateName', + array(new xmlrpcval($HTTP_POST_VARS["stateno"], "int"))); + $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); + $r = $c->send($m); + if (!$r->faultCode()) { + $v = $r->value(); + print "State number " . htmlentities($HTTP_POST_VARS["stateno"]) . " is " . + htmlentities($v->scalarval()) . "<BR>"; + print "<HR>I got this value back<BR><PRE>" . + htmlentities($r->serialize()) . "</PRE><HR>\n"; + } else { + print "Fault <BR>"; + print "Code: " . htmlentities($r->faultCode()) . "<BR>" . + "Reason: '" . htmlentities($r->faultString()) . "'<BR>"; + } + +---- + +=== Executing a multicall call + +To be documented... + + +[[faq]] + +[qanda] +== Frequently Asked Questions + +=== Hi + +==== How to send custom XML as payload of a method call:: + +Unfortunately, at the time the XML-RPC spec was designed, support + for namespaces in XML was not as ubiquitous as it is now. As a + consequence, no support was provided in the protocol for embedding XML + elements from other namespaces into an xmlrpc request. + +To send an XML "chunk" as payload of a method call or response, + two options are available: either send the complete XML block as a + string xmlrpc value, or as a base64 value. Since the '<' character in + string values is encoded as '&lt;' in the xml payload of the method + call, the XML string will not break the surrounding xmlrpc, unless + characters outside of the assumed character set are used. The second + method has the added benefits of working independently of the charset + encoding used for the xml to be transmitted, and preserving exactly + whitespace, whilst incurring in some extra message length and cpu load + (for carrying out the base64 encoding/decoding). + + +==== Is there any limitation on the size of the requests / responses that can be successfully sent?:: + +Yes. But I have no hard figure to give; it most likely will depend + on the version of PHP in usage and its configuration. + +Keep in mind that this library is not optimized for speed nor for + memory usage. Better alternatives exist when there are strict + requirements on throughput or resource usage, such as the php native + xmlrpc extension (see the PHP manual for more information). + +Keep in mind also that HTTP is probably not the best choice in + such a situation, and XML is a deadly enemy. CSV formatted data over + socket would be much more efficient. + +If you really need to move a massive amount of data around, and + you are crazy enough to do it using phpxmlrpc, your best bet is to + bypass usage of the xmlrpcval objects, at least in the decoding phase, + and have the server (or client) object return to the calling function + directly php values (see xmlrpc_client::return_type + and xmlrpc_server::functions_parameters_type for more + details). + + +==== My server (client) returns an error whenever the client (server) returns accented characters + +To be documented... + + +==== How to enable long-lasting method calls + +To be documented... + + +==== My client returns "XML-RPC Fault #2: Invalid return payload: enable debugging to examine incoming payload": what should I do? + +The response you are seeing is a default error response that the + client object returns to the php application when the server did not + respond to the call with a valid xmlrpc response. + +The most likely cause is that you are not using the correct URL + when creating the client object, or you do not have appropriate access + rights to the web page you are requesting, or some other common http + misconfiguration. + +To find out what the server is really returning to your client, + you have to enable the debug mode of the client, using + $client->setdebug(1); + + +==== How can I save to a file the xml of the xmlrpc responses received from servers? + +If what you need is to save the responses received from the server + as xml, you have two options: + +1- use the serialize() method on the response object. + + +[source, php] +---- + +$resp = $client->send($msg); +if (!$resp->faultCode()) + $data_to_be_saved = $resp->serialize(); + +---- + +Note that this will not be 100% accurate, since the xml generated + by the response object can be different from the xml received, + especially if there is some character set conversion involved, or such + (eg. if you receive an empty string tag as <string/>, serialize() + will output <string></string>), or if the server sent back + as response something invalid (in which case the xml generated client + side using serialize() will correspond to the error response generated + internally by the lib). + +2 - set the client object to return the raw xml received instead + of the decoded objects: + + +[source, php] +---- + +$client = new xmlrpc_client($url); +$client->return_type = 'xml'; +$resp = $client->send($msg); +if (!$resp->faultCode()) + $data_to_be_saved = $resp->value(); + +---- + +Note that using this method the xml response response will not be + parsed at all by the library, only the http communication protocol will + be checked. This means that xmlrpc responses sent by the server that + would have generated an error response on the client (eg. malformed xml, + responses that have faultcode set, etc...) now will not be flagged as + invalid, and you might end up saving not valid xml but random + junk... + + +==== Can I use the ms windows character set? + +If the data your application is using comes from a Microsoft + application, there are some chances that the character set used to + encode it is CP1252 (the same might apply to data received from an + external xmlrpc server/client, but it is quite rare to find xmlrpc + toolkits that encode to CP1252 instead of UTF8). It is a character set + which is "almost" compatible with ISO 8859-1, but for a few extra + characters. + +PHP-XMLRPC only supports the ISO 8859-1 and UTF8 character sets. + The net result of this situation is that those extra characters will not + be properly encoded, and will be received at the other end of the + XML-RPC transmission as "garbled data". Unfortunately the library cannot + provide real support for CP1252 because of limitations in the PHP 4 xml + parser. Luckily, we tried our best to support this character set anyway, + and, since version 2.2.1, there is some form of support, left commented + in the code. + +To properly encode outgoing data that is natively in CP1252, you + will have to uncomment all relative code in the file + __xmlrpc.inc__ (you can search for the string "1252"), + then set ++$$$GLOBALS['xmlrpc_internalencoding']='CP1252';$$++ + Please note that all incoming data will then be fed to your application + as UTF-8 to avoid any potential data loss. + + +==== Does the library support using cookies / http sessions? + +In short: yes, but a little coding is needed to make it + happen. + +The code below uses sessions to e.g. let the client store a value + on the server and retrieve it later. + +[source, php] +---- + +$resp = $client->send(new xmlrpcmsg('registervalue', array(new xmlrpcval('foo'), new xmlrpcval('bar')))); +if (!$resp->faultCode()) +{ + $cookies = $resp->cookies(); + if (array_key_exists('PHPSESSID', $cookies)) // nb: make sure to use the correct session cookie name + { + $session_id = $cookies['PHPSESSID']['value']; + + // do some other stuff here... + + $client->setcookie('PHPSESSID', $session_id); + $val = $client->send(new xmlrpcmsg('getvalue', array(new xmlrpcval('foo'))); + } +} + +---- + +Server-side sessions are handled normally like in any other + php application. Please see the php manual for more information about + sessions. + +NB: unlike web browsers, not all xmlrpc clients support usage of + http cookies. If you have troubles with sessions and control only the + server side of the communication, please check with the makers of the + xmlrpc client in use. + + +[[integration]] + +[appendix] +== Integration with the PHP xmlrpc extension + +To be documented more... + +In short: for the fastest execution possible, you can enable the php + native xmlrpc extension, and use it in conjunction with phpxmlrpc. The + following code snippet gives an example of such integration + + +[source, php] +---- + +/*** client side ***/ +$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); + +// tell the client to return raw xml as response value +$c->return_type = 'xml'; + +// let the native xmlrpc extension take care of encoding request parameters +$r = $c->send(xmlrpc_encode_request('examples.getStateName', $_POST['stateno'])); + +if ($r->faultCode()) + // HTTP transport error + echo 'Got error '.$r->faultCode(); +else +{ + // HTTP request OK, but XML returned from server not parsed yet + $v = xmlrpc_decode($r->value()); + // check if we got a valid xmlrpc response from server + if ($v === NULL) + echo 'Got invalid response'; + else + // check if server sent a fault response + if (xmlrpc_is_fault($v)) + echo 'Got xmlrpc fault '.$v['faultCode']; + else + echo'Got response: '.htmlentities($v); +} + +---- + + +[[substitution]] + +[appendix] +== Substitution of the PHP xmlrpc extension + +Yet another interesting situation is when you are using a ready-made + php application, that provides support for the XMLRPC protocol via the + native php xmlrpc extension, but the extension is not available on your + php install (e.g. because of shared hosting constraints). + +Since version 2.1, the PHP-XMLRPC library provides a compatibility + layer that aims to be 100% compliant with the xmlrpc extension API. This + means that any code written to run on the extension should obtain the + exact same results, albeit using more resources and a longer processing + time, using the PHP-XMLRPC library and the extension compatibility module. + The module is part of the EXTRAS package, available as a separate download + from the sourceforge.net website, since version 0.2 + + +[[enough]] + +[appendix] +== 'Enough of xmlrpcvals!': new style library usage + +To be documented... + +In the meantime, see docs about xmlrpc_client::return_type and + xmlrpc_server::functions_parameters_types, as well as php_xmlrpc_encode, + php_xmlrpc_decode and php_xmlrpc_decode_xml + + +[[debugger]] + +[appendix] +== Usage of the debugger + +A webservice debugger is included in the library to help during + development and testing. + +The interface should be self-explicative enough to need little + documentation. + +image::debugger.gif[,,,,align="center"] + +The most useful feature of the debugger is without doubt the "Show + debug info" option. It allows to have a screen dump of the complete http + communication between client and server, including the http headers as + well as the request and response payloads, and is invaluable when + troubleshooting problems with charset encoding, authentication or http + compression. + +The debugger can take advantage of the JSONRPC library extension, to + allow debugging of JSON-RPC webservices, and of the JS-XMLRPC library + visual editor to allow easy mouse-driven construction of the payload for + remote methods. Both components have to be downloaded separately from the + sourceforge.net web pages and copied to the debugger directory to enable + the extra functionality: + + +* to enable jsonrpc functionality, download the PHP-XMLRPC + EXTRAS package, and copy the file __jsonrpc.inc__ + either to the same directory as the debugger or somewhere in your + php include path + + +* to enable the visual value editing dialog, download the + JS-XMLRPC library, and copy somewhere in the web root files + __visualeditor.php__, + __visualeditor.css__ and the folders + __yui__ and __img__. Then edit the + debugger file __controller.php__ and set + appropriately the variable $editorpath. + + +[[news]] + +[appendix] +== Whats's new + +__Note:__ not all items the following list have + (yet) been fully documented, and some might not be present in any other + chapter in the manual. To find a more detailed description of new + functions and methods please take a look at the source code of the + library, which is quite thoroughly commented in phpdoc form. + +=== 4.0.0 + +...to be documented... + +=== 3.0.0 + +__Note:__ this is the last release of the library that will support PHP 5.1 and up. + Future releases will target php 5.3 as minimum supported version. + +* when using curl and keepalive, reset curl handle if we did not get back an http 200 response (eg a 302) + +* omit port on http 'Host' header if it is 80 + +* test suite allows interrogating https servers ignoring their certs + +* method setAcceptedCompression was failing to disable reception of compressed responses if the + client supported them + +=== 3.0.0 beta + +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 + +=== 2.2.2 + +__Note:__ this is the last release of the + library that will support PHP 4. Future releases (if any) should target + php 5.0 as minimum supported version. + +* fixed: encoding of utf-8 characters outside of the BMP + plane + +* fixed: character set declarations surrounded by double + quotes were not recognized in http headers + +* fixed: be more tolerant in detection of charset in http + headers + +* fixed: fix detection of zlib.output_compression + +* 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: format floating point values using the correct + decimal separator even when php locale is set to one that uses + comma + +* fixed: improve robustness of the debugger when parsing weird + results from non-compliant servers + +* php warning when receiving 'false' in a bool value + +* 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 + +=== 2.2.1 + +* fixed: work aroung 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 +=== 2.2 + +* 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. + See Appendix D for more details) + +* new: support for the <NIL/> xmlrpc extension. see below + for more details + +* new: server support for the system.getCapabilities xmlrpc + extension + +* new: <<wrap_xmlrpc_method,wrap_xmlrpc_method()>> + accepts two new options: debug and return_on_fault + +=== 2.1 + +* 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.php$$__. 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 re-enabled). 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 + +* The constructor of xmlrpcval() values has seen some internal + 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 + +* 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 + +* 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 + +* A new file has been added: + __$$verify_compat.php$$__, to help users diagnose the + level of compliance of their php installation with the + library + +* Restored compatibility with php 4.0.5 (for those poor souls + still stuck on it) + +* Method xmlrpc_server->service() + now returns a value: either the response payload or xmlrpcresp + object instance + +* Method + xmlrpc_server->add_to_map() now + accepts xmlrpc methods with no param definitions + +* 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 + +* The debugger can now generate code that wraps a remote + method into a php function (works for jsonrpc, too); it also has + better support for being activated via a single GET call (e.g. for + integration into other tools) + +* 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) + +* More logging of errors in a lot of situations + +* Javadoc documentation of lib files (almost) complete + +* Many performance tweaks and code cleanups, plus the usual + crop of bugs fixed (see NEWS file for complete list of + bugs) + +* 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 (or go read Appendix + B)... + +=== 2.0 final + +* Added to the client class the possibility to use Digest and + NTLM authentication methods (when using the CURL library) for + connecting to servers and NTLM for connecting to proxies + +* Added to the client class the possibility to specify + alternate certificate files/directories for authenticating the + peer with when using HTTPS communication + +* Reviewed all examples and added a new demo file, containing + a proxy to forward xmlrpc requests to other servers (useful e.g. + for ajax coding) + +* The debugger has been upgraded to reflect the new client + capabilities + +* All known bugs have been squashed, and the lib is more + tolerant than ever of commonly-found mistakes + +=== 2.0 Release candidate 3 + +* Added to server class the property + functions_parameters_type, that allows the + server to register plain php functions as xmlrpc methods (i.e. + functions that do not take an xmlrpcmsg object as unique + param) + +* let server and client objects serialize calls using a + specified character set encoding for the produced xml instead of + US-ASCII (ISO-8859-1 and UTF-8 supported) + +* let php_xmlrpc_decode accept xmlrpcmsg objects as valid + input + +* 'class::method' syntax is now accepted in the server + dispatch map + +* xmlrpc_clent::SetDebug() accepts + integer values instead of a boolean value, with debugging level 2 + adding to the information printed to screen the complete client + request + +=== 2.0 Release candidate 2 + +* Added a new property of the client object: + ++$$xmlrpc_client->return_type$$++, indicating whether + calls to the send() method will return xmlrpcresp objects whose + value() is an xmlrpcval object, a php value (automatically + decoded) or the raw xml received from the server. + +* Added in the extras dir. two new library file: + __jsonrpc.inc__ and + __jsonrpcs.inc__ containing new classes that + implement support for the json-rpc protocol (alpha quality + code) + +* Added a new client method: ++setKey($key, + $keypass)++ to be used in HTTPS connections + +* Added a new file containing some benchmarks in the testsuite + directory + +=== 2.0 Release candidate 1 + +* Support for HTTP proxies (new method: + ++$$xmlrpc_client::setProxy()$$++) + +* Support HTTP compression of both requests and responses. + Clients can specify what kind of compression they accept for + responses between deflate/gzip/any, and whether to compress the + requests. Servers by default compress responses to clients that + explicitly declare support for compression (new methods: + ++$$xmlrpc_client::setAcceptedCompression()$$++, + ++$$xmlrpc_client::setRequestCompression()$$++). Note that the + ZLIB php extension needs to be enabled in PHP to support + compression. + +* Implement HTTP 1.1 connections, but only if CURL is enabled + (added an extra parameter to + ++$$xmlrpc_client::xmlrpc_client$$++ to set the desired HTTP + protocol at creation time and a new supported value for the last + parameter of ++$$xmlrpc_client::send$$++, which now can be + safely omitted if it has been specified at creation time) ++ +With PHP versions greater than 4.3.8 keep-alives are enabled + by default for HTTP 1.1 connections. This should yield faster + execution times when making multiple calls in sequence to the same + xml-rpc server from a single client. + +* Introduce support for cookies. Cookies to be sent to the + server with a request can be set using + ++$$xmlrpc_client::setCookie()$$++, while cookies received from + the server are found in ++xmlrpcresp::cookies()++. It is + left to the user to check for validity of received cookies and + decide whether they apply to successive calls or not. + +* Better support for detecting different character set encodings + of xml-rpc requests and responses: both client and server objects + will correctly detect the charset encoding of received xml, and use + an appropriate xml parser. ++ +Supported encodings are US-ASCII, UTF-8 and ISO-8859-1. + +* Added one new xmlrpcmsg constructor syntax, allowing usage of + a single string with the complete URL of the target server + +* Convert xml-rpc boolean values into native php values instead + of 0 and 1 + +* Force the ++$$php_xmlrpc_encode$$++ function to properly + encode numerically indexed php arrays into xml-rpc arrays + (numerically indexed php arrays always start with a key of 0 and + increment keys by values of 1) + +* Prevent the ++$$php_xmlrpc_encode$$++ function from + further re-encoding any objects of class ++xmlrpcval++ that + are passed to it. This allows to call the function with arguments + consisting of mixed php values / xmlrpcval objects. + +* Allow a server to NOT respond to system.* method calls + (setting the ++$$$server->allow_system_funcs$$++ + property). + +* Implement a new xmlrpcval method to determine if a value of + type struct has a member of a given name without having to loop + trough all members: ++xmlrpcval::structMemExists()++ + +* Expand methods ++xmlrpcval::addArray++, + ++addScalar++ and ++addStruct++ allowing extra php + values to be added to xmlrpcval objects already formed. + +* Let the ++$$xmlrpc_client::send$$++ method accept an XML + string for sending instead of an xmlrpcmsg object, to facilitate + debugging and integration with the php native xmlrpc + extension + +* Extend the ++$$php_xmlrpc_encode$$++ and + ++$$php_xmlrpc_decode$$++ functions to allow serialization and + rebuilding of PHP objects. To successfully rebuild a serialized + object, the object class must be defined in the deserializing end of + the transfer. Note that object members of type resource will be + deserialized as NULL values. ++ +Note that his has been implemented adding a "php_class" + attribute to xml representation of xmlrpcval of STRUCT type, which, + strictly speaking, breaks the xml-rpc spec. Other xmlrpc + implementations are supposed to ignore such an attribute (unless + they implement a brain-dead custom xml parser...), so it should be + safe enabling it in heterogeneous environments. The activation of + this feature is done by usage of an option passed as second + parameter to both ++$$php_xmlrpc_encode$$++ and + ++$$php_xmlrpc_decode$$++. + +* Extend the ++$$php_xmlrpc_encode$$++ function to allow + automatic serialization of iso8601-conforming php strings as + datetime.iso8601 xmlrpcvals, by usage of an optional + parameter + +* Added an automatic stub code generator for converting xmlrpc + methods to php functions and vice-versa. ++ +This is done via two new functions: + ++$$wrap_php_function$$++ and ++$$wrap_xmlrpc_method$$++, + and has many caveats, with php being a typeless language and + all... + +* Allow object methods to be used in server dispatch map + +* Added a complete debugger solution, in the + __debugger__ folder + +* Added configurable server-side debug messages, controlled by + the new method ++$$xmlrpc_server::SetDebug()$$++. At level 0, + no debug messages are sent to the client; level 1 is the same as the + old behaviour; at level 2 a lot more info is echoed back to the + client, regarding the received call; at level 3 all warnings raised + during server processing are trapped (this prevents breaking the xml + to be echoed back to the client) and added to the debug info sent + back to the client + +* New XML parsing code, yields smaller memory footprint and + faster execution times, not to mention complete elimination of the + dreaded __eval()__ construct, so prone to code + injection exploits + +* Rewritten most of the error messages, making text more + explicative + +++++++++++++++++++++++++++++++++++++++ +<!-- Keep this comment at the end of the file +Local variables: +mode: sgml +sgml-omittag:nil +sgml-shorttag:t +sgml-minimize-attributes:nil +sgml-always-quote-attributes:t +sgml-indent-step:2 +sgml-indent-data:t +sgml-parent-document:nil +sgml-exposed-tags:nil +sgml-local-catalogs:nil +sgml-local-ecat-files:nil +sgml-namecase-general:t +sgml-general-insert-case:lower +End: +--> +++++++++++++++++++++++++++++++++++++++ diff --git a/doc/manual/phpxmlrpc_manual.xml b/doc/manual/phpxmlrpc_manual.xml deleted file mode 100644 index 5c69ba7e..00000000 --- a/doc/manual/phpxmlrpc_manual.xml +++ /dev/null @@ -1,4274 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?xml-stylesheet href="css-docbook/driver.css" type="text/css"?> -<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" -"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"> -<!-- -PHP-XMLRPC User manual ---> -<book lang="en"> - <title>XML-RPC for PHP - - version 3.0.0 - - - June 15, 2014 - - - - Edd - - Dumbill - - - - Gaetano - - Giunta - - - - Miles - - Lott - - - - Justin R. - - Miller - - - - Andres - - Salomon - - - - - 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. - - - - - Introduction - - XML-RPC is a format devised by Userland Software for achieving - remote procedure call via XML using HTTP as the transport. XML-RPC has its - own web site, www.xmlrpc.com - - This collection of PHP classes provides a framework for writing - XML-RPC clients and servers in PHP. - - Main goals of the project are ease of use, flexibility and - completeness. - - The original author is Edd Dumbill of Useful Information Company. As of the - 1.0 stable release, the project was opened to wider involvement and moved - to SourceForge; later, to Github - - A list of XML-RPC implementations for other languages such as Perl - and Python can be found on the www.xmlrpc.com site. - - - Acknowledgements - - Daniel E. Baumann - - James Bercegay - - Leon Blackwell - - Stephane Bortzmeyer - - Daniel Convissor - - Geoffrey T. Dairiki - - Stefan Esser - - James Flemer - - Ernst de Haan - - Tom Knight - - Axel Kollmorgen - - Peter Kocks - - Daniel Krippner - - S. Kuip - - A. Lambert - - Frederic Lecointre - - Dan Libby - - Arnaud Limbourg - - Ernest MacDougal Campbell III - - Lukasz Mach - - Kjartan Mannes - - Ben Margolin - - Nicolay Mausz - - Justin Miller - - Jan Pfeifer - - Giancarlo Pinerolo - - Peter Russel - - Jean-Jacques Sarton - - Viliam Simko - - Idan Sofer - - Douglas Squirrel - - Heiko Stübner - - Anatoly Techtonik - - Tommaso Trani - - Eric van der Vlist - - Christian Wenz - - Jim Winstead - - Przemyslaw Wroblewski - - Bruno Zanetti Melotti - - - - - What's new - - Note: not all items the following list have - (yet) been fully documented, and some might not be present in any other - chapter in the manual. To find a more detailed description of new - functions and methods please take a look at the source code of the - library, which is quite thoroughly commented in javadoc-like form. - - - 3.0.0 - - Note: this is the last release of the library that will support PHP 5.1 and up. - Future releases will target php 5.3 as minimum supported version. - - - - when using curl and keepalive, reset curl handle if we did not get back an http 200 response (eg a 302) - - - - omit port on http 'Host' header if it is 80 - - - - test suite allows interrogating https servers ignoring their certs - - - - method setAcceptedCompression was failing to disable reception of compressed responses if the - client supported them - - - - - - - 3.0.0 beta - - 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 - - - - - - 2.2.2 - - Note: this might the last release of the - library that will support PHP 4. Future releases (if any) should target - php 5.0 as minimum supported version. - - - - fixed: encoding of utf-8 characters outside of the BMP - plane - - - - fixed: character set declarations surrounded by double - quotes were not recognized in http headers - - - - fixed: be more tolerant in detection of charset in http - headers - - - - fixed: fix detection of zlib.output_compression - - - - 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: format floating point values using the correct - decimal separator even when php locale is set to one that uses - comma - - - - fixed: improve robustness of the debugger when parsing weird - results from non-compliant servers - - - - php warning when receiving 'false' in a bool value - - - - 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 - - - - - - 2.2.1 - - - - fixed: work aroung 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 - - - - - - 2.2 - - - - 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. - See Appendix D for more details) - - - - new: support for the <NIL/> xmlrpc extension. see below - for more details - - - - new: server support for the system.getCapabilities xmlrpc - extension - - - - new: wrap_xmlrpc_method() - accepts two new options: debug and return_on_fault - - - - - - 2.1 - - - - 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.php. 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 re-enabled). 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 - - - - The constructor of xmlrpcval() values has seen some internal - 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 - - - - 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 - - - - 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 - - - - A new file has been added: - verify_compat.php, to help users diagnose the - level of compliance of their php installation with the - library - - - - Restored compatibility with php 4.0.5 (for those poor souls - still stuck on it) - - - - Method xmlrpc_server->service() - now returns a value: either the response payload or xmlrpcresp - object instance - - - - Method - xmlrpc_server->add_to_map() now - accepts xmlrpc methods with no param definitions - - - - 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 - - - - The debugger can now generate code that wraps a remote - method into a php function (works for jsonrpc, too); it also has - better support for being activated via a single GET call (e.g. for - integration into other tools) - - - - 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) - - - - More logging of errors in a lot of situations - - - - Javadoc documentation of lib files (almost) complete - - - - Many performance tweaks and code cleanups, plus the usual - crop of bugs fixed (see NEWS file for complete list of - bugs) - - - - 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 (or go read Appendix - B)... - - - - - - 2.0 final - - - - Added to the client class the possibility to use Digest and - NTLM authentication methods (when using the CURL library) for - connecting to servers and NTLM for connecting to proxies - - - - Added to the client class the possibility to specify - alternate certificate files/directories for authenticating the - peer with when using HTTPS communication - - - - Reviewed all examples and added a new demo file, containing - a proxy to forward xmlrpc requests to other servers (useful e.g. - for ajax coding) - - - - The debugger has been upgraded to reflect the new client - capabilities - - - - All known bugs have been squashed, and the lib is more - tolerant than ever of commonly-found mistakes - - - - - - 2.0 Release candidate 3 - - - - Added to server class the property - functions_parameters_type, that allows the - server to register plain php functions as xmlrpc methods (i.e. - functions that do not take an xmlrpcmsg object as unique - param) - - - - let server and client objects serialize calls using a - specified character set encoding for the produced xml instead of - US-ASCII (ISO-8859-1 and UTF-8 supported) - - - - let php_xmlrpc_decode accept xmlrpcmsg objects as valid - input - - - - 'class::method' syntax is now accepted in the server - dispatch map - - - - xmlrpc_clent::SetDebug() accepts - integer values instead of a boolean value, with debugging level 2 - adding to the information printed to screen the complete client - request - - - - - - 2.0 Release candidate 2 - - - - Added a new property of the client object: - xmlrpc_client->return_type, indicating whether - calls to the send() method will return xmlrpcresp objects whose - value() is an xmlrpcval object, a php value (automatically - decoded) or the raw xml received from the server. - - - - Added in the extras dir. two new library file: - jsonrpc.inc and - jsonrpcs.inc containing new classes that - implement support for the json-rpc protocol (alpha quality - code) - - - - Added a new client method: setKey($key, - $keypass) to be used in HTTPS connections - - - - Added a new file containing some benchmarks in the testsuite - directory - - - - - - 2.0 Release candidate 1 - - - - Support for HTTP proxies (new method: - xmlrpc_client::setProxy()) - - - - Support HTTP compression of both requests and responses. - Clients can specify what kind of compression they accept for - responses between deflate/gzip/any, and whether to compress the - requests. Servers by default compress responses to clients that - explicitly declare support for compression (new methods: - xmlrpc_client::setAcceptedCompression(), - xmlrpc_client::setRequestCompression()). Note that the - ZLIB php extension needs to be enabled in PHP to support - compression. - - - - Implement HTTP 1.1 connections, but only if CURL is enabled - (added an extra parameter to - xmlrpc_client::xmlrpc_client to set the desired HTTP - protocol at creation time and a new supported value for the last - parameter of xmlrpc_client::send, which now can be - safely omitted if it has been specified at creation time) - - With PHP versions greater than 4.3.8 keep-alives are enabled - by default for HTTP 1.1 connections. This should yield faster - execution times when making multiple calls in sequence to the same - xml-rpc server from a single client. - - - - Introduce support for cookies. Cookies to be sent to the - server with a request can be set using - xmlrpc_client::setCookie(), while cookies received from - the server are found in xmlrpcresp::cookies(). It is - left to the user to check for validity of received cookies and - decide whether they apply to successive calls or not. - - - - Better support for detecting different character set encodings - of xml-rpc requests and responses: both client and server objects - will correctly detect the charset encoding of received xml, and use - an appropriate xml parser. - - Supported encodings are US-ASCII, UTF-8 and ISO-8859-1. - - - - Added one new xmlrpcmsg constructor syntax, allowing usage of - a single string with the complete URL of the target server - - - - Convert xml-rpc boolean values into native php values instead - of 0 and 1 - - - - Force the php_xmlrpc_encode function to properly - encode numerically indexed php arrays into xml-rpc arrays - (numerically indexed php arrays always start with a key of 0 and - increment keys by values of 1) - - - - Prevent the php_xmlrpc_encode function from - further re-encoding any objects of class xmlrpcval that - are passed to it. This allows to call the function with arguments - consisting of mixed php values / xmlrpcval objects. - - - - Allow a server to NOT respond to system.* method calls - (setting the $server->allow_system_funcs - property). - - - - Implement a new xmlrpcval method to determine if a value of - type struct has a member of a given name without having to loop - trough all members: xmlrpcval::structMemExists() - - - - Expand methods xmlrpcval::addArray, - addScalar and addStruct allowing extra php - values to be added to xmlrpcval objects already formed. - - - - Let the xmlrpc_client::send method accept an XML - string for sending instead of an xmlrpcmsg object, to facilitate - debugging and integration with the php native xmlrpc - extension - - - - Extend the php_xmlrpc_encode and - php_xmlrpc_decode functions to allow serialization and - rebuilding of PHP objects. To successfully rebuild a serialized - object, the object class must be defined in the deserializing end of - the transfer. Note that object members of type resource will be - deserialized as NULL values. - - Note that his has been implemented adding a "php_class" - attribute to xml representation of xmlrpcval of STRUCT type, which, - strictly speaking, breaks the xml-rpc spec. Other xmlrpc - implementations are supposed to ignore such an attribute (unless - they implement a brain-dead custom xml parser...), so it should be - safe enabling it in heterogeneous environments. The activation of - this feature is done by usage of an option passed as second - parameter to both php_xmlrpc_encode and - php_xmlrpc_decode. - - - - Extend the php_xmlrpc_encode function to allow - automatic serialization of iso8601-conforming php strings as - datetime.iso8601 xmlrpcvals, by usage of an optional - parameter - - - - Added an automatic stub code generator for converting xmlrpc - methods to php functions and vice-versa. - - This is done via two new functions: - wrap_php_function and wrap_xmlrpc_method, - and has many caveats, with php being a typeless language and - all... - - - - Allow object methods to be used in server dispatch map - - - - Added a complete debugger solution, in the - debugger folder - - - - Added configurable server-side debug messages, controlled by - the new method xmlrpc_server::SetDebug(). At level 0, - no debug messages are sent to the client; level 1 is the same as the - old behaviour; at level 2 a lot more info is echoed back to the - client, regarding the received call; at level 3 all warnings raised - during server processing are trapped (this prevents breaking the xml - to be echoed back to the client) and added to the debug info sent - back to the client - - - - New XML parsing code, yields smaller memory footprint and - faster execution times, not to mention complete elimination of the - dreaded eval() construct, so prone to code - injection exploits - - - - Rewritten most of the error messages, making text more - explicative - - - - - - - System Requirements - - The library has been designed with goals of scalability and backward - compatibility. As such, it supports a wide range of PHP installs. Note - that not all features of the lib are available in every - configuration. - - The minimum supported PHP version is - 5.3. - - If you wish to use SSL or HTTP 1.1 to communicate with remote - servers, you need the "curl" extension compiled into your PHP - installation. - - The "xmlrpc" native extension is not required to be compiled into - your PHP installation, but if it is, there will be no interference with - the operation of this library. - - - - Files in the distribution - - - - lib/xmlrpc.inc - - - the XML-RPC classes. include() this in - your PHP files to use the classes. - - - - - lib/xmlrpcs.inc - - - the XML-RPC server class. include() this - in addition to xmlrpc.inc to get server functionality - - - - - lib/xmlrpc_wrappers.php - - - helper functions to "automagically" convert plain php - functions to xmlrpc services and vice versa - - - - - demo/server/proxy.php - - - a sample server implementing xmlrpc proxy - functionality. - - - - - demo/server/server.php - - - a sample server hosting various demo functions, as well as a - full suite of functions used for interoperability testing. It is - used by testsuite.php (see below) for unit testing the library, and - is not to be copied literally into your production servers - - - - - demo/client/client.php, demo/client/agesort.php, - demo/client/which.php - - - client code to exercise some of the functions in server.php, - including the interopEchoTests.whichToolkit - method. - - - - - demo/client/wrap.php - - - client code to illustrate 'wrapping' of remote methods into - php functions. - - - - - demo/client/introspect.php - - - client code to illustrate usage of introspection capabilities - offered by server.php. - - - - - demo/client/mail.php - - - client code to illustrate usage of an xmlrpc-to-email gateway - using Dave Winer's XML-RPC server at userland.com. - - - - - demo/client/zopetest.php - - - example client code that queries an xmlrpc server built in - Zope. - - - - - demo/vardemo.php - - - examples of how to construct xmlrpcval types - - - - - demo/demo1.xml, demo/demo2.xml, demo/demo3.xml - - - XML-RPC responses captured in a file for testing purposes (you - can use these to test the - xmlrpcmsg->parseResponse() method). - - - - - demo/server/discuss.php, - demo/client/comment.php - - - Software used in the PHP chapter of to provide a comment server and allow the - attachment of comments to stories from Meerkat's data store. - - - - - test/testsuite.php, test/parse_args.php - - - A unit test suite for this software package. If you do - development on this software, please consider submitting tests for - this suite. - - - - - test/benchmark.php - - - A (very limited) benchmarking suite for this software package. - If you do development on this software, please consider submitting - benchmarks for this suite. - - - - - test/phpunit.php, test/PHPUnit/*.php - - - An (incomplete) version PEAR's unit test framework for PHP. - The complete package can be found at http://pear.php.net/package/PHPUnit - - - - - test/verify_compat.php - - - Script designed to help the user to verify the level of - compatibility of the library with the current php install - - - - - extras/test.pl, extras/test.py - - - Perl and Python programs to exercise server.php to test that - some of the methods work. - - - - - extras/workspace.testPhpServer.fttb - - - Frontier scripts to exercise the demo server. Thanks to Dave - Winer for permission to include these. See Dave's - announcement of these. - - - - - extras/rsakey.pem - - - A test certificate key for the SSL support, which can be used - to generate dummy certificates. It has the passphrase "test." - - - - - - - Known bugs and limitations - - This started out as a bare framework. Many "nice" bits haven't been - put in yet. Specifically, very little type validation or coercion has been - put in. PHP being a loosely-typed language, this is going to have to be - done explicitly (in other words: you can call a lot of library functions - passing them arguments of the wrong type and receive an error message only - much further down the code, where it will be difficult to - understand). - - dateTime.iso8601 is supported opaquely. It can't be done natively as - the XML-RPC specification explicitly forbids passing of timezone - specifiers in ISO8601 format dates. You can, however, use the and functions - to do the encoding and decoding for you. - - Very little HTTP response checking is performed (e.g. HTTP redirects - are not followed and the Content-Length HTTP header, mandated by the - xml-rpc spec, is not validated); cookie support still involves quite a bit - of coding on the part of the user. - - If a specific character set encoding other than US-ASCII, ISO-8859-1 - or UTF-8 is received in the HTTP header or XML prologue of xml-rpc request - or response messages then it will be ignored for the moment, and the - content will be parsed as if it had been encoded using the charset defined - by - - Support for receiving from servers version 1 cookies (i.e. - conforming to RFC 2965) is quite incomplete, and might cause unforeseen - errors. - - - - Support - - - Online Support - - XML-RPC for PHP is offered "as-is" without any warranty or - commitment to support. However, informal advice and help is available - via the XML-RPC for PHP website and mailing list and from - XML-RPC.com. - - - - The XML-RPC for PHP development is hosted - on github.com/gggeek/phpxmlrpc. - Bugs, feature requests and patches can be posted to the project's - website. - - - - The PHP XML-RPC interest mailing list is - run by the author. More details can be - found here. - - - - For more general XML-RPC questions, there is a Yahoo! Groups - XML-RPC mailing - list. - - - - The XML-RPC.com discussion - group is a useful place to get help with using XML-RPC. This group - is also gatewayed into the Yahoo! Groups mailing list. - - - - - - The Jellyfish Book - - Together with Simon St.Laurent and Joe - Johnston, Edd Dumbill wrote a book on XML-RPC for O'Reilly and - Associates on XML-RPC. It features a rather fetching jellyfish on the - cover. - - Complete details of the book are available from - O'Reilly's web site. - - Edd is responsible for the chapter on PHP, which includes a worked - example of creating a forum server, and hooking it up the O'Reilly's - Meerkat service in - order to allow commenting on news stories from around the Web. - - If you've benefited from the effort that has been put into writing - this software, then please consider buying the book! - - - - - Class documentation - - - xmlrpcval - - This is where a lot of the hard work gets done. This class enables - the creation and encapsulation of values for XML-RPC. - - Ensure you've read the XML-RPC spec at http://www.xmlrpc.com/stories/storyReader$7 - before reading on as it will make things clearer. - - The xmlrpcval class can store arbitrarily - complicated values using the following types: i4 int boolean - string double dateTime.iso8601 base64 array struct - null. You should refer to the spec for more information on - what each of these types mean. - - - Notes on types - - - int - - The type i4 is accepted as a synonym - for int when creating xmlrpcval objects. The - xml parsing code will always convert i4 to - int: int is regarded - by this implementation as the canonical name for this type. - - - - base64 - - Base 64 encoding is performed transparently to the caller when - using this type. Decoding is also transparent. Therefore you ought - to consider it as a "binary" data type, for use when you want to - pass data that is not 7-bit clean. - - - - boolean - - The php values true and - 1 map to true. All other - values (including the empty string) are converted to - false. - - - - string - - Characters <, >, ', ", &, are encoded using their - entity reference as &lt; &gt; &apos; &quot; and - &amp; All other characters outside of the ASCII range are - encoded using their character reference representation (e.g. - &#200 for é). The XML-RPC spec recommends only encoding - < & but this implementation goes further, - for reasons explained by the XML 1.0 - recommendation. In particular, using character reference - representation has the advantage of producing XML that is valid - independently of the charset encoding assumed. - - - - null - - There is no support for encoding null - values in the XML-RPC spec, but at least a couple of extensions (and - many toolkits) do support it. Before using null - values in your messages, make sure that the responding party accepts - them, and uses the same encoding convention (see ...). - - - - - Creation - - The constructor is the normal way to create an - xmlrpcval. The constructor can take these - forms: - - - - xmlrpcvalnew - xmlrpcval - - - - - - xmlrpcvalnew - xmlrpcval - - string$stringVal - - - - xmlrpcvalnew - xmlrpcval - - mixed$scalarVal - - string$scalartyp - - - - xmlrpcvalnew - xmlrpcval - - array$arrayVal - - string$arraytyp - - - - The first constructor creates an empty value, which must be - altered using the methods addScalar, - addArray or addStruct before - it can be used. - - The second constructor creates a simple string value. - - The third constructor is used to create a scalar value. The - second parameter must be a name of an XML-RPC type. Valid types are: - "int", "boolean", - "string", "double", - "dateTime.iso8601", "base64" or - "null". - - Examples: - - -$myInt = new xmlrpcval(1267, "int"); -$myString = new xmlrpcval("Hello, World!", "string"); -$myBool = new xmlrpcval(1, "boolean"); -$myString2 = new xmlrpcval(1.24, "string"); // note: this will serialize a php float value as xmlrpc string - - - The fourth constructor form can be used to compose complex - XML-RPC values. The first argument is either a simple array in the - case of an XML-RPC array or an associative - array in the case of a struct. The elements of - the array must be xmlrpcval objects - themselves. - - The second parameter must be either "array" - or "struct". - - Examples: - - -$myArray = new xmlrpcval( - array( - new xmlrpcval("Tom"), - new xmlrpcval("Dick"), - new xmlrpcval("Harry") - ), - "array"); - -// recursive struct -$myStruct = new xmlrpcval( - array( - "name" => new xmlrpcval("Tom", "string"), - "age" => new xmlrpcval(34, "int"), - "address" => new xmlrpcval( - array( - "street" => new xmlrpcval("Fifht Ave", "string"), - "city" => new xmlrpcval("NY", "string") - ), - "struct") - ), - "struct"); - - - See the file vardemo.php in this distribution - for more examples. - - - - Methods - - - addScalar - - - - intaddScalar - - string$stringVal - - - - intaddScalar - - mixed$scalarVal - - string$scalartyp - - - - If $val is an empty - xmlrpcval this method makes it a scalar - value, and sets that value. - - If $val is already a scalar value, then - no more scalars can be added and 0 is - returned. - - If $val is an xmlrpcval of type array, - the php value $scalarval is added as its last - element. - - If all went OK, 1 is returned, otherwise - 0. - - - - addArray - - - - intaddArray - - array$arrayVal - - - - The argument is a simple (numerically indexed) array. The - elements of the array must be - xmlrpcval objects - themselves. - - Turns an empty xmlrpcval into an - array with contents as specified by - $arrayVal. - - If $val is an xmlrpcval of type array, - the elements of $arrayVal are appended to the - existing ones. - - See the fourth constructor form for more information. - - If all went OK, 1 is returned, otherwise - 0. - - - - addStruct - - - - intaddStruct - - array$assocArrayVal - - - - The argument is an associative array. The elements of the - array must be xmlrpcval objects - themselves. - - Turns an empty xmlrpcval into a - struct with contents as specified by - $assocArrayVal. - - If $val is an xmlrpcval of type struct, - the elements of $arrayVal are merged with the - existing ones. - - See the fourth constructor form for more information. - - If all went OK, 1 is returned, otherwise - 0. - - - - kindOf - - - - stringkindOf - - - - - - Returns a string containing "struct", "array" or "scalar" - describing the base type of the value. If it returns "undef" it - means that the value hasn't been initialised. - - - - serialize - - - - stringserialize - - - - - - Returns a string containing the XML-RPC representation of this - value. - - - - scalarVal - - - - mixedscalarVal - - - - - - If $val->kindOf() == "scalar", this - method returns the actual PHP-language value of the scalar (base 64 - decoding is automatically handled here). - - - - scalarTyp - - - - stringscalarTyp - - - - - - If $val->kindOf() == "scalar", this - method returns a string denoting the type of the scalar. As - mentioned before, i4 is always coerced to - int. - - - - arrayMem - - - - xmlrpcvalarrayMem - - int$n - - - - If $val->kindOf() == "array", returns - the $nth element in the array represented by - the value $val. The value returned is an - xmlrpcval object. - - -// iterating over values of an array object -for ($i = 0; $i < $val->arraySize(); $i++) -{ - $v = $val->arrayMem($i); - echo "Element $i of the array is of type ".$v->kindOf(); -} - - - - - arraySize - - - - intarraySize - - - - - - If $val is an - array, returns the number of elements in that - array. - - - - structMem - - - - xmlrpcvalstructMem - - string$memberName - - - - If $val->kindOf() == "struct", returns - the element called $memberName from the - struct represented by the value $val. The - value returned is an xmlrpcval object. - - - - structEach - - - - arraystructEach - - - - - - Returns the next (key, value) pair from the struct, when - $val is a struct. - $value is an xmlrpcval itself. See also . - - -// iterating over all values of a struct object -$val->structreset(); -while (list($key, $v) = $val->structEach()) -{ - echo "Element $key of the struct is of type ".$v->kindOf(); -} - - - - - structReset - - - - voidstructReset - - - - - - Resets the internal pointer for - structEach() to the beginning of the struct, - where $val is a struct. - - - - structMemExists - - - - boolstructMemExsists - - string$memberName - - - - Returns TRUE or - FALSE depending on whether a member of the - given name exists in the struct. - - - - - - xmlrpcmsg - - This class provides a representation for a request to an XML-RPC - server. A client sends an xmlrpcmsg to a server, - and receives back an xmlrpcresp (see ). - - - Creation - - The constructor takes the following forms: - - - - xmlrpcmsgnew - xmlrpcmsg - - string$methodName - - array$parameterArraynull - - - - Where methodName is a string indicating - the name of the method you wish to invoke, and - parameterArray is a simple php - Array of xmlrpcval - objects. Here's an example message to the US state - name server: - - -$msg = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int"))); - - - This example requests the name of state number 23. For more - information on xmlrpcval objects, see . - - Note that the parameterArray parameter is - optional and can be omitted for methods that take no input parameters - or if you plan to add parameters one by one. - - - - Methods - - - addParam - - - - booladdParam - - xmlrpcval$xmlrpcVal - - - - Adds the xmlrpcval - xmlrpcVal to the parameter list for this - method call. Returns TRUE or FALSE on error. - - - - getNumParams - - - - intgetNumParams - - - - - - Returns the number of parameters attached to this - message. - - - - getParam - - - - xmlrpcvalgetParam - - int$n - - - - Gets the nth parameter in the message - (with the index zero-based). Use this method in server - implementations to retrieve the values sent by the client. - - - - method - - - - stringmethod - - - - - - stringmethod - - string$methName - - - - Gets or sets the method contained in the XML-RPC - message. - - - - parseResponse - - - - xmlrpcrespparseResponse - - string$xmlString - - - - Given an incoming XML-RPC server response contained in the - string $xmlString, this method constructs an - xmlrpcresp response object and returns it, - setting error codes as appropriate (see ). - - This method processes any HTTP/MIME headers it finds. - - - - parseResponseFile - - - - xmlrpcrespparseResponseFile - - file handle - resource$fileHandle - - - - Given an incoming XML-RPC server response on the open file - handle fileHandle, this method reads all the - data it finds and passes it to - parseResponse. - - This method is useful to construct responses from pre-prepared - files (see files demo1.xml, demo2.xml, demo3.xml - in this distribution). It processes any HTTP headers it finds, and - does not close the file handle. - - - - serialize - - - - string - serialize - - - - - - Returns the an XML string representing the XML-RPC - message. - - - - - - xmlrpc_client - - This is the basic class used to represent a client of an XML-RPC - server. - - - Creation - - The constructor accepts one of two possible syntaxes: - - - - xmlrpc_clientnew - xmlrpc_client - - string$server_url - - - - xmlrpc_clientnew - xmlrpc_client - - string$server_path - - string$server_hostname - - int$server_port80 - - string$transport'http' - - - - Here are a couple of usage examples of the first form: - - -$client = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php"); -$another_client = new xmlrpc_client("https://james:bond@secret.service.com:443/xmlrpcserver?agent=007"); - - - The second syntax does not allow to express a username and - password to be used for basic HTTP authorization as in the second - example above, but instead it allows to choose whether xmlrpc calls - will be made using the HTTP 1.0 or 1.1 protocol. - - Here's another example client set up to query Userland's XML-RPC - server at betty.userland.com: - - -$client = new xmlrpc_client("/RPC2", "betty.userland.com", 80); - - - The server_port parameter is optional, - and if omitted will default to 80 when using HTTP and 443 when using - HTTPS (see the method - below). - - The transport parameter is optional, and - if omitted will default to 'http'. Allowed values are either - 'http', 'https' or - 'http11'. Its value can be overridden with every call - to the send method. See the - send method below for more details about the - meaning of the different values. - - - - Methods - - This class supports the following methods. - - - send - - This method takes the forms: - - - - xmlrpcrespsend - - xmlrpcmsg$xmlrpc_message - - int$timeout - - string$transport - - - - arraysend - - array$xmlrpc_messages - - int$timeout - - string$transport - - - - xmlrpcrespsend - - string$xml_payload - - int$timeout - - string$transport - - - - Where xmlrpc_message is an instance of - xmlrpcmsg (see ), - and response is an instance of - xmlrpcresp (see ). - - If xmlrpc_messages is an array of - message instances, responses will be an array of - response instances. The client will try to make use of a single - system.multicall xml-rpc method call to forward to the - server all the messages in a single HTTP round trip, unless - $client->no_multicall has been previously set to - TRUE (see the multicall method below), in which case - many consecutive xmlrpc requests will be sent. - - The third syntax allows to build by hand (or any other means) - a complete xmlrpc request message, and send it to the server. - xml_payload should be a string containing the - complete xml representation of the request. It is e.g. useful when, - for maximal speed of execution, the request is serialized into a - string using the native php xmlrpc functions (see the php manual on - xmlrpc). - - The timeout is optional, and will be - set to 0 (wait for platform-specific predefined - timeout) if omitted. This timeout value is passed to - fsockopen(). It is also used for detecting - server timeouts during communication (i.e. if the server does not - send anything to the client for timeout - seconds, the connection will be closed). - - The transport parameter is optional, - and if omitted will default to the transport set using instance - creator or 'http' if omitted. The only other valid values are - 'https', which will use an SSL HTTP connection to connect to the - remote server, and 'http11'. Note that your PHP must have the "curl" - extension compiled in order to use both these features. Note that - when using SSL you should normally set your port number to 443, - unless the SSL server you are contacting runs at any other - port. - - - PHP 4.0.6 has a bug which prevents SSL working. - - - In addition to low-level errors, the XML-RPC server you were - querying may return an error in the - xmlrpcresp object. See for details of how to handle these - errors. - - - - multiCall - - This method takes the form: - - - - arraymultiCall - - array$messages - - int$timeout - - string$transport - - bool$fallback - - - - This method is used to boxcar many method calls in a single - xml-rpc request. It will try first to make use of the - system.multicall xml-rpc method call, and fall back to - executing many separate requests if the server returns any - error. - - msgs is an array of - xmlrpcmsg objects (see ), and response is an - array of xmlrpcresp objects (see ). - - The timeout and - transport parameters are optional, and behave - as in the send method above. - - The fallback parameter is optional, and - defaults to TRUE. When set to - FALSE it will prevent the client to try using - many single method calls in case of failure of the first multicall - request. It should be set only when the server is known to support - the multicall extension. - - - - setAcceptedCompression - - - - voidsetAcceptedCompression - - string$compressionmethod - - - - This method defines whether the client will accept compressed - xml payload forming the bodies of the xmlrpc responses received from - servers. Note that enabling reception of compressed responses merely - adds some standard http headers to xmlrpc requests. It is up to the - xmlrpc server to return compressed responses when receiving such - requests. Allowed values for - compressionmethod are: 'gzip', 'deflate', - 'any' or null (with any meaning either gzip or deflate). - - This requires the "zlib" extension to be enabled in your php - install. If it is, by default xmlrpc_client - instances will enable reception of compressed content. - - - - setCaCertificate - - - - voidsetCaCertificate - - string$certificate - - bool$is_dir - - - - This method sets an optional certificate to be used in - SSL-enabled communication to validate a remote server with (when the - server_method is set to 'https' in the - client's construction or in the send method and - SetSSLVerifypeer has been set to - TRUE). - - The certificate parameter must be the - filename of a PEM formatted certificate, or a directory containing - multiple certificate files. The is_dir - parameter defaults to FALSE, set it to - TRUE to specify that - certificate indicates a directory instead of - a single file. - - This requires the "curl" extension to be compiled into your - installation of PHP. For more details see the man page for the - curl_setopt function. - - - - setCertificate - - - - voidsetCertificate - - string$certificate - - string$passphrase - - - - This method sets the optional certificate and passphrase used - in SSL-enabled communication with a remote server (when the - server_method is set to 'https' in the - client's construction or in the send method). - - The certificate parameter must be the - filename of a PEM formatted certificate. The - passphrase parameter must contain the - password required to use the certificate. - - This requires the "curl" extension to be compiled into your - installation of PHP. For more details see the man page for the - curl_setopt function. - - Note: to retrieve information about the client certificate on - the server side, you will need to look into the environment - variables which are set up by the webserver. Different webservers - will typically set up different variables. - - - - setCookie - - - - voidsetCookie - - string$name - - string$value - - string$path - - string$domain - - int$port - - - - This method sets a cookie that will be sent to the xmlrpc - server along with every further request (useful e.g. for keeping - session info outside of the xml-rpc payload). - - $value is optional, and defaults to - null. - - $path, $domain and $port are optional, - and will be omitted from the cookie header if unspecified. Note that - setting any of these values will turn the cookie into a 'version 1' - cookie, that might not be fully supported by the server (see RFC2965 - for more details). - - - - setCredentials - - - - voidsetCredentials - - string$username - - string$password - - int$authtype - - - - This method sets the username and password for authorizing the - client to a server. With the default (HTTP) transport, this - information is used for HTTP Basic authorization. Note that username - and password can also be set using the class constructor. With HTTP - 1.1 and HTTPS transport, NTLM and Digest authentication protocols - are also supported. To enable them use the constants - CURLAUTH_DIGEST and - CURLAUTH_NTLM as values for the authtype - parameter. - - - - setCurlOptions - - - - voidsetCurlOptions - - array$options - - This method allows to directly set any desired - option to manipulate the usage of the cURL client (when in cURL - mode). It can be used eg. to explicitly bind to an outgoing ip - address when the server is multihomed - - - - setDebug - - - - voidsetDebug - - int$debugLvl - - - - debugLvl is either 0, - 1 or 2 depending on whether you require the client to - print debugging information to the browser. The default is not to - output this information (0). - - The debugging information at level 1includes the raw data - returned from the XML-RPC server it was querying (including bot HTTP - headers and the full XML payload), and the PHP value the client - attempts to create to represent the value returned by the server. At - level2, the complete payload of the xmlrpc request is also printed, - before being sent t the server. - - This option can be very useful when debugging servers as it - allows you to see exactly what the client sends and the server - returns. - - - - setKey - - - - voidsetKey - - int$key - - int$keypass - - - - This method sets the optional certificate key and passphrase - used in SSL-enabled communication with a remote server (when the - transport is set to 'https' in the client's - construction or in the send method). - - This requires the "curl" extension to be compiled into your - installation of PHP. For more details see the man page for the - curl_setopt function. - - - - setProxy - - - - voidsetProxy - - string$proxyhost - - int$proxyport - - string$proxyusername - - string$proxypassword - - int$authtype - - - - This method enables calling servers via an HTTP proxy. The - proxyusername, - proxypassword and authtype - parameters are optional. Authtype defaults to - CURLAUTH_BASIC (Basic authentication protocol); - the only other valid value is the constant - CURLAUTH_NTLM, and has effect only when the - client uses the HTTP 1.1 protocol. - - NB: CURL versions before 7.11.10 cannot use a proxy to - communicate with https servers. - - - - setRequestCompression - - - - voidsetRequestCompression - - string$compressionmethod - - - - This method defines whether the xml payload forming the - request body will be sent to the server in compressed format, as per - the HTTP specification. This is particularly useful for large - request parameters and over slow network connections. Allowed values - for compressionmethod are: 'gzip', 'deflate', - 'any' or null (with any meaning either gzip or deflate). Note that - there is no automatic fallback mechanism in place for errors due to - servers not supporting receiving compressed request bodies, so make - sure that the particular server you are querying does accept - compressed requests before turning it on. - - This requires the "zlib" extension to be enabled in your php - install. - - - - setSSLVerifyHost - - - - voidsetSSLVerifyHost - - int$i - - - - This method defines whether connections made to XML-RPC - backends via HTTPS should verify the remote host's SSL certificate's - common name (CN). By default, only the existence of a CN is checked. - $i should be an - integer value; 0 to not check the CN at all, 1 to merely check for - its existence, and 2 to check that the CN on the certificate matches - the hostname that is being connected to. - - - - setSSLVerifyPeer - - - - voidsetSSLVerifyPeer - - bool$i - - - - This method defines whether connections made to XML-RPC - backends via HTTPS should verify the remote host's SSL certificate, - and cause the connection to fail if the cert verification fails. - $i should be a boolean - value. Default value: TRUE. To specify custom - SSL certificates to validate the server with, use the - setCaCertificate method. - - - - setUserAgent - - - - voidUseragent - - string$useragent - - This method sets a custom user-agent that will be - used by the client in the http headers sent with the request. The - default value is built using the library name and version - constants. - - - - - Variables - - NB: direct manipulation of these variables is only recommended - for advanced users. - - - no_multicall - - This member variable determines whether the multicall() method - will try to take advantage of the system.multicall xmlrpc method to - dispatch to the server an array of requests in a single http - roundtrip or simply execute many consecutive http calls. Defaults to - FALSE, but it will be enabled automatically on the first failure of - execution of system.multicall. - - - - request_charset_encoding - - This is the charset encoding that will be used for serializing - request sent by the client. - - If defaults to NULL, which means using US-ASCII and encoding - all characters outside of the ASCII range using their xml character - entity representation (this has the benefit that line end characters - will not be mangled in the transfer, a CR-LF will be preserved as - well as a singe LF). - - Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1' - - - - return_type - - This member variable determines whether the value returned - inside an xmlrpcresp object as results of calls to the send() and - multicall() methods will be an xmlrpcval object, a plain php value - or a raw xml string. Allowed values are 'xmlrpcvals' (the default), - 'phpvals' and 'xml'. To allow the user to differentiate between a - correct and a faulty response, fault responses will be returned as - xmlrpcresp objects in any case. Note that the 'phpvals' setting will - yield faster execution times, but some of the information from the - original response will be lost. It will be e.g. impossible to tell - whether a particular php string value was sent by the server as an - xmlrpc string or base64 value. - - Example usage: - - -$client = new xmlrpc_client("phpxmlrpc.sourceforge.net/server.php"); -$client->return_type = 'phpvals'; -$message = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int"))); -$resp = $client->send($message); -if ($resp->faultCode()) echo 'KO. Error: '.$resp->faultString(); else echo 'OK: got '.$resp->value(); - - - For more details about usage of the 'xml' value, see Appendix - A. - - - - - - xmlrpcresp - - This class is used to contain responses to XML-RPC requests. A - server method handler will construct an - xmlrpcresp and pass it as a return value. This - same value will be returned by the result of an invocation of the - send method of the - xmlrpc_client class. - - - Creation - - - - xmlrpcrespnew - xmlrpcresp - - xmlrpcval$xmlrpcval - - - - xmlrpcrespnew - xmlrpcresp - - 0 - - int$errcode - - string$err_string - - - - The first syntax is used when execution has happened without - difficulty: $xmlrpcval is an - xmlrpcval value with the result of the method - execution contained in it. Alternatively it can be a string containing - the xml serialization of the single xml-rpc value result of method - execution. - - The second type of constructor is used in case of failure. - errcode and err_string - are used to provide indication of what has gone wrong. See for more information on passing error - codes. - - - - Methods - - - faultCode - - - - intfaultCode - - - - - - Returns the integer fault code return from the XML-RPC - response. A zero value indicates success, any other value indicates - a failure response. - - - - faultString - - - - stringfaultString - - - - - - Returns the human readable explanation of the fault indicated - by $resp->faultCode(). - - - - value - - - - xmlrpcvalvalue - - - - - - Returns an xmlrpcval object containing - the return value sent 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). - - Note: if the xmlrpcresp instance in question has been created - by an xmlrpc_client object whose - return_type was set to 'phpvals', then a plain - php value will be returned instead of an - xmlrpcval object. If the - return_type was set to 'xml', an xml string will - be returned (see the return_type member var above for more - details). - - - - serialize - - - - stringserialize - - - - - - Returns an XML string representation of the response (xml - prologue not included). - - - - - - xmlrpc_server - - The implementation of this class has been kept as simple to use as - possible. The constructor for the server basically does all the work. - Here's a minimal example: - - - function foo ($xmlrpcmsg) { - ... - return new xmlrpcresp($some_xmlrpc_val); - } - - class bar { - function foobar($xmlrpcmsg) { - ... - return new xmlrpcresp($some_xmlrpc_val); - } - } - - $s = new xmlrpc_server( - array( - "examples.myFunc1" => array("function" => "foo"), - "examples.myFunc2" => array("function" => "bar::foobar"), - )); - - - This performs everything you need to do with a server. The single - constructor argument is an associative array from xmlrpc method names to - php function names. The incoming request is parsed and dispatched to the - relevant php function, which is responsible for returning a - xmlrpcresp object, that will be serialized back - to the caller. - - - Method handler functions - - Both php functions and class methods can be registered as xmlrpc - method handlers. - - The synopsis of a method handler function is: - - xmlrpcresp $resp = function (xmlrpcmsg $msg) - - No text should be echoed 'to screen' by the handler function, or - it will break the xml response sent back to the client. This applies - also to error and warning messages that PHP prints to screen unless - the appropriate parameters have been set in the php.in file. Another - way to prevent echoing of errors inside the response and facilitate - debugging is to use the server SetDebug method with debug level 3 (see - ...). Exceptions thrown duting execution of handler functions are - caught by default and a XML-RPC error reponse is generated instead. - This behaviour can be finetuned by usage of the - exception_handling member variable (see - ...). - - Note that if you implement a method with a name prefixed by - system. the handler function will be invoked by the - server with two parameters, the first being the server itself and the - second being the xmlrpcmsg object. - - The same php function can be registered as handler of multiple - xmlrpc methods. - - Here is a more detailed example of what the handler function - foo may do: - - - function foo ($xmlrpcmsg) { - global $xmlrpcerruser; // import user errcode base value - - $meth = $xmlrpcmsg->method(); // retrieve method name - $par = $xmlrpcmsg->getParam(0); // retrieve value of first parameter - assumes at least one param received - $val = $par->scalarval(); // decode value of first parameter - assumes it is a scalar value - - ... - - if ($err) { - // this is an error condition - return new xmlrpcresp(0, $xmlrpcerruser+1, // user error 1 - "There's a problem, Captain"); - } else { - // this is a successful value being returned - return new xmlrpcresp(new xmlrpcval("All's fine!", "string")); - } - } - - - See server.php in this distribution for - more examples of how to do this. - - Since release 2.0RC3 there is a new, even simpler way of - registering php functions with the server. See section 5.7 - below - - - - The dispatch map - - The first argument to the xmlrpc_server - constructor is an array, called the dispatch map. - In this array is the information the server needs to service the - XML-RPC methods you define. - - The dispatch map takes the form of an associative array of - associative arrays: the outer array has one entry for each method, the - key being the method name. The corresponding value is another - associative array, which can have the following members: - - - - function - this - entry is mandatory. It must be either a name of a function in the - global scope which services the XML-RPC method, or an array - containing an instance of an object and a static method name (for - static class methods the 'class::method' syntax is also - supported). - - - - signature - this - entry is an array containing the possible signatures (see ) for the method. If this entry is present - then the server will check that the correct number and type of - parameters have been sent for this method before dispatching - it. - - - - docstring - this - entry is a string containing documentation for the method. The - documentation may contain HTML markup. - - - - signature_docs - this entry can be used - to provide documentation for the single parameters. It must match - in structure the 'signature' member. By default, only the - documenting_xmlrpc_server class in the - extras package will take advantage of this, since the - "system.methodHelp" protocol does not support documenting method - parameters individually. - - - - parameters_type - this entry can be used - when the server is working in 'xmlrpcvals' mode (see ...) to - define one or more entries in the dispatch map as being functions - that follow the 'phpvals' calling convention. The only useful - value is currently the string phpvals. - - - - Look at the server.php example in the - distribution to see what a dispatch map looks like. - - - - Method signatures - - A signature is a description of a method's return type and its - parameter types. A method may have more than one signature. - - Within a server's dispatch map, each method has an array of - possible signatures. Each signature is an array of types. The first - entry is the return type. For instance, the method string examples.getStateName(int) - has the signature array($xmlrpcString, $xmlrpcInt) - and, assuming that it is the only possible signature for the - method, it might be used like this in server creation: -$findstate_sig = array(array($xmlrpcString, $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.'; - -$s = new xmlrpc_server( array( - "examples.getStateName" => array( - "function" => "findstate", - "signature" => $findstate_sig, - "docstring" => $findstate_doc - ))); - - - Note that method signatures do not allow to check nested - parameters, e.g. the number, names and types of the members of a - struct param cannot be validated. - - If a method that you want to expose has a definite number of - parameters, but each of those parameters could reasonably be of - multiple types, the array of acceptable signatures will easily grow - into a combinatorial explosion. To avoid such a situation, the lib - defines the global var $xmlrpcValue, which can be - used in method signatures as a placeholder for 'any xmlrpc - type': - - -$echoback_sig = array(array($xmlrpcValue, $xmlrpcValue)); - -$findstate_doc = 'Echoes back to the client the received value, regardless of its type'; - -$s = new xmlrpc_server( array( - "echoBack" => array( - "function" => "echoback", - "signature" => $echoback_sig, // this sig guarantees that the method handler will be called with one and only one parameter - "docstring" => $echoback_doc - ))); - - - Methods system.listMethods, - system.methodHelp, - system.methodSignature and - system.multicall are already defined by the - server, and should not be reimplemented (see Reserved Methods - below). - - - - Delaying the server response - - You may want to construct the server, but for some reason not - fulfill the request immediately (security verification, for instance). - If you omit to pass to the constructor the dispatch map or pass it a - second argument of 0 this will have the desired - effect. You can then use the service() method of - the server class to service the request. For example: - - -$s = new xmlrpc_server($myDispMap, 0); // second parameter = 0 prevents automatic servicing of request - -// ... some code that does other stuff here - -$s->service(); - - - Note that the service method will print - the complete result payload to screen and send appropriate HTTP - headers back to the client, but also return the response object. This - permits further manipulation of the response, possibly in combination - with output buffering. - - To prevent the server from sending HTTP headers back to the - client, you can pass a second parameter with a value of - TRUE to the service - method. In this case, the response payload will be returned instead of - the response object. - - Xmlrpc requests retrieved by other means than HTTP POST bodies - can also be processed. For example: - - -$s = new xmlrpc_server(); // not passing a dispatch map prevents automatic servicing of request - -// ... some code that does other stuff here, including setting dispatch map into server object - -$resp = $s->service($xmlrpc_request_body, true); // parse a variable instead of POST body, retrieve response payload - -// ... some code that does other stuff with xml response $resp here - - - - - Modifying the server behaviour - - A couple of methods / class variables are available to modify - the behaviour of the server. The only way to take advantage of their - existence is by usage of a delayed server response (see above) - - - setDebug() - - This function controls weather the server is going to echo - debugging messages back to the client as comments in response body. - Valid values: 0,1,2,3, with 1 being the default. At level 0, no - debug info is returned to the client. At level 2, the complete - client request is added to the response, as part of the xml - comments. At level 3, a new PHP error handler is set when executing - user functions exposed as server methods, and all non-fatal errors - are trapped and added as comments into the response. - - - - allow_system_funcs - - Default_value: TRUE. When set to FALSE, disables support for - System.xxx functions in the server. It - might be useful e.g. if you do not wish the server to respond to - requests to System.ListMethods. - - - - compress_response - - When set to TRUE, enables the server to take advantage of HTTP - compression, otherwise disables it. Responses will be transparently - compressed, but only when an xmlrpc-client declares its support for - compression in the HTTP headers of the request. - - Note that the ZLIB php extension must be installed for this to - work. If it is, compress_response will default to - TRUE. - - - - exception_handling - - This variable controls the behaviour of the server when an - exception is thrown by a method handler php function. Valid values: - 0,1,2, with 0 being the default. At level 0, the server catches the - exception and return an 'internal error' xmlrpc response; at 1 it - catches the exceptions and return an xmlrpc response with the error - code and error message corresponding to the exception that was - thron; at 2 = the exception is floated to the upper layers in the - code - - - - response_charset_encoding - - Charset encoding to be used for response (only affects string - values). - - If it can, the server will convert the generated response from - internal_encoding to the intended one. - - Valid values are: a supported xml encoding (only UTF-8 and - ISO-8859-1 at present, unless mbstring is enabled), null (leave - charset unspecified in response and convert output stream to - US_ASCII), 'default' (use xmlrpc library default as specified in - xmlrpc.inc, convert output stream if needed), or 'auto' (use - client-specified charset encoding or same as request if request - headers do not specify it (unless request is US-ASCII: then use - library default anyway). - - - - - Fault reporting - - Fault codes for your servers should start at the value indicated - by the global $xmlrpcerruser + 1. - - Standard errors returned by the server include: - - - - 1 Unknown method - - - Returned if the server was asked to dispatch a method it - didn't know about - - - - - 2 Invalid return - payload - - - This error is actually generated by the client, not - server, code, but signifies that a server returned something it - couldn't understand. A more detailed error report is sometimes - added onto the end of the phrase above. - - - - - 3 Incorrect - parameters - - - This error is generated when the server has signature(s) - defined for a method, and the parameters passed by the client do - not match any of signatures. - - - - - 4 Can't introspect: method - unknown - - - This error is generated by the builtin - system.* methods when any kind of - introspection is attempted on a method undefined by the - server. - - - - - 5 Didn't receive 200 OK from - remote server - - - This error is generated by the client when a remote server - doesn't return HTTP/1.1 200 OK in response to a request. A more - detailed error report is added onto the end of the phrase - above. - - - - - 6 No data received from - server - - - This error is generated by the client when a remote server - returns HTTP/1.1 200 OK in response to a request, but no - response body follows the HTTP headers. - - - - - 7 No SSL support compiled - in - - - This error is generated by the client when trying to send - a request with HTTPS and the CURL extension is not available to - PHP. - - - - - 8 CURL error - - - This error is generated by the client when trying to send - a request with HTTPS and the HTTPS communication fails. - - - - - 9-14 multicall - errors - - - These errors are generated by the server when something - fails inside a system.multicall request. - - - - - 100- XML parse - errors - - - Returns 100 plus the XML parser error code for the fault - that occurred. The faultString returned - explains where the parse error was in the incoming XML - stream. - - - - - - - 'New style' servers - - In the same spirit of simplification that inspired the - xmlrpc_client::return_type class variable, a new - class variable has been added to the server class: - functions_parameters_type. When set to 'phpvals', - the functions registered in the server dispatch map will be called - with plain php values as parameters, instead of a single xmlrpcmsg - instance parameter. The return value of those functions is expected to - be a plain php value, too. An example is worth a thousand - words: - function foo($usr_id, $out_lang='en') { - global $xmlrpcerruser; - - ... - - if ($someErrorCondition) - return new xmlrpcresp(0, $xmlrpcerruser+1, 'DOH!'); - else - return array( - 'name' => 'Joe', - 'age' => 27, - 'picture' => new xmlrpcval(file_get_contents($picOfTheGuy), 'base64') - ); - } - - $s = new xmlrpc_server( - array( - "examples.myFunc" => array( - "function" => "bar::foobar", - "signature" => array( - array($xmlrpcString, $xmlrpcInt), - array($xmlrpcString, $xmlrpcInt, $xmlrpcString) - ) - ) - ), false); - $s->functions_parameters_type = 'phpvals'; - $s->service(); -There are a few things to keep in mind when using this - simplified syntax: - - to return an xmlrpc error, the method handler function must - return an instance of xmlrpcresp. The only - other way for the server to know when an error response should be - served to the client is to throw an exception and set the server's - exception_handling memeber var to 1; - - to return a base64 value, the method handler function must - encode it on its own, creating an instance of an xmlrpcval - object; - - the method handler function cannot determine the name of the - xmlrpc method it is serving, unlike standard handler functions that - can retrieve it from the message object; - - when receiving nested parameters, the method handler function - has no way to distinguish a php string that was sent as base64 value - from one that was sent as a string value; - - this has a direct consequence on the support of - system.multicall: a method whose signature contains datetime or base64 - values will not be available to multicall calls; - - last but not least, the direct parsing of xml to php values is - much faster than using xmlrpcvals, and allows the library to handle - much bigger messages without allocating all available server memory or - smashing PHP recursive call stack. - - - - - - Global variables - - Many global variables are defined in the xmlrpc.inc file. Some of - those are meant to be used as constants (and modifying their value might - cause unpredictable behaviour), while some others can be modified in your - php scripts to alter the behaviour of the xml-rpc client and - server. - - - "Constant" variables - - - $xmlrpcerruser - - - $xmlrpcerruser - - 800 - The minimum value for errors reported by user - implemented XML-RPC servers. Error numbers lower than that are - reserved for library usage. - - - - $xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, - $xmlrpcString, $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, - $xmlrpcStruct, $xmlrpcValue, $xmlrpcNull - - For convenience the strings representing the XML-RPC types have - been encoded as global variables: -$xmlrpcI4="i4"; -$xmlrpcInt="int"; -$xmlrpcBoolean="boolean"; -$xmlrpcDouble="double"; -$xmlrpcString="string"; -$xmlrpcDateTime="dateTime.iso8601"; -$xmlrpcBase64="base64"; -$xmlrpcArray="array"; -$xmlrpcStruct="struct"; -$xmlrpcValue="undefined"; -$xmlrpcNull="null"; - - - - - $xmlrpcTypes, $xmlrpc_valid_parents, $xmlrpcerr, $xmlrpcstr, - $xmlrpcerrxml, $xmlrpc_backslash, $_xh, $xml_iso88591_Entities, - $xmlEntities, $xmlrpcs_capabilities - - Reserved for internal usage. - - - - - Variables whose value can be modified - - - xmlrpc_defencoding - - - $xmlrpc_defencoding - - "UTF8" - - - This variable defines the character set encoding that will be - used by the xml-rpc client and server to decode the received messages, - when a specific charset declaration is not found (in the messages sent - non-ascii chars are always encoded using character references, so that - the produced xml is valid regardless of the charset encoding - assumed). - - Allowed values: "UTF8", - "ISO-8859-1", "ASCII". - - Note that the appropriate RFC actually mandates that XML - received over HTTP without indication of charset encoding be treated - as US-ASCII, but many servers and clients 'in the wild' violate the - standard, and assume the default encoding is UTF-8. - - - - xmlrpc_internalencoding - - - $xmlrpc_internalencoding - - "ISO-8859-1" - This variable defines the character set encoding - that the library uses to transparently encode into valid XML the - xml-rpc values created by the user and to re-encode the received - xml-rpc values when it passes them to the PHP application. It only - affects xml-rpc values of string type. It is a separate value from - xmlrpc_defencoding, allowing e.g. to send/receive xml messages encoded - on-the-wire in US-ASCII and process them as UTF-8. It defaults to the - character set used internally by PHP (unless you are running an - MBString-enabled installation), so you should change it only in - special situations, if e.g. the string values exchanged in the xml-rpc - messages are directly inserted into / fetched from a database - configured to return UTF8 encoded strings to PHP. Example - usage: - - -<?php - -include('xmlrpc.inc'); -$xmlrpc_internalencoding = 'UTF-8'; // this has to be set after the inclusion above -$v = new xmlrpcval('κόσμε'); // This xmlrpc value will be correctly serialized as the greek word 'kosme' - - - - - xmlrpcName - - - $xmlrpcName - - "XML-RPC for PHP" - The string representation of the name of the XML-RPC - for PHP library. It is used by the client for building the User-Agent - HTTP header that is sent with every request to the server. You can - change its value if you need to customize the User-Agent - string. - - - - xmlrpcVersion - - - $xmlrpcVersion - - "2.2" - The string representation of the version number of - the XML-RPC for PHP library in use. It is used by the client for - building the User-Agent HTTP header that is sent with every request to - the server. You can change its value if you need to customize the - User-Agent string. - - - - xmlrpc_null_extension - - When set to TRUE, the lib will enable - support for the <NIL/> (and <EX:NIL/>) xmlrpc value, as - per the extension to the standard proposed here. This means that - <NIL/> and <EX:NIL/> tags received will be parsed as valid - xmlrpc, and the corresponding xmlrpcvals will return "null" for - scalarTyp(). - - - - xmlrpc_null_apache_encoding - - When set to TRUE, php NULL values encoded - into xmlrpcval objects get serialized using the - <EX:NIL/> tag instead of - <NIL/>. Please note that both forms are - always accepted as input regardless of the value of this - variable. - - - - - - Helper functions - - XML-RPC for PHP contains some helper functions which you can use to - make processing of XML-RPC requests easier. - - - Date functions - - The XML-RPC specification has this to say on dates: - -
      - Don't assume a timezone. It should be - specified by the server in its documentation what assumptions it makes - about timezones. -
      - - Unfortunately, this means that date processing isn't - straightforward. Although XML-RPC uses ISO 8601 format dates, it doesn't - use the timezone specifier. - - We strongly recommend that in every case where you pass dates in - XML-RPC calls, you use UTC (GMT) as your timezone. Most computer - languages include routines for handling GMT times natively, and you - won't have to translate between timezones. - - For more information about dates, see ISO 8601: The Right - Format for Dates, which has a handy link to a PDF of the ISO - 8601 specification. Note that XML-RPC uses exactly one of the available - representations: CCYYMMDDTHH:MM:SS. - - - iso8601_encode - - - - stringiso8601_encode - - string$time_t - - int$utc0 - - - - Returns an ISO 8601 formatted date generated from the UNIX - timestamp $time_t, as returned by the PHP - function time(). - - The argument $utc can be omitted, in - which case it defaults to 0. If it is set to - 1, then the function corrects the time passed in - for UTC. Example: if you're in the GMT-6:00 timezone and set - $utc, you will receive a date representation - six hours ahead of your local time. - - The included demo program vardemo.php - includes a demonstration of this function. - - - - iso8601_decode - - - - intiso8601_decode - - string$isoString - - int$utc0 - - - - Returns a UNIX timestamp from an ISO 8601 encoded time and date - string passed in. If $utc is - 1 then $isoString is assumed - to be in the UTC timezone, and thus the result is also UTC: otherwise, - the timezone is assumed to be your local timezone and you receive a - local timestamp. - -
      - - - Easy use with nested PHP values - - Dan Libby was kind enough to contribute two helper functions that - make it easier to translate to and from PHP values. This makes it easier - to deal with complex structures. At the moment support is limited to - int, double, string, - array, datetime and struct - datatypes; note also that all PHP arrays are encoded as structs, except - arrays whose keys are integer numbers starting with 0 and incremented by - 1. - - These functions reside in xmlrpc.inc. - - - php_xmlrpc_decode - - - - mixedphp_xmlrpc_decode - - xmlrpcval$xmlrpc_val - - array$options - - - - arrayphp_xmlrpc_decode - - xmlrpcmsg$xmlrpcmsg_val - - string$options - - - - Returns a native PHP value corresponding to the values found in - the xmlrpcval $xmlrpc_val, - translated into PHP types. Base-64 and datetime values are - automatically decoded to strings. - - In the second form, returns an array containing the parameters - of the given - xmlrpcmsg_val, decoded - to php types. - - The options parameter is optional. If - specified, it must consist of an array of options to be enabled in the - decoding process. At the moment the only valid option are - decode_php_objs and - dates_as_objects. When the first is set, php - objects that have been converted to xml-rpc structs using the - php_xmlrpc_encode function and a corresponding - encoding option will be converted back into object values instead of - arrays (provided that the class definition is available at - reconstruction time). When the second is set, XML-RPC datetime values - will be converted into native dateTime objects - instead of strings. - - WARNING: please take - extreme care before enabling the decode_php_objs - option: when php objects are rebuilt from the received xml, their - constructor function will be silently invoked. This means that you are - allowing the remote end to trigger execution of uncontrolled PHP code - on your server, opening the door to code injection exploits. Only - enable this option when you have complete trust of the remote - server/client. - - Example: -// wrapper to expose an existing php function as xmlrpc method handler -function foo_wrapper($m) -{ - $params = php_xmlrpc_decode($m); - $retval = call_user_func_array('foo', $params); - return new xmlrpcresp(new xmlrpcval($retval)); // foo return value will be serialized as string -} - -$s = new xmlrpc_server(array( - "examples.myFunc1" => array( - "function" => "foo_wrapper", - "signatures" => ... - ))); - - - - - php_xmlrpc_encode - - - - xmlrpcvalphp_xmlrpc_encode - - mixed$phpval - - array$options - - - - Returns an xmlrpcval object populated with the PHP - values in $phpval. Works recursively on arrays - and objects, encoding numerically indexed php arrays into array-type - xmlrpcval objects and non numerically indexed php arrays into - struct-type xmlrpcval objects. Php objects are encoded into - struct-type xmlrpcvals, excepted for php values that are already - instances of the xmlrpcval class or descendants thereof, which will - not be further encoded. Note that there's no support for encoding php - values into base-64 values. Encoding of date-times is optionally - carried on on php strings with the correct format. - - The options parameter is optional. If - specified, it must consist of an array of options to be enabled in the - encoding process. At the moment the only valid options are - encode_php_objs, null_extension - and auto_dates. - - The first will enable the creation of 'particular' xmlrpcval - objects out of php objects, that add a "php_class" xml attribute to - their serialized representation. This attribute allows the function - php_xmlrpc_decode to rebuild the native php objects (provided that the - same class definition exists on both sides of the communication). The - second allows to encode php NULL values to the - <NIL/> (or - <EX:NIL/>, see ...) tag. The last encodes any - string that matches the ISO8601 format into an XML-RPC - datetime. - - Example: -// the easy way to build a complex xml-rpc struct, showing nested base64 value and datetime values -$val = php_xmlrpc_encode(array( - 'first struct_element: an int' => 666, - 'second: an array' => array ('apple', 'orange', 'banana'), - 'third: a base64 element' => new xmlrpcval('hello world', 'base64'), - 'fourth: a datetime' => '20060107T01:53:00' - ), array('auto_dates')); - - - - - php_xmlrpc_decode_xml - - - - xmlrpcval | xmlrpcresp | - xmlrpcmsgphp_xmlrpc_decode_xml - - string$xml - - array$options - - - - Decodes the xml representation of either an xmlrpc request, - response or single value, returning the corresponding php-xmlrpc - object, or FALSE in case of an error. - - The options parameter is optional. If - specified, it must consist of an array of options to be enabled in the - decoding process. At the moment, no option is supported. - - Example: -$text = '<value><array><data><value>Hello world</value></data></array></value>'; -$val = php_xmlrpc_decode_xml($text); -if ($val) echo 'Found a value of type '.$val->kindOf(); else echo 'Found invalid xml'; - - - - - - Automatic conversion of php functions into xmlrpc methods (and - vice versa) - - For the extremely lazy coder, helper functions have been added - that allow to convert a php function into an xmlrpc method, and a - remotely exposed xmlrpc method into a local php function - or a set of - methods into a php class. Note that these comes with many caveat. - - - wrap_xmlrpc_method - - - - stringwrap_xmlrpc_method - - $client - - $methodname - - $extra_options - - - - stringwrap_xmlrpc_method - - $client - - $methodname - - $signum - - $timeout - - $protocol - - $funcname - - - - Given an xmlrpc server and a method name, creates a php wrapper - function that will call the remote method and return results using - native php types for both params and results. The generated php - function will return an xmlrpcresp object for failed xmlrpc - calls. - - The second syntax is deprecated, and is listed here only for - backward compatibility. - - The server must support the - system.methodSignature xmlrpc method call for - this function to work. - - The client param must be a valid - xmlrpc_client object, previously created with the address of the - target xmlrpc server, and to which the preferred communication options - have been set. - - The optional parameters can be passed as array key,value pairs - in the extra_options param. - - The signum optional param has the purpose - of indicating which method signature to use, if the given server - method has multiple signatures (defaults to 0). - - The timeout and - protocol optional params are the same as in the - xmlrpc_client::send() method. - - If set, the optional new_function_name - parameter indicates which name should be used for the generated - function. In case it is not set the function name will be - auto-generated. - - If the return_source optional parameter is - set, the function will return the php source code to build the wrapper - function, instead of evaluating it (useful to save the code and use it - later as stand-alone xmlrpc client). - - If the encode_php_objs optional parameter is - set, instances of php objects later passed as parameters to the newly - created function will receive a 'special' treatment that allows the - server to rebuild them as php objects instead of simple arrays. Note - that this entails using a "slightly augmented" version of the xmlrpc - protocol (ie. using element attributes), which might not be understood - by xmlrpc servers implemented using other libraries. - - If the decode_php_objs optional parameter is - set, instances of php objects that have been appropriately encoded by - the server using a coordinate option will be deserialized as php - objects instead of simple arrays (the same class definition should be - present server side and client side). - - Note that this might pose a security risk, - since in order to rebuild the object instances their constructor - method has to be invoked, and this means that the remote server can - trigger execution of unforeseen php code on the client: not really a - code injection, but almost. Please enable this option only when you - trust the remote server. - - In case of an error during generation of the wrapper function, - FALSE is returned, otherwise the name (or source code) of the new - function. - - Known limitations: server must support - system.methodsignature for the wanted xmlrpc - method; for methods that expose multiple signatures, only one can be - picked; for remote calls with 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 base64. - - Note: 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 the parameter - list of the generated php function, useful for debugging - purposes. - - Example usage: - - -$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); - -$function = wrap_xmlrpc_method($client, 'examples.getStateName'); - -if (!$function) - die('Cannot introspect remote method'); -else { - $stateno = 15; - $statename = $function($a); - if (is_a($statename, 'xmlrpcresp')) // call failed - { - echo 'Call failed: '.$statename->faultCode().'. Calling again with debug on'; - $function($a, true); - } - else - echo "OK, state nr. $stateno is $statename"; -} - - - - - wrap_php_function - - - - arraywrap_php_function - - string$funcname - - string$wrapper_function_name - - array$extra_options - - - - 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, and return the appropriate - definition to be added to a server's dispatch map. - - The optional $wrapper_function_name - specifies the name that will be used for the auto-generated - function. - - 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 docblock @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: only works for - user-defined functions, not for PHP internal functions (reflection - does not support retrieving number/type of params for those); the - wrapped php function will not be able to programmatically return an - xmlrpc error response. - - If the return_source optional parameter is - set, the function will return the php source code to build the wrapper - function, instead of evaluating it (useful to save the code and use it - later in a stand-alone xmlrpc server). It will be in the stored in the - source member of the returned array. - - If the suppress_warnings optional parameter - is set, any runtime warning generated while processing the - user-defined php function will be catched and not be printed in the - generated xml response. - - If the extra_options array contains the - encode_php_objs value, wrapped 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 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) - - If the decode_php_objs optional parameter is - set, instances of php objects that have been appropriately encoded by - the client using a coordinate option will be deserialized and passed - to the user function as php objects instead of simple arrays (the same - class definition should be present server side and client - side). - - Note that this might pose a security risk, - since in order to rebuild the object instances their constructor - method has to be invoked, and this means that the remote client can - trigger execution of unforeseen php code on the server: not really a - code injection, but almost. Please enable this option only when you - trust the remote clients. - - Example usage: - - /** -* State name from state number decoder. NB: do NOT remove this comment block. -* @param integer $stateno the state number -* @return string the name of the state (or error description) -*/ -function findstate($stateno) -{ - global $stateNames; - if (isset($stateNames[$stateno-1])) - { - return $stateNames[$stateno-1]; - } - else - { - return "I don't have a state for the index '" . $stateno . "'"; - } -} - -// wrap php function, build xmlrpc server -$methods = array(); -$findstate_sig = wrap_php_function('findstate'); -if ($findstate_sig) - $methods['examples.getStateName'] = $findstate_sig; -$srv = new xmlrpc_server($methods); - - - - - - Functions removed from the library - - The following two functions have been deprecated in version 1.1 of - the library, and removed in version 2, in order to avoid conflicts with - the EPI xml-rpc library, which also defines two functions with the same - names. - - To ease the transition to the new naming scheme and avoid breaking - existing implementations, the following scheme has been adopted: - - - If EPI-XMLRPC is not active in the current PHP installation, - the constant XMLRPC_EPI_ENABLED will be set to - '0' - - - - If EPI-XMLRPC is active in the current PHP installation, the - constant XMLRPC_EPI_ENABLED will be set to - '1' - - - - The following documentation is kept for historical - reference: - - - xmlrpc_decode - - - - mixedxmlrpc_decode - - xmlrpcval$xmlrpc_val - - - - Alias for php_xmlrpc_decode. - - - - xmlrpc_encode - - - - xmlrpcvalxmlrpc_encode - - mixed$phpval - - - - Alias for php_xmlrpc_encode. - - - - - Debugging aids - - - xmlrpc_debugmsg - - - - voidxmlrpc_debugmsg - - string$debugstring - - - - Sends the contents of $debugstring in XML - comments in the server return payload. If a PHP client has debugging - turned on, the user will be able to see server debug - information. - - Use this function in your methods so you can pass back - diagnostic information. It is only available from - xmlrpcs.inc. - - -
      - - - Reserved methods - - In order to extend the functionality offered by XML-RPC servers - without impacting on the protocol, reserved methods are supported in this - release. - - All methods starting with system. are - considered reserved by the server. PHP for XML-RPC itself provides four - special methods, detailed in this chapter. - - Note that all server objects will automatically respond to clients - querying these methods, unless the property - allow_system_funcs has been set to - false before calling the - service() method. This might pose a security risk - if the server is exposed to public access, e.g. on the internet. - - - system.getCapabilities - - - - - - system.listMethods - - This method may be used to enumerate the methods implemented by - the XML-RPC server. - - The system.listMethods method requires no - parameters. It returns an array of strings, each of which is the name of - a method implemented by the server. - - - - system.methodSignature - - This method takes one parameter, the name of a method implemented - by the XML-RPC server. - - It returns an array of possible signatures for this method. A - signature is an array of types. The first of these types is the return - type of the method, the rest are parameters. - - Multiple signatures (i.e. overloading) are permitted: this is the - reason that an array of signatures are returned by this method. - - Signatures themselves are restricted to the top level parameters - expected by a method. For instance if a method expects one array of - structs as a parameter, and it returns a string, its signature is simply - "string, array". If it expects three integers, its signature is "string, - int, int, int". - - For parameters that can be of more than one type, the "undefined" - string is supported. - - If no signature is defined for the method, a not-array value is - returned. Therefore this is the way to test for a non-signature, if - $resp below is the response object from a method - call to system.methodSignature: - - -$v = $resp->value(); -if ($v->kindOf() != "array") { - // then the method did not have a signature defined -} - - - See the introspect.php demo included in this - distribution for an example of using this method. - - - - system.methodHelp - - This method takes one parameter, the name of a method implemented - by the XML-RPC server. - - It returns a documentation string describing the use of that - method. If no such string is available, an empty string is - returned. - - The documentation string may contain HTML markup. - - - - system.multicall - - This method takes one parameter, an array of 'request' struct - types. Each request struct must contain a - methodName member of type string and a - params member of type array, and corresponds to - the invocation of the corresponding method. - - It returns a response of type array, with each value of the array - being either an error struct (containing the faultCode and faultString - members) or the successful response value of the corresponding single - method call. - - - - - Examples - - The best examples are to be found in the sample files included with - the distribution. Some are included here. - - - XML-RPC client: state name query - - Code to get the corresponding state name from a number (1-50) from - the demo server available on SourceForge - - - $m = new xmlrpcmsg('examples.getStateName', - array(new xmlrpcval($HTTP_POST_VARS["stateno"], "int"))); - $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80); - $r = $c->send($m); - if (!$r->faultCode()) { - $v = $r->value(); - print "State number " . htmlentities($HTTP_POST_VARS["stateno"]) . " is " . - htmlentities($v->scalarval()) . "<BR>"; - print "<HR>I got this value back<BR><PRE>" . - htmlentities($r->serialize()) . "</PRE><HR>\n"; - } else { - print "Fault <BR>"; - print "Code: " . htmlentities($r->faultCode()) . "<BR>" . - "Reason: '" . htmlentities($r->faultString()) . "'<BR>"; - } - - - - - Executing a multicall call - - To be documented... - - - - - Frequently Asked Questions - - - How to send custom XML as payload of a method call - - Unfortunately, at the time the XML-RPC spec was designed, support - for namespaces in XML was not as ubiquitous as it is now. As a - consequence, no support was provided in the protocol for embedding XML - elements from other namespaces into an xmlrpc request. - - To send an XML "chunk" as payload of a method call or response, - two options are available: either send the complete XML block as a - string xmlrpc value, or as a base64 value. Since the '<' character in - string values is encoded as '&lt;' in the xml payload of the method - call, the XML string will not break the surrounding xmlrpc, unless - characters outside of the assumed character set are used. The second - method has the added benefits of working independently of the charset - encoding used for the xml to be transmitted, and preserving exactly - whitespace, whilst incurring in some extra message length and cpu load - (for carrying out the base64 encoding/decoding). - - - - Is there any limitation on the size of the requests / responses - that can be successfully sent? - - Yes. But I have no hard figure to give; it most likely will depend - on the version of PHP in usage and its configuration. - - Keep in mind that this library is not optimized for speed nor for - memory usage. Better alternatives exist when there are strict - requirements on throughput or resource usage, such as the php native - xmlrpc extension (see the PHP manual for more information). - - Keep in mind also that HTTP is probably not the best choice in - such a situation, and XML is a deadly enemy. CSV formatted data over - socket would be much more efficient. - - If you really need to move a massive amount of data around, and - you are crazy enough to do it using phpxmlrpc, your best bet is to - bypass usage of the xmlrpcval objects, at least in the decoding phase, - and have the server (or client) object return to the calling function - directly php values (see xmlrpc_client::return_type - and xmlrpc_server::functions_parameters_type for more - details). - - - - My server (client) returns an error whenever the client (server) - returns accented characters - - To be documented... - - - - How to enable long-lasting method calls - - To be documented... - - - - My client returns "XML-RPC Fault #2: Invalid return payload: - enable debugging to examine incoming payload": what should I do? - - The response you are seeing is a default error response that the - client object returns to the php application when the server did not - respond to the call with a valid xmlrpc response. - - The most likely cause is that you are not using the correct URL - when creating the client object, or you do not have appropriate access - rights to the web page you are requesting, or some other common http - misconfiguration. - - To find out what the server is really returning to your client, - you have to enable the debug mode of the client, using - $client->setdebug(1); - - - - How can I save to a file the xml of the xmlrpc responses received - from servers? - - If what you need is to save the responses received from the server - as xml, you have two options: - - 1- use the serialize() method on the response object. - - -$resp = $client->send($msg); -if (!$resp->faultCode()) - $data_to_be_saved = $resp->serialize(); - - - Note that this will not be 100% accurate, since the xml generated - by the response object can be different from the xml received, - especially if there is some character set conversion involved, or such - (eg. if you receive an empty string tag as <string/>, serialize() - will output <string></string>), or if the server sent back - as response something invalid (in which case the xml generated client - side using serialize() will correspond to the error response generated - internally by the lib). - - 2 - set the client object to return the raw xml received instead - of the decoded objects: - - -$client = new xmlrpc_client($url); -$client->return_type = 'xml'; -$resp = $client->send($msg); -if (!$resp->faultCode()) - $data_to_be_saved = $resp->value(); - - - Note that using this method the xml response response will not be - parsed at all by the library, only the http communication protocol will - be checked. This means that xmlrpc responses sent by the server that - would have generated an error response on the client (eg. malformed xml, - responses that have faultcode set, etc...) now will not be flagged as - invalid, and you might end up saving not valid xml but random - junk... - - - - Can I use the ms windows character set? - - If the data your application is using comes from a Microsoft - application, there are some chances that the character set used to - encode it is CP1252 (the same might apply to data received from an - external xmlrpc server/client, but it is quite rare to find xmlrpc - toolkits that encode to CP1252 instead of UTF8). It is a character set - which is "almost" compatible with ISO 8859-1, but for a few extra - characters. - - PHP-XMLRPC only supports the ISO 8859-1 and UTF8 character sets. - The net result of this situation is that those extra characters will not - be properly encoded, and will be received at the other end of the - XML-RPC transmission as "garbled data". Unfortunately the library cannot - provide real support for CP1252 because of limitations in the PHP 4 xml - parser. Luckily, we tried our best to support this character set anyway, - and, since version 2.2.1, there is some form of support, left commented - in the code. - - To properly encode outgoing data that is natively in CP1252, you - will have to uncomment all relative code in the file - xmlrpc.inc (you can search for the string "1252"), - then set $GLOBALS['xmlrpc_internalencoding']='CP1252'; - Please note that all incoming data will then be fed to your application - as UTF-8 to avoid any potential data loss. - - - - Does the library support using cookies / http sessions? - - In short: yes, but a little coding is needed to make it - happen. - - The code below uses sessions to e.g. let the client store a value - on the server and retrieve it later. - - -$resp = $client->send(new xmlrpcmsg('registervalue', array(new xmlrpcval('foo'), new xmlrpcval('bar')))); -if (!$resp->faultCode()) -{ - $cookies = $resp->cookies(); - if (array_key_exists('PHPSESSID', $cookies)) // nb: make sure to use the correct session cookie name - { - $session_id = $cookies['PHPSESSID']['value']; - - // do some other stuff here... - - $client->setcookie('PHPSESSID', $session_id); - $val = $client->send(new xmlrpcmsg('getvalue', array(new xmlrpcval('foo'))); - } -} -Server-side sessions are handled normally like in any other - php application. Please see the php manual for more information about - sessions. - - NB: unlike web browsers, not all xmlrpc clients support usage of - http cookies. If you have troubles with sessions and control only the - server side of the communication, please check with the makers of the - xmlrpc client in use. - - - - - Integration with the PHP xmlrpc extension - - To be documented more... - - In short: for the fastest execution possible, you can enable the php - native xmlrpc extension, and use it in conjunction with phpxmlrpc. The - following code snippet gives an example of such integration - - -/*** client side ***/ -$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php'); - -// tell the client to return raw xml as response value -$c->return_type = 'xml'; - -// let the native xmlrpc extension take care of encoding request parameters -$r = $c->send(xmlrpc_encode_request('examples.getStateName', $_POST['stateno'])); - -if ($r->faultCode()) - // HTTP transport error - echo 'Got error '.$r->faultCode(); -else -{ - // HTTP request OK, but XML returned from server not parsed yet - $v = xmlrpc_decode($r->value()); - // check if we got a valid xmlrpc response from server - if ($v === NULL) - echo 'Got invalid response'; - else - // check if server sent a fault response - if (xmlrpc_is_fault($v)) - echo 'Got xmlrpc fault '.$v['faultCode']; - else - echo'Got response: '.htmlentities($v); -} - - - - - Substitution of the PHP xmlrpc extension - - Yet another interesting situation is when you are using a ready-made - php application, that provides support for the XMLRPC protocol via the - native php xmlrpc extension, but the extension is not available on your - php install (e.g. because of shared hosting constraints). - - Since version 2.1, the PHP-XMLRPC library provides a compatibility - layer that aims to be 100% compliant with the xmlrpc extension API. This - means that any code written to run on the extension should obtain the - exact same results, albeit using more resources and a longer processing - time, using the PHP-XMLRPC library and the extension compatibility module. - The module is part of the EXTRAS package, available as a separate download - from the sourceforge.net website, since version 0.2 - - - - 'Enough of xmlrpcvals!': new style library usage - - To be documented... - - In the meantime, see docs about xmlrpc_client::return_type and - xmlrpc_server::functions_parameters_types, as well as php_xmlrpc_encode, - php_xmlrpc_decode and php_xmlrpc_decode_xml - - - - Usage of the debugger - - A webservice debugger is included in the library to help during - development and testing. - - The interface should be self-explicative enough to need little - documentation. - - - - The most useful feature of the debugger is without doubt the "Show - debug info" option. It allows to have a screen dump of the complete http - communication between client and server, including the http headers as - well as the request and response payloads, and is invaluable when - troubleshooting problems with charset encoding, authentication or http - compression. - - The debugger can take advantage of the JSONRPC library extension, to - allow debugging of JSON-RPC webservices, and of the JS-XMLRPC library - visual editor to allow easy mouse-driven construction of the payload for - remote methods. Both components have to be downloaded separately from the - sourceforge.net web pages and copied to the debugger directory to enable - the extra functionality: - - - - to enable jsonrpc functionality, download the PHP-XMLRPC - EXTRAS package, and copy the file jsonrpc.inc - either to the same directory as the debugger or somewhere in your - php include path - - - - to enable the visual value editing dialog, download the - JS-XMLRPC library, and copy somewhere in the web root files - visualeditor.php, - visualeditor.css and the folders - yui and img. Then edit the - debugger file controller.php and set - appropriately the variable $editorpath. - - - - - diff --git a/pakefile.php b/pakefile.php index 35a33013..30acead2 100644 --- a/pakefile.php +++ b/pakefile.php @@ -5,7 +5,6 @@ * * @copyright (c) 2015 G. Giunta * - * @todo allow user to specify release number and tag/branch to use * @todo !important allow user to specify location of docbook xslt instead of the one installed via composer */ @@ -15,11 +14,11 @@ class Builder { protected static $buildDir = 'build'; protected static $libVersion; - protected static $sourceBranch = 'master'; protected static $tools = array( - 'zip' => 'zip', + 'asciidoctor' => 'asciidoctor', 'fop' => 'fop', - 'php' => 'php' + 'php' => 'php', + 'zip' => 'zip', ); protected static $options = array( 'repo' => 'https://github.com/gggeek/phpxmlrpc', @@ -58,14 +57,11 @@ public static function distFiles() ); } - /// @todo move git branch to be a named option? public static function getOpts($args=array(), $cliOpts=array()) { if (count($args) > 0) // throw new \Exception('Missing library version argument'); self::$libVersion = $args[0]; - if (count($args) > 1) - self::$sourceBranch = $args[1]; foreach (self::$tools as $name => $binary) { if (isset($cliOpts[$name])) { @@ -186,10 +182,11 @@ function run_default($task=null, $args=array(), $cliOpts=array()) 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 " --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 " --fop=FOP Location of the fop command-line tool\n"; echo " --zip=ZIP Location of the zip tool\n"; } @@ -235,10 +232,11 @@ function run_build($task=null, $args=array(), $cliOpts=array()) function run_clean_doc() { - //pake_remove_dir(Builder::workspaceDir().'/doc/out'); 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'); } /** @@ -248,11 +246,26 @@ function run_doc($task=null, $args=array(), $cliOpts=array()) { $docDir = Builder::workspaceDir().'/doc'; - // API docs from phpdoc comments using phpdocumentor + // 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'); - # Jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g. + // 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 @@ -267,16 +280,13 @@ function run_doc($task=null, $args=array(), $cliOpts=array()) # -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 - //pake_mkdirs($docDir.'/out'); - - // HTML files from docbook - - Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.xsl', $docDir.'/manual'); + // 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 @@ -284,6 +294,9 @@ function run_doc($task=null, $args=array(), $cliOpts=array()) 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'); } From bed57b3c24a75c182af4cff2aa17d840e4c2fe27 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 29 Apr 2015 00:30:12 +0100 Subject: [PATCH 170/228] improve readme --- README.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dfc96311..a75235b3 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,18 @@ A php library for building xml-rpc clients and servers. Installation ------------ -Installation instructions are in the [INSTALL.md](INSTALL.md) file. +The recommended way to install this library is using Composer. -Docs ----- -The manual can be found in the doc/manual directory, in HTML and PDF versions for release tarballs and Docbook always. +Detailed installation instructions are in the [INSTALL.md](INSTALL.md) file, along with system requirements listing. +Documentation +------------- +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. + +License +------- Use of this software is subject to the terms in the [license.txt](license.txt) file SSL-certificate @@ -17,9 +23,9 @@ 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) -[![License](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/license)](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) From 99530b7cb64e5ddc9be8036acae49eff38f1e278 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 29 Apr 2015 00:47:39 +0100 Subject: [PATCH 171/228] set code highlighting in snippets --- doc/manual/phpxmlrpc_manual.adoc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/manual/phpxmlrpc_manual.adoc b/doc/manual/phpxmlrpc_manual.adoc index 1480b402..907f00b5 100644 --- a/doc/manual/phpxmlrpc_manual.adoc +++ b/doc/manual/phpxmlrpc_manual.adoc @@ -3,6 +3,8 @@ :keywords: xml, rpc, xmlrpc, webservices, http :toc: left :imagesdir: images +:source-highlighter: highlightjs + [preface] == Introduction From b74db4b586aab9fab355cce855776debea6e9819 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 2 May 2015 17:45:12 +0100 Subject: [PATCH 172/228] Add a test for registering anonymous functions in the server dispatch map --- demo/server/server.php | 189 +++++++++++++++++++++------------------ src/Server.php | 81 +++++++++-------- tests/3LocalhostTest.php | 9 ++ 3 files changed, 152 insertions(+), 127 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index aa604b85..efc25bc9 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -38,7 +38,7 @@ class xmlrpcServerMethodsContainer /** * Method used to test logging of php warnings generated by user functions. */ - public function phpWarningGenerator($m) + 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, 'boolean')); @@ -47,19 +47,19 @@ public function phpWarningGenerator($m) /** * Method used to test catching of exceptions in the server. */ - public function exceptionGenerator($m) + public function exceptionGenerator($req) { throw new Exception("it's just a test", 1); } /** * A PHP version of the state-number server. Send me an integer and i'll sell you a state - * @param integer $s + * @param integer $num * @return string */ - public static function findState($s) + public static function findState($num) { - return inner_findstate($s); + return inner_findstate($num); } } @@ -83,13 +83,13 @@ public static function findState($s) name of a US state, where the integer is the index of that state name in an alphabetic order.'; -function findState($m) +function findState($req) { global $stateNames; $err = ""; // get the first param - $sno = $m->getParam(0); + $sno = $req->getParam(0); // param must be there and of the correct type: server object does the validation for us @@ -132,6 +132,11 @@ function inner_findstate($stateNo) } } +$findStateClosure = function ($req) +{ + return findState($req); +}; + $wrapper = new PhpXmlRpc\Wrapper(); $findstate2_sig = $wrapper->wrap_php_function('inner_findstate'); @@ -145,58 +150,58 @@ function inner_findstate($stateNo) $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; -function addTwo($m) +function addTwo($req) { - $s = $m->getParam(0); - $t = $m->getParam(1); + $s = $req->getParam(0); + $t = $req->getParam(1); return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), "int")); } $addtwodouble_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble, Value::$xmlrpcDouble)); $addtwodouble_doc = 'Add two doubles together and return the result'; -function addTwoDouble($m) +function addTwoDouble($req) { - $s = $m->getParam(0); - $t = $m->getParam(1); + $s = $req->getParam(0); + $t = $req->getParam(1); return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), "double")); } $stringecho_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString)); $stringecho_doc = 'Accepts a string parameter, returns the string.'; -function stringEcho($m) +function stringEcho($req) { // just sends back a string - return new PhpXmlRpc\Response(new Value($m->getParam(0)->scalarval())); + 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($m) +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" . $m->serialize(); + $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($m) +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 = $m->getParam(0); + $incoming = $req->getParam(0); return new PhpXmlRpc\Response(new Value($incoming->scalarval(), "string")); } $bitflipper_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray)); $bitflipper_doc = 'Accepts an array of booleans, and returns them inverted'; -function bitFlipper($m) +function bitFlipper($req) { - $v = $m->getParam(0); + $v = $req->getParam(0); $sz = $v->arraysize(); $rv = new Value(array(), Value::$xmlrpcArray); @@ -248,13 +253,13 @@ function agesorter_compare($a, $b) And the array will be returned with the entries sorted by their numbers. '; -function ageSorter($m) +function ageSorter($req) { global $agesorter_arr, $s; PhpXmlRpc\Server::xmlrpc_debugmsg("Entering 'agesorter'"); // get the parameter - $sno = $m->getParam(0); + $sno = $req->getParam(0); // error string for [if|when] things go wrong $err = ""; // create the output value @@ -315,17 +320,17 @@ function ageSorter($m) // 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($m) +function mailSend($req) { $err = ""; - $mTo = $m->getParam(0); - $mSub = $m->getParam(1); - $mBody = $m->getParam(2); - $mFrom = $m->getParam(3); - $mCc = $m->getParam(4); - $mBcc = $m->getParam(5); - $mMime = $m->getParam(6); + $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"; @@ -335,25 +340,25 @@ function mailSend($m) $err = "Error, no 'From' field specified"; } - $msghdr = "From: " . $mFrom->scalarval() . "\n"; - $msghdr .= "To: " . $mTo->scalarval() . "\n"; + $msgHdr = "From: " . $mFrom->scalarval() . "\n"; + $msgHdr .= "To: " . $mTo->scalarval() . "\n"; if ($mCc->scalarval() != "") { - $msghdr .= "Cc: " . $mCc->scalarval() . "\n"; + $msgHdr .= "Cc: " . $mCc->scalarval() . "\n"; } if ($mBcc->scalarval() != "") { - $msghdr .= "Bcc: " . $mBcc->scalarval() . "\n"; + $msgHdr .= "Bcc: " . $mBcc->scalarval() . "\n"; } if ($mMime->scalarval() != "") { - $msghdr .= "Content-type: " . $mMime->scalarval() . "\n"; + $msgHdr .= "Content-type: " . $mMime->scalarval() . "\n"; } - $msghdr .= "X-Mailer: XML-RPC for PHP mailer 1.0"; + $msgHdr .= "X-Mailer: XML-RPC for PHP mailer 1.0"; if ($err == "") { if (!mail("", $mSub->scalarval(), $mBody->scalarval(), - $msghdr) + $msgHdr) ) { $err = "Error, could not send the mail."; } @@ -368,7 +373,7 @@ function mailSend($m) $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($m) +function getAllHeaders_xmlrpc($req) { $encoder = new PhpXmlRpc\Encoder(); @@ -390,10 +395,10 @@ function getallheaders_xmlrpc($m) $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($m) +function setCookies($req) { $encoder = new PhpXmlRpc\Encoder(); - $m = $m->getParam(0); + $m = $req->getParam(0); while (list($name, $value) = $m->structeach()) { $cookieDesc = $encoder->decode($value); setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']); @@ -404,7 +409,7 @@ function setCookies($m) $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($m) +function getCookies($req) { $encoder = new PhpXmlRpc\Encoder(); return new PhpXmlRpc\Response($encoder->encode($_COOKIE)); @@ -412,9 +417,9 @@ function getCookies($m) $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 s. Your handler must add all the struct elements named curly and return the result.'; -function v1_arrayOfStructs($m) +function v1_arrayOfStructs($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); $numCurly = 0; for ($i = 0; $i < $sno->arraysize(); $i++) { $str = $sno->arraymem($i); @@ -431,9 +436,9 @@ function v1_arrayOfStructs($m) $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 <i4>s. Your handler must add the three numbers and return the result.'; -function v1_easyStruct($m) +function v1_easyStruct($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); $moe = $sno->structmem("moe"); $larry = $sno->structmem("larry"); $curly = $sno->structmem("curly"); @@ -444,9 +449,9 @@ function v1_easyStruct($m) $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($m) +function v1_echoStruct($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); return new PhpXmlRpc\Response($sno); } @@ -457,24 +462,24 @@ function v1_echoStruct($m) Value::$xmlrpcBase64, )); $v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.'; -function v1_manyTypes($m) +function v1_manyTypes($req) { return new PhpXmlRpc\Response(new Value(array( - $m->getParam(0), - $m->getParam(1), - $m->getParam(2), - $m->getParam(3), - $m->getParam(4), - $m->getParam(5),), + $req->getParam(0), + $req->getParam(1), + $req->getParam(2), + $req->getParam(3), + $req->getParam(4), + $req->getParam(5),), "array" )); } $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($m) +function v1_moderateSizeArrayCheck($req) { - $ar = $m->getParam(0); + $ar = $req->getParam(0); $sz = $ar->arraysize(); $first = $ar->arraymem(0); $last = $ar->arraymem($sz - 1); @@ -485,9 +490,9 @@ function v1_moderateSizeArrayCheck($m) $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($m) +function v1_simpleStructReturn($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); $v = $sno->scalarval(); return new PhpXmlRpc\Response(new Value(array( @@ -500,9 +505,9 @@ function v1_simpleStructReturn($m) $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 <i4>s. Your handler must add the three numbers and return the result.'; -function v1_nestedStruct($m) +function v1_nestedStruct($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); $twoK = $sno->structmem("2000"); $april = $twoK->structmem("04"); @@ -516,9 +521,9 @@ function v1_nestedStruct($m) $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 <, >, & \' and ".
      Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.'; -function v1_countTheEntities($m) +function v1_countTheEntities($req) { - $sno = $m->getParam(0); + $sno = $req->getParam(0); $str = $sno->scalarval(); $gt = 0; $lt = 0; @@ -594,72 +599,72 @@ function v1_countTheEntities($m) $i_echoDate_sig = array(array(Value::$xmlrpcDateTime, Value::$xmlrpcDateTime)); $i_echoDate_doc = "Echoes dateTime."; -function i_echoParam($m) +function i_echoParam($req) { - $s = $m->getParam(0); + $s = $req->getParam(0); return new PhpXmlRpc\Response($s); } -function i_echoString($m) +function i_echoString($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoInteger($m) +function i_echoInteger($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoFloat($m) +function i_echoFloat($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoStruct($m) +function i_echoStruct($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoStringArray($m) +function i_echoStringArray($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoIntegerArray($m) +function i_echoIntegerArray($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoFloatArray($m) +function i_echoFloatArray($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoStructArray($m) +function i_echoStructArray($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoValue($m) +function i_echoValue($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoBase64($m) +function i_echoBase64($req) { - return i_echoParam($m); + return i_echoParam($req); } -function i_echoDate($m) +function i_echoDate($req) { - return i_echoParam($m); + 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($m) +function i_whichToolkit($req) { global $SERVER_SOFTWARE; $ret = array( @@ -736,7 +741,7 @@ function i_whichToolkit($m) "docstring" => $stringecho_doc, ),*/ "examples.getallheaders" => array( - "function" => 'getallheaders_xmlrpc', + "function" => 'getAllHeaders_xmlrpc', "signature" => $getallheaders_sig, "docstring" => $getallheaders_doc, ), @@ -873,6 +878,12 @@ function i_whichToolkit($m) $signatures['examples.php4.getStateName'] = $findstate5_sig; } +$signatures['examples.php5.getStateName'] = array( + "function" => $findStateClosure, + "signature" => $findstate_sig, + "docstring" => $findstate_doc, +); + $s = new PhpXmlRpc\Server($signatures, false); $s->setdebug(3); $s->compress_response = true; diff --git a/src/Server.php b/src/Server.php index 22808475..2eca096d 100644 --- a/src/Server.php +++ b/src/Server.php @@ -11,59 +11,62 @@ class Server * Array defining php functions exposed as xmlrpc methods by this server. */ protected $dmap = array(); - /* - * Defines how functions in dmap will be invoked: either using an xmlrpc msg object - * or plain php values. - * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' - */ + /** + * Defines how functions in dmap will be invoked: either using an xmlrpc msg object + * or plain php values. + * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' + */ public $functions_parameters_type = 'xmlrpcvals'; - /* - * Option used for fine-tuning the encoding the php values returned from - * functions registered in the dispatch map when the functions_parameters_types - * member is set to 'phpvals' - * @see php_xmlrpc_encode for a list of values - */ + /** + * Option used for fine-tuning the encoding the php values returned from + * functions registered in the dispatch map when the functions_parameters_types + * member is set to 'phpvals' + * @see php_xmlrpc_encode for a list of values + */ public $phpvals_encoding_options = array('auto_dates'); - /// controls whether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3 + /** + * Controls whether the server is going to echo debugging messages back to the client as comments in response body. + * Valid values: 0,1,2,3 + */ public $debug = 1; - /* - * Controls behaviour of server when invoked user function throws an exception: - * 0 = catch it and return an 'internal error' xmlrpc response (default) - * 1 = catch it and return an xmlrpc response with the error corresponding to the exception - * 2 = allow the exception to float to the upper layers - */ + /** + * Controls behaviour of server when invoked user function throws an exception: + * 0 = catch it and return an 'internal error' xmlrpc response (default) + * 1 = catch it and return an xmlrpc response with the error corresponding to the exception + * 2 = allow the exception to float to the upper layers + */ public $exception_handling = 0; - /* - * When set to true, it will enable HTTP compression of the response, in case - * the client has declared its support for compression in the request. - */ + /** + * When set to true, it will enable HTTP compression of the response, in case + * the client has declared its support for compression in the request. + */ public $compress_response = false; - /* - * List of http compression methods accepted by the server for requests. - * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib - */ + /** + * List of http compression methods accepted by the server for requests. + * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib + */ public $accepted_compression = array(); /// shall we serve calls to system.* methods? public $allow_system_funcs = true; /// list of charset encodings natively accepted for requests public $accepted_charset_encodings = array(); - /* - * charset encoding to be used for response. - * NB: if we can, we will convert the generated response from internal_encoding to the intended one. - * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), - * null (leave unspecified in response, convert output stream to US_ASCII), - * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), - * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). - * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) - */ + /** + * charset encoding to be used for response. + * NB: if we can, we will convert the generated response from internal_encoding to the intended one. + * Can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled), + * null (leave unspecified in response, convert output stream to US_ASCII), + * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed), + * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway). + * NB: pretty dangerous if you accept every charset and do not have mbstring enabled) + */ public $response_charset_encoding = ''; /** * Storage for internal debug info. */ protected $debug_info = ''; - /* - * Extra data passed at runtime to method handling functions. Used only by EPI layer - */ + /** + * Extra data passed at runtime to method handling functions. Used only by EPI layer + */ public $user_data = null; protected static $_xmlrpc_debuginfo = ''; @@ -541,6 +544,8 @@ public function parseRequest($data, $reqEncoding = '') * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only) * * @return Response + * + * @throws \Exception in case the executed method does throw an exception (and depending on ) */ protected function execute($m, $params = null, $paramTypes = null) { diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index b782319f..629fc7c6 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -601,6 +601,15 @@ public function testAutoRegisteredMethod() } } + public function testClosure() + { + $f = new xmlrpcmsg('examples.php5.getStateName', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + } + public function testGetCookies() { // let server set to us some cookies we tell it From a518f173b88b757ad83e694d088331fe5496d977 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 6 May 2015 23:38:35 +0100 Subject: [PATCH 173/228] Refactor the Wrapper class to generate closures by default and avoid usage of 'eval' --- demo/server/server.php | 53 ++-- src/Encoder.php | 2 +- src/Server.php | 79 ++--- src/Wrapper.php | 603 ++++++++++++++++++++++++--------------- tests/3LocalhostTest.php | 85 ++++-- 5 files changed, 521 insertions(+), 301 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index efc25bc9..c3eedf4c 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -143,11 +143,31 @@ function inner_findstate($stateNo) $findstate3_sig = $wrapper->wrap_php_function(array('xmlrpcServerMethodsContainer', 'findState')); -$findstate5_sig = $wrapper->wrap_php_function('xmlrpcServerMethodsContainer::findState'); - $obj = new xmlrpcServerMethodsContainer(); $findstate4_sig = $wrapper->wrap_php_function(array($obj, 'findstate')); +$findstate5_sig = $wrapper->wrap_php_function('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +eval($findstate5_sig['source']); + +$findstate6_sig = $wrapper->wrap_php_function('inner_findstate', '', array('return_source' => true)); +eval($findstate6_sig['source']); + +$findstate7_sig = $wrapper->wrap_php_function(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true)); +eval($findstate7_sig['source']); + +$obj = new xmlrpcServerMethodsContainer(); +$findstate8_sig = $wrapper->wrap_php_function(array($obj, 'findstate'), '', array('return_source' => true)); +eval($findstate8_sig['source']); + +$findstate9_sig = $wrapper->wrap_php_function('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +eval($findstate9_sig['source']); + +$findstate10_sig = array( + "function" => $findStateClosure, + "signature" => $findstate_sig, + "docstring" => $findstate_doc, +); + $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; function addTwo($req) @@ -860,28 +880,17 @@ function i_whichToolkit($req) "signature" => $i_whichToolkit_sig, "docstring" => $i_whichToolkit_doc, ), -); - -if ($findstate2_sig) { - $signatures['examples.php.getStateName'] = $findstate2_sig; -} -if ($findstate3_sig) { - $signatures['examples.php2.getStateName'] = $findstate3_sig; -} - -if ($findstate4_sig) { - $signatures['examples.php3.getStateName'] = $findstate4_sig; -} + '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, -if ($findstate5_sig) { - $signatures['examples.php4.getStateName'] = $findstate5_sig; -} - -$signatures['examples.php5.getStateName'] = array( - "function" => $findStateClosure, - "signature" => $findstate_sig, - "docstring" => $findstate_doc, ); $s = new PhpXmlRpc\Server($signatures, false); diff --git a/src/Encoder.php b/src/Encoder.php index e19dada2..21be70f4 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -105,7 +105,7 @@ public function decode($xmlrpcVal, $options = array()) $paramCount = $xmlrpcVal->getNumParams(); $arr = array(); for ($i = 0; $i < $paramCount; $i++) { - $arr[] = $this->decode($xmlrpcVal->getParam($i)); + $arr[] = $this->decode($xmlrpcVal->getParam($i), $options); } return $arr; diff --git a/src/Server.php b/src/Server.php index 2eca096d..930edff4 100644 --- a/src/Server.php +++ b/src/Server.php @@ -520,16 +520,16 @@ public function parseRequest($data, $reqEncoding = '') $r = $this->execute($xmlRpcParser->_xh['method'], $xmlRpcParser->_xh['params'], $xmlRpcParser->_xh['pt']); } else { // build a Request object with data parsed from xml - $m = new Request($xmlRpcParser->_xh['method']); + $req = new Request($xmlRpcParser->_xh['method']); // now add parameters in for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) { - $m->addParam($xmlRpcParser->_xh['params'][$i]); + $req->addParam($xmlRpcParser->_xh['params'][$i]); } if ($this->debug > 1) { - $this->debugmsg("\n+++PARSED+++\n" . var_export($m, true) . "\n+++END+++"); + $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++"); } - $r = $this->execute($m); + $r = $this->execute($req); } } @@ -539,7 +539,7 @@ public function parseRequest($data, $reqEncoding = '') /** * Execute a method invoked by the client, checking parameters used. * - * @param mixed $m either a Request obj or a method name + * @param mixed $req either a Request obj or a method name * @param array $params array with method parameters as php types (if m is method name only) * @param array $paramTypes array with xmlrpc types of method parameters (if m is method name only) * @@ -547,12 +547,12 @@ public function parseRequest($data, $reqEncoding = '') * * @throws \Exception in case the executed method does throw an exception (and depending on ) */ - protected function execute($m, $params = null, $paramTypes = null) + protected function execute($req, $params = null, $paramTypes = null) { - if (is_object($m)) { - $methName = $m->method(); + if (is_object($req)) { + $methName = $req->method(); } else { - $methName = $m; + $methName = $req; } $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0); $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap; @@ -567,8 +567,8 @@ protected function execute($m, $params = null, $paramTypes = null) // Check signature if (isset($dmap[$methName]['signature'])) { $sig = $dmap[$methName]['signature']; - if (is_object($m)) { - list($ok, $errStr) = $this->verifySignature($m, $sig); + if (is_object($req)) { + list($ok, $errStr) = $this->verifySignature($req, $sig); } else { list($ok, $errStr) = $this->verifySignature($paramTypes, $sig); } @@ -577,7 +577,7 @@ protected function execute($m, $params = null, $paramTypes = null) return new Response( 0, PhpXmlRpc::$xmlrpcerr['incorrect_params'], - PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errstr}" + PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": ${errStr}" ); } } @@ -587,9 +587,22 @@ protected function execute($m, $params = null, $paramTypes = null) if (is_string($func) && strpos($func, '::')) { $func = explode('::', $func); } + + if (is_array($func)) { + if (is_object($func[0])) { + $funcName = get_class($func[0]) . '->' . $func[1]; + } else { + $funcName = implode('::', $func); + } + } else if ($func instanceof \Closure) { + $funcName = 'Closure'; + } else { + $funcName = $func; + } + // verify that function to be invoked is in fact callable if (!is_callable($func)) { - error_log("XML-RPC: " . __METHOD__ . ": function $func registered as method handler is not callable"); + error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable"); return new Response( 0, @@ -605,14 +618,14 @@ protected function execute($m, $params = null, $paramTypes = null) } try { // Allow mixed-convention servers - if (is_object($m)) { + if (is_object($req)) { if ($sysCall) { - $r = call_user_func($func, $this, $m); + $r = call_user_func($func, $this, $req); } else { - $r = call_user_func($func, $m); + $r = call_user_func($func, $req); } if (!is_a($r, 'PhpXmlRpc\Response')) { - error_log("XML-RPC: " . __METHOD__ . ": function $func registered as method handler does not return an xmlrpc response object"); + error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler does not return an xmlrpc response object but a " . gettype($r)); if (is_a($r, 'PhpXmlRpc\Value')) { $r = new Response($r); } else { @@ -738,7 +751,7 @@ public function getSystemDispatchMap() ); } - public static function _xmlrpcs_getCapabilities($server, $m = null) + public static function _xmlrpcs_getCapabilities($server, $req = null) { $outAr = array( // xmlrpc spec: always supported @@ -770,7 +783,7 @@ public static function _xmlrpcs_getCapabilities($server, $m = null) return new Response(new Value($outAr, 'struct')); } - public static function _xmlrpcs_listMethods($server, $m = null) // if called in plain php values mode, second param is missing + public static function _xmlrpcs_listMethods($server, $req = null) // if called in plain php values mode, second param is missing { $outAr = array(); foreach ($server->dmap as $key => $val) { @@ -785,14 +798,14 @@ public static function _xmlrpcs_listMethods($server, $m = null) // if called in return new Response(new Value($outAr, 'array')); } - public static function _xmlrpcs_methodSignature($server, $m) + public static function _xmlrpcs_methodSignature($server, $req) { // let accept as parameter both an xmlrpc value or string - if (is_object($m)) { - $methName = $m->getParam(0); + if (is_object($req)) { + $methName = $req->getParam(0); $methName = $methName->scalarval(); } else { - $methName = $m; + $methName = $req; } if (strpos($methName, "system.") === 0) { $dmap = $server->getSystemDispatchMap(); @@ -822,14 +835,14 @@ public static function _xmlrpcs_methodSignature($server, $m) return $r; } - public static function _xmlrpcs_methodHelp($server, $m) + public static function _xmlrpcs_methodHelp($server, $req) { // let accept as parameter both an xmlrpc value or string - if (is_object($m)) { - $methName = $m->getParam(0); + if (is_object($req)) { + $methName = $req->getParam(0); $methName = $methName->scalarval(); } else { - $methName = $m; + $methName = $req; } if (strpos($methName, "system.") === 0) { $dmap = $server->getSystemDispatchMap(); @@ -949,21 +962,21 @@ public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) return new Value(array($result->value()), 'array'); } - public static function _xmlrpcs_multicall($server, $m) + public static function _xmlrpcs_multicall($server, $req) { $result = array(); // let accept a plain list of php parameters, beside a single xmlrpc msg object - if (is_object($m)) { - $calls = $m->getParam(0); + if (is_object($req)) { + $calls = $req->getParam(0); $numCalls = $calls->arraysize(); for ($i = 0; $i < $numCalls; $i++) { $call = $calls->arraymem($i); $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call); } } else { - $numCalls = count($m); + $numCalls = count($req); for ($i = 0; $i < $numCalls; $i++) { - $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $m[$i]); + $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]); } } @@ -1004,7 +1017,7 @@ public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = n // the following works both with static class methods and plain object methods as error handler call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errCode, $errString, $filename, $lineNo, $context)); } else { - $GLOBALS['_xmlrpcs_prev_ehandler']($errCode, $errString, $filename, $lineno, $context); + $GLOBALS['_xmlrpcs_prev_ehandler']($errCode, $errString, $filename, $lineNo, $context); } } } diff --git a/src/Wrapper.php b/src/Wrapper.php index 0b7663ca..48244fb4 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -12,7 +12,6 @@ * Generate stubs to transparently access xmlrpc methods as php functions and vice-versa. * Note: this class implements the PROXY pattern, but it is not named so to avoid confusion with http proxies. * - * @todo separate introspection from code generation for func-2-method wrapping * @todo use some better templating system for 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) @@ -123,7 +122,7 @@ public function xmlrpc_2_php_type($xmlrpcType) * php functions (ie. functions not expecting a single Request 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') and array('class', 'methodname') are ok too + * @param string|array $funcName the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too * @param string $newFuncName (optional) name for function to be created * @param array $extraOptions (optional) array of options for conversion. valid values include: * bool return_source when true, php code w. function definition will be returned, not evaluated @@ -131,287 +130,431 @@ public function xmlrpc_2_php_type($xmlrpcType) * 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 + * @return array|false 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 finish using phpdoc 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 returning an empty string value... + * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value... * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance? */ - public function wrap_php_function($funcName, $newFuncName = '', $extraOptions = array()) + public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array()) { $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; - $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; - $namespace = '\\PhpXmlRpc\\'; - $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; - $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; - $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; - if (is_string($funcName) && strpos($funcName, '::') !== false) { - $funcName = explode('::', $funcName); + if (is_string($callable) && strpos($callable, '::') !== false) { + $callable = explode('::', $callable); } - if (is_array($funcName)) { - if (count($funcName) < 2 || (!is_string($funcName[0]) && !is_object($funcName[0]))) { + if (is_array($callable)) { + if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) { error_log('XML-RPC: syntax for function to be wrapped is wrong'); - return false; } - if (is_string($funcName[0])) { - $plainFuncName = implode('::', $funcName); - } elseif (is_object($funcName[0])) { - $plainFuncName = get_class($funcName[0]) . '->' . $funcName[1]; + if (is_string($callable[0])) { + $plainFuncName = implode('::', $callable); + } elseif (is_object($callable[0])) { + $plainFuncName = get_class($callable[0]) . '->' . $callable[1]; } - $exists = method_exists($funcName[0], $funcName[1]); - } else { - $plainFuncName = $funcName; - $exists = function_exists($funcName); + $exists = method_exists($callable[0], $callable[1]); + } else if ($callable instanceof \Closure) { + $plainFuncName = 'Closure'; + $exists = true; + } + else { + $plainFuncName = $callable; + $exists = function_exists($callable); } if (!$exists) { error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName); + return false; + } + $funcDesc = $this->introspectFunction($callable, $plainFuncName); + if (!$funcDesc) { return false; + } + + $funcSigs = $this->buildMethodSignatures($funcDesc); + + 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 ' . $plainFuncName); + + return false; + }*/ + $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null); + $code = ''; } else { - // determine name of new php function - if ($newFuncName == '') { - if (is_array($funcName)) { - if (is_string($funcName[0])) { - $xmlrpcFuncName = "{$prefix}_" . implode('_', $funcName); - } else { - $xmlrpcFuncName = "{$prefix}_" . get_class($funcName[0]) . '_' . $funcName[1]; - } - } else { - $xmlrpcFuncName = "{$prefix}_$funcName"; - } - } else { - $xmlrpcFuncName = $newFuncName; - } - while ($buildIt && function_exists($xmlrpcFuncName)) { - $xmlrpcFuncName .= 'x'; - } + $newFuncName =$this->newFunctionName($callable, $newFuncName, $extraOptions); + $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); + // replace the original callable to be set in the results + $callable = $newFuncName; + } - // start to introspect PHP code - if (is_array($funcName)) { - $func = new \ReflectionMethod($funcName[0], $funcName[1]); - if ($func->isPrivate()) { - error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); + /// @todo examine if $paramDocs matches $parsVariations and build array for + /// usage as method signature, plus put together a nice string for docs - return false; - } - if ($func->isProtected()) { - error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); + $ret = array( + 'function' => $callable, + 'signature' => $funcSigs['sigs'], + 'docstring' => $funcDesc['desc'], + 'signature_docs' => $funcSigs['pSigs'], + 'source' => $code + ); - return false; - } - if ($func->isConstructor()) { - error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); + return $ret; + } - return false; - } - if ($func->isDestructor()) { - error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); + /** + * Introspect a php callable and its phpdoc block and extract information about its signature + * + * @param callable $callable + * @param string $plainFuncName + * @return array|false + */ + protected function introspectFunction($callable, $plainFuncName) + { + // start to introspect PHP code + if (is_array($callable)) { + $func = new \ReflectionMethod($callable[0], $callable[1]); + if ($func->isPrivate()) { + error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); - return false; - } - if ($func->isAbstract()) { - error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); + return false; + } + if ($func->isProtected()) { + error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); - return false; - } - /// @todo add more checks for static vs. nonstatic? - } else { - $func = new \ReflectionFunction($funcName); + return false; } - 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: ' . $plainFuncName); + if ($func->isConstructor()) { + error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); return false; } + if ($func->isDestructor()) { + error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); - // retrieve parameter names, types and description from javadoc comments - - // function description - $desc = ''; - // type of return val: by default 'any' - $returns = Value::$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]; + return false; + } + if ($func->isAbstract()) { + error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); + + return false; + } + /// @todo add more checks for static vs. nonstatic? + } else { + $func = new \ReflectionFunction($callable); + } + 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: ' . $plainFuncName); + + return false; + } + + // retrieve parameter names, types and description from javadoc comments + + // function description + $desc = ''; + // type of return val: by default 'any' + $returns = Value::$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]; } - $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 = $this->php_2_xmlrpc_type($matches[1]); - if (isset($matches[2])) { - $returnsDocs = $matches[2]; - } + $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 = $this->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++; + // 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++; + } + + return array( + 'desc' => $desc, + 'docs' => $docs, + 'params' => $params, + 'paramsDocs' => $paramDocs, + 'returns' => $returns, + 'returnsDocs' =>$returnsDocs, + ); + } + + /** + * Given the method description given by introspection, create method signature data + * + * @param array $funcDesc as generated by self::introspectFunction() + * + * @return array + * + * @todo missing parameters + */ + protected function buildMethodSignatures($funcDesc) + { + $i = 0; + $parsVariations = array(); + $pars = array(); + $pNum = count($funcDesc['params']); + foreach ($funcDesc['params'] as $param) { + if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] && + strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) { + // param name from phpdoc info does not match param definition! + $funcDesc['paramDocs'][$i]['type'] = 'mixed'; } - // start building of PHP code to be eval'd + if ($param['isoptional']) { + // this particular parameter is optional. save as valid previous list of parameters + $parsVariations[] = $pars; + } - $innerCode = "\$encoder = new {$namespace}Encoder();\n"; - $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'; - } + $pars[] = "\$p$i"; + $i++; + if ($i == $pNum) { + // last allowed parameters combination + $parsVariations[] = $pars; + } + } - 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 ($decodePhpObjects) { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; - } else { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; - } + if (count($parsVariations) == 0) { + // only known good synopsis = no parameters + $parsVariations[] = array(); + } - $pars[] = "\$p$i"; - $i++; - if ($param['isoptional']) { - $innerCode .= "}\n"; - } - if ($i == $pNum) { - // last allowed parameters combination - $parsVariations[] = $pars; + $sigs = array(); + $pSigs = array(); + foreach ($parsVariations as $pars) { + // build a 'generic' signature (only use an appropriate return type) + $sig = array($funcDesc['returns']); + $pSig = array($funcDesc['returnsDocs']); + for ($i = 0; $i < count($pars); $i++) { + if (isset($funcDesc['paramDocs'][$i]['type'])) { + $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$i]['type']); + } else { + $sig[] = Value::$xmlrpcValue; } + $pSig[] = isset($funcDesc['paramDocs'][$i]['doc']) ? $funcDesc['paramDocs'][$i]['doc'] : ''; } + $sigs[] = $sig; + $pSigs[] = $pSig; + } - $sigs = array(); - $pSigs = array(); - if (count($parsVariations) == 0) { - // only known good synopsis = no parameters - $parsVariations[] = array(); - $minPars = 0; - } else { - $minPars = count($parsVariations[0]); + return array( + 'sigs' => $sigs, + 'pSigs' => $pSigs + ); + } + + /// @todo use namespace, options to encode/decode objects, validate params + protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc) + { + $function = function($req) use($callable, $extraOptions) + { + $encoder = new \PhpXmlRpc\Encoder(); + $params = $encoder->decode($req); + + $result = call_user_func_array($callable, $params); + + if (! $result instanceof \PhpXmlRpc\Response) { + $result = new \PhpXmlRpc\Response($encoder->encode($result)); } + return $result; + }; + + return $function; + } - 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 {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "');\n" . $innerCode; + /** + * Return a name for the new function + * @param $callable + * @param string $newFuncName + * @return string + */ + protected function newFunctionName($callable, $newFuncName, $extraOptions) + { + // determine name of new php function + + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + + if ($newFuncName == '') { + if (is_array($callable)) { + if (is_string($callable[0])) { + $xmlrpcFuncName = "{$prefix}_" . implode('_', $callable); + } else { + $xmlrpcFuncName = "{$prefix}_" . get_class($callable[0]) . '_' . $callable[1]; + } } else { - $innerCode = "\$paramcount = \$msg->getNumParams();\n" . $innerCode; + if ($callable instanceof \Closure) { + $xmlrpcFuncName = "{$prefix}_closure"; + } else { + $xmlrpcFuncName = "{$prefix}_$callable"; + } } + } else { + $xmlrpcFuncName = $newFuncName; + } - $innerCode .= "\$np = false;\n"; - // since there are no closures in php, if we are given an object instance, - // we store a pointer to it in a global var... - if (is_array($funcName) && is_object($funcName[0])) { - $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcFuncName] = &$funcName[0]; - $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcFuncName'];\n"; - $realFuncName = '$obj->' . $funcName[1]; - } else { - $realFuncName = $plainFuncName; + while (function_exists($xmlrpcFuncName)) { + $xmlrpcFuncName .= 'x'; + } + + return $xmlrpcFuncName; + } + + /** + * @param $callable + * @param string $newFuncName + * @param array $extraOptions + * @param string $plainFuncName + * @param array $funcDesc + * @return array + */ + protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc) + { + $namespace = '\\PhpXmlRpc\\'; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; + + // build body of new function + + $innerCode = "\$encoder = new {$namespace}Encoder();\n"; + $i = 0; + $parsVariations = array(); + $pars = array(); + $pNum = count($funcDesc['params']); + foreach ($funcDesc['params'] as $param) { + if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] && + strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) { + // param name from phpdoc info does not match param definition! + $funcDesc['paramDocs'][$i]['type'] = 'mixed'; } - foreach ($parsVariations as $pars) { - $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . 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[] = $this->php_2_xmlrpc_type($paramDocs[$i]['type']); - } else { - $sig[] = Value::$xmlrpcValue; - } - $pSig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : ''; - } - $sigs[] = $sig; - $pSigs[] = $pSig; + + if ($param['isoptional']) { + // this particular parameter is optional. save as valid previous list of parameters + $innerCode .= "if (\$paramcount > $i) {\n"; + $parsVariations[] = $pars; } - $innerCode .= "\$np = true;\n"; - $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . "'); else {\n"; - //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; - $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; - if ($returns == Value::$xmlrpcDateTime || $returns == Value::$xmlrpcBase64) { - $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '$returns'));"; + $innerCode .= "\$p$i = \$req->getParam($i);\n"; + if ($decodePhpObjects) { + $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; } else { - if ($encodePhpObjects) { - $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; - } else { - $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; - } + $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\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 ' . $plainFuncName); - - return false; - } + + $pars[] = "\$p$i"; + $i++; + if ($param['isoptional']) { + $innerCode .= "}\n"; } + if ($i == $pNum) { + // last allowed parameters combination + $parsVariations[] = $pars; + } + } - /// @todo examine if $paramDocs matches $parsVariations and build array for - /// usage as method signature, plus put together a nice string for docs + if (count($parsVariations) == 0) { + // only known good synopsis = no parameters + $parsVariations[] = array(); + $minPars = 0; + } else { + $minPars = count($parsVariations[0]); + } - $ret = array('function' => $xmlrpcFuncName, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $pSigs, 'source' => $code); + if ($minPars) { + // add to code the check for min params number + // NB: this check needs to be done BEFORE decoding param values + $innerCode = "\$paramcount = \$req->getNumParams();\n" . + "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n" . $innerCode; + } else { + $innerCode = "\$paramcount = \$req->getNumParams();\n" . $innerCode; + } - return $ret; + $innerCode .= "\$np = false;\n"; + // since there are no closures in php, if we are given an object instance, + // we store a pointer to it in a global var... + if (is_array($callable) && is_object($callable[0])) { + $GLOBALS['xmlrpcWPFObjHolder'][$newFuncName] = &$callable[0]; + $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$newFuncName'];\n"; + $realFuncName = '$obj->' . $callable[1]; + } else { + $realFuncName = $plainFuncName; } + foreach ($parsVariations as $pars) { + $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n"; + } + $innerCode .= "\$np = true;\n"; + $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "'); else {\n"; + //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; + $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; + if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { + $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));"; + } else { + if ($encodePhpObjects) { + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval, array('encode_php_objs')));\n"; + } else { + $innerCode .= "return new {$namespace}Response(\$encoder->encode(\$retval));\n"; + } + } + // shall we exclude functions returning by ref? + // if($func->returnsReference()) + // return false; + + $code = "function $newFuncName(\$req) {\n" . $innerCode . "}\n}"; + + return $code; } /** @@ -582,7 +725,7 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simpleClientCopy, $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, $faultResponse, $namespace); - //print_r($code); + if ($buildIt) { $allOK = 0; eval($results['source'] . '$allOK=1;'); @@ -611,6 +754,15 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim * * @param Client $client the client obj all set to query the desired server * @param array $extraOptions list of options for wrapped code + * - method_filter + * - timeout + * - protocol + * - new_class_name + * - encode_php_objs + * - decode_php_objs + * - simple_client_copy + * - return_source + * - prefix * * @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) */ @@ -729,7 +881,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $innerCode = ''; $this_ = 'this->'; } - $innerCode .= "\$msg = new {$namespace}Request('$methodName');\n"; + $innerCode .= "\$req = new {$namespace}Request('$methodName');\n"; if ($mdesc != '') { // take care that PHP comment is not terminated unwillingly by method description @@ -757,7 +909,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n"; } } - $innerCode .= "\$msg->addparam(\$p$i);\n"; + $innerCode .= "\$req->addparam(\$p$i);\n"; $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n"; } if ($clientCopyMode < 2) { @@ -767,7 +919,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $plist = implode(', ', $plist); $mdesc .= '* @return ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; - $innerCode .= "\$res = \${$this_}client->send(\$msg, $timeout, '$protocol');\n"; + $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n"; if ($decdoeFault) { 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) . "')"; @@ -796,6 +948,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu * @param bool $verbatimClientCopy * @param string $prefix * @param string $namespace + * * @return string */ protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 629fc7c6..e686b8db 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -554,35 +554,80 @@ public function testCodeInjectionServerSide() public function testAutoRegisteredFunction() { - $f = new xmlrpcmsg('examples.php.getStateName', array( + $f = new xmlrpcmsg('tests.getStateName.2', array( new xmlrpcval(23, 'int'), )); $v = $this->send($f); - if ($v) { - $this->assertEquals('Michigan', $v->scalarval()); - } else { - $this->fail('Note: server can only auto register functions if running with PHP 5.0.3 and up'); - } + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testAutoRegisteredFunction2() + { + $f = new xmlrpcmsg('tests.getStateName.6', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); } public function testAutoRegisteredClass() { - $f = new xmlrpcmsg('examples.php2.getStateName', array( + $f = new xmlrpcmsg('tests.getStateName.3', array( new xmlrpcval(23, 'int'), )); $v = $this->send($f); - if ($v) { - $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('examples.php3.getStateName', array( - new xmlrpcval(23, 'int'), - )); - $v = $this->send($f); - if ($v) { - $this->assertEquals('Michigan', $v->scalarval()); - } - } else { - $this->fail('Note: server can only auto register class methods if running with PHP 5.0.3 and up'); - } + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.4', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.5', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.7', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.8', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.9', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testAutoRegisteredClass2() + { + $f = new xmlrpcmsg('tests.getStateName.7', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.8', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + + $f = new xmlrpcmsg('tests.getStateName.9', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); } public function testAutoRegisteredMethod() @@ -603,7 +648,7 @@ public function testAutoRegisteredMethod() public function testClosure() { - $f = new xmlrpcmsg('examples.php5.getStateName', array( + $f = new xmlrpcmsg('tests.getStateName.10', array( new xmlrpcval(23, 'int'), )); $v = $this->send($f); From 92e61c97411b8652b235e9c05d64934d83c53671 Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 12 May 2015 23:49:19 +0100 Subject: [PATCH 174/228] Refactor demo files (client side): remove redundant ones; make sure all use existing servers; add a proxy example --- demo/client/comment.php | 211 ------------------- demo/client/{client.php => getstatename.php} | 8 +- demo/client/introspect.php | 20 +- demo/client/mail.php | 17 +- demo/client/proxy.php | 58 +++++ demo/client/simple_call.php | 57 ----- demo/client/wrap.php | 9 +- demo/client/zopetest.php | 29 --- tests/5DemofilesTest.php | 27 +-- 9 files changed, 88 insertions(+), 348 deletions(-) delete mode 100644 demo/client/comment.php rename demo/client/{client.php => getstatename.php} (81%) create mode 100644 demo/client/proxy.php delete mode 100644 demo/client/simple_call.php delete mode 100644 demo/client/zopetest.php diff --git a/demo/client/comment.php b/demo/client/comment.php deleted file mode 100644 index 2c34d3f2..00000000 --- a/demo/client/comment.php +++ /dev/null @@ -1,211 +0,0 @@ -"; - exit(); -} - -function dispatch($client, $method, $args) -{ - $req = new PhpXmlRpc\Request($method, $args); - $resp = $client->send($req); - if (!$resp) { - print "

      IO error: " . $client->errstr . "

      "; - bomb(); - } - if ($resp->faultCode()) { - print "

      There was an error: " . $resp->faultCode() . " " . - $resp->faultString() . "

      "; - bomb(); - } - - $encoder = new PhpXmlRpc\Encoder(); - return $encoder->decode($resp->value()); -} - -// create client for discussion server -$dclient = new PhpXmlRpc\Client("http://xmlrpc.usefulinc.com/${mydir}discuss.php"); - -// check if we're posting a comment, and send it if so -@$storyid = $_POST["storyid"]; -if ($storyid) { - - // print "Returning to " . $HTTP_POST_VARS["returnto"]; - - $res = dispatch($dclient, "discuss.addComment", - array(new PhpXmlRpc\Value($storyid), - new PhpXmlRpc\Value(stripslashes(@$_POST["name"])), - new PhpXmlRpc\Value(stripslashes(@$_POST["commenttext"])),)); - - // send the browser back to the originating page - Header("Location: ${mydir}/comment.php?catid=" . - $_POST["catid"] . "&chanid=" . - $_POST["chanid"] . "&oc=" . - $_POST["catid"]); - exit(0); -} - -// now we've got here, we're exploring the story store - -?> - -meerkat browser - -

      Meerkat integration

      - -

      Make a comment on the story

      - -

      Your name:

      - -

      Your comment:

      - - "/> - - - - - new PhpXmlRpc\Value($chanid, "int"), - "ids" => new PhpXmlRpc\Value(1, "int"), - "descriptions" => new PhpXmlRpc\Value(200, "int"), - "num_items" => new PhpXmlRpc\Value(5, "int"), - "dates" => new PhpXmlRpc\Value(0, "int"), - ), "struct"))); - } - ?> -
      -

      Subject area:
      -

      - -

      News source:
      - -

      - - - -

      - -
      - - - -

      Stories available

      - - "; - print ""; - print "\n"; - // now look for existing comments - $res = dispatch($dclient, "discuss.getComments", - array(new PhpXmlRpc\Value($v['id']))); - if (sizeof($res) > 0) { - print "\n"; - } - print "\n"; - } - ?> -
      " . $v['title'] . "
      "; - print $v['description'] . "
      "; - print "Read full story "; - print "Comment on this story"; - print ""; - print "

      " . - "Comments on this story:

      "; - for ($i = 0; $i < sizeof($res); $i++) { - $s = $res[$i]; - print "

      From: " . htmlentities($s['name']) . "
      "; - print "Comment: " . htmlentities($s['comment']) . "

      "; - } - print "

      - - -
      -

      - Meerkat powered, yeah! -

      - - diff --git a/demo/client/client.php b/demo/client/getstatename.php similarity index 81% rename from demo/client/client.php rename to demo/client/getstatename.php index 06a256a1..69ce3e0f 100644 --- a/demo/client/client.php +++ b/demo/client/getstatename.php @@ -5,7 +5,7 @@

      Send a U.S. state number to the server and get back the state name

      -

      The code demonstrates usage of the php_xmlrpc_encode function

      +

      The code demonstrates usage of automatic encoding/decoding of php variables into xmlrpc values

      faultCode()) { $v = $r->value(); print "
      State number " . $stateNo . " is " - . htmlspecialchars($v->scalarval()) . "
      "; - // print "
      I got this value back
      " .
      -        //  htmlentities($r->serialize()). "

      \n"; + . htmlspecialchars($encoder->decode($v)) . "
      "; } else { print "An error occurred: "; print "Code: " . htmlspecialchars($r->faultCode()) @@ -36,7 +34,7 @@ $stateNo = ""; } -print "
      +print "

      Enter a state number to query its name

      "; diff --git a/demo/client/introspect.php b/demo/client/introspect.php index 72006048..e11ac0e5 100644 --- a/demo/client/introspect.php +++ b/demo/client/introspect.php @@ -15,26 +15,31 @@ function display_error($r) print "Code: " . $r->faultCode() . " Reason: '" . $r->faultString() . "'
      "; } -// 'new style' client constructor + $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 "

      methods available at http://" . $client->server . $client->path . "

      \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 for ($i = 0; $i < $v->arraysize(); $i++) { - $mname = $v->arraymem($i); - print "

      " . $mname->scalarval() . "

      \n"; + $methodName = $v->arraymem($i); + print "

      " . $methodName->scalarval() . "

      \n"; // build messages first, add params later $m1 = new PhpXmlRpc\Request('system.methodHelp'); $m2 = new PhpXmlRpc\Request('system.methodSignature'); - $val = new PhpXmlRpc\Value($mname->scalarval(), "string"); + $val = new PhpXmlRpc\Value($methodName->scalarval(), "string"); $m1->addParam($val); $m2->addParam($val); - // send multiple messages in one pass. - // If server does not support multicall, client will fall back to 2 separate calls + // 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()) { @@ -52,13 +57,14 @@ function display_error($r) display_error($rs[1]); } else { print "

      Signature

      \n"; + // note: using PhpXmlRpc\Encoder::decode() here would lead to cleaner code $val = $rs[1]->value(); if ($val->kindOf() == "array") { for ($j = 0; $j < $val->arraysize(); $j++) { $x = $val->arraymem($j); $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " - . $mname->scalarval() . "("; + . $methodName->scalarval() . "("; if ($x->arraysize() > 1) { for ($k = 1; $k < $x->arraysize(); $k++) { $y = $x->arraymem($k); diff --git a/demo/client/mail.php b/demo/client/mail.php index e1966b38..9486e095 100644 --- a/demo/client/mail.php +++ b/demo/client/mail.php @@ -10,9 +10,7 @@

      Mail demo

      -

      This form enables you to send mail via an XML-RPC server. For public use - only the "Userland" server will work (see Dave Winer's - message). +

      This form enables you to send mail via an XML-RPC server. When you press Send 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.

      @@ -25,12 +23,8 @@ include_once __DIR__ . "/../../src/Autoloader.php"; PhpXmlRpc\Autoloader::register(); -if (isset($_POST["server"]) && $_POST["server"]) { - if ($_POST["server"] == "Userland") { - $server = "http://206.204.24.2/RPC2"; - } else { - $server = "http://pingu.heddley.com/xmlrpc/server.php"; - } +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"]), @@ -57,11 +51,6 @@ } ?>
      - Server -
      From

      To
      diff --git a/demo/client/proxy.php b/demo/client/proxy.php new file mode 100644 index 00000000..2ffc0c42 --- /dev/null +++ b/demo/client/proxy.php @@ -0,0 +1,58 @@ + +xmlrpc - Proxy demo + +

      proxy demo

      +

      Query server using a 'proxy' object

      +

      The code demonstrates usage for the terminally lazy

      +client = $client; + } + + /** + * @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->faultMessage(), $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); \ No newline at end of file diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php deleted file mode 100644 index 4e904bea..00000000 --- a/demo/client/simple_call.php +++ /dev/null @@ -1,57 +0,0 @@ -encode($parameter); - } - - return $client->send(new PhpXmlRpc\Request($remote_function_name, $valueArray)); - } -} diff --git a/demo/client/wrap.php b/demo/client/wrap.php index f1a7e005..4dde5ba0 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -5,9 +5,10 @@

      Wrap methods exposed by server into php functions

      -

      The code demonstrates usage of the most automagic client usage possible:
      +

      The code demonstrates usage of some the most automagic client usage possible:
      1) client that returns php values instead of xmlrpc value objects
      - 2) wrapping of remote methods into php functions + 2) wrapping of remote methods into php functions
      + See also proxy.php for an alternative take

      Server methods list retrieved, now wrapping it up...

      \n
        \n"; foreach ($resp->value() as $methodName) { - // $r->value is an array of strings + // $resp->value is an array of strings // do not wrap remote server system methods if (strpos($methodName, 'system.') !== 0) { @@ -42,7 +43,7 @@ echo "
      \n"; if ($testCase) { echo "Now testing function $testCase: remote method to convert U.S. state number into state name"; - $stateNum = 25; + $stateNum = rand(1, 51); $stateName = $testCase($stateNum, 2); echo "State number $stateNum is " . htmlspecialchars($stateName); } diff --git a/demo/client/zopetest.php b/demo/client/zopetest.php deleted file mode 100644 index 39e705e4..00000000 --- a/demo/client/zopetest.php +++ /dev/null @@ -1,29 +0,0 @@ - -xmlrpc - Zope test demo - -

      Zope test demo

      - -

      The code demonstrates usage of basic authentication to connect to the server

      -setCredentials("username", "password"); -$client->setDebug(2); -$resp = $client->send($req); -if (!$resp->faultCode()) { - $value = $resp->value(); - print "I received:" . htmlspecialchars($value->scalarval()) . "
      "; - print "
      I got this value back
      pre>" . - htmlentities($resp->serialize()) . "\n"; -} else { - print "An error occurred: "; - print "Code: " . htmlspecialchars($resp->faultCode()) - . " Reason: '" . ($resp->faultString()) . "'
      "; -} -?> - - diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index b7a38716..01ed6214 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -18,19 +18,10 @@ public function testAgeSort() $page = $this->request('client/agesort.php'); } - public function testClient() + public function testGetStateName() { - $page = $this->request('client/client.php'); - - // we could test many more calls to the client demo, but the upstream server is gone anyway... - - $page = $this->request('client/client.php', 'POST', array('stateno' => '1')); - } - - public function testComment() - { - $page = $this->request('client/comment.php'); - $page = $this->request('client/client.php', 'POST', array('storyid' => '1')); + $page = $this->request('client/getstatename.php'); + $page = $this->request('client/getstatename.php', 'POST', array('stateno' => '1')); } public function testIntrospect() @@ -41,8 +32,7 @@ public function testIntrospect() public function testMail() { $page = $this->request('client/mail.php'); - $page = $this->request('client/client.php', 'POST', array( - 'server' => '', + $page = $this->request('client/mail.php', 'POST', array( "mailto" => '', "mailsub" => '', "mailmsg" => '', @@ -52,9 +42,9 @@ public function testMail() )); } - public function testSimpleCall() + public function testProxy() { - $page = $this->request('client/simple_call.php', 'GET', null, true); + $page = $this->request('client/proxy.php', 'GET', null, true); } public function testWhich() @@ -67,11 +57,6 @@ public function testWrap() $page = $this->request('client/wrap.php'); } - public function testZopeTest() - { - $page = $this->request('client/zopetest.php'); - } - public function testDiscussServer() { $page = $this->request('server/discuss.php'); From 70b5a85b3f6831d37e34a7b86bf87383247f16bb Mon Sep 17 00:00:00 2001 From: gggeek Date: Tue, 12 May 2015 23:56:03 +0100 Subject: [PATCH 175/228] Update comments --- demo/server/proxy.php | 6 ++++-- src/Wrapper.php | 17 ++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/demo/server/proxy.php b/demo/server/proxy.php index 4f860de1..adf80041 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -15,6 +15,8 @@ /** * 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 @@ -58,9 +60,9 @@ function forward_request($req) /// @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... - $reqethod = $encoder->decode($req->getParam(1)); + $reqMethod = $encoder->decode($req->getParam(1)); $pars = $req->getParam(2); - $req = new PhpXmlRpc\Request($reqethod); + $req = new PhpXmlRpc\Request($reqMethod); for ($i = 0; $i < $pars->arraySize(); $i++) { $req->addParam($pars->arraymem($i)); } diff --git a/src/Wrapper.php b/src/Wrapper.php index 48244fb4..a870202f 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -338,8 +338,6 @@ protected function introspectFunction($callable, $plainFuncName) * @param array $funcDesc as generated by self::introspectFunction() * * @return array - * - * @todo missing parameters */ protected function buildMethodSignatures($funcDesc) { @@ -396,7 +394,16 @@ protected function buildMethodSignatures($funcDesc) ); } - /// @todo use namespace, options to encode/decode objects, validate params + /** + * Creates a closure that will execute $callable + * @todo use namespace, options to encode/decode objects, validate params + * + * @param $callable + * @param array $extraOptions + * @param string $plainFuncName + * @param string $funcDesc + * @return callable + */ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc) { $function = function($req) use($callable, $extraOptions) @@ -569,7 +576,7 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption * @return array or false on failure * * @todo get_class_methods will return both static and non-static methods. - * we have to differentiate the action, depending on wheter we recived a class name or object + * we have to differentiate the action, depending on whether we received a class name or object */ public function wrap_php_class($classname, $extraOptions = array()) { @@ -822,7 +829,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) 'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix, 'decode_php_objs' => $decodePhpObjects, ); - /// @todo build javadoc for class definition, too + /// @todo build phpdoc 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]/'), From 4c4a011460289d5803cf6cd623f228e0df3c6ad2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 15 May 2015 01:51:53 +0100 Subject: [PATCH 176/228] Fix wrap_php_class(); add more tests for wrapping --- demo/server/server.php | 5 ++ src/Wrapper.php | 183 ++++++++++++++++++++++----------------- tests/3LocalhostTest.php | 44 ++++++++-- 3 files changed, 144 insertions(+), 88 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index c3eedf4c..beae193d 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -893,6 +893,11 @@ function i_whichToolkit($req) ); +$wrapper = new \PhpXmlRpc\Wrapper(); +$c = new xmlrpcServerMethodsContainer; +$moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); +$signatures = array_merge($signatures, $moreSignatures); + $s = new PhpXmlRpc\Server($signatures, false); $s->setdebug(3); $s->compress_response = true; diff --git a/src/Wrapper.php b/src/Wrapper.php index a870202f..6631aa7a 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -122,13 +122,13 @@ public function xmlrpc_2_php_type($xmlrpcType) * php functions (ie. functions not expecting a single Request obj as parameter) * is by making use of the functions_parameters_type class member. * - * @param string|array $funcName the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too - * @param string $newFuncName (optional) name for function to be created + * @param string|array $callable the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too + * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true * @param array $extraOptions (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 + * 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 array|false 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 @@ -195,7 +195,7 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null); $code = ''; } else { - $newFuncName =$this->newFunctionName($callable, $newFuncName, $extraOptions); + $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions); $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); // replace the original callable to be set in the results $callable = $newFuncName; @@ -396,7 +396,7 @@ protected function buildMethodSignatures($funcDesc) /** * Creates a closure that will execute $callable - * @todo use namespace, options to encode/decode objects, validate params + * @todo validate params * * @param $callable * @param array $extraOptions @@ -408,14 +408,27 @@ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFunc { $function = function($req) use($callable, $extraOptions) { - $encoder = new \PhpXmlRpc\Encoder(); - $params = $encoder->decode($req); + $nameSpace = '\\PhpXmlRpc\\'; + $encoderClass = $nameSpace.'Encoder'; + $responseClass = $nameSpace.'Response'; + + $encoder = new $encoderClass(); + $options = array(); + if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) { + $options[] = 'decode_php_objs'; + } + $params = $encoder->decode($req, $options); $result = call_user_func_array($callable, $params); - if (! $result instanceof \PhpXmlRpc\Response) { - $result = new \PhpXmlRpc\Response($encoder->encode($result)); + if (! is_a($result, $responseClass)) { + $options = array(); + if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) { + $options[] = 'encode_php_objs'; + } + $result = new $responseClass($encoder->encode($result, $options)); } + return $result; }; @@ -569,40 +582,47 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server * object and called from remote clients (as well as their corresponding signature info). * - * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class - * @param array $extraOptions see the docs for wrap_php_method for more options - * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance + * @param mixed $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class + * @param array $extraOptions see the docs for wrap_php_method for basic options, plus + * - string method_type: 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance + * - string method_filter: a regexp used to filter methods to wrap based on their names + * - string $prefix/ used for the names of the xmlrpc methods created * * @return array or false on failure * * @todo get_class_methods will return both static and non-static methods. * we have to differentiate the action, depending on whether we received a class name or object */ - public function wrap_php_class($classname, $extraOptions = array()) + public function wrap_php_class($className, $extraOptions = array()) { - $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; - $methodtype = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; - - $result = array(); - $mlist = get_class_methods($classname); - foreach ($mlist as $mname) { - if ($methodfilter == '' || preg_match($methodfilter, $mname)) { - // echo $mlist."\n"; - $func = new \ReflectionMethod($classname, $mname); + $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : ''; + + $results = array(); + $mList = get_class_methods($className); + foreach ($mList as $mName) { + if ($methodFilter == '' || preg_match($methodFilter, $mName)) { + $func = new \ReflectionMethod($className, $mName); if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) { - if (($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) || - (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))) + if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) || + (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className)))) ) { - $methodwrap = $this->wrap_php_function(array($classname, $mname), '', $extraOptions); - if ($methodwrap) { - $result[$methodwrap['function']] = $methodwrap['function']; + $methodWrap = $this->wrap_php_function(array($className, $mName), '', $extraOptions); + if ($methodWrap) { + if (is_object($className)) { + $realClassName = get_class($className); + }else { + $realClassName = $className; + } + $results[$prefix."$realClassName.$mName"] = $methodWrap; } } } } } - return $result; + return $results; } /** @@ -628,6 +648,8 @@ public function wrap_php_class($classname, $extraOptions = array()) * An extra 'debug' param is appended to param list of xmlrpc method, useful * for debugging purposes. * + * @todo in case user wants back a function, return a closure instead of using eval + * * @param 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 $extraOptions array of options that specify conversion details. valid options include @@ -648,10 +670,10 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim // mind numbing: let caller use sane calling convention (as per javadoc, 3 params), // OR the 2.0 calling convention (no options) - we really love backward compat, don't we? if (!is_array($extraOptions)) { - $signum = $extraOptions; + $sigNum = $extraOptions; $extraOptions = array(); } else { - $signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; @@ -676,12 +698,12 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim } $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; - $msgclass = $namespace . 'Request'; - $valclass = $namespace . 'Value'; + $msgClass = $namespace . 'Request'; + $valClass = $namespace . 'Value'; $decoderClass = $namespace . 'Encoder'; - $msg = new $msgclass('system.methodSignature'); - $msg->addparam(new $valclass($methodName)); + $msg = new $msgClass('system.methodSignature'); + $msg->addparam(new $valClass($methodName)); $client->setDebug($debug); $response = $client->send($msg, $timeout, $protocol); if ($response->faultCode()) { @@ -689,13 +711,13 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim return false; } else { - $msig = $response->value(); + $mSig = $response->value(); if ($client->return_type != 'phpvals') { $decoder = new $decoderClass(); - $msig = $decoder->decode($msig); + $mSig = $decoder->decode($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); + 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 { @@ -712,24 +734,24 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim $xmlrpcFuncName .= 'x'; } - $msig = $msig[$signum]; - $mdesc = ''; + $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)); + $msg = new $msgClass('system.methodHelp'); + $msg->addparam(new $valClass($methodName)); $response = $client->send($msg, $timeout, $protocol); if (!$response->faultCode()) { - $mdesc = $response->value(); + $mDesc = $response->value(); if ($client->return_type != 'phpvals') { - $mdesc = $mdesc->scalarval(); + $mDesc = $mDesc->scalarval(); } } } $results = $this->build_remote_method_wrapper_code($client, $methodName, - $xmlrpcFuncName, $msig, $mdesc, $timeout, $protocol, $simpleClientCopy, + $xmlrpcFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy, $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, $faultResponse, $namespace); @@ -759,6 +781,8 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim * all xmlrpc methods exposed by the remote server as own methods. * For more details see wrap_xmlrpc_method. * + * NB: for a slimmer alternative, see the code in demo/client/proxy.php + * * @param Client $client the client obj all set to query the desired server * @param array $extraOptions list of options for wrapped code * - method_filter @@ -775,11 +799,11 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim */ public function wrap_xmlrpc_server($client, $extraOptions = array()) { - $methodfilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; - //$signum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; + //$sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; - $newclassname = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : ''; + $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : ''; $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; $verbatimClientCopy = isset($extraOptions['simple_client_copy']) ? !($extraOptions['simple_client_copy']) : true; @@ -787,30 +811,30 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; - $msgclass = $namespace . 'Request'; - //$valclass = $prefix.'val'; + $msgClass = $namespace . 'Request'; + //$valClass = $prefix.'val'; $decoderClass = $namespace . 'Encoder'; - $msg = new $msgclass('system.listMethods'); + $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(); + $mList = $response->value(); if ($client->return_type != 'phpvals') { $decoder = new $decoderClass(); - $mlist = $decoder->decode($mlist); + $mList = $decoder->decode($mList); } - if (!is_array($mlist) || !count($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; + if ($newClassName != '') { + $xmlrpcClassName = $newClassName; } else { $xmlrpcClassName = $prefix . '_' . preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), array('_', ''), $client->server) . '_client'; @@ -830,18 +854,19 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) 'decode_php_objs' => $decodePhpObjects, ); /// @todo build phpdoc for class definition, too - foreach ($mlist as $mname) { - if ($methodfilter == '' || preg_match($methodfilter, $mname)) { + foreach ($mList as $mName) { + if ($methodFilter == '' || preg_match($methodFilter, $mName)) { + // note: this will fail if server exposes 2 methods called f.e. do.something and do_something $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), - array('_', ''), $mname); - $methodwrap = $this->wrap_xmlrpc_method($client, $mname, $opts); - if ($methodwrap) { + array('_', ''), $mName); + $methodWrap = $this->wrap_xmlrpc_method($client, $mName, $opts); + if ($methodWrap) { if (!$buildIt) { - $source .= $methodwrap['docstring']; + $source .= $methodWrap['docstring']; } - $source .= $methodwrap['source'] . "\n"; + $source .= $methodWrap['source'] . "\n"; } else { - error_log('XML-RPC: will not create class method to wrap remote method ' . $mname); + error_log('XML-RPC: will not create class method to wrap remote method ' . $mName); } } } @@ -873,8 +898,8 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) * Note: real spaghetti code follows... */ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, - $msig, $mdesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc', - $decodePhpObjects = false, $encodePhpObjects = false, $decdoeFault = false, + $mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc', + $decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false, $faultResponse = '', $namespace = '\\PhpXmlRpc\\') { $code = "function $xmlrpcFuncName ("; @@ -890,20 +915,20 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu } $innerCode .= "\$req = new {$namespace}Request('$methodName');\n"; - if ($mdesc != '') { + if ($mDesc != '') { // take care that PHP comment is not terminated unwillingly by method description - $mdesc = "/**\n* " . str_replace('*/', '* /', $mdesc) . "\n"; + $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n"; } else { - $mdesc = "/**\nFunction $xmlrpcFuncName\n"; + $mDesc = "/**\nFunction $xmlrpcFuncName\n"; } // param parsing $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; $plist = array(); - $pcount = count($msig); + $pcount = count($mSig); for ($i = 1; $i < $pcount; $i++) { $plist[] = "\$p$i"; - $ptype = $msig[$i]; + $ptype = $mSig[$i]; if ($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' || $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null' ) { @@ -917,17 +942,17 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu } } $innerCode .= "\$req->addparam(\$p$i);\n"; - $mdesc .= '* @param ' . $this->xmlrpc_2_php_type($ptype) . " \$p$i\n"; + $mDesc .= '* @param ' . $this->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"; + $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 ' . $this->xmlrpc_2_php_type($msig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + $mDesc .= '* @return ' . $this->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 ($decdoeFault) { + 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 { @@ -944,7 +969,7 @@ public function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFu $code = $code . $plist . ") {\n" . $innerCode . "\n}\n"; - return array('source' => $code, 'docstring' => $mdesc); + return array('source' => $code, 'docstring' => $mDesc); } /** diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index e686b8db..be17d69a 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -570,7 +570,7 @@ public function testAutoRegisteredFunction2() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredClass() + public function testAutoRegisteredMethods() { $f = new xmlrpcmsg('tests.getStateName.3', array( new xmlrpcval(23, 'int'), @@ -609,7 +609,7 @@ public function testAutoRegisteredClass() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredClass2() + public function testAutoRegisteredMethods2() { $f = new xmlrpcmsg('tests.getStateName.7', array( new xmlrpcval(23, 'int'), @@ -630,7 +630,25 @@ public function testAutoRegisteredClass2() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredMethod() + public function testAutoRegisteredClosure() + { + $f = new xmlrpcmsg('tests.getStateName.10', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testAutoRegisteredClass() + { + $f = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $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' => 1)); @@ -646,13 +664,21 @@ public function testAutoRegisteredMethod() } } - public function testClosure() + public function testWrappedClass() { - $f = new xmlrpcmsg('tests.getStateName.10', array( - new xmlrpcval(23, 'int'), - )); - $v = $this->send($f); - $this->assertEquals('Michigan', $v->scalarval()); + // make a 'deep client copy' as the original one might have many properties set + $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 1)); + if ($class == '') { + $this->fail('Registration of remote server failed'); + } else { + $obj = new $class(); + $v = $obj->examples_getStateName(23); + // work around bug in current version of phpunit + if (is_object($v)) { + $v = var_export($v, true); + } + $this->assertEquals('Michigan', $v); + } } public function testGetCookies() From dc81107c8486d21cc48144ae0e218afded36997b Mon Sep 17 00:00:00 2001 From: gggeek Date: Fri, 15 May 2015 01:52:23 +0100 Subject: [PATCH 177/228] Show in debugger the count of server methods found --- debugger/action.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debugger/action.php b/debugger/action.php index 3e22c692..05cc99a5 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -286,7 +286,7 @@ if ($v->kindOf() == "array") { $max = $v->arraysize(); echo "\n"; - echo "\n\n\n\n"; + echo "\n\n\n\n"; for ($i = 0; $i < $max; $i++) { $rec = $v->arraymem($i); if ($i % 2) { From a11cdd0958187d3a023241df34bd81464a586d7e Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 17 May 2015 02:17:04 +0100 Subject: [PATCH 178/228] Improve generation of methods signature by the Wrapper class --- demo/server/server.php | 8 +++--- src/Wrapper.php | 59 ++++++++++++++++++++++++------------------ 2 files changed, 39 insertions(+), 28 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index beae193d..6e2f7716 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -168,6 +168,11 @@ function inner_findstate($stateNo) "docstring" => $findstate_doc, ); +$c = new xmlrpcServerMethodsContainer; +$moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); +var_dump($moreSignatures); +die(); + $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; function addTwo($req) @@ -893,9 +898,6 @@ function i_whichToolkit($req) ); -$wrapper = new \PhpXmlRpc\Wrapper(); -$c = new xmlrpcServerMethodsContainer; -$moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); $signatures = array_merge($signatures, $moreSignatures); $s = new PhpXmlRpc\Server($signatures, false); diff --git a/src/Wrapper.php b/src/Wrapper.php index 6631aa7a..fe4fae7b 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -208,7 +208,7 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = 'function' => $callable, 'signature' => $funcSigs['sigs'], 'docstring' => $funcDesc['desc'], - 'signature_docs' => $funcSigs['pSigs'], + 'signature_docs' => $funcSigs['sigsDocs'], 'source' => $code ); @@ -289,23 +289,26 @@ protected function introspectFunction($callable, $plainFuncName) } 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'; + if ($matches[2] == '' && substr($matches[3], 0, 1) == '$') { + // syntax: @param type $name + $name = strtolower(trim($matches[3])); + $paramDocs[$name]['name'] = trim($matches[3]); + $paramDocs[$name]['doc'] = ''; } else { - $paramDocs[$i]['type'] = $matches[1]; + $name = strtolower(trim($matches[2])); + $paramDocs[$name]['name'] = trim($matches[2]); + $paramDocs[$name]['doc'] = $matches[3]; } - $paramDocs[$i]['name'] = trim($matches[2]); - $paramDocs[$i]['doc'] = $matches[3]; + + $paramDocs[$name]['type'] = $matches[1]; } $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 = $this->php_2_xmlrpc_type($matches[1]); + // syntax: @return type [desc] + if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) { + $returns = $matches[1]; if (isset($matches[2])) { - $returnsDocs = $matches[2]; + $returnsDocs = trim($matches[2]); } } } @@ -326,7 +329,7 @@ protected function introspectFunction($callable, $plainFuncName) 'desc' => $desc, 'docs' => $docs, 'params' => $params, - 'paramsDocs' => $paramDocs, + 'paramDocs' => $paramDocs, 'returns' => $returns, 'returnsDocs' =>$returnsDocs, ); @@ -335,6 +338,8 @@ protected function introspectFunction($callable, $plainFuncName) /** * Given the method description given by introspection, create method signature data * + * @todo support better docs with multiple types separated by pipes by creating multiple signatures + * * @param array $funcDesc as generated by self::introspectFunction() * * @return array @@ -346,11 +351,14 @@ protected function buildMethodSignatures($funcDesc) $pars = array(); $pNum = count($funcDesc['params']); foreach ($funcDesc['params'] as $param) { - if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] && - strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) { - // param name from phpdoc info does not match param definition! - $funcDesc['paramDocs'][$i]['type'] = 'mixed'; + /* // match by name real param and documented params + $name = strtolower($param['name']); + if (!isset($funcDesc['paramDocs'][$name])) { + $funcDesc['paramDocs'][$name] = array(); } + if (!isset($funcDesc['paramDocs'][$name]['type'])) { + $funcDesc['paramDocs'][$name]['type'] = 'mixed'; + }*/ if ($param['isoptional']) { // this particular parameter is optional. save as valid previous list of parameters @@ -371,26 +379,27 @@ protected function buildMethodSignatures($funcDesc) } $sigs = array(); - $pSigs = array(); + $sigsDocs = array(); foreach ($parsVariations as $pars) { - // build a 'generic' signature (only use an appropriate return type) - $sig = array($funcDesc['returns']); + // build a signature + $sig = array($this->php_2_xmlrpc_type($funcDesc['returns'])); $pSig = array($funcDesc['returnsDocs']); for ($i = 0; $i < count($pars); $i++) { - if (isset($funcDesc['paramDocs'][$i]['type'])) { - $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$i]['type']); + $name = strtolower($funcDesc['params'][$i]['name']); + if (isset($funcDesc['paramDocs'][$name]['type'])) { + $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$name]['type']); } else { $sig[] = Value::$xmlrpcValue; } - $pSig[] = isset($funcDesc['paramDocs'][$i]['doc']) ? $funcDesc['paramDocs'][$i]['doc'] : ''; + $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : ''; } $sigs[] = $sig; - $pSigs[] = $pSig; + $sigsDocs[] = $pSig; } return array( 'sigs' => $sigs, - 'pSigs' => $pSigs + 'sigsDocs' => $sigsDocs ); } From cc8f06ca0b580d2ce38cccbc6706e07537ee83f6 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 17 May 2015 02:25:49 +0100 Subject: [PATCH 179/228] fix previous commit: leftover debug code in server.php --- demo/server/server.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index 6e2f7716..775b077c 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -170,8 +170,6 @@ function inner_findstate($stateNo) $c = new xmlrpcServerMethodsContainer; $moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); -var_dump($moreSignatures); -die(); $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; From 749bcf1b412822e08dbcab366cfbf7ad1cb77db0 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 17 May 2015 16:55:46 +0100 Subject: [PATCH 180/228] rename variables and clean up comments --- src/Client.php | 16 +++++++------- src/Server.php | 57 +++++++++++++++++++++++++------------------------ src/Wrapper.php | 20 ++++++++--------- 3 files changed, 47 insertions(+), 46 deletions(-) diff --git a/src/Client.php b/src/Client.php index 214d9703..21060e8b 100644 --- a/src/Client.php +++ b/src/Client.php @@ -352,7 +352,7 @@ public function send($req, $timeout = 0, $method = '') } if (is_array($req)) { - // $msg is an array of Requests + // $req is an array of Requests $r = $this->multicall($req, $timeout, $method); return $r; @@ -634,7 +634,7 @@ protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $usernam * Requires curl to be built into PHP * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers! * - * @param Request $msg + * @param Request $req * @param string $server * @param int $port * @param int $timeout @@ -657,7 +657,7 @@ protected function sendPayloadHTTPS($req, $server, $port, $timeout = 0, $usernam * @param int $sslVersion * @return Response */ - protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username = '', + protected function sendPayloadCURL($req, $server, $port, $timeout = 0, $username = '', $password = '', $authType = 1, $cert = '', $certPass = '', $caCert = '', $caCertDir = '', $proxyHost = '', $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1, $method = 'https', $keepAlive = false, $key = '', $keyPass = '', $sslVersion = 0) @@ -684,12 +684,12 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username } // Only create the payload if it was not created previously - if (empty($msg->payload)) { - $msg->createPayload($this->request_charset_encoding); + if (empty($req->payload)) { + $req->createPayload($this->request_charset_encoding); } // Deflate request body and set appropriate request headers - $payload = $msg->payload; + $payload = $req->payload; if (function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate')) { if ($this->request_compression == 'gzip') { $a = @gzencode($payload); @@ -750,7 +750,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username } } // extra headers - $headers = array('Content-Type: ' . $msg->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); + $headers = array('Content-Type: ' . $req->content_type, 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings)); // if no keepalive is wanted, let the server know it in advance if (!$keepAlive) { $headers[] = 'Connection: close'; @@ -865,7 +865,7 @@ protected function sendPayloadCURL($msg, $server, $port, $timeout = 0, $username if (!$keepAlive) { curl_close($curl); } - $resp = $msg->parseResponse($result, true, $this->return_type); + $resp = $req->parseResponse($result, true, $this->return_type); // if we got back a 302, we can not reuse the curl handle for later calls if ($resp->faultCode() == PhpXmlRpc::$xmlrpcerr['http_error'] && $keepAlive) { curl_close($curl); diff --git a/src/Server.php b/src/Server.php index 930edff4..8a2f5117 100644 --- a/src/Server.php +++ b/src/Server.php @@ -12,16 +12,16 @@ class Server */ protected $dmap = array(); /** - * Defines how functions in dmap will be invoked: either using an xmlrpc msg object + * Defines how functions in dmap will be invoked: either using an xmlrpc request object * or plain php values. - * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' + * Valid strings are 'xmlrpcvals', 'phpvals' or 'epivals' */ public $functions_parameters_type = 'xmlrpcvals'; /** * Option used for fine-tuning the encoding the php values returned from * functions registered in the dispatch map when the functions_parameters_types * member is set to 'phpvals' - * @see php_xmlrpc_encode for a list of values + * @see Encoder::encode for a list of values */ public $phpvals_encoding_options = array('auto_dates'); /** @@ -30,7 +30,7 @@ class Server */ public $debug = 1; /** - * Controls behaviour of server when invoked user function throws an exception: + * Controls behaviour of server when the invoked user function throws an exception: * 0 = catch it and return an 'internal error' xmlrpc response (default) * 1 = catch it and return an xmlrpc response with the error corresponding to the exception * 2 = allow the exception to float to the upper layers @@ -39,16 +39,20 @@ class Server /** * When set to true, it will enable HTTP compression of the response, in case * the client has declared its support for compression in the request. + * Set at constructor time. */ public $compress_response = false; /** - * List of http compression methods accepted by the server for requests. + * List of http compression methods accepted by the server for requests. Set at constructor time. * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib */ public $accepted_compression = array(); /// shall we serve calls to system.* methods? public $allow_system_funcs = true; - /// list of charset encodings natively accepted for requests + /** + * List of charset encodings natively accepted for requests. + * Set at constructor time. + */ public $accepted_charset_encodings = array(); /** * charset encoding to be used for response. @@ -75,7 +79,7 @@ class Server /** * @param array $dispatchMap the dispatch map with definition of exposed services - * @param boolean $servicenow set to false to prevent the server from running upon construction + * @param boolean $serviceNow set to false to prevent the server from running upon construction */ public function __construct($dispatchMap = null, $serviceNow = true) { @@ -89,15 +93,12 @@ public function __construct($dispatchMap = null, $serviceNow = true) // by default the xml parser can support these 3 charset encodings $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII'); - // dispMap is a dispatch array of methods - // mapped to function names and signatures - // if a method - // doesn't appear in the map then an unknown - // method error is generated + // dispMap is a dispatch array of methods mapped to function names and signatures. + // If a method doesn't appear in the map then an unknown method error is generated /* milosch - changed to make passing dispMap optional. - * instead, you can use the class add_to_map() function - * to add functions manually (borrowed from SOAPX4) - */ + * instead, you can use the class add_to_map() function + * to add functions manually (borrowed from SOAPX4) + */ if ($dispatchMap) { $this->dmap = $dispatchMap; if ($serviceNow) { @@ -291,12 +292,12 @@ public function add_to_map($methodName, $function, $sig = null, $doc = false, $s /** * Verify type and number of parameters received against a list of known signatures. * - * @param array $in array of either xmlrpc value objects or xmlrpc type definitions - * @param array $sig array of known signatures to match against + * @param array|Request $in array of either xmlrpc value objects or xmlrpc type definitions + * @param array $sigs array of known signatures to match against * * @return array */ - protected function verifySignature($in, $sig) + protected function verifySignature($in, $sigs) { // check each possible signature in turn if (is_object($in)) { @@ -304,8 +305,8 @@ protected function verifySignature($in, $sig) } else { $numParams = count($in); } - foreach ($sig as $cursig) { - if (count($cursig) == $numParams + 1) { + foreach ($sigs as $curSig) { + if (count($curSig) == $numParams + 1) { $itsOK = 1; for ($n = 0; $n < $numParams; $n++) { if (is_object($in)) { @@ -320,10 +321,10 @@ protected function verifySignature($in, $sig) } // param index is $n+1, as first member of sig is return type - if ($pt != $cursig[$n + 1] && $cursig[$n + 1] != Value::$xmlrpcValue) { + if ($pt != $curSig[$n + 1] && $curSig[$n + 1] != Value::$xmlrpcValue) { $itsOK = 0; $pno = $n + 1; - $wanted = $cursig[$n + 1]; + $wanted = $curSig[$n + 1]; $got = $pt; break; } @@ -816,11 +817,11 @@ public static function _xmlrpcs_methodSignature($server, $req) if (isset($dmap[$methName]['signature'])) { $sigs = array(); foreach ($dmap[$methName]['signature'] as $inSig) { - $cursig = array(); + $curSig = array(); foreach ($inSig as $sig) { - $cursig[] = new Value($sig, 'string'); + $curSig[] = new Value($sig, 'string'); } - $sigs[] = new Value($cursig, 'array'); + $sigs[] = new Value($curSig, 'array'); } $r = new Response(new Value($sigs, 'array')); } else { @@ -903,9 +904,9 @@ public static function _xmlrpcs_multicall_do_call($server, $call) } $numParams = $params->arraysize(); - $msg = new Request($methName->scalarval()); + $req = new Request($methName->scalarval()); for ($i = 0; $i < $numParams; $i++) { - if (!$msg->addParam($params->arraymem($i))) { + if (!$req->addParam($params->arraymem($i))) { $i++; return static::_xmlrpcs_multicall_error(new Response(0, @@ -914,7 +915,7 @@ public static function _xmlrpcs_multicall_do_call($server, $call) } } - $result = $server->execute($msg); + $result = $server->execute($req); if ($result->faultCode() != 0) { return static::_xmlrpcs_multicall_error($result); // Method returned fault. diff --git a/src/Wrapper.php b/src/Wrapper.php index fe4fae7b..6cd2538c 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -707,14 +707,14 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim } $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; - $msgClass = $namespace . 'Request'; + $reqClass = $namespace . 'Request'; $valClass = $namespace . 'Value'; $decoderClass = $namespace . 'Encoder'; - $msg = new $msgClass('system.methodSignature'); - $msg->addparam(new $valClass($methodName)); + $req = new $reqClass('system.methodSignature'); + $req->addparam(new $valClass($methodName)); $client->setDebug($debug); - $response = $client->send($msg, $timeout, $protocol); + $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName); @@ -748,9 +748,9 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim // 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); + $req = new $reqClass('system.methodHelp'); + $req->addparam(new $valClass($methodName)); + $response = $client->send($req, $timeout, $protocol); if (!$response->faultCode()) { $mDesc = $response->value(); if ($client->return_type != 'phpvals') { @@ -820,12 +820,12 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; $namespace = '\\PhpXmlRpc\\'; - $msgClass = $namespace . 'Request'; + $reqClass = $namespace . 'Request'; //$valClass = $prefix.'val'; $decoderClass = $namespace . 'Encoder'; - $msg = new $msgClass('system.listMethods'); - $response = $client->send($msg, $timeout, $protocol); + $req = new $reqClass('system.listMethods'); + $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { error_log('XML-RPC: could not retrieve method list from remote server'); From 891efe4262d3cc5a379e0454f1f92c9dbdade9f7 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 17 May 2015 23:44:14 +0100 Subject: [PATCH 181/228] WIP: Make wrap_xmlrpc_method return a closure by default instead of eval'ing a function definition --- demo/client/proxy.php | 4 +- demo/client/wrap.php | 30 +- lib/xmlrpc_wrappers.inc | 88 ++++++ src/Wrapper.php | 607 +++++++++++++++++++++++----------------- 4 files changed, 449 insertions(+), 280 deletions(-) diff --git a/demo/client/proxy.php b/demo/client/proxy.php index 2ffc0c42..6d0d3c5a 100644 --- a/demo/client/proxy.php +++ b/demo/client/proxy.php @@ -3,7 +3,7 @@

      proxy demo

      Query server using a 'proxy' object

      -

      The code demonstrates usage for the terminally lazy

      +

      The code demonstrates usage for the terminally lazy. For a more complete proxy, look at at the Wrapper class

      faultCode()) { echo "

      Server methods list could not be retrieved: error {$resp->faultCode()} '" . htmlspecialchars($resp->faultString()) . "'

      \n"; } else { - $testCase = ''; - $wrapper = new PhpXmlRpc\Wrapper(); echo "

      Server methods list retrieved, now wrapping it up...

      \n
        \n"; + flush(); + + $callable = false; + $wrapper = new PhpXmlRpc\Wrapper(); foreach ($resp->value() as $methodName) { // $resp->value is an array of strings - - // do not wrap remote server system methods - if (strpos($methodName, 'system.') !== 0) { - $funcName = $wrapper->wrap_xmlrpc_method($client, $methodName); - if ($funcName) { - echo "
      • Remote server method " . htmlspecialchars($methodName) . " wrapped into php function " . $funcName . "
      • \n"; + if ($methodName == 'examples.getStateName') { + $callable = $wrapper->wrap_xmlrpc_method($client, $methodName); + if ($callable) { + echo "
      • Remote server method " . htmlspecialchars($methodName) . " wrapped into php function
      • \n"; } else { echo "
      • Remote server method " . htmlspecialchars($methodName) . " could not be wrapped!
      • \n"; } - if ($methodName == 'examples.getStateName') { - $testCase = $funcName; - } + break; } } echo "
      \n"; - if ($testCase) { - echo "Now testing function $testCase: remote method to convert U.S. state number into state name"; + flush(); + + if ($callable) { + echo "Now testing function for remote method to convert U.S. state number into state name"; $stateNum = rand(1, 51); - $stateName = $testCase($stateNum, 2); - echo "State number $stateNum is " . htmlspecialchars($stateName); + // the 2nd parameter gets added to the closure - it is teh debug level to be used for the client + $stateName = $callable($stateNum, 2); } } ?> diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc index 180656e5..fc178dc9 100644 --- a/lib/xmlrpc_wrappers.inc +++ b/lib/xmlrpc_wrappers.inc @@ -24,26 +24,114 @@ function xmlrpc_2_php_type($xmlrpcType) return $wrapper->xmlrpc_2_php_type($xmlrpcType); } +/// @todo return string instead of callable function wrap_php_function($funcName, $newFuncName='', $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); return $wrapper->wrap_php_function($funcName, $newFuncName, $extraOptions); } +/// @todo return strings instead of callables function wrap_php_class($className, $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); return $wrapper->wrap_php_class($className, $extraOptions); } +/// @todo support different calling convention +/// @todo return string instead of callable function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $protocol='', $newFuncName='') { $wrapper = new PhpXmlRpc\Wrapper(); return $wrapper->wrap_xmlrpc_method($client, $methodName, $extraOptions, $timeout, $protocol, $newFuncName); } +/// @todo return strings instead of callables function wrap_xmlrpc_server($client, $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); return $wrapper->wrap_xmlrpc_server($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 = $this->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 == '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 ' . $this->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 ' . $this->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); +} diff --git a/src/Wrapper.php b/src/Wrapper.php index 6cd2538c..2c0d1f78 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -21,9 +21,11 @@ class Wrapper /** * 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 - * for php arrays always return array, even though arrays sometimes serialize as json structs. + * Notes: + * - 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 + * - for php arrays always return array, even though arrays sometimes serialize as json structs + * - for 'void' and 'null' returns 'undefined' * * @param string $phpType * @@ -38,17 +40,20 @@ public function php_2_xmlrpc_type($phpType) case Value::$xmlrpcInt: // 'int' case Value::$xmlrpcI4: return Value::$xmlrpcInt; - case 'double': + case Value::$xmlrpcDouble: // 'double' return Value::$xmlrpcDouble; - case 'boolean': + case 'bool': + case Value::$xmlrpcBoolean: // 'boolean' + case 'false': + case 'true': return Value::$xmlrpcBoolean; - case 'array': + case Value::$xmlrpcArray: // 'array': return Value::$xmlrpcArray; case 'object': + case Value::$xmlrpcStruct: // 'struct' return Value::$xmlrpcStruct; case Value::$xmlrpcBase64: - case Value::$xmlrpcStruct: - return strtolower($phpType); + return Value::$xmlrpcBase64; case 'resource': return ''; default: @@ -62,7 +67,7 @@ public function php_2_xmlrpc_type($phpType) } /** - * Given a string defining a phpxmlrpc type return corresponding php type. + * Given a string defining a phpxmlrpc type return the corresponding php type. * * @param string $xmlrpcType * @@ -108,15 +113,13 @@ public function xmlrpc_2_php_type($xmlrpcType) * Known limitations: * - 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: + * - functions returning php objects will generate special structs in 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 Request obj as parameter) @@ -125,22 +128,21 @@ public function xmlrpc_2_php_type($xmlrpcType) * @param string|array $callable the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true * @param array $extraOptions (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 + * - bool return_source when true, php code w. function definition will be returned, instead of a closure + * - 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 warnings generated at runtime by the php function being invoked * * @return array|false 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 decide how to deal with params passed by ref in function definition: bomb out or allow? * @todo finish using phpdoc 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 returning an empty string value... * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? - * @todo if $newFuncName is empty, we could use create_user_func instead of eval, as it is possibly faster - * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance? + * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance? */ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array()) { @@ -182,23 +184,10 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = $funcSigs = $this->buildMethodSignatures($funcDesc); 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 ' . $plainFuncName); - - return false; - }*/ $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null); - $code = ''; } else { $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions); $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); - // replace the original callable to be set in the results - $callable = $newFuncName; } /// @todo examine if $paramDocs matches $parsVariations and build array for @@ -209,9 +198,11 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = 'signature' => $funcSigs['sigs'], 'docstring' => $funcDesc['desc'], 'signature_docs' => $funcSigs['sigsDocs'], - 'source' => $code ); - + if (!$buildIt) { + $ret['function'] = $newFuncName; + $ret['source'] = $code; + } return $ret; } @@ -229,27 +220,22 @@ protected function introspectFunction($callable, $plainFuncName) $func = new \ReflectionMethod($callable[0], $callable[1]); if ($func->isPrivate()) { error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); - return false; } if ($func->isProtected()) { error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); - return false; } if ($func->isConstructor()) { error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); - return false; } if ($func->isDestructor()) { error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); - return false; } if ($func->isAbstract()) { error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); - return false; } /// @todo add more checks for static vs. nonstatic? @@ -260,7 +246,6 @@ protected function introspectFunction($callable, $plainFuncName) // 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: ' . $plainFuncName); - return false; } @@ -287,19 +272,11 @@ protected function introspectFunction($callable, $plainFuncName) } $desc .= $doc; } elseif (strpos($doc, '@param') === 0) { - // syntax: @param type [$name] desc - if (preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches)) { - if ($matches[2] == '' && substr($matches[3], 0, 1) == '$') { - // syntax: @param type $name - $name = strtolower(trim($matches[3])); - $paramDocs[$name]['name'] = trim($matches[3]); - $paramDocs[$name]['doc'] = ''; - } else { - $name = strtolower(trim($matches[2])); - $paramDocs[$name]['name'] = trim($matches[2]); - $paramDocs[$name]['doc'] = $matches[3]; - } - + // syntax: @param type $name [desc] + if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s+(.+)?/', $doc, $matches)) { + $name = strtolower(trim($matches[2])); + //$paramDocs[$name]['name'] = trim($matches[2]); + $paramDocs[$name]['doc'] = $matches[3]; $paramDocs[$name]['type'] = $matches[1]; } $i++; @@ -339,6 +316,7 @@ protected function introspectFunction($callable, $plainFuncName) * Given the method description given by introspection, create method signature data * * @todo support better docs with multiple types separated by pipes by creating multiple signatures + * (this is questionable, as it might produce a big matrix of possible signatures with many such occurrences) * * @param array $funcDesc as generated by self::introspectFunction() * @@ -405,7 +383,8 @@ protected function buildMethodSignatures($funcDesc) /** * Creates a closure that will execute $callable - * @todo validate params + * @todo validate params? In theory all validation is left to the dispatch map... + * @todo add support for $catchWarnings * * @param $callable * @param array $extraOptions @@ -415,11 +394,12 @@ protected function buildMethodSignatures($funcDesc) */ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc) { - $function = function($req) use($callable, $extraOptions) + $function = function($req) use($callable, $extraOptions, $funcDesc) { $nameSpace = '\\PhpXmlRpc\\'; $encoderClass = $nameSpace.'Encoder'; $responseClass = $nameSpace.'Response'; + $valueClass = $nameSpace.'Value'; $encoder = new $encoderClass(); $options = array(); @@ -431,11 +411,17 @@ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFunc $result = call_user_func_array($callable, $params); if (! is_a($result, $responseClass)) { - $options = array(); - if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) { - $options[] = 'encode_php_objs'; + if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { + $result = new $valueClass($result, $funcDesc['returns']); + } else { + $options = array(); + if (isset($extraOptions['encode_php_objs']) && $extraOptions['encode_php_objs']) { + $options[] = 'encode_php_objs'; + } + + $result = $encoder->encode($result, $options); } - $result = new $responseClass($encoder->encode($result, $options)); + $result = new $responseClass($result); } return $result; @@ -445,9 +431,9 @@ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFunc } /** - * Return a name for the new function - * @param $callable - * @param string $newFuncName + * Return a name for a new function, based on $callable, insuring its uniqueness + * @param mixed $callable a php callable, or the name of an xmlrpc method + * @param string $newFuncName when not empty, it is used instead of the calculated version * @return string */ protected function newFunctionName($callable, $newFuncName, $extraOptions) @@ -467,6 +453,8 @@ protected function newFunctionName($callable, $newFuncName, $extraOptions) if ($callable instanceof \Closure) { $xmlrpcFuncName = "{$prefix}_closure"; } else { + $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), + array('_', ''), $callable); $xmlrpcFuncName = "{$prefix}_$callable"; } } @@ -492,7 +480,7 @@ protected function newFunctionName($callable, $newFuncName, $extraOptions) protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc) { $namespace = '\\PhpXmlRpc\\'; - $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; @@ -552,8 +540,8 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption } $innerCode .= "\$np = false;\n"; - // since there are no closures in php, if we are given an object instance, - // we store a pointer to it in a global var... + // since we are building source code for later use, if we are given an object instance, + // we go out of our way and store a pointer to it in a global var... if (is_array($callable) && is_object($callable[0])) { $GLOBALS['xmlrpcWPFObjHolder'][$newFuncName] = &$callable[0]; $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$newFuncName'];\n"; @@ -593,14 +581,11 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption * * @param mixed $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class * @param array $extraOptions see the docs for wrap_php_method for basic options, plus - * - string method_type: 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance - * - string method_filter: a regexp used to filter methods to wrap based on their names - * - string $prefix/ used for the names of the xmlrpc methods created - * - * @return array or false on failure + * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance + * - string method_filter a regexp used to filter methods to wrap based on their names + * - string prefix used for the names of the xmlrpc methods created * - * @todo get_class_methods will return both static and non-static methods. - * we have to differentiate the action, depending on whether we received a class name or object + * @return array|false false on failure */ public function wrap_php_class($className, $extraOptions = array()) { @@ -657,132 +642,312 @@ public function wrap_php_class($className, $extraOptions = array()) * An extra 'debug' param is appended to param list of xmlrpc method, useful * for debugging purposes. * - * @todo in case user wants back a function, return a closure instead of using eval + * @todo allow caller to give us the method signature instead of querying for it, or just say 'skip it' + * @todo if we can not retrieve method signature, create a php function with varargs + * @todo allow the created function to throw exceptions on method calls failures + * @todo if caller did not specify a specific sig, shall we support all of them? + * It might be hard (hence slow) to match based on type and number of arguments... * * @param 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 $extraOptions array of options that specify conversion details. valid options 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 unspecified, 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 Response 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 + * @param array $extraOptions array of options that specify conversion details. Valid options 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, when return_source is used. If unspecified, lib will pick an appropriate name + * - string return_source if true return php code w. function definition instead of function itself (closure) + * - 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 Response 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 + * - int simple_client_copy set it to 1 to have a lightweight copy of the $client object made in the generated code (only used when return_source = true) * - * @return string the name of the generated php function (or false) - OR AN ARRAY... + * @return \closure|array|false false on failure, closure by default and array for return_source = true */ - public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $timeout = 0, $protocol = '', $newFuncName = '') + public function wrap_xmlrpc_method($client, $methodName, $extraOptions = array()) { - // mind numbing: let caller use sane calling convention (as per javadoc, 3 params), - // OR the 2.0 calling convention (no options) - we really love backward compat, don't we? - if (!is_array($extraOptions)) { - $sigNum = $extraOptions; - $extraOptions = array(); - } else { - $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; - $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; - $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; - $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; - } - //$encodePhpObjects = in_array('encode_php_objects', $extraOptions); - //$verbatimClientCopy = in_array('simple_client_copy', $extraOptions) ? 1 : - // in_array('build_class_code', $extraOptions) ? 2 : 0; + $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; - $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; - $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; - // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on... - $simpleClientCopy = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; - $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; - $namespace = '\\PhpXmlRpc\\'; - if (isset($extraOptions['return_on_fault'])) { - $decodeFault = true; - $faultResponse = $extraOptions['return_on_fault']; + + $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions); + if (!$mSig) { + return false; + } + + if ($buildIt) { + return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig); } else { - $decodeFault = false; - $faultResponse = ''; + // if in 'offline' mode, retrieve method description too. + // in online mode, favour speed of operation + $mDesc = $this->retrieveMethodHelp($client, $methodName, $extraOptions); + + $newFuncName = $this->newFunctionName($methodName, $newFuncName, $extraOptions); + + $results = $this->buildWrapMethodSource($client, $methodName, $extraOptions, $newFuncName, $mSig, $mDesc); + /* was: $results = $this->build_remote_method_wrapper_code($client, $methodName, + $newFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy, + $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, + $faultResponse, $namespace);*/ + + $results['function'] = $newFuncName; + + return $results; } - $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; + } + + /** + * Retrieves an xmlrpc method signature from a server which supports system.methodSignature + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @return false|array + */ + protected function retrieveMethodSignature($client, $methodName, array $extraOptions = array()) + { + $namespace = '\\PhpXmlRpc\\'; $reqClass = $namespace . 'Request'; $valClass = $namespace . 'Value'; $decoderClass = $namespace . 'Encoder'; + $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; + $req = new $reqClass('system.methodSignature'); $req->addparam(new $valClass($methodName)); $client->setDebug($debug); $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName); + return false; + } + $mSig = $response->value(); + if ($client->return_type != 'phpvals') { + $decoder = new $decoderClass(); + $mSig = $decoder->decode($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 { - $mSig = $response->value(); + } + + return $mSig[$sigNum]; + } + + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @return string in case of any error, an empty string is returned, no warnings generated + */ + protected function retrieveMethodHelp($client, $methodName, array $extraOptions = array()) + { + $namespace = '\\PhpXmlRpc\\'; + $reqClass = $namespace . 'Request'; + $valClass = $namespace . 'Value'; + + $debug = isset($extraOptions['debug']) ? ($extraOptions['debug']) : 0; + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + + $mDesc = ''; + + $req = new $reqClass('system.methodHelp'); + $req->addparam(new $valClass($methodName)); + $client->setDebug($debug); + $response = $client->send($req, $timeout, $protocol); + if (!$response->faultCode()) { + $mDesc = $response->value(); if ($client->return_type != 'phpvals') { - $decoder = new $decoderClass(); - $mSig = $decoder->decode($mSig); + $mDesc = $mDesc->scalarval(); } - 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; + return $mDesc; + } + + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @param string $mSig + * @return callable + */ + protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig) + { + // we clone the client, so that we can modify it a bit independently of the original + $clientClone = clone $client; + $function = function() use($clientClone, $methodName, $extraOptions, $mSig) + { + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + if (isset($extraOptions['return_on_fault'])) { + $decodeFault = true; + $faultResponse = $extraOptions['return_on_fault']; } 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); + $decodeFault = false; + } + + $namespace = '\\PhpXmlRpc\\'; + $reqClass = $namespace . 'Request'; + $encoderClass = $namespace . 'Encoder'; + $valueClass = $namespace . 'Value'; + + $encoder = new $encoderClass(); + $encodeOptions = array(); + if ($encodePhpObjects) { + $encodeOptions[] = 'encode_php_objs'; + } + $decodeOptions = array(); + if ($decodePhpObjects) { + $decodeOptions[] = 'decode_php_objs'; + } + + /// @todo check for insufficient nr. of args besides excess ones + + // support one extra parameter: debug + $maxArgs = count($mSig)-1; // 1st element is the return type + $currentArgs = func_get_args(); + if (func_num_args() == ($maxArgs+1)) { + $debug = array_pop($currentArgs); + $clientClone->setDebug($debug); + } + + $xmlrpcArgs = array(); + foreach($currentArgs as $i => $arg) { + if ($i == $maxArgs) { + /// @todo log warning? check what happens with the 'source' version + break; } - while ($buildIt && function_exists($xmlrpcFuncName)) { - $xmlrpcFuncName .= 'x'; + $pType = $mSig[$i+1]; + if ($pType == 'i4' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' || + $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null' + ) { + // by building directly xmlrpc values when type is known and scalar (instead of encode() calls), + // we make sure to honour the xmlrpc signature + $xmlrpcArgs[] = new $valueClass($arg, $pType); + } else { + $xmlrpcArgs[] = $encoder->encode($arg, $encodeOptions); } + } - $mSig = $mSig[$sigNum]; - $mDesc = ''; - // if in 'offline' mode, get method description too. - // in online mode, favour speed of operation - if (!$buildIt) { - $req = new $reqClass('system.methodHelp'); - $req->addparam(new $valClass($methodName)); - $response = $client->send($req, $timeout, $protocol); - if (!$response->faultCode()) { - $mDesc = $response->value(); - if ($client->return_type != 'phpvals') { - $mDesc = $mDesc->scalarval(); - } + $req = new $reqClass($methodName, $xmlrpcArgs); + // use this to get the maximum decoding flexibility + $clientClone->return_type = 'xmlrpcvals'; + $resp = $clientClone->send($req, $timeout, $protocol); + if ($resp->faultcode()) { + if ($decodeFault) { + if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || + (strpos($faultResponse, '%faultString%') !== false))) { + $faultResponse = str_replace(array('%faultCode%', '%faultString%'), + array($resp->faultCode(), $resp->faultString()), $faultResponse); } + return $faultResponse; + } else { + return $resp; } + } else { + return $encoder->decode($resp->value(), $decodeOptions); + } + }; - $results = $this->build_remote_method_wrapper_code($client, $methodName, - $xmlrpcFuncName, $mSig, $mDesc, $timeout, $protocol, $simpleClientCopy, - $prefix, $decodePhpObjects, $encodePhpObjects, $decodeFault, - $faultResponse, $namespace); + return $function; + } - 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); + protected function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') + { + $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; + $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; + $encodePhpObjects = isset($extraOptions['encode_php_objs']) ? (bool)$extraOptions['encode_php_objs'] : false; + $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; + $clientCopyMode = isset($extraOptions['simple_client_copy']) ? (int)($extraOptions['simple_client_copy']) : 0; + $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : 'xmlrpc'; + if (isset($extraOptions['return_on_fault'])) { + $decodeFault = true; + $faultResponse = $extraOptions['return_on_fault']; + } else { + $decodeFault = false; + $faultResponse = ''; + } - return false; - } - } else { - $results['function'] = $xmlrpcFuncName; + $namespace = '\\PhpXmlRpc\\'; - return $results; + $code = "function $newFuncName ("; + if ($clientCopyMode < 2) { + // client copy mode 0 or 1 == full / partial client copy in emitted code + $verbatimClientCopy = !$clientCopyMode; + $innerCode = $this->build_client_wrapper_code($client, $verbatimClientCopy, $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 $newFuncName\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 == '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 ' . $this->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 ' . $this->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); } /** @@ -790,26 +955,22 @@ public function wrap_xmlrpc_method($client, $methodName, $extraOptions = 0, $tim * all xmlrpc methods exposed by the remote server as own methods. * For more details see wrap_xmlrpc_method. * - * NB: for a slimmer alternative, see the code in demo/client/proxy.php + * For a slimmer alternative, see the code in demo/client/proxy.php + * + * Note that unlike wrap_xmlrpc_method, we always have to generate php code here. It seems that php 7 will have anon classes... * * @param Client $client the client obj all set to query the desired server - * @param array $extraOptions list of options for wrapped code - * - method_filter - * - timeout - * - protocol - * - new_class_name - * - encode_php_objs - * - decode_php_objs - * - simple_client_copy - * - return_source - * - prefix + * @param array $extraOptions list of options for wrapped code. See the ones from wrap_xmlrpc_method plus + * - string method_filter + * - string new_class_name + * - string prefix + * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class * * @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) */ public function wrap_xmlrpc_server($client, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; - //$sigNum = isset($extraOptions['signum']) ? (int)$extraOptions['signum'] : 0; $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; $newClassName = isset($extraOptions['new_class_name']) ? $extraOptions['new_class_name'] : ''; @@ -821,7 +982,6 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) $namespace = '\\PhpXmlRpc\\'; $reqClass = $namespace . 'Request'; - //$valClass = $prefix.'val'; $decoderClass = $namespace . 'Encoder'; $req = new $reqClass('system.listMethods'); @@ -853,14 +1013,18 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) } /// @todo add function setdebug() to new class, to enable/disable debugging - $source = "class $xmlrpcClassName\n{\nvar \$client;\n\n"; + $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n"; $source .= "function __construct()\n{\n"; $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); $source .= "\$this->client = \$client;\n}\n\n"; - $opts = array('simple_client_copy' => 2, 'return_source' => true, - 'timeout' => $timeout, 'protocol' => $protocol, - 'encode_php_objs' => $encodePhpObjects, 'prefix' => $prefix, + $opts = array( + 'return_source' => true, + 'simple_client_copy' => 2, // do not produce code to copy the client object + 'timeout' => $timeout, + 'protocol' => $protocol, + 'encode_php_objs' => $encodePhpObjects, 'decode_php_objs' => $decodePhpObjects, + 'prefix' => $prefix, ); /// @todo build phpdoc for class definition, too foreach ($mList as $mName) { @@ -883,13 +1047,10 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) 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 { @@ -900,94 +1061,12 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) } /** - * 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... - */ - public 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 = $this->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 == '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 ' . $this->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 ' . $this->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); - } - - /** - * Given necessary info, generate php code that will rebuild a client object + * Given necessary info, generate php code that will build a client object just like the given one. * Take care that no full checking of input parameters is done to ensure that * valid php code is emitted. * @param Client $client - * @param bool $verbatimClientCopy - * @param string $prefix + * @param bool $verbatimClientCopy when true, copy all of the state of the client, except for 'debug' and 'return_type' + * @param string $prefix used for the return_type of the created client * @param string $namespace * * @return string From 4a96cc50a093dca5e40b78531b1efa8fa5ee7852 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 19:29:03 +0100 Subject: [PATCH 182/228] Fix one signature of proxy method in proxy.php demo file --- demo/server/proxy.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/server/proxy.php b/demo/server/proxy.php index adf80041..fa74d3a7 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -80,7 +80,7 @@ function forward_request($req) 'function' => 'forward_request', 'signature' => array( array('mixed', 'string', 'string', 'array'), - array('mixed', 'string', 'string', 'array', 'stuct'), + 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', ), From a5da33dc74d339b73996a566fefd59336d44b295 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 19:57:34 +0100 Subject: [PATCH 183/228] Remove usage of one global var in favor of static class var --- src/Wrapper.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Wrapper.php b/src/Wrapper.php index 2c0d1f78..6529950c 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -18,6 +18,9 @@ */ class Wrapper { + /// used to hold a reference to object instances whose methods get wrapped by wrap_php_function(), in 'create source' mode + public static $objHolder = array(); + /** * Given a string defining a php type or phpxmlrpc type (loosely defined: strings * accepted come from javadoc blocks), return corresponding phpxmlrpc type. @@ -541,10 +544,10 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption $innerCode .= "\$np = false;\n"; // since we are building source code for later use, if we are given an object instance, - // we go out of our way and store a pointer to it in a global var... + // we go out of our way and store a pointer to it in a static class var var... if (is_array($callable) && is_object($callable[0])) { - $GLOBALS['xmlrpcWPFObjHolder'][$newFuncName] = &$callable[0]; - $innerCode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$newFuncName'];\n"; + self::$objHolder[$newFuncName] = $callable[0]; + $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n"; $realFuncName = '$obj->' . $callable[1]; } else { $realFuncName = $plainFuncName; @@ -777,6 +780,8 @@ protected function retrieveMethodHelp($client, $methodName, array $extraOptions * @param array $extraOptions * @param string $mSig * @return callable + * + * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case? */ protected function buildWrapMethodClosure($client, $methodName, array $extraOptions, $mSig) { From 58c58d4953465ea14af366ddc2afc8d901715461 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 19:58:45 +0100 Subject: [PATCH 184/228] Add one more test for wrap_method; add some comments to tests files; mark http tests skipped when skipped instead of failed --- tests/1ParsingBugsTest.php | 3 +++ tests/2InvalidHostTest.php | 3 +++ tests/3LocalhostTest.php | 28 +++++++++++++++++++++++++--- tests/4LocalhostMultiTest.php | 28 ++++++++++++++++------------ tests/5DemofilesTest.php | 3 +++ tests/7ExtraTest.php | 4 +++- 6 files changed, 53 insertions(+), 16 deletions(-) diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 06fb36ac..8ed214bd 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -5,6 +5,9 @@ include_once __DIR__ . '/../lib/xmlrpc.inc'; include_once __DIR__ . '/../lib/xmlrpcs.inc'; +/** + * Tests involving parsing of xml and handling of xmlrpc values + */ class ParsingBugsTests extends PHPUnit_Framework_TestCase { public $args = array(); diff --git a/tests/2InvalidHostTest.php b/tests/2InvalidHostTest.php index 0168c91e..7e0062cc 100644 --- a/tests/2InvalidHostTest.php +++ b/tests/2InvalidHostTest.php @@ -4,6 +4,9 @@ include_once __DIR__ . '/parse_args.php'; +/** + * Tests involving requests sent to non-existing servers + */ class InvalidHostTest extends PHPUnit_Framework_TestCase { /** @var xmlrpc_client $client */ diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index be17d69a..e205c9e8 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -5,6 +5,10 @@ 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 */ @@ -651,8 +655,8 @@ public function testAutoRegisteredClass() 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' => 1)); - if ($func == '') { + $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); @@ -664,10 +668,28 @@ public function testWrappedMethod() } } + 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 version of phpunit + 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 - $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 1)); + $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 0)); if ($class == '') { $this->fail('Registration of remote server failed'); } else { diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 5ef6a3cf..9243514b 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -7,6 +7,10 @@ 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 { /** @@ -34,7 +38,7 @@ function testDeflate() { if(!function_exists('gzdeflate')) { - $this->fail('Zlib missing: cannot test deflate functionality'); + $this->markTestSkipped('Zlib missing: cannot test deflate functionality'); return; } $this->client->accepted_compression = array('deflate'); @@ -46,7 +50,7 @@ function testGzip() { if(!function_exists('gzdeflate')) { - $this->fail('Zlib missing: cannot test gzip functionality'); + $this->markTestSkipped('Zlib missing: cannot test gzip functionality'); return; } $this->client->accepted_compression = array('gzip'); @@ -58,7 +62,7 @@ function testKeepAlives() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test http 1.1'); + $this->markTestSkipped('CURL missing: cannot test http 1.1'); return; } $this->method = 'http11'; @@ -74,14 +78,14 @@ function testProxy() $this->_runtests(); } else - $this->fail('PROXY definition missing: cannot test proxy'); + $this->markTestSkipped('PROXY definition missing: cannot test proxy'); } function testHttp11() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test http 1.1'); + $this->markTestSkipped('CURL missing: cannot test http 1.1'); return; } $this->method = 'http11'; // not an error the double assignment! @@ -96,7 +100,7 @@ function testHttp11Gzip() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test http 1.1'); + $this->markTestSkipped('CURL missing: cannot test http 1.1'); return; } $this->method = 'http11'; // not an error the double assignment! @@ -111,7 +115,7 @@ function testHttp11Deflate() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test http 1.1'); + $this->markTestSkipped('CURL missing: cannot test http 1.1'); return; } $this->method = 'http11'; // not an error the double assignment! @@ -126,12 +130,12 @@ function testHttp11Proxy() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test http 1.1 w. proxy'); + $this->markTestSkipped('CURL missing: cannot test http 1.1 w. proxy'); return; } else if ($this->args['PROXYSERVER'] == '') { - $this->fail('PROXY definition missing: cannot test proxy w. http 1.1'); + $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1'); return; } $this->method = 'http11'; // not an error the double assignment! @@ -147,7 +151,7 @@ function testHttps() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test https functionality'); + $this->markTestSkipped('CURL missing: cannot test https functionality'); return; } $this->client->server = $this->args['HTTPSSERVER']; @@ -164,12 +168,12 @@ function testHttpsProxy() { if(!function_exists('curl_init')) { - $this->fail('CURL missing: cannot test https functionality'); + $this->markTestSkipped('CURL missing: cannot test https functionality'); return; } else if ($this->args['PROXYSERVER'] == '') { - $this->fail('PROXY definition missing: cannot test proxy w. http 1.1'); + $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1'); return; } $this->client->server = $this->args['HTTPSSERVER']; diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php index 01ed6214..3cbb5b44 100644 --- a/tests/5DemofilesTest.php +++ b/tests/5DemofilesTest.php @@ -2,6 +2,9 @@ include_once __DIR__ . '/LocalFileTestCase.php'; +/** + * Tests for php files in the 'demo' directory + */ class DemoFilesTest extends PhpXmlRpc_LocalFileTestCase { public function setUp() diff --git a/tests/7ExtraTest.php b/tests/7ExtraTest.php index ff2d056d..14488e8f 100644 --- a/tests/7ExtraTest.php +++ b/tests/7ExtraTest.php @@ -2,9 +2,11 @@ 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(); From 4a8e6a7b0c0dccbfc8ed6404139b8012063062e5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 20:41:11 +0100 Subject: [PATCH 185/228] remove last global variable from the codebase --- src/Server.php | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/Server.php b/src/Server.php index 8a2f5117..fdcd6200 100644 --- a/src/Server.php +++ b/src/Server.php @@ -75,7 +75,7 @@ class Server protected static $_xmlrpc_debuginfo = ''; protected static $_xmlrpcs_occurred_errors = ''; - public static $_xmlrpcs_prev_ehandler = ''; + protected static $_xmlrpcs_prev_ehandler = ''; /** * @param array $dispatchMap the dispatch map with definition of exposed services @@ -615,7 +615,7 @@ protected function execute($req, $params = null, $paramTypes = null) // If debug level is 3, we should catch all errors generated during // processing of user function, and log them as part of response if ($this->debug > 2) { - $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')); + self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')); } try { // Allow mixed-convention servers @@ -683,8 +683,8 @@ protected function execute($req, $params = null, $paramTypes = null) if ($this->debug > 2) { // note: restore the error handler we found before calling the // user func, even if it has been changed inside the func itself - if ($GLOBALS['_xmlrpcs_prev_ehandler']) { - set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); + if (self::$_xmlrpcs_prev_ehandler) { + set_error_handler(self::$_xmlrpcs_prev_ehandler); } else { restore_error_handler(); } @@ -1005,7 +1005,7 @@ public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = n } // Try to avoid as much as possible disruption to the previous error handling // mechanism in place - if ($GLOBALS['_xmlrpcs_prev_ehandler'] == '') { + if (self::$_xmlrpcs_prev_ehandler == '') { // The previous error handler was the default: all we should do is log error // to the default error log (if level high enough) if (ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errCode)) { @@ -1013,12 +1013,13 @@ public static function _xmlrpcs_errorHandler($errCode, $errString, $filename = n } } else { // Pass control on to previous error handler, trying to avoid loops... - if ($GLOBALS['_xmlrpcs_prev_ehandler'] != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) { - if (is_array($GLOBALS['_xmlrpcs_prev_ehandler'])) { + if (self::$_xmlrpcs_prev_ehandler != array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')) { + if (is_array(self::$_xmlrpcs_prev_ehandler)) { // the following works both with static class methods and plain object methods as error handler - call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errCode, $errString, $filename, $lineNo, $context)); + call_user_func_array(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context)); } else { - $GLOBALS['_xmlrpcs_prev_ehandler']($errCode, $errString, $filename, $lineNo, $context); + $method = self::$_xmlrpcs_prev_ehandler; + $method($errCode, $errString, $filename, $lineNo, $context); } } } From fad2b474319b54adea5d1b16c135b7fde389c8dc Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 21:13:49 +0100 Subject: [PATCH 186/228] Fix buildWrapFunctionSource which had been forgotten when moving analyzed phpdoc params to named instead of positional --- src/Wrapper.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Wrapper.php b/src/Wrapper.php index 6529950c..4b70dc18 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -308,8 +308,8 @@ protected function introspectFunction($callable, $plainFuncName) return array( 'desc' => $desc, 'docs' => $docs, - 'params' => $params, - 'paramDocs' => $paramDocs, + 'params' => $params, // array, positionally indexed + 'paramDocs' => $paramDocs, // array, indexed by name 'returns' => $returns, 'returnsDocs' =>$returnsDocs, ); @@ -496,11 +496,11 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption $pars = array(); $pNum = count($funcDesc['params']); foreach ($funcDesc['params'] as $param) { - if (isset($funcDesc['paramDocs'][$i]['name']) && $funcDesc['paramDocs'][$i]['name'] && - strtolower($funcDesc['paramDocs'][$i]['name']) != strtolower($param['name'])) { - // param name from phpdoc info does not match param definition! - $funcDesc['paramDocs'][$i]['type'] = 'mixed'; - } + /*$name = strtolower($funcDesc['params'][$i]['name']); + if (!isset($funcDesc['paramDocs'][$name])) { + // no param found in phpdoc info matching param definition! + $funcDesc['paramDocs'][$name]['type'] = 'mixed'; + }*/ if ($param['isoptional']) { // this particular parameter is optional. save as valid previous list of parameters From 2503e40912ae30a40c339127519846c2f66bbd4a Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 21:14:27 +0100 Subject: [PATCH 187/228] Add a test for wrapping closures --- demo/server/server.php | 11 ++++------- tests/3LocalhostTest.php | 21 +++++++++++++++------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index 775b077c..6f0a4309 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -132,11 +132,6 @@ function inner_findstate($stateNo) } } -$findStateClosure = function ($req) -{ - return findState($req); -}; - $wrapper = new PhpXmlRpc\Wrapper(); $findstate2_sig = $wrapper->wrap_php_function('inner_findstate'); @@ -163,11 +158,13 @@ function inner_findstate($stateNo) eval($findstate9_sig['source']); $findstate10_sig = array( - "function" => $findStateClosure, + "function" => function ($req) { return findState($req); }, "signature" => $findstate_sig, "docstring" => $findstate_doc, ); +$findstate11_sig = $wrapper->wrap_php_function(function ($stateNo) { return inner_findstate($stateNo); }); + $c = new xmlrpcServerMethodsContainer; $moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); @@ -893,7 +890,7 @@ function i_whichToolkit($req) 'tests.getStateName.8' => $findstate8_sig, 'tests.getStateName.9' => $findstate9_sig, 'tests.getStateName.10' => $findstate10_sig, - + 'tests.getStateName.11' => $findstate11_sig, ); $signatures = array_merge($signatures, $moreSignatures); diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index e205c9e8..f559fa6f 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -556,7 +556,7 @@ public function testCodeInjectionServerSide() } } - public function testAutoRegisteredFunction() + public function testServerWrappedFunction() { $f = new xmlrpcmsg('tests.getStateName.2', array( new xmlrpcval(23, 'int'), @@ -565,7 +565,7 @@ public function testAutoRegisteredFunction() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredFunction2() + public function testServerWrappedFunctionAsSource() { $f = new xmlrpcmsg('tests.getStateName.6', array( new xmlrpcval(23, 'int'), @@ -574,7 +574,7 @@ public function testAutoRegisteredFunction2() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredMethods() + public function testServerWrappedObjectMethods() { $f = new xmlrpcmsg('tests.getStateName.3', array( new xmlrpcval(23, 'int'), @@ -613,7 +613,7 @@ public function testAutoRegisteredMethods() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredMethods2() + public function testServerWrappedObjectMethodsAsSource() { $f = new xmlrpcmsg('tests.getStateName.7', array( new xmlrpcval(23, 'int'), @@ -634,7 +634,7 @@ public function testAutoRegisteredMethods2() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredClosure() + public function testServerClosure() { $f = new xmlrpcmsg('tests.getStateName.10', array( new xmlrpcval(23, 'int'), @@ -643,7 +643,16 @@ public function testAutoRegisteredClosure() $this->assertEquals('Michigan', $v->scalarval()); } - public function testAutoRegisteredClass() + public function testServerWrappedClosure() + { + $f = new xmlrpcmsg('tests.getStateName.11', array( + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + $this->assertEquals('Michigan', $v->scalarval()); + } + + public function testServerWrappedClass() { $f = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array( new xmlrpcval(23, 'int'), From 2563dc16dca36ef97c14503a98dd79725d10f755 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 21:40:54 +0100 Subject: [PATCH 188/228] test exceptions thrown in wrapped code; make testsuite faster by not wrapping the whole server --- demo/server/server.php | 16 ++++++++++------ src/Wrapper.php | 2 +- tests/3LocalhostTest.php | 17 +++++++++++++++-- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index 6f0a4309..38804280 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -53,10 +53,12 @@ public function exceptionGenerator($req) } /** - * A PHP version of the state-number server. Send me an integer and i'll sell you a state - * @param integer $num - * @return string - */ + * A PHP version of the state-number server. Send me an integer and i'll sell you a state. + * + * @param integer $num + * @return string + * @throws Exception + */ public static function findState($num) { return inner_findstate($num); @@ -114,11 +116,13 @@ function findState($req) /** * Inner code of the state-number server. - * Used to test auto-registration of PHP functions as xmlrpc methods. + * 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) { @@ -128,7 +132,7 @@ function inner_findstate($stateNo) return $stateNames[$stateNo - 1]; } else { // not, there so complain - return "I don't have a state for the index '" . $stateNo . "'"; + throw new Exception("I don't have a state for the index '" . $stateNo . "'", PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser); } } diff --git a/src/Wrapper.php b/src/Wrapper.php index 4b70dc18..f94f807a 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -966,7 +966,7 @@ protected function buildWrapMethodSource($client, $methodName, array $extraOptio * * @param Client $client the client obj all set to query the desired server * @param array $extraOptions list of options for wrapped code. See the ones from wrap_xmlrpc_method plus - * - string method_filter + * - string method_filter regular expression * - string new_class_name * - string prefix * - bool simple_client_copy set it to true to avoid copying all properties of $client into the copy made in the new class diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index f559fa6f..3675d9d2 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -533,7 +533,7 @@ public function testCatchExceptions() )); $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1'; - $v = $this->send($f, 1); + $v = $this->send($f, 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... @@ -563,6 +563,12 @@ public function testServerWrappedFunction() )); $v = $this->send($f); $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 + $f = new xmlrpcmsg('tests.getStateName.2', array( + new xmlrpcval(0, 'int'), + )); + $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); } public function testServerWrappedFunctionAsSource() @@ -572,6 +578,12 @@ public function testServerWrappedFunctionAsSource() )); $v = $this->send($f); $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 + $f = new xmlrpcmsg('tests.getStateName.6', array( + new xmlrpcval(0, 'int'), + )); + $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); } public function testServerWrappedObjectMethods() @@ -698,7 +710,8 @@ public function testWrappedMethodAsSource() public function testWrappedClass() { // make a 'deep client copy' as the original one might have many properties set - $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 0)); + // 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 { From f4a5a664335b25312e1632536ef5c3f0ea8f71af Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 23:13:31 +0100 Subject: [PATCH 189/228] Do not generate invalid php code when wrapping a closure in generate-code mode --- src/Wrapper.php | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/Wrapper.php b/src/Wrapper.php index f94f807a..c2643a75 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -156,7 +156,7 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = } if (is_array($callable)) { if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) { - error_log('XML-RPC: syntax for function to be wrapped is wrong'); + error_log('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong'); return false; } if (is_string($callable[0])) { @@ -166,6 +166,12 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = } $exists = method_exists($callable[0], $callable[1]); } else if ($callable instanceof \Closure) { + // we do not support creating code which wraps closures, as php does not allow to serialize them + if (!$buildIt) { + error_log('XML-RPC: ' . __METHOD__ . ': a closure can not be wrapped in generated source code'); + return false; + } + $plainFuncName = 'Closure'; $exists = true; } @@ -175,7 +181,7 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = } if (!$exists) { - error_log('XML-RPC: function to be wrapped is not defined: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is not defined: ' . $plainFuncName); return false; } @@ -222,23 +228,23 @@ protected function introspectFunction($callable, $plainFuncName) if (is_array($callable)) { $func = new \ReflectionMethod($callable[0], $callable[1]); if ($func->isPrivate()) { - error_log('XML-RPC: method to be wrapped is private: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is private: ' . $plainFuncName); return false; } if ($func->isProtected()) { - error_log('XML-RPC: method to be wrapped is protected: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName); return false; } if ($func->isConstructor()) { - error_log('XML-RPC: method to be wrapped is the constructor: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName); return false; } if ($func->isDestructor()) { - error_log('XML-RPC: method to be wrapped is the destructor: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName); return false; } if ($func->isAbstract()) { - error_log('XML-RPC: method to be wrapped is abstract: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is abstract: ' . $plainFuncName); return false; } /// @todo add more checks for static vs. nonstatic? @@ -248,7 +254,7 @@ protected function introspectFunction($callable, $plainFuncName) 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: ' . $plainFuncName); + error_log('XML-RPC: ' . __METHOD__ . ': function to be wrapped is internal: ' . $plainFuncName); return false; } @@ -724,7 +730,7 @@ protected function retrieveMethodSignature($client, $methodName, array $extraOpt $client->setDebug($debug); $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { - error_log('XML-RPC: could not retrieve method signature from remote server for method ' . $methodName); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature from remote server for method ' . $methodName); return false; } @@ -735,7 +741,7 @@ protected function retrieveMethodSignature($client, $methodName, array $extraOpt } if (!is_array($mSig) || count($mSig) <= $sigNum) { - error_log('XML-RPC: could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName); return false; } @@ -992,7 +998,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) $req = new $reqClass('system.listMethods'); $response = $client->send($req, $timeout, $protocol); if ($response->faultCode()) { - error_log('XML-RPC: could not retrieve method list from remote server'); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server'); return false; } else { @@ -1002,7 +1008,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) $mList = $decoder->decode($mList); } if (!is_array($mList) || !count($mList)) { - error_log('XML-RPC: could not retrieve meaningful method list from remote server'); + error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve meaningful method list from remote server'); return false; } else { @@ -1044,7 +1050,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) } $source .= $methodWrap['source'] . "\n"; } else { - error_log('XML-RPC: will not create class method to wrap remote method ' . $mName); + error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName); } } } @@ -1055,7 +1061,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) if ($allOK) { return $xmlrpcClassName; } else { - error_log('XML-RPC: could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server); + error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server); return false; } } else { From cba9de39a4637376d5e06e2a909d0904f443868d Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 23 May 2015 23:13:56 +0100 Subject: [PATCH 190/228] Make sure all error messages have the method name --- src/Helper/Charset.php | 2 +- src/Helper/XMLParser.php | 12 ++++++------ src/Server.php | 1 - 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php index a4064d89..9000ffb3 100644 --- a/src/Helper/Charset.php +++ b/src/Helper/Charset.php @@ -203,7 +203,7 @@ public function encodeEntities($data, $srcEncoding = '', $destEncoding = '') */ default: $escapedData = ''; - error_log("Converting from $srcEncoding to $destEncoding: not supported..."); + error_log('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported..."); } return $escapedData; diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index 58acdafb..d8790c5e 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -271,7 +271,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) $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: invalid value received in DATETIME: ' . $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']; @@ -290,7 +290,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = 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: invalid value received in BOOLEAN: ' . $this->_xh['ac']); + error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']); } $this->_xh['value'] = false; } @@ -300,7 +300,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) // 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: non numeric value received in DOUBLE: ' . $this->_xh['ac']); + 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 @@ -311,7 +311,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) // we must check that only 0123456789- 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: non numeric value received in INT: ' . $this->_xh['ac']); + 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 @@ -332,7 +332,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) $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: missing VALUE inside STRUCT in received xml'); + error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml'); } break; case 'DATA': @@ -356,7 +356,7 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) $this->_xh['params'][] = $this->_xh['value']; $this->_xh['pt'][] = $this->_xh['vt']; } else { - error_log('XML-RPC: missing VALUE inside PARAM in received xml'); + error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml'); } break; case 'METHODNAME': diff --git a/src/Server.php b/src/Server.php index fdcd6200..9f74412d 100644 --- a/src/Server.php +++ b/src/Server.php @@ -390,7 +390,6 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ return $r; } } else { - //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.'); $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$xmlrpcstr['server_cannot_decompress']); return $r; From 68237fa2303e889db0f0fbdf1e9fff75a0512e08 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 24 May 2015 00:33:52 +0100 Subject: [PATCH 191/228] Simplify code generated by wrap_php_function; make sure its closure version is identical wrt the nr. of parameters received --- src/Wrapper.php | 73 +++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/src/Wrapper.php b/src/Wrapper.php index c2643a75..02ced671 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -146,6 +146,7 @@ public function xmlrpc_2_php_type($xmlrpcType) * @todo what to do when the PHP function returns NULL? We are currently returning an empty string value... * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3? * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance? + * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway */ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array()) { @@ -193,15 +194,12 @@ public function wrap_php_function($callable, $newFuncName = '', $extraOptions = $funcSigs = $this->buildMethodSignatures($funcDesc); if ($buildIt) { - $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, null, null); + $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc); } else { $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions); $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc); } - /// @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' => $callable, 'signature' => $funcSigs['sigs'], @@ -410,6 +408,22 @@ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFunc $responseClass = $nameSpace.'Response'; $valueClass = $nameSpace.'Value'; + // validate number of parameters received + // this should be optional really, as we assume the server does the validation + $minPars = count($funcDesc['params']); + $maxPars = $minPars; + foreach ($funcDesc['params'] as $i => $param) { + if ($param['isoptional']) { + // this particular parameter is optional. We assume later ones are as well + $minPars = $i; + break; + } + } + $numPars = $req->getNumParams(); + if ($numPars < $minPars || $numPars > $maxPars) { + return new $responseClass(0, 3, 'Incorrect parameters passed to method'); + } + $encoder = new $encoderClass(); $options = array(); if (isset($extraOptions['decode_php_objs']) && $extraOptions['decode_php_objs']) { @@ -485,6 +499,8 @@ protected function newFunctionName($callable, $newFuncName, $extraOptions) * @param string $plainFuncName * @param array $funcDesc * @return array + * + * @todo add a nice phpdoc block in the generated source */ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc) { @@ -494,37 +510,19 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption $decodePhpObjects = isset($extraOptions['decode_php_objs']) ? (bool)$extraOptions['decode_php_objs'] : false; $catchWarnings = isset($extraOptions['suppress_warnings']) && $extraOptions['suppress_warnings'] ? '@' : ''; - // build body of new function - - $innerCode = "\$encoder = new {$namespace}Encoder();\n"; $i = 0; $parsVariations = array(); $pars = array(); $pNum = count($funcDesc['params']); foreach ($funcDesc['params'] as $param) { - /*$name = strtolower($funcDesc['params'][$i]['name']); - if (!isset($funcDesc['paramDocs'][$name])) { - // no param found in phpdoc info matching param definition! - $funcDesc['paramDocs'][$name]['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 = \$req->getParam($i);\n"; - if ($decodePhpObjects) { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i, array('decode_php_objs'));\n"; - } else { - $innerCode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = \$encoder->decode(\$p$i);\n"; - } - $pars[] = "\$p$i"; + $pars[] = "\$p[$i]"; $i++; - if ($param['isoptional']) { - $innerCode .= "}\n"; - } if ($i == $pNum) { // last allowed parameters combination $parsVariations[] = $pars; @@ -535,20 +533,24 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption // only known good synopsis = no parameters $parsVariations[] = array(); $minPars = 0; + $maxPars = 0; } else { $minPars = count($parsVariations[0]); + $maxPars = count($parsVariations[count($parsVariations)-1]); } - if ($minPars) { - // add to code the check for min params number - // NB: this check needs to be done BEFORE decoding param values - $innerCode = "\$paramcount = \$req->getNumParams();\n" . - "if (\$paramcount < $minPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n" . $innerCode; + // build body of new function + + $innerCode = "\$paramCount = \$req->getNumParams();\n"; + $innerCode .= "if (\$paramCount < $minPars || \$paramCount > $maxPars) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "');\n"; + + $innerCode .= "\$encoder = new {$namespace}Encoder();\n"; + if ($decodePhpObjects) { + $innerCode .= "\$p = \$encoder->decode(\$req, array('decode_php_objs'));\n"; } else { - $innerCode = "\$paramcount = \$req->getNumParams();\n" . $innerCode; + $innerCode .= "\$p = \$encoder->decode(\$req);\n"; } - $innerCode .= "\$np = false;\n"; // since we are building source code for later use, if we are given an object instance, // we go out of our way and store a pointer to it in a static class var var... if (is_array($callable) && is_object($callable[0])) { @@ -558,12 +560,11 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption } else { $realFuncName = $plainFuncName; } - foreach ($parsVariations as $pars) { - $innerCode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . "); else\n"; + foreach ($parsVariations as $i => $pars) { + $innerCode .= "if (\$paramCount == " . count($pars) . ") \$retval = {$catchWarnings}$realFuncName(" . implode(',', $pars) . ");\n"; + if ($i < (count($parsVariations) - 1)) + $innerCode .= "else\n"; } - $innerCode .= "\$np = true;\n"; - $innerCode .= "if (\$np) return new {$namespace}Response(0, " . PhpXmlRpc::$xmlrpcerr['incorrect_params'] . ", '" . PhpXmlRpc::$xmlrpcstr['incorrect_params'] . "'); else {\n"; - //$innerCode .= "if (\$_xmlrpcs_error_occurred) return new Response(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n"; $innerCode .= "if (is_a(\$retval, '{$namespace}Response')) return \$retval; else\n"; if ($funcDesc['returns'] == Value::$xmlrpcDateTime || $funcDesc['returns'] == Value::$xmlrpcBase64) { $innerCode .= "return new {$namespace}Response(new {$namespace}Value(\$retval, '{$funcDesc['returns']}'));"; @@ -578,7 +579,7 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption // if($func->returnsReference()) // return false; - $code = "function $newFuncName(\$req) {\n" . $innerCode . "}\n}"; + $code = "function $newFuncName(\$req) {\n" . $innerCode . "\n}"; return $code; } From be406d63c36f48190a44117158d92cdbc7f72565 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 24 May 2015 00:49:08 +0100 Subject: [PATCH 192/228] Add test for the method signature of wrapped functions --- tests/3LocalhostTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 3675d9d2..ec3ba17c 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -569,6 +569,14 @@ public function testServerWrappedFunction() new xmlrpcval(0, 'int'), )); $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); + + // check if the generated function dispatch map is fine, by checking if the server registered it + $f = new xmlrpcmsg('system.methodSignature', array( + new xmlrpcval('tests.getStateName.2'), + )); + $v = $this->send($f); + $encoder = new \PhpXmlRpc\Encoder(); + $this->assertEquals(array(array('string', 'int')), $encoder->decode($v)); } public function testServerWrappedFunctionAsSource() From a56b8ca18c8f34d2018d6f2099c25b3539804d19 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 24 May 2015 01:59:27 +0100 Subject: [PATCH 193/228] Add one more test for wrapped php functions: preserve php objects in results --- demo/server/server.php | 19 +++++++++++++++++-- tests/3LocalhostTest.php | 33 ++++++++++++++++++++++++--------- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index 38804280..e2e3c6f7 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -54,6 +54,7 @@ public function exceptionGenerator($req) /** * 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 @@ -63,6 +64,17 @@ 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 @@ -172,6 +184,8 @@ function inner_findstate($stateNo) $c = new xmlrpcServerMethodsContainer; $moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); +$returnObj_sig = $wrapper->wrap_php_function(array($c, 'returnObject'), '', array('encode_php_objs' => true)); + $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; function addTwo($req) @@ -326,8 +340,7 @@ function ageSorter($req) } } -// signature and instructions, place these in the dispatch -// map +// 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, @@ -895,6 +908,8 @@ function i_whichToolkit($req) 'tests.getStateName.9' => $findstate9_sig, 'tests.getStateName.10' => $findstate10_sig, 'tests.getStateName.11' => $findstate11_sig, + + 'tests.returnPhpObject' => $returnObj_sig, ); $signatures = array_merge($signatures, $moreSignatures); diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index ec3ba17c..4b721d62 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -689,10 +689,10 @@ public function testWrappedMethod() $this->fail('Registration of examples.getStateName failed'); } else { $v = $func(23); - // work around bug in current version of phpunit - if (is_object($v)) { + // 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); } } @@ -707,10 +707,10 @@ public function testWrappedMethodAsSource() eval($func['source']); $func = $func['function']; $v = $func(23); - // work around bug in current version of phpunit - if (is_object($v)) { + // 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); } } @@ -725,14 +725,29 @@ public function testWrappedClass() } else { $obj = new $class(); $v = $obj->examples_getStateName(23); - // work around bug in current version of phpunit - if (is_object($v)) { + // 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 From 5481456fe553efa3dbdb90c3c05799637b595737 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 25 May 2015 18:42:21 +0100 Subject: [PATCH 194/228] Add a warning to the manual; move more method names to camelCase; fix support for very legacy calling convention in wrap_xmlrpc_method --- demo/client/wrap.php | 2 +- demo/server/server.php | 22 ++++----- demo/vardemo.php | 10 ++-- doc/manual/phpxmlrpc_manual.adoc | 5 +- lib/xmlrpc.inc | 8 ++-- lib/xmlrpc_wrappers.inc | 82 +++++++++++++++++++++++++------- src/Encoder.php | 4 +- src/Helper/Date.php | 4 +- src/Wrapper.php | 55 ++++++++++++--------- 9 files changed, 127 insertions(+), 65 deletions(-) diff --git a/demo/client/wrap.php b/demo/client/wrap.php index 0b3022d9..c13c55d3 100644 --- a/demo/client/wrap.php +++ b/demo/client/wrap.php @@ -29,7 +29,7 @@ foreach ($resp->value() as $methodName) { // $resp->value is an array of strings if ($methodName == 'examples.getStateName') { - $callable = $wrapper->wrap_xmlrpc_method($client, $methodName); + $callable = $wrapper->wrapXmlrpcMethod($client, $methodName); if ($callable) { echo "
    • Remote server method " . htmlspecialchars($methodName) . " wrapped into php function
    • \n"; } else { diff --git a/demo/server/server.php b/demo/server/server.php index e2e3c6f7..1fdd49ba 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -150,27 +150,27 @@ function inner_findstate($stateNo) $wrapper = new PhpXmlRpc\Wrapper(); -$findstate2_sig = $wrapper->wrap_php_function('inner_findstate'); +$findstate2_sig = $wrapper->wrapPhpFunction('inner_findstate'); -$findstate3_sig = $wrapper->wrap_php_function(array('xmlrpcServerMethodsContainer', 'findState')); +$findstate3_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState')); $obj = new xmlrpcServerMethodsContainer(); -$findstate4_sig = $wrapper->wrap_php_function(array($obj, 'findstate')); +$findstate4_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate')); -$findstate5_sig = $wrapper->wrap_php_function('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +$findstate5_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); eval($findstate5_sig['source']); -$findstate6_sig = $wrapper->wrap_php_function('inner_findstate', '', array('return_source' => true)); +$findstate6_sig = $wrapper->wrapPhpFunction('inner_findstate', '', array('return_source' => true)); eval($findstate6_sig['source']); -$findstate7_sig = $wrapper->wrap_php_function(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true)); +$findstate7_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true)); eval($findstate7_sig['source']); $obj = new xmlrpcServerMethodsContainer(); -$findstate8_sig = $wrapper->wrap_php_function(array($obj, 'findstate'), '', array('return_source' => true)); +$findstate8_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'), '', array('return_source' => true)); eval($findstate8_sig['source']); -$findstate9_sig = $wrapper->wrap_php_function('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); +$findstate9_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true)); eval($findstate9_sig['source']); $findstate10_sig = array( @@ -179,12 +179,12 @@ function inner_findstate($stateNo) "docstring" => $findstate_doc, ); -$findstate11_sig = $wrapper->wrap_php_function(function ($stateNo) { return inner_findstate($stateNo); }); +$findstate11_sig = $wrapper->wrapPhpFunction(function ($stateNo) { return inner_findstate($stateNo); }); $c = new xmlrpcServerMethodsContainer; -$moreSignatures = $wrapper->wrap_php_class($c, array('prefix' => 'tests.', 'method_type' => 'all')); +$moreSignatures = $wrapper->wrapPhpClass($c, array('prefix' => 'tests.', 'method_type' => 'all')); -$returnObj_sig = $wrapper->wrap_php_function(array($c, 'returnObject'), '', array('encode_php_objs' => true)); +$returnObj_sig = $wrapper->wrapPhpFunction(array($c, 'returnObject'), '', array('encode_php_objs' => true)); $addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt)); $addtwo_doc = 'Add two integers together and return the result'; diff --git a/demo/vardemo.php b/demo/vardemo.php index d24d04ec..bb697561 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -78,13 +78,13 @@ print "

      Testing ISO date format

      \n";
       
       $t = time();
      -$date = PhpXmlRpc\Helper\Date::iso8601_encode($t);
      +$date = PhpXmlRpc\Helper\Date::iso8601Encode($t);
       print "Now is $t --> $date\n";
      -print "Or in UTC, that is " . PhpXmlRpc\Helper\Date::iso8601_encode($t, 1) . "\n";
      -$tb = PhpXmlRpc\Helper\Date::iso8601_decode($date);
      +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::iso8601_encode($tb) . "\n";
      -print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601_decode($date, 1) . "\n";
      +print "Which comes out at " . PhpXmlRpc\Helper\Date::iso8601Encode($tb) . "\n";
      +print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601Eecode($date, 1) . "\n";
       
       print "
      \n"; diff --git a/doc/manual/phpxmlrpc_manual.adoc b/doc/manual/phpxmlrpc_manual.adoc index 907f00b5..7a8b880f 100644 --- a/doc/manual/phpxmlrpc_manual.adoc +++ b/doc/manual/phpxmlrpc_manual.adoc @@ -1,6 +1,6 @@ = XML-RPC for PHP :revision: 4.0.0 -:keywords: xml, rpc, xmlrpc, webservices, http +:keywords: xmlrpc, ,xml, rpc, webservices, http :toc: left :imagesdir: images :source-highlighter: highlightjs @@ -9,6 +9,9 @@ [preface] == Introduction +NB: THIS MANUAL HAS NOT YET BEEN UPDATED TO REFLECT ALL THE CHANGES WHICH HAVE MADE IN VERSION 4. +DO NOT USE FOR NOW. + XML-RPC is a format devised by link:$$http://www.userland.com/$$[Userland Software] for achieving remote procedure call via XML using HTTP as the transport. XML-RPC has its own web site, link:$$http://www.xmlrpc.com/$$[www.xmlrpc.com] diff --git a/lib/xmlrpc.inc b/lib/xmlrpc.inc index 450e881f..0ae42fd0 100644 --- a/lib/xmlrpc.inc +++ b/lib/xmlrpc.inc @@ -160,12 +160,12 @@ function xmlrpc_encode_entitites($data, $srcEncoding='', $destEncoding='') function iso8601_encode($timeT, $utc=0) { - return PhpXmlRpc\Helper\Date::iso8601_encode($timeT, $utc); + return PhpXmlRpc\Helper\Date::iso8601Encode($timeT, $utc); } function iso8601_decode($iDate, $utc=0) { - return PhpXmlRpc\Helper\Date::iso8601_decode($iDate, $utc); + return PhpXmlRpc\Helper\Date::iso8601Decode($iDate, $utc); } function decode_chunked($buffer) @@ -188,7 +188,7 @@ function php_xmlrpc_encode($phpVal, $options=array()) function php_xmlrpc_decode_xml($xmlVal, $options=array()) { $encoder = new PhpXmlRpc\Encoder(); - return $encoder->decode_xml($xmlVal, $options); + return $encoder->decodeXml($xmlVal, $options); } function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null) @@ -203,5 +203,5 @@ function has_encoding($xmlChunk) function is_valid_charset($encoding, $validList) { - return PhpXmlRpc\Helper\Charset::instance()->is_valid_charset($encoding, $validList); + return PhpXmlRpc\Helper\Charset::instance()->isValidCharset($encoding, $validList); } diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc index fc178dc9..c9e34494 100644 --- a/lib/xmlrpc_wrappers.inc +++ b/lib/xmlrpc_wrappers.inc @@ -12,47 +12,97 @@ 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->php_2_xmlrpc_type($phpType); + 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->xmlrpc_2_php_type($xmlrpcType); + return $wrapper->xmlrpc2PhpType($xmlrpcType); } -/// @todo return string instead of callable +/// @todo backwards compat: return string instead of callable +/** + * @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(); - return $wrapper->wrap_php_function($funcName, $newFuncName, $extraOptions); + return $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions); } -/// @todo return strings instead of callables +/// @todo backwards compat: return strings instead of callables +/** + * @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(); - return $wrapper->wrap_php_class($className, $extraOptions); + return $wrapper->wrapPhpClass($className, $extraOptions); } -/// @todo support different calling convention -/// @todo return string instead of callable +/// @todo backwards compat: return string instead of callable +/** + * @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(); - return $wrapper->wrap_xmlrpc_method($client, $methodName, $extraOptions, $timeout, $protocol, $newFuncName); + return $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions); } -/// @todo return strings instead of callables +/// @todo backwards compat: return strings instead of callables +/** + * @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->wrap_xmlrpc_server($client, $extraOptions); + return $wrapper->wrapXmlrpcServer($client, $extraOptions); } +/// @todo fix dangling usage of $this-> /** * 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. @@ -62,9 +112,9 @@ function wrap_xmlrpc_server($client, $extraOptions=array()) * @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\\') + $mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc', + $decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false, + $faultResponse = '', $namespace = '\\PhpXmlRpc\\') { $code = "function $xmlrpcFuncName ("; if ($clientCopyMode < 2) { @@ -106,14 +156,14 @@ function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, } } $innerCode .= "\$req->addparam(\$p$i);\n"; - $mDesc .= '* @param ' . $this->xmlrpc_2_php_type($pType) . " \$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 ' . $this->xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + $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) { diff --git a/src/Encoder.php b/src/Encoder.php index 21be70f4..7f51cfa9 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -39,7 +39,7 @@ public function decode($xmlrpcVal, $options = array()) case 'dateTime.iso8601': $xmlrpcVal->scalar = $val; $xmlrpcVal->type = 'datetime'; - $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601_decode($val); + $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val); return $xmlrpcVal; case 'base64': @@ -230,7 +230,7 @@ public function encode($phpVal, $options = array()) * * @return mixed false on error, or an instance of either Value, Request or Response */ - public function decode_xml($xmlVal, $options = array()) + public function decodeXml($xmlVal, $options = array()) { // 'guestimate' encoding $valEncoding = XMLParser::guessEncoding('', $xmlVal); diff --git a/src/Helper/Date.php b/src/Helper/Date.php index 8bd79937..f97f52cd 100644 --- a/src/Helper/Date.php +++ b/src/Helper/Date.php @@ -22,7 +22,7 @@ class Date * * @return string */ - public static function iso8601_encode($timet, $utc = 0) + public static function iso8601Encode($timet, $utc = 0) { if (!$utc) { $t = strftime("%Y%m%dT%H:%M:%S", $timet); @@ -47,7 +47,7 @@ public static function iso8601_encode($timet, $utc = 0) * * @return int (datetime) */ - public static function iso8601_decode($idate, $utc = 0) + 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)) { diff --git a/src/Wrapper.php b/src/Wrapper.php index 02ced671..21321a64 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -18,7 +18,7 @@ */ class Wrapper { - /// used to hold a reference to object instances whose methods get wrapped by wrap_php_function(), in 'create source' mode + /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), in 'create source' mode public static $objHolder = array(); /** @@ -34,7 +34,7 @@ class Wrapper * * @return string */ - public function php_2_xmlrpc_type($phpType) + public function php2XmlrpcType($phpType) { switch (strtolower($phpType)) { case 'string': @@ -76,7 +76,7 @@ public function php_2_xmlrpc_type($phpType) * * @return string */ - public function xmlrpc_2_php_type($xmlrpcType) + public function xmlrpc2PhpType($xmlrpcType) { switch (strtolower($xmlrpcType)) { case 'base64': @@ -128,7 +128,7 @@ public function xmlrpc_2_php_type($xmlrpcType) * php functions (ie. functions not expecting a single Request obj as parameter) * is by making use of the functions_parameters_type class member. * - * @param string|array $callable the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too + * @param callable $callable the PHP user function to be exposed as xmlrpc method/ a closure, function name, array($obj, 'methodname') or array('class', 'methodname') are ok * @param string $newFuncName (optional) name for function to be created. Used only when return_source in $extraOptions is true * @param array $extraOptions (optional) array of options for conversion. valid values include: * - bool return_source when true, php code w. function definition will be returned, instead of a closure @@ -148,7 +148,7 @@ public function xmlrpc_2_php_type($xmlrpcType) * @todo add a verbatim_object_copy parameter to allow avoiding usage the same obj instance? * @todo add an option to allow generated function to skip validation of number of parameters, as that is done by the server anyway */ - public function wrap_php_function($callable, $newFuncName = '', $extraOptions = array()) + public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array()) { $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true; @@ -367,12 +367,12 @@ protected function buildMethodSignatures($funcDesc) $sigsDocs = array(); foreach ($parsVariations as $pars) { // build a signature - $sig = array($this->php_2_xmlrpc_type($funcDesc['returns'])); + $sig = array($this->php2XmlrpcType($funcDesc['returns'])); $pSig = array($funcDesc['returnsDocs']); for ($i = 0; $i < count($pars); $i++) { $name = strtolower($funcDesc['params'][$i]['name']); if (isset($funcDesc['paramDocs'][$name]['type'])) { - $sig[] = $this->php_2_xmlrpc_type($funcDesc['paramDocs'][$name]['type']); + $sig[] = $this->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']); } else { $sig[] = Value::$xmlrpcValue; } @@ -589,15 +589,15 @@ protected function buildWrapFunctionSource($callable, $newFuncName, $extraOption * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server * object and called from remote clients (as well as their corresponding signature info). * - * @param mixed $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class - * @param array $extraOptions see the docs for wrap_php_method for basic options, plus + * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class + * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance * - string method_filter a regexp used to filter methods to wrap based on their names * - string prefix used for the names of the xmlrpc methods created * * @return array|false false on failure */ - public function wrap_php_class($className, $extraOptions = array()) + public function wrapPhpClass($className, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; @@ -612,7 +612,7 @@ public function wrap_php_class($className, $extraOptions = array()) if (($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || ($methodType == 'auto' && is_string($className)))) || (!$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || ($methodType == 'auto' && is_object($className)))) ) { - $methodWrap = $this->wrap_php_function(array($className, $mName), '', $extraOptions); + $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions); if ($methodWrap) { if (is_object($className)) { $realClassName = get_class($className); @@ -674,7 +674,7 @@ public function wrap_php_class($className, $extraOptions = array()) * * @return \closure|array|false false on failure, closure by default and array for return_source = true */ - public function wrap_xmlrpc_method($client, $methodName, $extraOptions = array()) + public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array()) { $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : ''; @@ -873,6 +873,15 @@ protected function buildWrapMethodClosure($client, $methodName, array $extraOpti return $function; } + /** + * @param Client $client + * @param string $methodName + * @param array $extraOptions + * @param string $newFuncName + * @param array $mSig + * @param string $mDesc + * @return array + */ protected function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') { $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; @@ -895,7 +904,7 @@ protected function buildWrapMethodSource($client, $methodName, array $extraOptio if ($clientCopyMode < 2) { // client copy mode 0 or 1 == full / partial client copy in emitted code $verbatimClientCopy = !$clientCopyMode; - $innerCode = $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); + $innerCode = $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); $innerCode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { @@ -932,14 +941,14 @@ protected function buildWrapMethodSource($client, $methodName, array $extraOptio } } $innerCode .= "\$req->addparam(\$p$i);\n"; - $mDesc .= '* @param ' . $this->xmlrpc_2_php_type($pType) . " \$p$i\n"; + $mDesc .= '* @param ' . $this->xmlrpc2PhpType($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 ' . $this->xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; + $mDesc .= '* @return ' . $this->xmlrpc2PhpType($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n"; $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n"; if ($decodeFault) { @@ -963,16 +972,16 @@ protected function buildWrapMethodSource($client, $methodName, array $extraOptio } /** - * Similar to wrap_xmlrpc_method, but will generate a php class that wraps + * Similar to wrapXmlrpcMethod, 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. + * For more details see wrapXmlrpcMethod. * * For a slimmer alternative, see the code in demo/client/proxy.php * - * Note that unlike wrap_xmlrpc_method, we always have to generate php code here. It seems that php 7 will have anon classes... + * Note that unlike wrapXmlrpcMethod, we always have to generate php code here. It seems that php 7 will have anon classes... * * @param Client $client the client obj all set to query the desired server - * @param array $extraOptions list of options for wrapped code. See the ones from wrap_xmlrpc_method plus + * @param array $extraOptions list of options for wrapped code. See the ones from wrapXmlrpcMethod plus * - string method_filter regular expression * - string new_class_name * - string prefix @@ -980,7 +989,7 @@ protected function buildWrapMethodSource($client, $methodName, array $extraOptio * * @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) */ - public function wrap_xmlrpc_server($client, $extraOptions = array()) + public function wrapXmlrpcServer($client, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; @@ -1027,7 +1036,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) /// @todo add function setdebug() to new class, to enable/disable debugging $source = "class $xmlrpcClassName\n{\npublic \$client;\n\n"; $source .= "function __construct()\n{\n"; - $source .= $this->build_client_wrapper_code($client, $verbatimClientCopy, $prefix, $namespace); + $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace); $source .= "\$this->client = \$client;\n}\n\n"; $opts = array( 'return_source' => true, @@ -1044,7 +1053,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) // note: this will fail if server exposes 2 methods called f.e. do.something and do_something $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'), array('_', ''), $mName); - $methodWrap = $this->wrap_xmlrpc_method($client, $mName, $opts); + $methodWrap = $this->wrapXmlrpcMethod($client, $mName, $opts); if ($methodWrap) { if (!$buildIt) { $source .= $methodWrap['docstring']; @@ -1083,7 +1092,7 @@ public function wrap_xmlrpc_server($client, $extraOptions = array()) * * @return string */ - protected function build_client_wrapper_code($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) + protected function buildClientWrapperCode($client, $verbatimClientCopy, $prefix = 'xmlrpc', $namespace = '\\PhpXmlRpc\\' ) { $code = "\$client = new {$namespace}Client('" . str_replace("'", "\'", $client->path) . "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n"; From ca1ecacd1a0c24c1b16aa7ecbd39ea3bb01e338b Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 25 May 2015 19:47:00 +0100 Subject: [PATCH 195/228] Add more compatibility stuff in xmlrpcs.inc; split the function used to serve system.getCapabilities call to allow it to be changed in subclasses --- lib/xmlrpc_wrappers.inc | 31 ++++++++++++++++++++-- lib/xmlrpcs.inc | 58 ++++++++++++++++++++++++++++++++++++++++- src/Server.php | 52 +++++++++++++++++++++++------------- 3 files changed, 120 insertions(+), 21 deletions(-) diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc index c9e34494..021b1ce1 100644 --- a/lib/xmlrpc_wrappers.inc +++ b/lib/xmlrpc_wrappers.inc @@ -2,7 +2,7 @@ /****************************************************************************** * - *** DEPRECATED *** + * *** DEPRECATED *** * * This file is only used to insure backwards compatibility * with the API of the library <= rev. 3 @@ -119,7 +119,7 @@ function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, $code = "function $xmlrpcFuncName ("; if ($clientCopyMode < 2) { // client copy mode 0 or 1 == partial / full client copy in emitted code - $innerCode = $this->build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace); + $innerCode = build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace); $innerCode .= "\$client->setDebug(\$debug);\n"; $this_ = ''; } else { @@ -185,3 +185,30 @@ function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName, 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; +} \ No newline at end of file diff --git a/lib/xmlrpcs.inc b/lib/xmlrpcs.inc index aa6a2422..71cde1ff 100644 --- a/lib/xmlrpcs.inc +++ b/lib/xmlrpcs.inc @@ -36,7 +36,7 @@ /****************************************************************************** * - *** DEPRECATED *** + * *** DEPRECATED *** * * This file is only used to insure backwards compatibility * with the API of the library <= rev. 3 @@ -59,7 +59,63 @@ class xmlrpc_server extends PhpXmlRpc\Server /* 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); +} diff --git a/src/Server.php b/src/Server.php index 9f74412d..d8e591db 100644 --- a/src/Server.php +++ b/src/Server.php @@ -702,6 +702,10 @@ protected function debugmsg($string) $this->debug_info .= $string . "\n"; } + /** + * @param string $charsetEncoding + * @return string + */ protected function xml_header($charsetEncoding = '') { if ($charsetEncoding != '') { @@ -713,6 +717,9 @@ protected function xml_header($charsetEncoding = '') /* Functions that implement system.XXX methods of xmlrpc servers */ + /** + * @return array + */ public function getSystemDispatchMap() { return array( @@ -751,36 +758,45 @@ public function getSystemDispatchMap() ); } - public static function _xmlrpcs_getCapabilities($server, $req = null) + /** + * @return array + */ + public function getCapabilities() { $outAr = array( // xmlrpc spec: always supported - 'xmlrpc' => new Value(array( - 'specUrl' => new Value('http://www.xmlrpc.com/spec', 'string'), - 'specVersion' => new Value(1, 'int'), - ), 'struct'), + 'xmlrpc' => array( + 'specUrl' => 'http://www.xmlrpc.com/spec', + 'specVersion' => 1 + ), // if we support system.xxx functions, we always support multicall, too... // Note that, as of 2006/09/17, the following URL does not respond anymore - 'system.multicall' => new Value(array( - 'specUrl' => new Value('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'), - 'specVersion' => new Value(1, 'int'), - ), 'struct'), + 'system.multicall' => array( + 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208', + 'specVersion' => 1 + ), // introspection: version 2! we support 'mixed', too - 'introspection' => new Value(array( - 'specUrl' => new Value('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'), - 'specVersion' => new Value(2, 'int'), - ), 'struct'), + 'introspection' => array( + 'specUrl' => 'http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', + 'specVersion' => 2, + ), ); // NIL extension if (PhpXmlRpc::$xmlrpc_null_extension) { - $outAr['nil'] = new Value(array( - 'specUrl' => new Value('http://www.ontosys.com/xml-rpc/extensions.php', 'string'), - 'specVersion' => new Value(1, 'int'), - ), 'struct'); + $outAr['nil'] = array( + 'specUrl' => 'http://www.ontosys.com/xml-rpc/extensions.php', + 'specVersion' => 1 + ); } - return new Response(new Value($outAr, 'struct')); + return $outAr; + } + + public static function _xmlrpcs_getCapabilities($server, $req = null) + { + $encoder = new Encoder(); + return new Response($encoder->encode($server->getCapabilities())); } public static function _xmlrpcs_listMethods($server, $req = null) // if called in plain php values mode, second param is missing From 8b2d389eac480d2021432fa88d8cb66ed9a13cc4 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 25 May 2015 20:14:08 +0100 Subject: [PATCH 196/228] Update docs - in particular add one (incomplete) file describing all API changes and the quirks of 'compatibility mode' --- INSTALL.md | 9 +- NEWS | 58 ++++++++---- README.md | 4 + doc/api_changes_v4.md | 204 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 254 insertions(+), 21 deletions(-) create mode 100644 doc/api_changes_v4.md diff --git a/INSTALL.md b/INSTALL.md index 8d77e7c9..f78f8f0e 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,4 +1,5 @@ XMLRPC for PHP +============== Requirements ------------ @@ -79,7 +80,9 @@ Installation of the library is quite easy: 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 'make' command for installation of the library is -not recommended, as it will generally involve editing of the makefile for a -successful run. +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. diff --git a/NEWS b/NEWS index bba59f7d..0a3a9a35 100644 --- a/NEWS +++ b/NEWS @@ -10,27 +10,31 @@ more recent versions. PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. -* new: introduction of namespaces. +* 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. + 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 encoding delivered from the library to your code is now utf8. It can be changed at anytime setting a value to PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding -* improved: all php code is now formatted according to the PSR-2 standard - * improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https with recent curl builds -* improved: debug messages are not html-escaped any more when executing from the command line - * 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 @@ -39,11 +43,15 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * improved: when phpunit is used to generate code-coverage data, the code executed server-side is accounted for -* improved: the testsuite has basic checks for the debugger and demo files +* improved: the test suite has basic checks for the debugger and demo files + +* improved: more tests in the test suite -* 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 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 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 @@ -54,8 +62,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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 - (this is visible e.g. in the debugger) +* 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) @@ -64,13 +72,20 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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. +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. @@ -87,15 +102,19 @@ The "beta" tag is meant to indicate the fact that the refactoring has been more 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: 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 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 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: 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 @@ -110,13 +129,16 @@ 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: 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 +* 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 diff --git a/README.md b/README.md index a75235b3..78d216de 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ The user manual can be found in the doc/manual directory, in Asciidoc format: [p 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, please read the docs in [doc/api_changes_v4.md](doc/api_changes_v4.md) + License ------- Use of this software is subject to the terms in the [license.txt](license.txt) file diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md new file mode 100644 index 00000000..ff462e5f --- /dev/null +++ b/doc/api_changes_v4.md @@ -0,0 +1,204 @@ +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 . "/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 | +| ------------- | ------------------ | +| xmlrpc_client | PhpXmlRpc\Client | +| xmlrpc_server | PhpXmlRpc\Server | +| xmlrpcmsg | PhpXmlRpc\Request | +| xmlrpcresp | PhpXmlRpc\Response | +| xmlrpcval | PhpXmlRpc\Value | + + +Global variables cleanup +------------------------ + +All variables in the global scope have been moved into classes. + +Conversion table: + +| Old variable | New variable | Notes | +| ------------------------ | ------------------------------------------- | --------- | +| _xmlrpcs_capabilities | NOT AVAILABLE YET | | +| _xmlrpc_debuginfo | PhpXmlRpc\Server::$_xmlrpc_debuginfo | protected | +| _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. + +| Old function | New function | +| ------------------------ | ------------------------------------------- | +| ... | | + + +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 teh 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 name + +* 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. + +### 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 + +### wrapping methods now return closures + +might be fixed later? + +### server behaviour can not be changed by setting global variables (the ones starting with _xmlrpcs_ ) + +might be fixed later? From 5a6fe2c4be2af29d295b5756483bffa7f74193f6 Mon Sep 17 00:00:00 2001 From: gggeek Date: Mon, 25 May 2015 20:39:33 +0100 Subject: [PATCH 197/228] Fix bugs found by Scrutinizer --- demo/client/proxy.php | 2 +- demo/vardemo.php | 2 +- src/Client.php | 2 +- src/Response.php | 2 +- src/Server.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/demo/client/proxy.php b/demo/client/proxy.php index 6d0d3c5a..7173db03 100644 --- a/demo/client/proxy.php +++ b/demo/client/proxy.php @@ -45,7 +45,7 @@ function __call($name, $arguments) $resp = $this->client->send(new PhpXmlRpc\Request($this->prefix.$name, $valueArray)); if ($resp->faultCode()) { - throw new Exception($resp->faultMessage(), $resp->faultCode); + throw new Exception($resp->faultString(), $resp->faultCode()); } else { return $resp->value(); } diff --git a/demo/vardemo.php b/demo/vardemo.php index bb697561..b1ab3c05 100644 --- a/demo/vardemo.php +++ b/demo/vardemo.php @@ -84,7 +84,7 @@ $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::iso8601Eecode($date, 1) . "\n"; +print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601Encode($date, 1) . "\n"; print "\n"; diff --git a/src/Client.php b/src/Client.php index 21060e8b..c0d86c37 100644 --- a/src/Client.php +++ b/src/Client.php @@ -341,7 +341,7 @@ public function SetUserAgent($agentString) * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used * - * @return Response + * @return Response|Response[] */ public function send($req, $timeout = 0, $method = '') { diff --git a/src/Response.php b/src/Response.php index 6ed243ac..7e2ebb66 100644 --- a/src/Response.php +++ b/src/Response.php @@ -75,7 +75,7 @@ public function faultString() /** * Returns the value received by the server. * - * @return mixed the xmlrpc value object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects + * @return Value|string|mixed the xmlrpc value object returned by the server. Might be an xml string or php value if the response has been created by specially configured Client objects */ public function value() { diff --git a/src/Server.php b/src/Server.php index d8e591db..089efdf7 100644 --- a/src/Server.php +++ b/src/Server.php @@ -966,7 +966,7 @@ public static function _xmlrpcs_multicall_do_call_phpvals($server, $call) $pt = array(); $wrapper = new Wrapper(); foreach ($call['params'] as $val) { - $pt[] = $wrapper->php_2_xmlrpc_type(gettype($val)); + $pt[] = $wrapper->php2XmlrpcType(gettype($val)); } $result = $server->execute($call['methodName'], $call['params'], $pt); From 393f882cb3a8a040bd7a0eb8da3c05cfacb8af99 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 11:04:18 +0200 Subject: [PATCH 198/228] two fixes for 'load method synopsis' action in the debugger; add tests for NIL values in the dispatch map --- NEWS | 5 +++++ debugger/action.php | 13 +++++++++---- demo/server/server.php | 26 ++++++++++++++++++++++++++ tests/3LocalhostTest.php | 30 ++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/NEWS b/NEWS index 0a3a9a35..d941bcfd 100644 --- a/NEWS +++ b/NEWS @@ -60,6 +60,11 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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 NULLs + +* 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; diff --git a/debugger/action.php b/debugger/action.php index 05cc99a5..18d92953 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -350,12 +350,13 @@ $desc = "-"; } echo "
      \n"; - $payload = ""; - $alt_payload = ""; + if ($r2->kindOf() != "array") { echo "\n"; } else { for ($i = 0; $i < $r2->arraysize(); $i++) { + $payload = ""; + $alt_payload = ""; if ($i + 1 % 2) { $class = ' class="oddrow"'; } else { @@ -371,9 +372,13 @@ $y = $x->arraymem($k); echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($wstype != 1) { + $type = $y->scalarval(); + if ($type == 'null') { + $type = 'nil'; + } $payload = $payload . '<' . - htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . - '>scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + '>\n"; } $alt_payload .= $y->scalarval(); diff --git a/demo/server/server.php b/demo/server/server.php index 1fdd49ba..180a1088 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -186,6 +186,23 @@ function inner_findstate($stateNo) $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) @@ -909,11 +926,20 @@ function i_whichToolkit($req) '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; diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 4b721d62..a1f7dbf5 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -112,6 +112,12 @@ protected function tearDown() } } + /** + * @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) { @@ -546,6 +552,30 @@ public function testZeroParams() $v = $this->send($f); } + public function testNullParams() + { + $f = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval('whatever', 'null'), + new xmlrpcval(23, 'int'), + )); + $v = $this->send($f); + if ($v) { + $this->assertEquals('Michigan', $v->scalarval()); + } + $f = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval(23, 'int'), + new xmlrpcval('whatever', 'null'), + )); + $v = $this->send($f); + if ($v) { + $this->assertEquals('Michigan', $v->scalarval()); + } + $f = new xmlrpcmsg('tests.getStateName.12', array( + new xmlrpcval(23, 'int') + )); + $v = $this->send($f, array($GLOBALS['xmlrpcerr']['incorrect_params'])); + } + public function testCodeInjectionServerSide() { $f = new xmlrpcmsg('system.MethodHelp'); From a82e460deba4bf91a047943de0ae2613a8acff4f Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 11:18:29 +0200 Subject: [PATCH 199/228] Better support for 'undefined' values in debugger's 'load method synopsis' --- debugger/action.php | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index 18d92953..0e6ee450 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -373,13 +373,20 @@ echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($wstype != 1) { $type = $y->scalarval(); - if ($type == 'null') { - $type = 'nil'; + $payload .= ''; + switch($type) { + case 'undefined': + break; + case 'null'; + $type = 'nil'; + // fall thru intentionally + default: + $payload .= '<' . + htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . + '>'; } - $payload = $payload . '<' . - htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . - '>\n"; + $payload .= "\n"; } $alt_payload .= $y->scalarval(); if ($k < $x->arraysize() - 1) { From 3cb8e96d8cab32cb117518cc305b953b358a2651 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 11:28:06 +0200 Subject: [PATCH 200/228] add test for debug messages set into the server by client code --- demo/server/server.php | 12 ++++++++++++ tests/3LocalhostTest.php | 9 +++++++++ tests/4LocalhostMultiTest.php | 2 +- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/demo/server/server.php b/demo/server/server.php index 180a1088..f05557a7 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -37,6 +37,8 @@ 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) { @@ -46,12 +48,22 @@ public function phpWarningGenerator($req) /** * 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. diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index a1f7dbf5..220878ea 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -852,6 +852,15 @@ public function testSetCookies() } } + public function testServerComments() + { + $f = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array( + new xmlrpcval('hello world', 'string'), + )); + $r = $this->send($f, 0, true); + $this->assertContains('hello world', $r->raw_data); + } + public function testSendTwiceSameMsg() { $f = new xmlrpcmsg('examples.stringecho', array( diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 9243514b..27eaafc3 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -19,7 +19,7 @@ class LocalhostMultiTest extends LocalhostTest */ function _runtests() { - $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method'); + $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments'); foreach(get_class_methods('LocalhostTest') as $method) { if(strpos($method, 'test') === 0 && !in_array($method, $unsafeMethods)) From 2e3b2ac38fb42c0b685a0c345f7f42ac823d7748 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 11:47:07 +0200 Subject: [PATCH 201/228] Fix: better generation of method signatures in wrap_php_ calls --- NEWS | 3 ++- src/Wrapper.php | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/NEWS b/NEWS index d941bcfd..8d8c130a 100644 --- a/NEWS +++ b/NEWS @@ -60,7 +60,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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 NULLs +* 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 diff --git a/src/Wrapper.php b/src/Wrapper.php index 21321a64..f7f20721 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -280,10 +280,10 @@ protected function introspectFunction($callable, $plainFuncName) $desc .= $doc; } elseif (strpos($doc, '@param') === 0) { // syntax: @param type $name [desc] - if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s+(.+)?/', $doc, $matches)) { + if (preg_match('/@param\s+(\S+)\s+(\$\S+)\s*(.+)?/', $doc, $matches)) { $name = strtolower(trim($matches[2])); //$paramDocs[$name]['name'] = trim($matches[2]); - $paramDocs[$name]['doc'] = $matches[3]; + $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : ''; $paramDocs[$name]['type'] = $matches[1]; } $i++; From b44fb9a21bea5fb357ab8ab09d3c530067cb76b3 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 12:09:55 +0200 Subject: [PATCH 202/228] Fix: reset debug and error messages between server execution calls --- src/Server.php | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Server.php b/src/Server.php index 089efdf7..96aac17c 100644 --- a/src/Server.php +++ b/src/Server.php @@ -179,7 +179,9 @@ public function serializeDebug($charsetEncoding = '') * @param string $data the request body. If null, the http POST request will be examined * @param bool $returnPayload When true, return the response but do not echo it or any http header * - * @return Response the response object (usually not used by caller...) + * @return Response|string the response object (usually not used by caller...) or its xml serialization + * + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) */ public function service($data = null, $returnPayload = false) { @@ -191,13 +193,14 @@ public function service($data = null, $returnPayload = false) // reset internal debug info $this->debug_info = ''; - // Echo back what we received, before parsing it + // Save what we received, before parsing it if ($this->debug > 1) { $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++"); } $r = $this->parseRequestHeaders($data, $reqCharset, $respCharset, $respEncoding); if (!$r) { + // this actually executes the request $r = $this->parseRequest($data, $reqCharset); } @@ -446,6 +449,8 @@ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$ * @param string $reqEncoding (optional) the charset encoding of the xml request * * @return Response + * + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) */ public function parseRequest($data, $reqEncoding = '') { @@ -545,10 +550,13 @@ public function parseRequest($data, $reqEncoding = '') * * @return Response * - * @throws \Exception in case the executed method does throw an exception (and depending on ) + * @throws \Exception in case the executed method does throw an exception (and depending on server configuration) */ protected function execute($req, $params = null, $paramTypes = null) { + static::$_xmlrpcs_occurred_errors = ''; + static::$_xmlrpc_debuginfo = ''; + if (is_object($req)) { $methName = $req->method(); } else { @@ -603,7 +611,6 @@ protected function execute($req, $params = null, $paramTypes = null) // verify that function to be invoked is in fact callable if (!is_callable($func)) { error_log("XML-RPC: " . __METHOD__ . ": function '$funcName' registered as method handler is not callable"); - return new Response( 0, PhpXmlRpc::$xmlrpcerr['server_error'], @@ -616,6 +623,7 @@ protected function execute($req, $params = null, $paramTypes = null) if ($this->debug > 2) { self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler')); } + try { // Allow mixed-convention servers if (is_object($req)) { From 4f055f25ad547e9faf94417dfd58c2082e8e31f1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 13:48:28 +0200 Subject: [PATCH 203/228] Correctly reset php error handler even when user-code raises an exception --- NEWS | 5 +++++ src/Server.php | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/NEWS b/NEWS index 8d8c130a..5880306c 100644 --- a/NEWS +++ b/NEWS @@ -47,6 +47,11 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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 diff --git a/src/Server.php b/src/Server.php index 96aac17c..70b45de3 100644 --- a/src/Server.php +++ b/src/Server.php @@ -678,6 +678,13 @@ protected function execute($req, $params = null, $paramTypes = null) // in the called function, we wrap it in a proper error-response switch ($this->exception_handling) { case 2: + if ($this->debug > 2) { + if (self::$_xmlrpcs_prev_ehandler) { + set_error_handler(self::$_xmlrpcs_prev_ehandler); + } else { + restore_error_handler(); + } + } throw $e; break; case 1: From c325fab48f8f3eabc35123efdf5916b77cc878e2 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 14:49:59 +0200 Subject: [PATCH 204/228] Fix: debugger was not able any more to generate wrapped client code --- debugger/action.php | 6 +++--- src/Wrapper.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index 0e6ee450..2e128861 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -481,9 +481,9 @@ if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression && $clientcookies == '' ) { - $opts = 0; // simple client copy in stub code + $opts = 1; // simple client copy in stub code } else { - $opts = 1; // complete client copy in stub code + $opts = 0; // complete client copy in stub code } if ($wstype == 1) { $prefix = 'jsonrpc'; @@ -492,7 +492,7 @@ } //$code = wrap_xmlrpc_method($client, $method, $methodsig, 0, $proto, '', $opts); $wrapper = new PhpXmlRpc\Wrapper(); - $code = $wrapper->build_remote_method_wrapper_code($client, $method, str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc, $timeout, $proto, $opts, $prefix); + $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 "
      \n"; diff --git a/src/Wrapper.php b/src/Wrapper.php index f7f20721..c3d1514d 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -882,7 +882,7 @@ protected function buildWrapMethodClosure($client, $methodName, array $extraOpti * @param string $mDesc * @return array */ - protected function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') + public function buildWrapMethodSource($client, $methodName, array $extraOptions, $newFuncName, $mSig, $mDesc='') { $timeout = isset($extraOptions['timeout']) ? (int)$extraOptions['timeout'] : 0; $protocol = isset($extraOptions['protocol']) ? $extraOptions['protocol'] : ''; From a7d8cdb3c8868c1d3d9ee1cb1356eeb8182c2522 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 15:22:12 +0200 Subject: [PATCH 205/228] Advance in compatibility docs --- doc/api_changes_v4.md | 50 ++++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md index ff462e5f..b587d9b0 100644 --- a/doc/api_changes_v4.md +++ b/doc/api_changes_v4.md @@ -36,13 +36,13 @@ Existing class methods and members have been preserved; all new method names fol Conversion table: -| Old class | New class | -| ------------- | ------------------ | -| xmlrpc_client | PhpXmlRpc\Client | -| xmlrpc_server | PhpXmlRpc\Server | -| xmlrpcmsg | PhpXmlRpc\Request | -| xmlrpcresp | PhpXmlRpc\Response | -| xmlrpcval | PhpXmlRpc\Value | +| 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 | Global variables cleanup @@ -54,8 +54,8 @@ Conversion table: | Old variable | New variable | Notes | | ------------------------ | ------------------------------------------- | --------- | -| _xmlrpcs_capabilities | NOT AVAILABLE YET | | | _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 | @@ -67,10 +67,30 @@ Global functions cleanup ------------------------ Most functions in the global scope have been moved into classes. - -| Old function | New function | -| ------------------------ | ------------------------------------------- | -| ... | | +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 | | +| iso8601_decode | PhpXmlRpc\Helper\Date::iso8601Decode | | +| iso8601_encode | PhpXmlRpc\Helper\Date::iso8601Encode | | +| php_2_xmlrpc_type | PhpXmlRpc\Wrapper::php2XmlrpcType | | +| php_xmlrpc_decode | PhpXmlRpc\Encoder::decode | | +| php_xmlrpc_decode_xml | PhpXmlRpc\Encoder::decodeXml | | +| php_xmlrpc_encode | PhpXmlRpc\Encoder::encode | | +| 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 | | +| xmlrpc_debugmsg | PhpXmlRpc\Server::xmlrpc_debugmsg | | +| xmlrpc_encode_entitites | PhpXmlRpc\Helper\Charset::encodeEntitites | | Character sets and encoding @@ -118,7 +138,7 @@ the purpose of backwards compatibility (you might notice that they are still in 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. +Below is the list of all known changes and possible pitfalls when enabling 'compatibility mode'. ### Default character set used for application data @@ -195,10 +215,6 @@ Below is the list of all known changes and possible pitfalls. is_a(php_xmlrpc_encode('hello world'), 'xmlrpcval') => false is_a(php_xmlrpc_encode('hello world'), 'PhpXmlRpc\Value') => true -### wrapping methods now return closures - -might be fixed later? - ### server behaviour can not be changed by setting global variables (the ones starting with _xmlrpcs_ ) might be fixed later? From 25cd0af7fd7f07459a9448be6b6454d0afde4fff Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 15:46:12 +0200 Subject: [PATCH 206/228] fix backwards compatibility in xmlrpc_wrappers.inc --- lib/xmlrpc_wrappers.inc | 47 +++++++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/lib/xmlrpc_wrappers.inc b/lib/xmlrpc_wrappers.inc index 021b1ce1..3c2390a2 100644 --- a/lib/xmlrpc_wrappers.inc +++ b/lib/xmlrpc_wrappers.inc @@ -34,7 +34,6 @@ function xmlrpc_2_php_type($xmlrpcType) return $wrapper->xmlrpc2PhpType($xmlrpcType); } -/// @todo backwards compat: return string instead of callable /** * @see PhpXmlRpc\Wrapper::wrap_php_function * @param callable $funcName @@ -45,11 +44,21 @@ function xmlrpc_2_php_type($xmlrpcType) function wrap_php_function($funcName, $newFuncName='', $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); - return $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions); + 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; } -/// @todo backwards compat: return strings instead of callables /** + * 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 @@ -58,10 +67,22 @@ function wrap_php_function($funcName, $newFuncName='', $extraOptions=array()) function wrap_php_class($className, $extraOptions=array()) { $wrapper = new PhpXmlRpc\Wrapper(); - return $wrapper->wrapPhpClass($className, $extraOptions); + $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; } -/// @todo backwards compat: return string instead of callable /** * @see PhpXmlRpc\Wrapper::wrapXmlrpcMethod * @param xmlrpc_client $client @@ -86,10 +107,19 @@ function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $ } $wrapper = new PhpXmlRpc\Wrapper(); - return $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions); + + 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; } -/// @todo backwards compat: return strings instead of callables /** * @see PhpXmlRpc\Wrapper::wrap_xmlrpc_server * @param xmlrpc_client $client @@ -102,7 +132,6 @@ function wrap_xmlrpc_server($client, $extraOptions=array()) return $wrapper->wrapXmlrpcServer($client, $extraOptions); } -/// @todo fix dangling usage of $this-> /** * 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. @@ -211,4 +240,4 @@ function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlr $code .= "\$client->return_type = '{$prefix}vals';\n"; //$code .= "\$client->setDebug(\$debug);\n"; return $code; -} \ No newline at end of file +} From 19b99735570521d8172f73124ade5997b9dca75d Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 15:47:06 +0200 Subject: [PATCH 207/228] write chagelog of debugger in its interface --- debugger/action.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debugger/action.php b/debugger/action.php index 2e128861..44d8a001 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -490,7 +490,6 @@ } else { $prefix = 'xmlrpc'; } - //$code = wrap_xmlrpc_method($client, $method, $methodsig, 0, $proto, '', $opts); $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) @@ -544,6 +543,7 @@

      Changelog

        +
      • 2015-05-30: fix problems with generating method payloads for NIL and Undefined parameters
      • 2015-04-19: fix problems with LATIN-1 characters in payload
      • 2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id
      • 2006-06-26: support building php code stub for calling remote methods
      • From 0acf4730dbcf97f6da9528d6f4d2fd5667465f8f Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 30 May 2015 17:29:41 +0200 Subject: [PATCH 208/228] make parsingbugstests executable on their own --- tests/1ParsingBugsTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php index 8ed214bd..d9a432a5 100644 --- a/tests/1ParsingBugsTest.php +++ b/tests/1ParsingBugsTest.php @@ -5,6 +5,8 @@ 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 */ From fc4f17849d8bb022c3b8ff38a2bed1d1c188ac7f Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 7 Jun 2015 15:47:01 +0200 Subject: [PATCH 209/228] Minor cleanup in variable names --- demo/server/server.php | 4 +- src/Encoder.php | 6 +- src/Wrapper.php | 3 +- tests/2InvalidHostTest.php | 14 ++-- tests/3LocalhostTest.php | 160 ++++++++++++++++++------------------- 5 files changed, 93 insertions(+), 94 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index f05557a7..4b8b8e41 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -464,8 +464,8 @@ function getAllHeaders_xmlrpc($req) function setCookies($req) { $encoder = new PhpXmlRpc\Encoder(); - $m = $req->getParam(0); - while (list($name, $value) = $m->structeach()) { + $cookies = $req->getParam(0); + while (list($name, $value) = $cookies->structeach()) { $cookieDesc = $encoder->decode($value); setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']); } diff --git a/src/Encoder.php b/src/Encoder.php index 7f51cfa9..f97096eb 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -300,12 +300,12 @@ public function decodeXml($xmlVal, $options = array()) return $r; case 'methodcall': - $m = new Request($xmlRpcParser->_xh['method']); + $req = new Request($xmlRpcParser->_xh['method']); for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) { - $m->addParam($xmlRpcParser->_xh['params'][$i]); + $req->addParam($xmlRpcParser->_xh['params'][$i]); } - return $m; + return $req; case 'value': return $xmlRpcParser->_xh['value']; default: diff --git a/src/Wrapper.php b/src/Wrapper.php index c3d1514d..10aae52e 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -822,7 +822,7 @@ protected function buildWrapMethodClosure($client, $methodName, array $extraOpti $decodeOptions[] = 'decode_php_objs'; } - /// @todo check for insufficient nr. of args besides excess ones + /// @todo check for insufficient nr. of args besides excess ones? note that 'source' version does not... // support one extra parameter: debug $maxArgs = count($mSig)-1; // 1st element is the return type @@ -835,7 +835,6 @@ protected function buildWrapMethodClosure($client, $methodName, array $extraOpti $xmlrpcArgs = array(); foreach($currentArgs as $i => $arg) { if ($i == $maxArgs) { - /// @todo log warning? check what happens with the 'source' version break; } $pType = $mSig[$i+1]; diff --git a/tests/2InvalidHostTest.php b/tests/2InvalidHostTest.php index 7e0062cc..1c81b550 100644 --- a/tests/2InvalidHostTest.php +++ b/tests/2InvalidHostTest.php @@ -38,20 +38,20 @@ protected function tearDown() public function test404() { - $f = new xmlrpcmsg('examples.echo', array( + $m = new xmlrpcmsg('examples.echo', array( new xmlrpcval('hello', 'string'), )); - $r = $this->client->send($f, 5); + $r = $this->client->send($m, 5); $this->assertEquals(5, $r->faultCode()); } public function testSrvNotFound() { - $f = new xmlrpcmsg('examples.echo', array( + $m = new xmlrpcmsg('examples.echo', array( new xmlrpcval('hello', 'string'), )); $this->client->server .= 'XXX'; - $r = $this->client->send($f, 5); + $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) { @@ -68,13 +68,13 @@ public function testCurlKAErr() return; } - $f = new xmlrpcmsg('examples.stringecho', array( + $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($f, 5, 'http11'); + $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); @@ -86,7 +86,7 @@ public function testCurlKAErr() $this->client->server = $server[0]; $this->client->path = $this->args['URI']; - $r = $this->client->send($f, 5, 'http11'); + $r = $this->client->send($m, 5, 'http11'); $this->assertEquals(0, $r->faultCode()); $ro = $r->value(); is_object($ro) && $this->assertEquals('hello', $ro->scalarVal()); diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 220878ea..186dd59c 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -156,10 +156,10 @@ public function testString() "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: -->"; - $f = new xmlrpcmsg('examples.stringecho', array( + $m = new xmlrpcmsg('examples.stringecho', array( new xmlrpcval($sendString, 'string'), )); - $v = $this->send($f); + $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... @@ -177,10 +177,10 @@ public function testLatin1String() { $sendString = "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne"; - $f = 'examples.stringecho'. + $x = 'examples.stringecho'. $sendString. ''; - $v = $this->send($f); + $v = $this->send($x); if ($v) { $this->assertEquals($sendString, $v->scalarval()); } @@ -200,10 +200,10 @@ public function testLatin1String() public function testUtf8Method() { PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8'; - $f = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array( + $m = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array( new xmlrpcval('hello') )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals('hello', $v->scalarval()); } @@ -216,11 +216,11 @@ public function testAddingDoubles() // keep precision to sensible levels here ;-) $a = 12.13; $b = -23.98; - $f = new xmlrpcmsg('examples.addtwodouble', array( + $m = new xmlrpcmsg('examples.addtwodouble', array( new xmlrpcval($a, 'double'), new xmlrpcval($b, 'double'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals($a + $b, $v->scalarval()); } @@ -228,11 +228,11 @@ public function testAddingDoubles() public function testAdding() { - $f = new xmlrpcmsg('examples.addtwo', array( + $m = new xmlrpcmsg('examples.addtwo', array( new xmlrpcval(12, 'int'), new xmlrpcval(-23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals(12 - 23, $v->scalarval()); } @@ -240,11 +240,11 @@ public function testAdding() public function testInvalidNumber() { - $f = new xmlrpcmsg('examples.addtwo', array( + $m = new xmlrpcmsg('examples.addtwo', array( new xmlrpcval('fred', 'int'), new xmlrpcval("\"; exec('ls')", 'int'), )); - $v = $this->send($f); + $v = $this->send($m); /// @todo a fault condition should be generated here /// by the server, which we pick up on if ($v) { @@ -254,7 +254,7 @@ public function testInvalidNumber() public function testBoolean() { - $f = new xmlrpcmsg('examples.invertBooleans', array( + $m = new xmlrpcmsg('examples.invertBooleans', array( new xmlrpcval(array( new xmlrpcval(true, 'boolean'), new xmlrpcval(false, 'boolean'), @@ -264,7 +264,7 @@ public function testBoolean() 'array' ),)); $answer = '0101'; - $v = $this->send($f); + $v = $this->send($m); if ($v) { $sz = $v->arraysize(); $got = ''; @@ -291,10 +291,10 @@ public function testBase64() She tied it to a pylon Ten thousand volts went down its back And turned it into nylon'; - $f = new xmlrpcmsg('examples.decode64', array( + $m = new xmlrpcmsg('examples.decode64', array( new xmlrpcval($sendString, 'base64'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { if (strlen($sendString) == strlen($v->scalarval())) { $this->assertEquals($sendString, $v->scalarval()); @@ -323,10 +323,10 @@ public function testDateTime() public function testCountEntities() { $sendString = "h'fd>onc>>l>>rw&bpu>q>esend($f); + $v = $this->send($m); if ($v) { $got = ''; $expected = '37210'; @@ -372,8 +372,8 @@ public function testServerMulticall() 'array' ); - $f = new xmlrpcmsg('system.multicall', array($arg)); - $v = $this->send($f); + $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"); @@ -523,10 +523,10 @@ public function testClientMulticall3() public function testCatchWarnings() { - $f = new xmlrpcmsg('tests.generatePHPWarning', array( + $m = new xmlrpcmsg('tests.generatePHPWarning', array( new xmlrpcval('whatever', 'string'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals(true, $v->scalarval()); } @@ -534,53 +534,53 @@ public function testCatchWarnings() public function testCatchExceptions() { - $f = new xmlrpcmsg('tests.raiseException', array( + $m = new xmlrpcmsg('tests.raiseException', array( new xmlrpcval('whatever', 'string'), )); - $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1'; - $v = $this->send($f, 1); // the error code of the expected exception + $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($f, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error'])); + $v = $this->send($m, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error'])); } public function testZeroParams() { - $f = new xmlrpcmsg('system.listMethods'); - $v = $this->send($f); + $m = new xmlrpcmsg('system.listMethods'); + $v = $this->send($m); } public function testNullParams() { - $f = new xmlrpcmsg('tests.getStateName.12', array( + $m = new xmlrpcmsg('tests.getStateName.12', array( new xmlrpcval('whatever', 'null'), new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals('Michigan', $v->scalarval()); } - $f = new xmlrpcmsg('tests.getStateName.12', array( + $m = new xmlrpcmsg('tests.getStateName.12', array( new xmlrpcval(23, 'int'), new xmlrpcval('whatever', 'null'), )); - $v = $this->send($f); + $v = $this->send($m); if ($v) { $this->assertEquals('Michigan', $v->scalarval()); } - $f = new xmlrpcmsg('tests.getStateName.12', array( + $m = new xmlrpcmsg('tests.getStateName.12', array( new xmlrpcval(23, 'int') )); - $v = $this->send($f, array($GLOBALS['xmlrpcerr']['incorrect_params'])); + $v = $this->send($m, array($GLOBALS['xmlrpcerr']['incorrect_params'])); } public function testCodeInjectionServerSide() { - $f = new xmlrpcmsg('system.MethodHelp'); - $f->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; - $v = $this->send($f); + $m = new xmlrpcmsg('system.MethodHelp'); + $m->payload = "validator1.echoStructTest','')); echo('gotcha!'); die(); //"; + $v = $this->send($m); if ($v) { $this->assertEquals(0, $v->structsize()); } @@ -588,126 +588,126 @@ public function testCodeInjectionServerSide() public function testServerWrappedFunction() { - $f = new xmlrpcmsg('tests.getStateName.2', array( + $m = new xmlrpcmsg('tests.getStateName.2', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $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 - $f = new xmlrpcmsg('tests.getStateName.2', array( + $m = new xmlrpcmsg('tests.getStateName.2', array( new xmlrpcval(0, 'int'), )); - $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); // check if the generated function dispatch map is fine, by checking if the server registered it - $f = new xmlrpcmsg('system.methodSignature', array( + $m = new xmlrpcmsg('system.methodSignature', array( new xmlrpcval('tests.getStateName.2'), )); - $v = $this->send($f); + $v = $this->send($m); $encoder = new \PhpXmlRpc\Encoder(); $this->assertEquals(array(array('string', 'int')), $encoder->decode($v)); } public function testServerWrappedFunctionAsSource() { - $f = new xmlrpcmsg('tests.getStateName.6', array( + $m = new xmlrpcmsg('tests.getStateName.6', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $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 - $f = new xmlrpcmsg('tests.getStateName.6', array( + $m = new xmlrpcmsg('tests.getStateName.6', array( new xmlrpcval(0, 'int'), )); - $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']); + $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']); } public function testServerWrappedObjectMethods() { - $f = new xmlrpcmsg('tests.getStateName.3', array( + $m = new xmlrpcmsg('tests.getStateName.3', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.4', array( + $m = new xmlrpcmsg('tests.getStateName.4', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.5', array( + $m = new xmlrpcmsg('tests.getStateName.5', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.7', array( + $m = new xmlrpcmsg('tests.getStateName.7', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.8', array( + $m = new xmlrpcmsg('tests.getStateName.8', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.9', array( + $m = new xmlrpcmsg('tests.getStateName.9', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); } public function testServerWrappedObjectMethodsAsSource() { - $f = new xmlrpcmsg('tests.getStateName.7', array( + $m = new xmlrpcmsg('tests.getStateName.7', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.8', array( + $m = new xmlrpcmsg('tests.getStateName.8', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); - $f = new xmlrpcmsg('tests.getStateName.9', array( + $m = new xmlrpcmsg('tests.getStateName.9', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); } public function testServerClosure() { - $f = new xmlrpcmsg('tests.getStateName.10', array( + $m = new xmlrpcmsg('tests.getStateName.10', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); } public function testServerWrappedClosure() { - $f = new xmlrpcmsg('tests.getStateName.11', array( + $m = new xmlrpcmsg('tests.getStateName.11', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); } public function testServerWrappedClass() { - $f = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array( + $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array( new xmlrpcval(23, 'int'), )); - $v = $this->send($f); + $v = $this->send($m); $this->assertEquals('Michigan', $v->scalarval()); } @@ -789,8 +789,8 @@ public function testGetCookies() 'c5' => array('value' => 'c5', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'localhost'), ); $cookiesval = php_xmlrpc_encode($cookies); - $f = new xmlrpcmsg('examples.setcookies', array($cookiesval)); - $r = $this->send($f, 0, true); + $m = new xmlrpcmsg('examples.setcookies', array($cookiesval)); + $r = $this->send($m, 0, true); if ($r) { $v = $r->value(); $this->assertEquals(1, $v->scalarval()); @@ -831,12 +831,12 @@ public function testSetCookies() 'c2' => '2 3', 'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-', ); - $f = new xmlrpcmsg('examples.getcookies', array()); + $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($f, $this->timeout, $this->method); + $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(); @@ -854,20 +854,20 @@ public function testSetCookies() public function testServerComments() { - $f = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array( + $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array( new xmlrpcval('hello world', 'string'), )); - $r = $this->send($f, 0, true); + $r = $this->send($m, 0, true); $this->assertContains('hello world', $r->raw_data); } public function testSendTwiceSameMsg() { - $f = new xmlrpcmsg('examples.stringecho', array( + $m = new xmlrpcmsg('examples.stringecho', array( new xmlrpcval('hello world', 'string'), )); - $v1 = $this->send($f); - $v2 = $this->send($f); + $v1 = $this->send($m); + $v2 = $this->send($m); if ($v1 && $v2) { $this->assertEquals($v1, $v2); } From 5b7db050a80da5d250316e8fd8db2ed7960b8a16 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 7 Jun 2015 16:36:58 +0200 Subject: [PATCH 210/228] Add a test for receiving requests which use non-utf8 encoding --- tests/3LocalhostTest.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 186dd59c..ec9c5618 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -186,6 +186,31 @@ public function testLatin1String() } } + 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 = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + // these calls will have no charset declaration in either http headers or xml prolog + $v = $this->send(mb_convert_encoding($str, 'UCS-4')); + $this->assertEquals($sendString, $v->scalarval()); + $v = $this->send(mb_convert_encoding($str, 'UTF-16')); + $this->assertEquals($sendString, $v->scalarval()); + } + /*public function testLatin1Method() { $f = new xmlrpcmsg("tests.iso88591methodname." . chr(224) . chr(252) . chr(232), array( From 751f9c979bd0d3ca2198ad31009d4cb4cff691cc Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 7 Jun 2015 21:13:59 +0200 Subject: [PATCH 211/228] Added support for Countable and IteratorAggregate interfaces --- NEWS | 2 ++ doc/api_changes_v4.md | 13 ++++++++ src/Value.php | 69 +++++++++++++++++++++++++------------------ 3 files changed, 56 insertions(+), 28 deletions(-) diff --git a/NEWS b/NEWS index 5880306c..65d245a5 100644 --- a/NEWS +++ b/NEWS @@ -25,6 +25,8 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. * 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) diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md index b587d9b0..2403020c 100644 --- a/doc/api_changes_v4.md +++ b/doc/api_changes_v4.md @@ -45,6 +45,19 @@ Conversion table: | 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 | + + Global variables cleanup ------------------------ diff --git a/src/Value.php b/src/Value.php index f544fa58..6e8d7efa 100644 --- a/src/Value.php +++ b/src/Value.php @@ -4,7 +4,7 @@ use PhpXmlRpc\Helper\Charset; -class Value +class Value implements \Countable, \IteratorAggregate { public static $xmlrpcI4 = "i4"; public static $xmlrpcInt = "int"; @@ -37,7 +37,8 @@ class Value public $_php_class = null; /** - * Build an xmlrpc value + * 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 * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed @@ -47,7 +48,6 @@ 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 != '') { - // optimization creep: inlined all work done by constructor switch ($type) { case '': $this->mytype = 1; @@ -75,28 +75,11 @@ public function __construct($val = -1, $type = '') default: error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)"); } - /* was: - if($type=='') - { - $type='string'; - } - if(static::$xmlrpcTypes[$type]==1) - { - $this->addScalar($val,$type); - } - elseif(static::$xmlrpcTypes[$type]==2) - { - $this->addArray($val); - } - elseif(static::$xmlrpcTypes[$type]==3) - { - $this->addStruct($val); - }*/ } } /** - * Add a single php value to an (unitialized) xmlrpc value. + * Add a single php value to an (uninitialized) xmlrpc value. * * @param mixed $val * @param string $type @@ -112,7 +95,6 @@ public function addScalar($val, $type = 'string') if ($typeOf !== 1) { error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)"); - return 0; } @@ -130,11 +112,9 @@ public function addScalar($val, $type = 'string') 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 @@ -173,7 +153,6 @@ public function addArray($values) return 1; } else { error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']'); - return 0; } } @@ -201,13 +180,12 @@ public function addStruct($values) return 1; } else { error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']'); - return 0; } } /** - * Returns a string containing "struct", "array" or "scalar" describing the base type of the value. + * Returns a string containing "struct", "array", "scalar" or "undef" describing the base type of the value. * * @return string */ @@ -428,6 +406,8 @@ public function arraymem($key) * Returns the number of members in an xmlrpc value of array type. * * @return integer + * + * @deprecated use count() instead */ public function arraysize() { @@ -438,9 +418,42 @@ public function arraysize() * Returns the number of members in an xmlrpc value of struct type. * * @return integer + * + * @deprecateduse 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 scalars + * - the number of elements for structs and arrays + * + * @return integer + */ + public function count() + { + switch ($this->mytype) { + case 3: + 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() { + return new \ArrayIterator($this->me); + } +} \ No newline at end of file From cc67a43993662a5a3f92801b96b89ee6e3998532 Mon Sep 17 00:00:00 2001 From: gggeek Date: Wed, 17 Jun 2015 23:18:50 +0100 Subject: [PATCH 212/228] Fix ArrayIterator interface implementation; remove usage of arraysize(), structsize(), structreset() and structeach() from the codebase --- debugger/action.php | 8 ++++---- demo/client/agesort.php | 4 +--- demo/client/introspect.php | 12 +++++------- demo/server/proxy.php | 4 ++-- demo/server/server.php | 19 +++++++------------ doc/api_changes_v4.md | 8 ++++---- src/Client.php | 4 ++-- src/Encoder.php | 7 +++---- src/Server.php | 4 ++-- src/Value.php | 17 +++++++++++++++-- 10 files changed, 45 insertions(+), 42 deletions(-) diff --git a/debugger/action.php b/debugger/action.php index 44d8a001..5427f675 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -284,7 +284,7 @@ $v = $response->value(); if ($v->kindOf() == "array") { - $max = $v->arraysize(); + $max = $v->count(); echo "
      MethodDescription
      Method ($max)Description
      Description$desc
      SignatureUnknown 
      \n"; echo "\n\n\n\n"; for ($i = 0; $i < $max; $i++) { @@ -367,7 +367,7 @@ if ($x->kindOf() == "array") { $ret = $x->arraymem(0); echo "OUT: " . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "
      IN: ("; - if ($x->arraysize() > 1) { + if ($x->count() > 1) { for ($k = 1; $k < $x->arraysize(); $k++) { $y = $x->arraymem($k); echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); @@ -389,7 +389,7 @@ $payload .= "\n"; } $alt_payload .= $y->scalarval(); - if ($k < $x->arraysize() - 1) { + if ($k < $x->count() - 1) { $alt_payload .= ';'; echo ", "; } @@ -470,7 +470,7 @@ case 'wrap': $r1 = $resp[0]->value(); $r2 = $resp[1]->value(); - if ($r2->kindOf() != "array" || $r2->arraysize() <= $methodsig) { + if ($r2->kindOf() != "array" || $r2->count() <= $methodsig) { echo "Error: signature unknown\n"; } else { $mdesc = $r1->scalarval(); diff --git a/demo/client/agesort.php b/demo/client/agesort.php index 7f870c63..b21bf89f 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -49,9 +49,7 @@ if (!$resp->faultCode()) { print "The server gave me these results:
      ";
           $value = $resp->value();
      -    $max = $value->arraysize();
      -    for ($i = 0; $i < $max; $i++) {
      -        $struct = $value->arraymem($i);
      +    foreach ($value as $struct) {
               $name = $struct->structmem("name");
               $age = $struct->structmem("age");
               print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
      diff --git a/demo/client/introspect.php b/demo/client/introspect.php
      index e11ac0e5..f25540e6 100644
      --- a/demo/client/introspect.php
      +++ b/demo/client/introspect.php
      @@ -29,8 +29,7 @@ function display_error($r)
           $v = $resp->value();
       
           // Then, retrieve the signature and help text of each available method
      -    for ($i = 0; $i < $v->arraysize(); $i++) {
      -        $methodName = $v->arraymem($i);
      +    foreach ($v as $methodName) {
               print "

      " . $methodName->scalarval() . "

      \n"; // build messages first, add params later $m1 = new PhpXmlRpc\Request('system.methodHelp'); @@ -60,16 +59,15 @@ function display_error($r) // note: using PhpXmlRpc\Encoder::decode() here would lead to cleaner code $val = $rs[1]->value(); if ($val->kindOf() == "array") { - for ($j = 0; $j < $val->arraysize(); $j++) { - $x = $val->arraymem($j); + foreach ($val as $x) { $ret = $x->arraymem(0); print "" . $ret->scalarval() . " " . $methodName->scalarval() . "("; - if ($x->arraysize() > 1) { - for ($k = 1; $k < $x->arraysize(); $k++) { + if ($x->count() > 1) { + for ($k = 1; $k < $x->count(); $k++) { $y = $x->arraymem($k); print $y->scalarval(); - if ($k < $x->arraysize() - 1) { + if ($k < $x->count() - 1) { print ", "; } } diff --git a/demo/server/proxy.php b/demo/server/proxy.php index fa74d3a7..6e791f4f 100644 --- a/demo/server/proxy.php +++ b/demo/server/proxy.php @@ -63,8 +63,8 @@ function forward_request($req) $reqMethod = $encoder->decode($req->getParam(1)); $pars = $req->getParam(2); $req = new PhpXmlRpc\Request($reqMethod); - for ($i = 0; $i < $pars->arraySize(); $i++) { - $req->addParam($pars->arraymem($i)); + foreach ($pars as $par) { + $req->addParam($par); } // add debug info into response we give back to caller diff --git a/demo/server/server.php b/demo/server/server.php index 4b8b8e41..546d2658 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -269,11 +269,9 @@ function echoSixtyFour($req) function bitFlipper($req) { $v = $req->getParam(0); - $sz = $v->arraysize(); $rv = new Value(array(), Value::$xmlrpcArray); - for ($j = 0; $j < $sz; $j++) { - $b = $v->arraymem($j); + foreach ($v as $b) { if ($b->scalarval()) { $rv->addScalar(false, "boolean"); } else { @@ -333,10 +331,9 @@ function ageSorter($req) $v = new Value(); $agar = array(); - $max = $sno->arraysize(); + $max = $sno->count(); PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements"); - for ($i = 0; $i < $max; $i++) { - $rec = $sno->arraymem($i); + foreach ($sno as $rec) { if ($rec->kindOf() != "struct") { $err = "Found non-struct in array at element $i"; break; @@ -465,7 +462,7 @@ function setCookies($req) { $encoder = new PhpXmlRpc\Encoder(); $cookies = $req->getParam(0); - while (list($name, $value) = $cookies->structeach()) { + foreach ($cookies as $name => $value) { $cookieDesc = $encoder->decode($value); setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']); } @@ -487,10 +484,8 @@ function v1_arrayOfStructs($req) { $sno = $req->getParam(0); $numCurly = 0; - for ($i = 0; $i < $sno->arraysize(); $i++) { - $str = $sno->arraymem($i); - $str->structreset(); - while (list($key, $val) = $str->structeach()) { + foreach ($sno as $str) { + foreach ($str as $key => $val) { if ($key == "curly") { $numCurly += $val->scalarval(); } @@ -546,7 +541,7 @@ function v1_manyTypes($req) function v1_moderateSizeArrayCheck($req) { $ar = $req->getParam(0); - $sz = $ar->arraysize(); + $sz = $ar->count(); $first = $ar->arraymem(0); $last = $ar->arraymem($sz - 1); diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md index 2403020c..ea9d4e1f 100644 --- a/doc/api_changes_v4.md +++ b/doc/api_changes_v4.md @@ -52,10 +52,10 @@ In case you had extended the classes of the library and added methods to the sub implementation clashes with the new one if you implemented: -| Class | Method | Notes | -| --------- | ----------- | -------------------------------------- | -| xmlrpcval | count | implements interface Countable | -| xmlrpcval | getIterator | implements interface IteratorAggregate | +| Class | Method | Notes | +| --------- | ----------- | --------------------------------------- | +| xmlrpcval | count | implements interface: Countable | +| xmlrpcval | getIterator | implements interface: IteratorAggregate | Global variables cleanup diff --git a/src/Client.php b/src/Client.php index c0d86c37..3ff4b7c9 100644 --- a/src/Client.php +++ b/src/Client.php @@ -1037,7 +1037,7 @@ private function _try_multicall($reqs, $timeout, $method) if ($rets->kindOf() != 'array') { return false; // bad return type from system.multicall } - $numRets = $rets->arraysize(); + $numRets = $rets->count(); if ($numRets != count($reqs)) { return false; // wrong number of return values. } @@ -1047,7 +1047,7 @@ private function _try_multicall($reqs, $timeout, $method) $val = $rets->arraymem($i); switch ($val->kindOf()) { case 'array': - if ($val->arraysize() != 1) { + if ($val->count() != 1) { return false; // Bad value } // Normal return value diff --git a/src/Encoder.php b/src/Encoder.php index f97096eb..86e518e2 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -71,7 +71,7 @@ public function decode($xmlrpcVal, $options = array()) return $xmlrpcVal->scalarval(); case 'array': - $size = $xmlrpcVal->arraysize(); + $size = $xmlrpcVal->count(); $arr = array(); for ($i = 0; $i < $size; $i++) { $arr[] = $this->decode($xmlrpcVal->arraymem($i), $options); @@ -79,7 +79,6 @@ public function decode($xmlrpcVal, $options = array()) return $arr; case 'struct': - $xmlrpcVal->structreset(); // 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 @@ -88,14 +87,14 @@ public function decode($xmlrpcVal, $options = array()) && class_exists($xmlrpcVal->_php_class) ) { $obj = @new $xmlrpcVal->_php_class(); - while (list($key, $value) = $xmlrpcVal->structeach()) { + foreach ($xmlrpcVal as $key => $value) { $obj->$key = $this->decode($value, $options); } return $obj; } else { $arr = array(); - while (list($key, $value) = $xmlrpcVal->structeach()) { + foreach ($xmlrpcVal as $key => $value) { $arr[$key] = $this->decode($value, $options); } diff --git a/src/Server.php b/src/Server.php index 70b45de3..8540553c 100644 --- a/src/Server.php +++ b/src/Server.php @@ -932,7 +932,7 @@ public static function _xmlrpcs_multicall_do_call($server, $call) if ($params->kindOf() != 'array') { return static::_xmlrpcs_multicall_error('notarray'); } - $numParams = $params->arraysize(); + $numParams = $params->count(); $req = new Request($methName->scalarval()); for ($i = 0; $i < $numParams; $i++) { @@ -999,7 +999,7 @@ public static function _xmlrpcs_multicall($server, $req) // let accept a plain list of php parameters, beside a single xmlrpc msg object if (is_object($req)) { $calls = $req->getParam(0); - $numCalls = $calls->arraysize(); + $numCalls = $calls->count(); for ($i = 0; $i < $numCalls; $i++) { $call = $calls->arraymem($i); $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call); diff --git a/src/Value.php b/src/Value.php index 6e8d7efa..84f04d1a 100644 --- a/src/Value.php +++ b/src/Value.php @@ -344,6 +344,7 @@ public function structmem($key) /** * Reset internal pointer for xmlrpc values of type struct. + * @deprecated iterate directly over the object using foreach instead */ public function structreset() { @@ -354,6 +355,8 @@ public function structreset() * Return next member element for xmlrpc values of type struct. * * @return Value + * + * @deprecated iterate directly over the object using foreach instead */ public function structeach() { @@ -419,7 +422,7 @@ public function arraysize() * * @return integer * - * @deprecateduse count() instead + * @deprecated use count() instead */ public function structsize() { @@ -454,6 +457,16 @@ public function count() * @return ArrayIterator */ public function getIterator() { - return new \ArrayIterator($this->me); + 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(); } } \ No newline at end of file From 51da835d34f41fae0a3dceb795e2af68ba73d28c Mon Sep 17 00:00:00 2001 From: gggeek Date: Sat, 11 Jul 2015 22:48:46 +0100 Subject: [PATCH 213/228] Allow hhvm testsuite failures not to fail the Travis build --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index efe4af90..6033065f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,11 @@ php: - 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 From 70ee98a9c00c79621db919e79082762ace00fe70 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 00:05:34 +0100 Subject: [PATCH 214/228] Try to stabilize recently introduced test --- tests/3LocalhostTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index ec9c5618..9d848ab2 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -205,9 +205,9 @@ public function testExoticCharsetsRequests() '; // these calls will have no charset declaration in either http headers or xml prolog - $v = $this->send(mb_convert_encoding($str, 'UCS-4')); + $v = $this->send(mb_convert_encoding($str, 'UCS-4', 'UTF-8')); $this->assertEquals($sendString, $v->scalarval()); - $v = $this->send(mb_convert_encoding($str, 'UTF-16')); + $v = $this->send(mb_convert_encoding($str, 'UTF-16', 'UTF-8')); $this->assertEquals($sendString, $v->scalarval()); } From 390edf48f54b0f0645cf7882146a9e117a2099c4 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 00:45:23 +0100 Subject: [PATCH 215/228] 2nd try at test stabilization --- tests/3LocalhostTest.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index 9d848ab2..ca2e631c 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -194,7 +194,7 @@ public function testExoticCharsetsRequests() return; } $sendString = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string! - $str = ' + $str = ' examples.stringecho @@ -204,10 +204,9 @@ public function testExoticCharsetsRequests() '; - // these calls will have no charset declaration in either http headers or xml prolog - $v = $this->send(mb_convert_encoding($str, 'UCS-4', 'UTF-8')); + $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, 'UTF-16', 'UTF-8')); + $v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UTF-16', $str), 'UTF-16', 'UTF-8')); $this->assertEquals($sendString, $v->scalarval()); } From cfa2ba8c5cb4c3cd219beb5ff3297099d7bd8fda Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 01:05:27 +0100 Subject: [PATCH 216/228] 3rd time is a charm? --- tests/3LocalhostTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index ca2e631c..d81c0d0a 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -204,10 +204,15 @@ public function testExoticCharsetsRequests() '; + 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 $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 testLatin1Method() From b24b6acde8360a1a0f8ac23b64c19a8dc61cc3ba Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 01:25:54 +0100 Subject: [PATCH 217/228] Try to make hhvm test runs faster --- .travis.yml | 4 ++-- src/Helper/XMLParser.php | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6033065f..7bf9067f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,8 +42,8 @@ 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 + #- cat /var/log/hhvm/error.log + #- if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then php -i; fi after_script: # Upload code-coverage to Scrutinizer diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index d8790c5e..b62bf487 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -446,6 +446,11 @@ public function xmlrpc_dh($parser, $data) * 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 From 22592a7334c7ae95b074c4e967cf18e519284f40 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 11:40:27 +0100 Subject: [PATCH 218/228] Docs and formatting to please Scrutinizer --- pakefile.php | 8 ++++++++ src/Server.php | 2 +- src/Wrapper.php | 9 ++++----- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/pakefile.php b/pakefile.php index 30acead2..74bcba84 100644 --- a/pakefile.php +++ b/pakefile.php @@ -78,11 +78,19 @@ public static function getOpts($args=array(), $cliOpts=array()) //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]; diff --git a/src/Server.php b/src/Server.php index 8540553c..d530fcde 100644 --- a/src/Server.php +++ b/src/Server.php @@ -347,7 +347,7 @@ protected function verifySignature($in, $sigs) /** * Parse http headers received along with xmlrpc request. If needed, inflate request. * - * @return mixed null on success or a Response + * @return mixed Response|null on success or an error Response */ protected function parseRequestHeaders(&$data, &$reqEncoding, &$respEncoding, &$respCompression) { diff --git a/src/Wrapper.php b/src/Wrapper.php index 10aae52e..7a8af5ea 100644 --- a/src/Wrapper.php +++ b/src/Wrapper.php @@ -175,8 +175,7 @@ public function wrapPhpFunction($callable, $newFuncName = '', $extraOptions = ar $plainFuncName = 'Closure'; $exists = true; - } - else { + } else { $plainFuncName = $callable; $exists = function_exists($callable); } @@ -397,7 +396,7 @@ protected function buildMethodSignatures($funcDesc) * @param array $extraOptions * @param string $plainFuncName * @param string $funcDesc - * @return callable + * @return \Closure */ protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc) { @@ -498,7 +497,7 @@ protected function newFunctionName($callable, $newFuncName, $extraOptions) * @param array $extraOptions * @param string $plainFuncName * @param array $funcDesc - * @return array + * @return string * * @todo add a nice phpdoc block in the generated source */ @@ -786,7 +785,7 @@ protected function retrieveMethodHelp($client, $methodName, array $extraOptions * @param string $methodName * @param array $extraOptions * @param string $mSig - * @return callable + * @return \Closure * * @todo should we allow usage of parameter simple_client_copy to mean 'do not clone' in this case? */ From 1ca4b1e930fd6d697d8c6947fca4a02ce5725fa9 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 12:34:53 +0100 Subject: [PATCH 219/228] Allow easier configuration to detect exotic charsets when the received payload does not declare them --- demo/server/server.php | 3 +++ src/Helper/XMLParser.php | 14 +++++++++----- src/PhpXmlRpc.php | 8 +++++++- tests/3LocalhostTest.php | 28 +++++++++++++++++++++++++++- tests/4LocalhostMultiTest.php | 2 +- 5 files changed, 47 insertions(+), 8 deletions(-) diff --git a/demo/server/server.php b/demo/server/server.php index 546d2658..6c36717a 100644 --- a/demo/server/server.php +++ b/demo/server/server.php @@ -956,6 +956,9 @@ function i_whichToolkit($req) 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']; } diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index b62bf487..2bd14e8d 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -454,8 +454,10 @@ public function xmlrpc_dh($parser, $data) * * @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) - * @return string + * @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!!! */ @@ -464,10 +466,10 @@ public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encoding // discussion: see http://www.yale.edu/pclt/encoding/ // 1 - test if encoding is specified in HTTP HEADERS - //Details: + // Details: // LWS: (\13\10)?( |\t)+ // token: (any char but excluded stuff)+ - // quoted string: " (any char but double quotes and cointrol chars)* " + // 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: @@ -507,8 +509,10 @@ public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encoding } // 4 - if mbstring is available, let it do the guesswork - // NB: we favour finding an encoding that is compatible with what we can process if (extension_loaded('mbstring')) { + if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) { + $encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings; + } if ($encodingPrefs) { $enc = mb_detect_encoding($xmlChunk, $encodingPrefs); } else { diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php index 84597e6b..0f39fafe 100644 --- a/src/PhpXmlRpc.php +++ b/src/PhpXmlRpc.php @@ -60,9 +60,15 @@ class PhpXmlRpc // The charset encoding used by the server for received requests and // by the client for received responses when received charset cannot be determined - // or is not supported + // 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. diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index d81c0d0a..bf517216 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -206,13 +206,39 @@ public function testExoticCharsetsRequests() 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 + // (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 = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + 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 testLatin1Method() diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 27eaafc3..2489ae54 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -19,7 +19,7 @@ class LocalhostMultiTest extends LocalhostTest */ function _runtests() { - $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments'); + $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments', 'testExoticCharsetsRequests2'); foreach(get_class_methods('LocalhostTest') as $method) { if(strpos($method, 'test') === 0 && !in_array($method, $unsafeMethods)) From b54394f5070543f05bb994ae8ca8efb3a33fb936 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 13:19:47 +0100 Subject: [PATCH 220/228] Remove code which has been commented out for almost ten years... --- src/Helper/XMLParser.php | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php index 2bd14e8d..d5c71766 100644 --- a/src/Helper/XMLParser.php +++ b/src/Helper/XMLParser.php @@ -318,14 +318,12 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) $this->_xh['value'] = (int)$this->_xh['ac']; } } - //$this->_xh['ac']=''; // is this necessary? $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': - //$this->_xh['ac']=''; // is this necessary? // add to array in the stack the last element built, // unless no VALUE was found if ($this->_xh['vt']) { @@ -336,7 +334,6 @@ public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true) } break; case 'DATA': - //$this->_xh['ac']=''; // is this necessary? $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty break; case 'STRUCT': @@ -402,18 +399,6 @@ public function xmlrpc_cd($parser, $data) // "lookforvalue==3" means that we've found an entire value // and should discard any further character data if ($this->_xh['lv'] != 3) { - // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2 - //if($this->_xh['lv']==1) - //{ - // if we've found text and we're just in a then - // say we've found a value - //$this->_xh['lv']=2; - //} - // we always initialize the accumulator before starting parsing, anyway... - //if(!@isset($this->_xh['ac'])) - //{ - // $this->_xh['ac'] = ''; - //} $this->_xh['ac'] .= $data; } } @@ -428,11 +413,6 @@ 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) == ';') { - // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2 - //if($this->_xh['lv']==1) - //{ - // $this->_xh['lv']=2; - //} $this->_xh['ac'] .= $data; } } From 1c9d202f3d5b51135c2ee91fb4a3795251bdba22 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 13:42:15 +0100 Subject: [PATCH 221/228] Update docs --- NEWS | 9 ++++++--- README.md | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/NEWS b/NEWS index 65d245a5..3b9b53fd 100644 --- a/NEWS +++ b/NEWS @@ -1,4 +1,4 @@ -XML-RPC for PHP version 4.0.0 - 2015/Y/Z +XML-RPC for PHP version 4.0.0 alpha - 2015/Y/Z This release does away with the past and starts a transition to modern-world php. @@ -19,8 +19,11 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. 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 encoding delivered from the library to your code is now utf8. - It can be changed at anytime setting a value to PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding +* 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 diff --git a/README.md b/README.md index 78d216de..304f080f 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ The user manual can be found in the doc/manual directory, in Asciidoc format: [p Release tarballs also contain the HTML and PDF versions, as well as an automatically generated API documentation. +*NB: the user manual has not been updated yet with all the changes made in version 4. Please consider it unreliable!* + Upgrading --------- If you are upgrading from version 3 or earlier, please read the docs in [doc/api_changes_v4.md](doc/api_changes_v4.md) From aa3574e0024996a06e7a19a28301944ae6c65fa1 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 14:07:43 +0100 Subject: [PATCH 222/228] One more character-set related test --- tests/3LocalhostTest.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php index bf517216..0290dbf9 100644 --- a/tests/3LocalhostTest.php +++ b/tests/3LocalhostTest.php @@ -241,6 +241,31 @@ public function testExoticCharsetsRequests2() 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 = ' + + examples.stringecho + + + '.$sendString.' + + +'; + + // 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( From 75234d12e752f022fcf8e5994a0dd8783dec54ab Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 14:17:07 +0100 Subject: [PATCH 223/228] Fix failing tests: charsets mixing up w.keepalives --- tests/4LocalhostMultiTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php index 2489ae54..e5d365a0 100644 --- a/tests/4LocalhostMultiTest.php +++ b/tests/4LocalhostMultiTest.php @@ -19,7 +19,7 @@ class LocalhostMultiTest extends LocalhostTest */ function _runtests() { - $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments', 'testExoticCharsetsRequests2'); + $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)) From b76d21c030bcd510dce8d7e245581842c62ab6b5 Mon Sep 17 00:00:00 2001 From: gggeek Date: Sun, 12 Jul 2015 18:59:39 +0100 Subject: [PATCH 224/228] Implement interface ArrayAccess in the Value class --- NEWS | 1 + debugger/action.php | 19 +++++--- demo/client/agesort.php | 6 ++- demo/client/introspect.php | 6 ++- demo/server/server.php | 6 ++- doc/api_changes_v4.md | 14 ++++-- src/Client.php | 34 ++++++++----- src/Encoder.php | 14 ++++-- src/Request.php | 6 ++- src/Server.php | 26 +++++----- src/Value.php | 98 +++++++++++++++++++++++++++++++++++++- 11 files changed, 180 insertions(+), 50 deletions(-) diff --git a/NEWS b/NEWS index 3b9b53fd..b35859b6 100644 --- a/NEWS +++ b/NEWS @@ -15,6 +15,7 @@ PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade. 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 diff --git a/debugger/action.php b/debugger/action.php index 5427f675..3b014445 100644 --- a/debugger/action.php +++ b/debugger/action.php @@ -287,8 +287,9 @@ $max = $v->count(); echo "
      Method ($max)Description
      \n"; echo "\n\n\n\n"; - for ($i = 0; $i < $max; $i++) { - $rec = $v->arraymem($i); + //for ($i = 0; $i < $max; $i++) { + foreach($v as $i => $rec) { + //$rec = $v->arraymem($i); if ($i % 2) { $class = ' class="oddrow"'; } else { @@ -354,7 +355,8 @@ if ($r2->kindOf() != "array") { echo "\n"; } else { - for ($i = 0; $i < $r2->arraysize(); $i++) { + //for ($i = 0; $i < $r2->arraysize(); $i++) { + foreach($r2 as $i => $x) { $payload = ""; $alt_payload = ""; if ($i + 1 % 2) { @@ -363,13 +365,16 @@ $class = ' class="evenrow"'; } echo "Signature " . ($i + 1) . ""; - $x = $r2->arraymem($i); + //$x = $r2->arraymem($i); if ($x->kindOf() == "array") { - $ret = $x->arraymem(0); + //$ret = $x->arraymem(0); + $ret = $x[0]; echo "OUT: " . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "
      IN: ("; if ($x->count() > 1) { - for ($k = 1; $k < $x->arraysize(); $k++) { - $y = $x->arraymem($k); + foreach($x as $k => $y) { + if ($k == 0) continue; + //for ($k = 1; $k < $x->arraysize(); $k++) { + //$y = $x->arraymem($k); echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($wstype != 1) { $type = $y->scalarval(); diff --git a/demo/client/agesort.php b/demo/client/agesort.php index b21bf89f..0b6aa9a9 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -50,8 +50,10 @@ print "The server gave me these results:
      ";
           $value = $resp->value();
           foreach ($value as $struct) {
      -        $name = $struct->structmem("name");
      -        $age = $struct->structmem("age");
      +        //$name = $struct->structmem("name");
      +        $name = $struct["name"];
      +        //$age = $struct->structmem("age");
      +        $age = $struct["age"];
               print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
           }
       
      diff --git a/demo/client/introspect.php b/demo/client/introspect.php
      index f25540e6..5c359504 100644
      --- a/demo/client/introspect.php
      +++ b/demo/client/introspect.php
      @@ -60,12 +60,14 @@ function display_error($r)
                   $val = $rs[1]->value();
                   if ($val->kindOf() == "array") {
                       foreach ($val as $x) {
      -                    $ret = $x->arraymem(0);
      +                    //$ret = $x->arraymem(0);
      +                    $ret = $x[0];
                           print "" . $ret->scalarval() . " "
                               . $methodName->scalarval() . "(";
                           if ($x->count() > 1) {
                               for ($k = 1; $k < $x->count(); $k++) {
      -                            $y = $x->arraymem($k);
      +                            //$y = $x->arraymem($k);
      +                            $y = $x[$k];
                                   print $y->scalarval();
                                   if ($k < $x->count() - 1) {
                                       print ", ";
      diff --git a/demo/server/server.php b/demo/server/server.php
      index 6c36717a..d060d977 100644
      --- a/demo/server/server.php
      +++ b/demo/server/server.php
      @@ -542,8 +542,10 @@ function v1_moderateSizeArrayCheck($req)
       {
           $ar = $req->getParam(0);
           $sz = $ar->count();
      -    $first = $ar->arraymem(0);
      -    $last = $ar->arraymem($sz - 1);
      +    //$first = $ar->arraymem(0);
      +    $first = $ar[0];
      +    //$last = $ar->arraymem($sz - 1);
      +    $last = $ar[$sz - 1];
       
           return new PhpXmlRpc\Response(new Value($first->scalarval() .
               $last->scalarval(), "string"));
      diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md
      index ea9d4e1f..7b04ecd7 100644
      --- a/doc/api_changes_v4.md
      +++ b/doc/api_changes_v4.md
      @@ -52,10 +52,14 @@ In case you had extended the classes of the library and added methods to the sub
       implementation clashes with the new one if you implemented:
       
       
      -| Class     | Method      | Notes                                   |
      -| --------- | ----------- | --------------------------------------- |
      -| xmlrpcval | count       | implements interface: Countable         |
      -| xmlrpcval | getIterator | implements interface: IteratorAggregate |
      +| 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
      @@ -111,7 +115,7 @@ 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 teh desired value to
      +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
      diff --git a/src/Client.php b/src/Client.php
      index 3ff4b7c9..e46e1d59 100644
      --- a/src/Client.php
      +++ b/src/Client.php
      @@ -422,7 +422,8 @@ public function send($req, $timeout = 0, $method = '')
                       $this->proxyport,
                       $this->proxy_user,
                       $this->proxy_pass,
      -                $this->proxy_authtype
      +                $this->proxy_authtype,
      +                $method
                   );
               }
       
      @@ -442,14 +443,16 @@ public function send($req, $timeout = 0, $method = '')
            * @param string $proxyUsername
            * @param string $proxyPassword
            * @param int $proxyAuthType
      +     * @param string $method
            * @return Response
            */
           protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
                                              $username = '', $password = '', $authType = 1, $proxyHost = '',
      -                                       $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1)
      +                                       $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
      +                                       $method='http')
           {
               if ($port == 0) {
      -            $port = 80;
      +            $port = ( $method === "https" ) ? 443 : 80;
               }
       
               // Only create the payload if it was not created previously
      @@ -498,6 +501,7 @@ protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
                   }
                   $connectServer = $proxyHost;
                   $connectPort = $proxyPort;
      +            $transport = "tcp";
                   $uri = 'http://' . $server . ':' . $port . $this->path;
                   if ($proxyUsername != '') {
                       if ($proxyAuthType != 1) {
      @@ -508,6 +512,8 @@ protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
               } else {
                   $connectServer = $server;
                   $connectPort = $port;
      +            /// @todo if supporting https, we should support all its current options as well: peer name verification etc...
      +            $transport = ( $method === "https" ) ? "tls" : "tcp";
                   $uri = $this->path;
               }
       
      @@ -557,12 +563,12 @@ protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
               }
       
               if ($timeout > 0) {
      -            $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr, $timeout);
      +            $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
               } else {
      -            $fp = @fsockopen($connectServer, $connectPort, $this->errno, $this->errstr);
      +            $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
               }
               if ($fp) {
      -            if ($timeout > 0 && function_exists('stream_set_timeout')) {
      +            if ($timeout > 0) {
                       stream_set_timeout($fp, $timeout);
                   }
               } else {
      @@ -1043,26 +1049,30 @@ private function _try_multicall($reqs, $timeout, $method)
                   }
       
                   $response = array();
      -            for ($i = 0; $i < $numRets; $i++) {
      -                $val = $rets->arraymem($i);
      +            //for ($i = 0; $i < $numRets; $i++) {
      +            foreach($rets as $val) {
      +                //$val = $rets->arraymem($i);
                       switch ($val->kindOf()) {
                           case 'array':
                               if ($val->count() != 1) {
                                   return false;       // Bad value
                               }
                               // Normal return value
      -                        $response[$i] = new Response($val->arraymem(0));
      +                        //$response[] = new Response($val->arraymem(0));
      +                        $response[] = new Response($val[0]);
                               break;
                           case 'struct':
      -                        $code = $val->structmem('faultCode');
      +                        //$code = $val->structmem('faultCode');
      +                        $code = $val['faultCode'];
                               if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
                                   return false;
                               }
      -                        $str = $val->structmem('faultString');
      +                        //$str = $val->structmem('faultString');
      +                        $str = $val['faultString'];
                               if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
                                   return false;
                               }
      -                        $response[$i] = new Response(0, $code->scalarval(), $str->scalarval());
      +                        $response[] = new Response(0, $code->scalarval(), $str->scalarval());
                               break;
                           default:
                               return false;
      diff --git a/src/Encoder.php b/src/Encoder.php
      index 86e518e2..16054184 100644
      --- a/src/Encoder.php
      +++ b/src/Encoder.php
      @@ -71,10 +71,12 @@ public function decode($xmlrpcVal, $options = array())
       
                       return $xmlrpcVal->scalarval();
                   case 'array':
      -                $size = $xmlrpcVal->count();
      +                //$size = $xmlrpcVal->count();
                       $arr = array();
      -                for ($i = 0; $i < $size; $i++) {
      -                    $arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
      +                //for ($i = 0; $i < $size; $i++) {
      +                foreach($xmlrpcVal as $value) {
      +                    //$arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
      +                    $arr[] = $this->decode($value, $options);
                       }
       
                       return $arr;
      @@ -290,8 +292,10 @@ public function decodeXml($xmlVal, $options = array())
                   case 'methodresponse':
                       $v = &$xmlRpcParser->_xh['value'];
                       if ($xmlRpcParser->_xh['isf'] == 1) {
      -                    $vc = $v->structmem('faultCode');
      -                    $vs = $v->structmem('faultString');
      +                    //$vc = $v->structmem('faultCode');
      +                    //$vs = $v->structmem('faultString');
      +                    $vc = $v['faultCode'];
      +                    $vs = $v['faultString'];
                           $r = new Response(0, $vc->scalarval(), $vs->scalarval());
                       } else {
                           $r = new Response($v);
      diff --git a/src/Request.php b/src/Request.php
      index 2c479408..5220968f 100644
      --- a/src/Request.php
      +++ b/src/Request.php
      @@ -330,8 +330,10 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType
                   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->structmem('faultCode');
      -                    $errStr_v = $v->structmem('faultString');
      +                    //$errNo_v = $v->structmem('faultCode');
      +                    //$errStr_v = $v->structmem('faultString');
      +                    $errNo_v = $v['faultCode'];
      +                    $errStr_v = $v['faultString'];
                           $errNo = $errNo_v->scalarval();
                           $errStr = $errStr_v->scalarval();
                       } else {
      diff --git a/src/Server.php b/src/Server.php
      index d530fcde..20ec5a0a 100644
      --- a/src/Server.php
      +++ b/src/Server.php
      @@ -914,7 +914,8 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
               if ($call->kindOf() != 'struct') {
                   return static::_xmlrpcs_multicall_error('notstruct');
               }
      -        $methName = @$call->structmem('methodName');
      +        //$methName = $call->structmem('methodName');
      +        $methName = @$call['methodName'];
               if (!$methName) {
                   return static::_xmlrpcs_multicall_error('nomethod');
               }
      @@ -925,20 +926,22 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
                   return static::_xmlrpcs_multicall_error('recursion');
               }
       
      -        $params = @$call->structmem('params');
      +        //$params = @$call->structmem('params');
      +        $params = @$call['params'];
               if (!$params) {
                   return static::_xmlrpcs_multicall_error('noparams');
               }
               if ($params->kindOf() != 'array') {
                   return static::_xmlrpcs_multicall_error('notarray');
               }
      -        $numParams = $params->count();
      +        //$numParams = $params->count();
       
               $req = new Request($methName->scalarval());
      -        for ($i = 0; $i < $numParams; $i++) {
      -            if (!$req->addParam($params->arraymem($i))) {
      -                $i++;
      -
      +        //for ($i = 0; $i < $numParams; $i++) {
      +        foreach($params as $i => $param) {
      +            //if (!$req->addParam($params->arraymem($i))) {
      +            if (!$req->addParam($param)) {
      +                $i++; // for error message, we count params from 1
                       return static::_xmlrpcs_multicall_error(new Response(0,
                           PhpXmlRpc::$xmlrpcerr['incorrect_params'],
                           PhpXmlRpc::$xmlrpcstr['incorrect_params'] . ": probable xml error in param " . $i));
      @@ -999,10 +1002,11 @@ public static function _xmlrpcs_multicall($server, $req)
               // let accept a plain list of php parameters, beside a single xmlrpc msg object
               if (is_object($req)) {
                   $calls = $req->getParam(0);
      -            $numCalls = $calls->count();
      -            for ($i = 0; $i < $numCalls; $i++) {
      -                $call = $calls->arraymem($i);
      -                $result[$i] = static::_xmlrpcs_multicall_do_call($server, $call);
      +            //$numCalls = $calls->count();
      +            //for ($i = 0; $i < $numCalls; $i++) {
      +            foreach($calls as $call) {
      +                //$call = $calls->arraymem($i);
      +                $result[] = static::_xmlrpcs_multicall_do_call($server, $call);
                   }
               } else {
                   $numCalls = count($req);
      diff --git a/src/Value.php b/src/Value.php
      index 84f04d1a..f0d331af 100644
      --- a/src/Value.php
      +++ b/src/Value.php
      @@ -4,7 +4,7 @@
       
       use PhpXmlRpc\Helper\Charset;
       
      -class Value implements \Countable, \IteratorAggregate
      +class Value implements \Countable, \IteratorAggregate, \ArrayAccess
       {
           public static $xmlrpcI4 = "i4";
           public static $xmlrpcInt = "int";
      @@ -323,6 +323,8 @@ public function serialize($charsetEncoding = '')
            * @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)
           {
      @@ -336,6 +338,8 @@ public function structmemexists($key)
            * @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)
           {
      @@ -399,6 +403,8 @@ public function scalartyp()
            * @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)
           {
      @@ -441,7 +447,7 @@ public function count()
           {
               switch ($this->mytype) {
                   case 3:
      -                count($this->me['struct']);
      +                return count($this->me['struct']);
                   case 2:
                       return count($this->me['array']);
                   case 1:
      @@ -469,4 +475,92 @@ public function getIterator() {
               }
               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,) = 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) = 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");
      +        }
      +    }
       }
      \ No newline at end of file
      
      From aeed2c3d2e362a5a14e69f1e65bd65a192d5eba7 Mon Sep 17 00:00:00 2001
      From: gggeek 
      Date: Sun, 12 Jul 2015 20:23:40 +0100
      Subject: [PATCH 225/228] Add a benchmark to see if the new api for Value is
       slower or faster than the old one
      
      ---
       tests/benchmark.php | 28 ++++++++++++++++++++++++----
       1 file changed, 24 insertions(+), 4 deletions(-)
      
      diff --git a/tests/benchmark.php b/tests/benchmark.php
      index 01087011..43cbc42e 100644
      --- a/tests/benchmark.php
      +++ b/tests/benchmark.php
      @@ -86,7 +86,7 @@ function end_test($test_name, $test_case, $test_result)
           }
       }
       
      -// test 'old style' data encoding vs. 'automatic style' encoding
      +// 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();
      @@ -145,12 +145,32 @@ function end_test($test_name, $test_case, $test_result)
           $response = $dummy->ParseResponse($in, true);
           $value = $response->value();
           $result = array();
      -    for ($k = 0; $k < $value->arraysize(); $k++) {
      +    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();
      -            for ($j = 0; $j < $val->arraysize(); $j++) {
      +            $m = $val->arraysize();
      +            for ($j = 0; $j < $m; $j++) {
                       $data = $val->arraymem($j);
                       $out[$name][] = $data->scalarval();
                   }
      @@ -158,7 +178,7 @@ function end_test($test_name, $test_case, $test_result)
               $result[] = $out;
           }
       }
      -end_test('Data decoding (large array)', 'manual decoding', $result);
      +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++) {
      
      From c672d42d1109a5daa4cf243ba1f0383717e43104 Mon Sep 17 00:00:00 2001
      From: gggeek 
      Date: Sun, 12 Jul 2015 20:24:09 +0100
      Subject: [PATCH 226/228] Add some commented code to remind the user that the
       client can accept many charsets now
      
      ---
       src/Client.php | 10 ++++++++++
       src/Server.php |  3 ++-
       2 files changed, 12 insertions(+), 1 deletion(-)
      
      diff --git a/src/Client.php b/src/Client.php
      index e46e1d59..e91ec51c 100644
      --- a/src/Client.php
      +++ b/src/Client.php
      @@ -137,6 +137,16 @@ function_exists('curl_init') && (($info = curl_version()) &&
               // by default the xml parser can support these 3 charset encodings
               $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
       
      +        // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
      +        // in http://www.iana.org/assignments/character-sets/character-sets.xhtml
      +        // NB: this is disabled to avoid making all the requests sent huge... mbstring supports more than 80 charsets!
      +        /*if (function_exists('mb_list_encodings')) {
      +
      +            $encodings = array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII',
      +                'HTML-ENTITIES', 'Quoted-Printable', '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'));
      +            $this->accepted_charset_encodings = array_unique(array_merge($this->accepted_charset_encodings, $encodings));
      +        }*/
      +
               // initialize user_agent string
               $this->user_agent = PhpXmlRpc::$xmlrpcName . ' ' . PhpXmlRpc::$xmlrpcVersion;
           }
      diff --git a/src/Server.php b/src/Server.php
      index 20ec5a0a..9b4c59df 100644
      --- a/src/Server.php
      +++ b/src/Server.php
      @@ -51,7 +51,8 @@ class Server
           public $allow_system_funcs = true;
           /**
            * List of charset encodings natively accepted for requests.
      -     *  Set at constructor time.
      +     * Set at constructor time.
      +     * UNUSED so far...
            */
           public $accepted_charset_encodings = array();
           /**
      
      From a48c09b3cc49bc7f603cd5b06de74ee2d2878ca4 Mon Sep 17 00:00:00 2001
      From: gggeek 
      Date: Sun, 12 Jul 2015 20:47:00 +0100
      Subject: [PATCH 227/228] Clean up old-API code
      
      ---
       debugger/action.php        |   7 ---
       demo/client/agesort.php    |   2 -
       demo/client/introspect.php |   2 -
       demo/server/server.php     | 113 ++++++++++++++++++++-----------------
       src/Client.php             |   5 --
       src/Encoder.php            |   5 --
       src/Request.php            |   2 -
       src/Server.php             |   8 ---
       8 files changed, 60 insertions(+), 84 deletions(-)
      
      diff --git a/debugger/action.php b/debugger/action.php
      index 3b014445..0d0a649e 100644
      --- a/debugger/action.php
      +++ b/debugger/action.php
      @@ -287,9 +287,7 @@
                               $max = $v->count();
                               echo "
      Method ($max)Description
      SignatureUnknown 
      \n"; echo "\n\n\n\n"; - //for ($i = 0; $i < $max; $i++) { foreach($v as $i => $rec) { - //$rec = $v->arraymem($i); if ($i % 2) { $class = ' class="oddrow"'; } else { @@ -355,7 +353,6 @@ if ($r2->kindOf() != "array") { echo "\n"; } else { - //for ($i = 0; $i < $r2->arraysize(); $i++) { foreach($r2 as $i => $x) { $payload = ""; $alt_payload = ""; @@ -365,16 +362,12 @@ $class = ' class="evenrow"'; } echo "Signature " . ($i + 1) . ""; - //$x = $r2->arraymem($i); if ($x->kindOf() == "array") { - //$ret = $x->arraymem(0); $ret = $x[0]; echo "OUT: " . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "
      IN: ("; if ($x->count() > 1) { foreach($x as $k => $y) { if ($k == 0) continue; - //for ($k = 1; $k < $x->arraysize(); $k++) { - //$y = $x->arraymem($k); echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding); if ($wstype != 1) { $type = $y->scalarval(); diff --git a/demo/client/agesort.php b/demo/client/agesort.php index 0b6aa9a9..90622d21 100644 --- a/demo/client/agesort.php +++ b/demo/client/agesort.php @@ -50,9 +50,7 @@ print "The server gave me these results:
      ";
           $value = $resp->value();
           foreach ($value as $struct) {
      -        //$name = $struct->structmem("name");
               $name = $struct["name"];
      -        //$age = $struct->structmem("age");
               $age = $struct["age"];
               print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
           }
      diff --git a/demo/client/introspect.php b/demo/client/introspect.php
      index 5c359504..7870a94c 100644
      --- a/demo/client/introspect.php
      +++ b/demo/client/introspect.php
      @@ -60,13 +60,11 @@ function display_error($r)
                   $val = $rs[1]->value();
                   if ($val->kindOf() == "array") {
                       foreach ($val as $x) {
      -                    //$ret = $x->arraymem(0);
                           $ret = $x[0];
                           print "" . $ret->scalarval() . " "
                               . $methodName->scalarval() . "(";
                           if ($x->count() > 1) {
                               for ($k = 1; $k < $x->count(); $k++) {
      -                            //$y = $x->arraymem($k);
                                   $y = $x[$k];
                                   print $y->scalarval();
                                   if ($k < $x->count() - 1) {
      diff --git a/demo/server/server.php b/demo/server/server.php
      index d060d977..b18cf467 100644
      --- a/demo/server/server.php
      +++ b/demo/server/server.php
      @@ -43,7 +43,7 @@ class xmlrpcServerMethodsContainer
           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, 'boolean'));
      +        return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcBoolean));
           }
       
           /**
      @@ -222,7 +222,7 @@ function addTwo($req)
           $s = $req->getParam(0);
           $t = $req->getParam(1);
       
      -    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), "int"));
      +    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcInt));
       }
       
       $addtwodouble_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble, Value::$xmlrpcDouble));
      @@ -232,7 +232,7 @@ function addTwoDouble($req)
           $s = $req->getParam(0);
           $t = $req->getParam(1);
       
      -    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), "double"));
      +    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcDouble));
       }
       
       $stringecho_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
      @@ -261,7 +261,7 @@ function echoSixtyFour($req)
           // This is to test that base64 encoding is working as expected
           $incoming = $req->getParam(0);
       
      -    return new PhpXmlRpc\Response(new Value($incoming->scalarval(), "string"));
      +    return new PhpXmlRpc\Response(new Value($incoming->scalarval(), Value::$xmlrpcString));
       }
       
       $bitflipper_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
      @@ -273,9 +273,9 @@ function bitFlipper($req)
       
           foreach ($v as $b) {
               if ($b->scalarval()) {
      -            $rv->addScalar(false, "boolean");
      +            $rv[] = new Value(false, Value::$xmlrpcBoolean);
               } else {
      -            $rv->addScalar(true, "boolean");
      +            $rv[] = new Value(true, Value::$xmlrpcBoolean);
               }
           }
       
      @@ -327,37 +327,40 @@ function ageSorter($req)
           $sno = $req->getParam(0);
           // error string for [if|when] things go wrong
           $err = "";
      -    // create the output value
      -    $v = new Value();
           $agar = array();
       
           $max = $sno->count();
           PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements");
      -    foreach ($sno as $rec) {
      +    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->structmem("name");
      -        $a = $rec->structmem("age");
      +        $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');
      -    $outAr = array();
           while (list($key, $val) = each($agesorter_arr)) {
               // recreate each struct element
      -        $outAr[] = new Value(array("name" => new Value($key),
      -            "age" => new Value($val, "int"),), "struct");
      +        $v[] = new Value(
      +            array(
      +                "name" => new Value($key),
      +                "age" => new Value($val, "int")
      +            ),
      +            Value::$xmlrpcStruct
      +        );
           }
      -    // add this array to the output value
      -    $v->addArray($outAr);
       
           if ($err) {
               return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
      @@ -430,7 +433,7 @@ function mailSend($req)
           if ($err) {
               return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
           } else {
      -        return new PhpXmlRpc\Response(new Value("true", Value::$xmlrpcBoolean));
      +        return new PhpXmlRpc\Response(new Value(true, Value::$xmlrpcBoolean));
           }
       }
       
      @@ -467,7 +470,7 @@ function setCookies($req)
               setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']);
           }
       
      -    return new PhpXmlRpc\Response(new Value(1, 'int'));
      +    return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcInt));
       }
       
       $getcookies_sig = array(array(Value::$xmlrpcStruct));
      @@ -492,7 +495,7 @@ function v1_arrayOfStructs($req)
               }
           }
       
      -    return new PhpXmlRpc\Response(new Value($numCurly, "int"));
      +    return new PhpXmlRpc\Response(new Value($numCurly, Value::$xmlrpcInt));
       }
       
       $v1_easyStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
      @@ -500,12 +503,12 @@ function v1_arrayOfStructs($req)
       function v1_easyStruct($req)
       {
           $sno = $req->getParam(0);
      -    $moe = $sno->structmem("moe");
      -    $larry = $sno->structmem("larry");
      -    $curly = $sno->structmem("curly");
      +    $moe = $sno["moe"];
      +    $larry = $sno["larry"];
      +    $curly = $sno["curly"];
           $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval();
       
      -    return new PhpXmlRpc\Response(new Value($num, "int"));
      +    return new PhpXmlRpc\Response(new Value($num, Value::$xmlrpcInt));
       }
       
       $v1_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct));
      @@ -525,14 +528,16 @@ function v1_echoStruct($req)
       $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),),
      -        "array"
      +    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
           ));
       }
       
      @@ -542,13 +547,11 @@ function v1_moderateSizeArrayCheck($req)
       {
           $ar = $req->getParam(0);
           $sz = $ar->count();
      -    //$first = $ar->arraymem(0);
           $first = $ar[0];
      -    //$last = $ar->arraymem($sz - 1);
           $last = $ar[$sz - 1];
       
           return new PhpXmlRpc\Response(new Value($first->scalarval() .
      -        $last->scalarval(), "string"));
      +        $last->scalarval(), Value::$xmlrpcString));
       }
       
       $v1_simpleStructReturn_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcInt));
      @@ -558,11 +561,13 @@ function v1_simpleStructReturn($req)
           $sno = $req->getParam(0);
           $v = $sno->scalarval();
       
      -    return new PhpXmlRpc\Response(new Value(array(
      -        "times10" => new Value($v * 10, "int"),
      -        "times100" => new Value($v * 100, "int"),
      -        "times1000" => new Value($v * 1000, "int"),),
      -        "struct"
      +    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
           ));
       }
       
      @@ -572,14 +577,14 @@ function v1_nestedStruct($req)
       {
           $sno = $req->getParam(0);
       
      -    $twoK = $sno->structmem("2000");
      -    $april = $twoK->structmem("04");
      -    $fools = $april->structmem("01");
      -    $curly = $fools->structmem("curly");
      -    $larry = $fools->structmem("larry");
      -    $moe = $fools->structmem("moe");
      +    $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(), "int"));
      +    return new PhpXmlRpc\Response(new Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), Value::$xmlrpcInt));
       }
       
       $v1_countTheEntities_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcString));
      @@ -616,13 +621,15 @@ function v1_countTheEntities($req)
               }
           }
       
      -    return new PhpXmlRpc\Response(new Value(array(
      -        "ctLeftAngleBrackets" => new Value($lt, "int"),
      -        "ctRightAngleBrackets" => new Value($gt, "int"),
      -        "ctAmpersands" => new Value($amp, "int"),
      -        "ctApostrophes" => new Value($ap, "int"),
      -        "ctQuotes" => new Value($qu, "int"),),
      -        "struct"
      +    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
           ));
       }
       
      diff --git a/src/Client.php b/src/Client.php
      index e91ec51c..8fce7045 100644
      --- a/src/Client.php
      +++ b/src/Client.php
      @@ -1059,25 +1059,20 @@ private function _try_multicall($reqs, $timeout, $method)
                   }
       
                   $response = array();
      -            //for ($i = 0; $i < $numRets; $i++) {
                   foreach($rets as $val) {
      -                //$val = $rets->arraymem($i);
                       switch ($val->kindOf()) {
                           case 'array':
                               if ($val->count() != 1) {
                                   return false;       // Bad value
                               }
                               // Normal return value
      -                        //$response[] = new Response($val->arraymem(0));
                               $response[] = new Response($val[0]);
                               break;
                           case 'struct':
      -                        //$code = $val->structmem('faultCode');
                               $code = $val['faultCode'];
                               if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
                                   return false;
                               }
      -                        //$str = $val->structmem('faultString');
                               $str = $val['faultString'];
                               if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
                                   return false;
      diff --git a/src/Encoder.php b/src/Encoder.php
      index 16054184..b9bdb08f 100644
      --- a/src/Encoder.php
      +++ b/src/Encoder.php
      @@ -71,11 +71,8 @@ public function decode($xmlrpcVal, $options = array())
       
                       return $xmlrpcVal->scalarval();
                   case 'array':
      -                //$size = $xmlrpcVal->count();
                       $arr = array();
      -                //for ($i = 0; $i < $size; $i++) {
                       foreach($xmlrpcVal as $value) {
      -                    //$arr[] = $this->decode($xmlrpcVal->arraymem($i), $options);
                           $arr[] = $this->decode($value, $options);
                       }
       
      @@ -292,8 +289,6 @@ public function decodeXml($xmlVal, $options = array())
                   case 'methodresponse':
                       $v = &$xmlRpcParser->_xh['value'];
                       if ($xmlRpcParser->_xh['isf'] == 1) {
      -                    //$vc = $v->structmem('faultCode');
      -                    //$vs = $v->structmem('faultString');
                           $vc = $v['faultCode'];
                           $vs = $v['faultString'];
                           $r = new Response(0, $vc->scalarval(), $vs->scalarval());
      diff --git a/src/Request.php b/src/Request.php
      index 5220968f..52a3b975 100644
      --- a/src/Request.php
      +++ b/src/Request.php
      @@ -330,8 +330,6 @@ public function parseResponse($data = '', $headersProcessed = false, $returnType
                   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->structmem('faultCode');
      -                    //$errStr_v = $v->structmem('faultString');
                           $errNo_v = $v['faultCode'];
                           $errStr_v = $v['faultString'];
                           $errNo = $errNo_v->scalarval();
      diff --git a/src/Server.php b/src/Server.php
      index 9b4c59df..07cfb9b4 100644
      --- a/src/Server.php
      +++ b/src/Server.php
      @@ -915,7 +915,6 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
               if ($call->kindOf() != 'struct') {
                   return static::_xmlrpcs_multicall_error('notstruct');
               }
      -        //$methName = $call->structmem('methodName');
               $methName = @$call['methodName'];
               if (!$methName) {
                   return static::_xmlrpcs_multicall_error('nomethod');
      @@ -927,7 +926,6 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
                   return static::_xmlrpcs_multicall_error('recursion');
               }
       
      -        //$params = @$call->structmem('params');
               $params = @$call['params'];
               if (!$params) {
                   return static::_xmlrpcs_multicall_error('noparams');
      @@ -935,12 +933,9 @@ public static function _xmlrpcs_multicall_do_call($server, $call)
               if ($params->kindOf() != 'array') {
                   return static::_xmlrpcs_multicall_error('notarray');
               }
      -        //$numParams = $params->count();
       
               $req = new Request($methName->scalarval());
      -        //for ($i = 0; $i < $numParams; $i++) {
               foreach($params as $i => $param) {
      -            //if (!$req->addParam($params->arraymem($i))) {
                   if (!$req->addParam($param)) {
                       $i++; // for error message, we count params from 1
                       return static::_xmlrpcs_multicall_error(new Response(0,
      @@ -1003,10 +998,7 @@ public static function _xmlrpcs_multicall($server, $req)
               // let accept a plain list of php parameters, beside a single xmlrpc msg object
               if (is_object($req)) {
                   $calls = $req->getParam(0);
      -            //$numCalls = $calls->count();
      -            //for ($i = 0; $i < $numCalls; $i++) {
                   foreach($calls as $call) {
      -                //$call = $calls->arraymem($i);
                       $result[] = static::_xmlrpcs_multicall_do_call($server, $call);
                   }
               } else {
      
      From 5e0dcb083a6c7e1f84fe3dd27bc9cae0d8f5ea7a Mon Sep 17 00:00:00 2001
      From: gggeek 
      Date: Mon, 13 Jul 2015 00:06:29 +0100
      Subject: [PATCH 228/228] Tag 4.0.0-alpha
      
      ---
       NEWS              | 2 +-
       src/PhpXmlRpc.php | 2 +-
       2 files changed, 2 insertions(+), 2 deletions(-)
      
      diff --git a/NEWS b/NEWS
      index b35859b6..48798f39 100644
      --- a/NEWS
      +++ b/NEWS
      @@ -1,4 +1,4 @@
      -XML-RPC for PHP version 4.0.0 alpha - 2015/Y/Z
      +XML-RPC for PHP version 4.0.0 alpha - 2015/7/13
       
       This release does away with the past and starts a transition to modern-world php.
       
      diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php
      index 0f39fafe..086a90a5 100644
      --- a/src/PhpXmlRpc.php
      +++ b/src/PhpXmlRpc.php
      @@ -76,7 +76,7 @@ class PhpXmlRpc
           public static $xmlrpc_internalencoding = "UTF-8";
       
           public static $xmlrpcName = "XML-RPC for PHP";
      -    public static $xmlrpcVersion = "4.0.0.beta";
      +    public static $xmlrpcVersion = "4.0.0.alpha";
       
           // let user errors start at 800
           public static $xmlrpcerruser = 800;
      
      Method ($max)Description
      SignatureUnknown