Merge pull request #27 from gggeek/php53 4.0.0-alpha
authorGaetano Giunta <giunta.gaetano@gmail.com>
Sun, 12 Jul 2015 23:08:24 +0000 (00:08 +0100)
committerGaetano Giunta <giunta.gaetano@gmail.com>
Sun, 12 Jul 2015 23:08:24 +0000 (00:08 +0100)
Move branch php53 into master

121 files changed:
.gitignore
.travis.yml
ChangeLog
INSTALL [deleted file]
INSTALL.md [new file with mode: 0644]
Makefile [deleted file]
NEWS
README [deleted file]
README.md [new file with mode: 0644]
composer.json
debugger/action.php
debugger/common.php
debugger/controller.php
debugger/index.html [deleted file]
debugger/index.php
demo/client/agesort.php
demo/client/client.php [deleted file]
demo/client/comment.php [deleted file]
demo/client/getstatename.php [new file with mode: 0644]
demo/client/introspect.php
demo/client/mail.php
demo/client/proxy.php [new file with mode: 0644]
demo/client/simple_call.php [deleted file]
demo/client/which.php
demo/client/wrap.php
demo/client/zopetest.php [deleted file]
demo/demo1.txt [deleted file]
demo/demo1.xml [new file with mode: 0644]
demo/demo2.txt [deleted file]
demo/demo2.xml [new file with mode: 0644]
demo/demo3.txt [deleted file]
demo/demo3.xml [new file with mode: 0644]
demo/server/discuss.php
demo/server/proxy.php
demo/server/server.php
demo/vardemo.php
doc/.gitignore [deleted file]
doc/Makefile [deleted file]
doc/announce1_0.txt [deleted file]
doc/announce1_1.txt [deleted file]
doc/announce1b6.txt [deleted file]
doc/announce1b7.txt [deleted file]
doc/announce1b8.txt [deleted file]
doc/announce1b9.txt [deleted file]
doc/api_changes_v4.md [new file with mode: 0644]
doc/build/custom.fo.xsl [moved from doc/custom.fo.xsl with 90% similarity]
doc/build/custom.xsl [moved from doc/custom.xsl with 79% similarity]
doc/convert.php [deleted file]
doc/custom.dsl [deleted file]
doc/docbook-css/COPYING [deleted file]
doc/docbook-css/CREDITS [deleted file]
doc/docbook-css/core.css [deleted file]
doc/docbook-css/db-bindings.xml [deleted file]
doc/docbook-css/driver.css [deleted file]
doc/docbook-css/l10n.css [deleted file]
doc/docbook-css/l10n/de.css [deleted file]
doc/docbook-css/l10n/en.css [deleted file]
doc/docbook-css/l10n/es.css [deleted file]
doc/docbook-css/l10n/pl.css [deleted file]
doc/docbook-css/mozilla.css [deleted file]
doc/docbook-css/opera.css [deleted file]
doc/docbook-css/styles.css [deleted file]
doc/docbook-css/tables.css [deleted file]
doc/docbook-css/xmlrpc.css [deleted file]
doc/highlight.php [deleted file]
doc/manual/images/debugger.gif [moved from doc/debugger.gif with 100% similarity]
doc/manual/images/progxmlrpc.s.gif [moved from doc/progxmlrpc.s.gif with 100% similarity]
doc/manual/phpxmlrpc_manual.adoc [new file with mode: 0644]
doc/xmlrpc_php.xml [deleted file]
lib/xmlrpc.inc
lib/xmlrpc_wrappers.inc
lib/xmlrpcs.inc
license.txt [new file with mode: 0644]
pakefile.php [new file with mode: 0644]
src/Autoloader.php [new file with mode: 0644]
src/Client.php [new file with mode: 0644]
src/Encoder.php [new file with mode: 0644]
src/Helper/Charset.php [new file with mode: 0644]
src/Helper/Date.php [new file with mode: 0644]
src/Helper/Http.php [new file with mode: 0644]
src/Helper/Logger.php [new file with mode: 0644]
src/Helper/XMLParser.php [new file with mode: 0644]
src/PhpXmlRpc.php [new file with mode: 0644]
src/Request.php [new file with mode: 0644]
src/Response.php [new file with mode: 0644]
src/Server.php [new file with mode: 0644]
src/Value.php [new file with mode: 0644]
src/Wrapper.php [new file with mode: 0644]
test/PHPUnit/Assert.php [deleted file]
test/PHPUnit/TestCase.php [deleted file]
test/PHPUnit/TestDecorator.php [deleted file]
test/PHPUnit/TestFailure.php [deleted file]
test/PHPUnit/TestListener.php [deleted file]
test/PHPUnit/TestResult.php [deleted file]
test/PHPUnit/TestSuite.php [deleted file]
test/PHPUnit/license.txt [deleted file]
test/benchmark.php [deleted file]
test/parse_args.php [deleted file]
test/phpunit.php [deleted file]
test/testsuite.php [deleted file]
test/verify_compat.php [deleted file]
tests/1ParsingBugsTest.php [new file with mode: 0644]
tests/2InvalidHostTest.php [new file with mode: 0644]
tests/3LocalhostTest.php [new file with mode: 0644]
tests/4LocalhostMultiTest.php [new file with mode: 0644]
tests/5DemofilesTest.php [new file with mode: 0644]
tests/6DebuggerTest.php [new file with mode: 0644]
tests/7ExtraTest.php [new file with mode: 0644]
tests/LocalFileTestCase.php [new file with mode: 0644]
tests/benchmark.php [new file with mode: 0644]
tests/ci/travis/apache_vhost [new file with mode: 0644]
tests/ci/travis/apache_vhost_hhvm [new file with mode: 0644]
tests/ci/travis/privoxy [new file with mode: 0644]
tests/ci/travis/setup_apache.sh [new file with mode: 0755]
tests/ci/travis/setup_apache_hhvm.sh [new file with mode: 0755]
tests/ci/travis/setup_hhvm.sh [new file with mode: 0755]
tests/ci/travis/setup_php_fpm.sh [new file with mode: 0755]
tests/ci/travis/setup_privoxy.sh [new file with mode: 0755]
tests/parse_args.php [new file with mode: 0644]
tests/phpunit_coverage.php [new file with mode: 0644]
tests/verify_compat.php [new file with mode: 0644]

index 8d880ea..1305331 100644 (file)
@@ -1,3 +1,6 @@
 /.idea
 composer.phar
-
+composer.lock
+/vendor/*
+/tests/coverage/*
+/build/*
index ca59cd0..7bf9067 100644 (file)
@@ -1,26 +1,53 @@
 language: php
 
 php:
-  - 5.2
   - 5.3
   - 5.4
   - 5.5
   - 5.6
+  - 7.0
   - hhvm
 
+matrix:
+    # current versions of hhvm do fail one test... see https://github.com/facebook/hhvm/issues/4837
+    allow_failures:
+        - php: hhvm
+
+before_install:
+  # This is mandatory or the 'apt-get install' calls following will fail
+  - sudo apt-get update -qq
+  - sudo apt-get install -y apache2 libapache2-mod-fastcgi
+  - sudo apt-get install -y privoxy
+
 install:
-  # 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...
-  - if [ $TRAVIS_PHP_VERSION != "hhvm" ]; 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
 
-  # 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
+  # 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:
-  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
+  # Travis currently compiles PHP with an oldish cURL/GnuTLS combination;
+  # to make the tests pass when Apache has a bogus SSL cert whe need the full set of options below
+  vendor/bin/phpunit --coverage-clover=coverage.clover tests LOCALSERVER=localhost URI=/demo/server/server.php HTTPSSERVER=localhost HTTPSURI=/demo/server/server.php PROXY=localhost:8080 HTTPSVERIFYHOST=0 HTTPSIGNOREPEER=1 SSLVERSION=3 DEBUG=1
+
+after_failure:
+  # Save as much info as we can to help developers
+  - cat apache_error.log
+  - cat apache_access.log
+  #- cat /var/log/hhvm/error.log
+  #- if [ "$TRAVIS_PHP_VERSION" = "hhvm" ]; then php -i; fi
+
+after_script:
+  # Upload code-coverage to Scrutinizer
+  - if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi
+  - if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi
+  # Upload code-coverage CodeClimate
+  - if [ "$TRAVIS_PHP_VERSION" = "5.6" ]; then CODECLIMATE_REPO_TOKEN=7fa6ee01e345090e059e5e42f3bfbcc8692feb8340396382dd76390a3019ac13 ./vendor/bin/test-reporter --coverage-report=coverage.clover; fi
index d91166c..e032f79 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -2,8 +2,21 @@ NB: All recent commits are available online.
 This file will not be updated further.
 See https://github.com/gggeek/phpxmlrpc/commits/master
 
+2014-05-26 - G. Giunta (giunta.gaetano@gmail.com)
 
-2014-02-3 - G. Giunta (giunta.gaetano@gmail.com)
+       * removed bundled phpunit
+       * 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
+       * 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.
+       * split off each class in its own file
+
+2014-02-03 - G. Giunta (giunta.gaetano@gmail.com)
 
        * bumped up requirements to php 5.1.0
 
diff --git a/INSTALL b/INSTALL
deleted file mode 100644 (file)
index b5eeddf..0000000
--- a/INSTALL
+++ /dev/null
@@ -1,38 +0,0 @@
-XMLRPC for PHP
-
-Requirements
-------------
-
-The following requirements should be met prior to using 'XMLRPC for PHP': 
-. PHP 5.1.0 or later
-. the php "curl" extension is needed if you wish to use SSL or HTTP 1.1 to
-  communicate with remote servers
-
-The php "xmlrpc" native extension is not required, but if it is installed,
-there will be no interference with the operation of this library.
-
-
-Installation instructions
--------------------------
-
-Installation of the library is quite easy:
-
-1. copy the contents of the lib/ folder to any location required by your
-   application (it can be inside the web server root or not).
-
-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
-
-
-Example of php code allowing an application to import 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' );
-
-
-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.
diff --git a/INSTALL.md b/INSTALL.md
new file mode 100644 (file)
index 0000000..f78f8f0
--- /dev/null
@@ -0,0 +1,88 @@
+XMLRPC for PHP
+==============
+
+Requirements
+------------
+
+The following requirements should be met prior to using 'XMLRPC for PHP':
+
+* PHP 5.3.0 or later
+
+* the php "curl" extension is needed if you wish to use SSL or HTTP 1.1 to
+  communicate with remote servers
+
+The php "xmlrpc" native extension is not required, but if it is installed,
+there will be no interference with the operation of this library.
+
+
+Installation instructions
+-------------------------
+
+Installation of the library is quite easy:
+
+1.  Via Composer (highly recommended):
+
+    1.  Install composer if you don't have it already present on your system.
+        Depending on how you install, you may end up with a composer.phar file in your directory.
+        In that case, no worries! Just substitute 'php composer.phar' for 'composer' in the commands below.
+
+    2.  If you're creating a new project, create a new empty directory for it.
+
+    3.  Open a terminal and use Composer to grab the library.
+
+            $ composer require phpxmlrpc/phpxmlrpc:4.0
+
+    4.  Write your code.
+        Once Composer has downloaded the component(s), all you need to do is include the vendor/autoload.php file that
+        was generated by Composer. This file takes care of autoloading all of the libraries so that you can use them
+        immediately, including phpxmlrpc:
+
+            // File example: src/script.php
+
+            // update this to the path to the "vendor/" directory, relative to this file
+            require_once __DIR__.'/../vendor/autoload.php';
+
+            use PhpXmlRpc\Value;
+            use PhpXmlRpc\Request;
+            use PhpXmlRpc\Client;
+
+            $client = new Client('http://some/server');
+            $response = $client->send(new Request('method', array(new Value('parameter'))));
+
+    5.  IMPORTANT! Make sure that the vendor/phpxmlrpc directory is not directly accessible from the internet,
+        as leaving it open to access means that any visitor can trigger execution of php code such as
+        the built-in debugger.
+
+
+2.  Via manual download and autoload configuration
+
+    1.  copy the contents of the src/ folder to any location required by your
+        application (it can be inside the web server root or not).
+
+    2.  configure your app autoloading mechanism so that all classes in the PhpXmlRpc namespace are loaded
+        from that location: any PSR-4 compliant autoloader can do that, if you don't have any there is one
+        available in src/Autoloader.php
+
+    3.  Write your code.
+
+            // File example: script.php
+
+            require_once __DIR__.'my_autoloader.php';
+
+            use PhpXmlRpc\Value;
+            use PhpXmlRpc\Request;
+            use PhpXmlRpc\Client;
+
+            $client = new Client('http://some/server');
+            $response = $client->send(new Request('method', array(new Value('parameter'))));
+
+    5.  IMPORTANT! Make sure that the vendor/phpxmlrpc directory is not directly accessible from the internet,
+        as leaving it open to access means that any visitor can trigger execution of php code such as
+        the built-in debugger.
+
+Tips
+----
+
+Please note that usage of the 'pake' command is not required for installation of the library.
+At this moment it is only useful to build the html and pdf versions of the documentation, and the tarballs
+for distribution of the library.
diff --git a/Makefile b/Makefile
deleted file mode 100644 (file)
index a421f20..0000000
--- a/Makefile
+++ /dev/null
@@ -1,122 +0,0 @@
-# Makefile for phpxmlrpc library\r
-\r
-### USER EDITABLE VARS ###\r
-\r
-# path to PHP executable, preferably CLI version\r
-PHP=/usr/local/bin/php\r
-\r
-# path were xmlrpc lib files will be copied to\r
-PHPINCLUDEDIR=/usr/local/lib/php\r
-\r
-# mkdir is a thorny beast under windows: make sure we can not use the cmd version, running eg. "make MKDIR=mkdir.exe"\r
-MKDIR=mkdir\r
-\r
-#find too\r
-FIND=find\r
-\r
-\r
-#### DO NOT TOUCH FROM HERE ONWARDS ###\r
-\r
-# recover version number from code\r
-# thanks to Firman Pribadi for unix command line help\r
-#   on unix shells lasts char should be \\2/g )\r
-export VERSION=$(shell egrep "\$GLOBALS *\[ *'xmlrpcVersion' *\] *= *'" lib/xmlrpc.inc | sed -r s/"(.*= *' *)([0-9a-zA-Z.-]+)(.*)"/\2/g )\r
-\r
-LIBFILES=lib/xmlrpc.inc lib/xmlrpcs.inc lib/xmlrpc_wrappers.inc\r
-\r
-EXTRAFILES=extras/test.pl \\r
- extras/test.py \\r
- extras/rsakey.pem \\r
- extras/workspace.testPhpServer.fttb\r
-\r
-DEMOFILES=demo/vardemo.php \\r
- demo/demo1.txt \\r
- demo/demo2.txt \\r
- demo/demo3.txt\r
-\r
-DEMOSFILES=demo/server/discuss.php \\r
- demo/server/server.php \\r
- demo/server/proxy.php\r
-\r
-DEMOCFILES=demo/client/agesort.php \\r
- demo/client/client.php \\r
- demo/client/comment.php \\r
- demo/client/introspect.php \\r
- demo/client/mail.php \\r
- demo/client/simple_call.php \\r
- demo/client/which.php \\r
- demo/client/wrap.php \\r
- demo/client/zopetest.php\r
-\r
-TESTFILES=test/testsuite.php \\r
- test/benchmark.php \\r
- test/parse_args.php \\r
- test/phpunit.php \\r
- test/verify_compat.php \\r
- test/PHPUnit/*.php\r
-\r
-INFOFILES=Changelog \\r
- Makefile \\r
- NEWS \\r
- README\r
-\r
-DEBUGGERFILES=debugger/index.php \\r
- debugger/action.php \\r
- debugger/common.php \\r
- debugger/controller.php\r
-\r
-\r
-all: install\r
-\r
-install:\r
-       cp ${LIBFILES} ${PHPINCLUDEDIR}\r
-       @echo Lib files have been copied to ${PHPINCLUDEDIR}\r
-       cd doc && $(MAKE) install\r
-\r
-test:\r
-       cd test && ${PHP} -q testsuite.php\r
-\r
-\r
-### the following targets are to be used for library development ###\r
-\r
-# make tag target: tag existing working copy as release in cvs.\r
-# todo: convert dots in underscore in $VERSION\r
-tag:\r
-       cvs -q tag -p release_${VERSION}\r
-\r
-dist: xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz\r
-\r
-xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz: ${LIBFILES} ${DEBUGGERFILES} ${INFOFILES} ${TESTFILES} ${EXTRAFILES} ${DEMOFILES} ${DEMOSFILES} ${DEMOCFILES}\r
-       @echo ---${VERSION}---\r
-       rm -rf xmlrpc-${VERSION}\r
-       ${MKDIR} xmlrpc-${VERSION}\r
-       ${MKDIR} xmlrpc-${VERSION}/demo\r
-       ${MKDIR} xmlrpc-${VERSION}/demo/client\r
-       ${MKDIR} xmlrpc-${VERSION}/demo/server\r
-       ${MKDIR} xmlrpc-${VERSION}/test\r
-       ${MKDIR} xmlrpc-${VERSION}/test/PHPUnit\r
-       ${MKDIR} xmlrpc-${VERSION}/extras\r
-       ${MKDIR} xmlrpc-${VERSION}/lib\r
-       ${MKDIR} xmlrpc-${VERSION}/debugger\r
-       cp --parents ${DEMOFILES} xmlrpc-${VERSION}\r
-       cp --parents ${DEMOCFILES} xmlrpc-${VERSION}\r
-       cp --parents ${DEMOSFILES} xmlrpc-${VERSION}\r
-       cp --parents ${TESTFILES} xmlrpc-${VERSION}\r
-       cp --parents ${EXTRAFILES} xmlrpc-${VERSION}\r
-       cp --parents ${LIBFILES} xmlrpc-${VERSION}\r
-       cp --parents ${DEBUGGERFILES} xmlrpc-${VERSION}\r
-       cp ${INFOFILES} xmlrpc-${VERSION}\r
-       cd doc && $(MAKE) dist\r
-#   on unix shells last char should be \;\r
-       ${FIND} xmlrpc-${VERSION} -type f ! -name "*.fttb" ! -name "*.pdf" ! -name "*.gif" -exec dos2unix "{}" \;\r
-       -rm xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz\r
-       tar -cvf xmlrpc-${VERSION}.tar xmlrpc-${VERSION}\r
-       gzip xmlrpc-${VERSION}.tar\r
-       zip -r xmlrpc-${VERSION}.zip xmlrpc-${VERSION}\r
-\r
-doc:\r
-       cd doc && $(MAKE) doc\r
-\r
-clean:\r
-       rm -rf xmlrpc-${VERSION} xmlrpc-${VERSION}.zip xmlrpc-${VERSION}.tar.gz\r
-       cd doc && $(MAKE) clean\r
diff --git a/NEWS b/NEWS
index 5d36f47..48798f3 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -1,8 +1,99 @@
-XML-RPC for PHP version 3.0.1 - 201X/Y/Z
+XML-RPC for PHP version 4.0.0 alpha - 2015/7/13
 
-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.
+
+The minimum required php version has been increased to 5.3, even though we strongly urge you to use
+more recent versions.
+
+PLEASE READ CAREFULLY THE NOTES BELOW to insure a smooth upgrade.
+
+* new: introduction of namespaces and full OOP.
+
+  All php classes have been renamed and moved to separate files.
+  Class autoloading can now be done in accord with the PSR-4 standard.
+  All global variables and global functions have been removed.
+  Iterating over xmlrpc value objects is now easier thank to support for ArrayAccess and Traversable interfaces.
+
+  Backward compatibility is maintained via lib/xmlrpc.inc, lib/xmlrpcs.inc and lib/xmlrpc_wrappers.inc.
+  For more details, head on to doc/api_changes_v4.md
+
+* changed: the default character encoding delivered from the library to your code is now utf8.
+  It can be changed at any time setting a value to PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding
+
+* improved: the library now accepts requests/responses sent using other character sets than UTF-8/ISO-8859-1/ASCII.
+  This only works when the mbstring php extension is enabled.
+
+* improved: no need to call anymore $client->setSSLVerifyHost(2) to silence a curl warning when using https
+  with recent curl builds
+
+* improved: the xmlrpcval class now supports the interfaces Countable and IteratorAggregate
+
+* improved: a specific option allows users to decide the version of SSL to use for https calls.
+  This is useful f.e. for the testing suite, when the server target of calls has no proper ssl certificate,
+  and the cURL extension has been compiled with GnuTLS (such as on Travis VMs)
+
+* improved: the function wrap_php_function() now can be used to wrap closures (it is now a method btw)
+
+* improved: all wrap_something() functions now return a closure by default instead of a function name
+
+* improved: debug messages are not html-escaped any more when executing from the command line
+
+* improved: the library is now tested using Travis ( https://travis-ci.org/ ).
+  Tests are executed using all php versions from 5.3 to 7.0 nightly, plus HHVM; code-coverage information
+  is generated using php 5.6 and uploaded to both Code Coverage and Scrutinizer online services
+
+* improved: phpunit is now installed via composer, not bundled anymore
+
+* improved: when phpunit is used to generate code-coverage data, the code executed server-side is accounted for
+
+* improved: the test suite has basic checks for the debugger and demo files
+
+* improved: more tests in the test suite
+
+* fixed: the server would not reset the user-set debug messages between subsequent service() calls
+
+* fixed: the server would not reset previous php error handlers when an exception was thrown by user code and
+  exception_handling set to 2
+
+* fixed: the server would fail to decode a request with ISO-8859-1 payload and character set declaration in the xml
+  prolog only
+
+* fixed: the client would fail to decode a response with ISO-8859-1 payload and character set declaration in the xml
+  prolog only
+
+* fixed: the function decode_xml() would not decode an xml with character set declaration in the xml prolog
+
+* fixed: the client can now successfully call methods using ISO-8859-1 or UTF-8 characters in their name
+
+* fixed: the debugger would fail sending a request with ISO-8859-1 payload (it missed the character set declaration).
+  It would have a hard time coping with ISO-8859-1 in other fields, such as e.g. the remote method name
+
+* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for signatures containing NULL
+  or undefined parameters
+
+* fixed: the debugger would generate a bad payload via the 'load method synopsis' button for methods with multiple
+  signatures
+
+* improved: the debugger is displayed using UTF-8, making it more useful to debug any kind of service
+
+* improved: echo all debug messages even when there are characters in them which php deems to be in a wrong encoding;
+  previously those messages would just disappear (this is visible e.g. in the debugger)
+
+* changed: debug info handling
+    - at debug level 1, the rebuilt php objects are not dumped to screen (server-side already did that)
+    - at debug level 1, curl communication info are not dumped to screen
+    - at debug level 1, the tests echo payloads of failures; at debug level 2 all payloads
+
+* improved: makefiles have been replaced with a php_based pakefile
+
+* improved: the source for the manual is stored in asciidoc format, which can be displayed natively by GitHub
+  with nice html formatting. Also the HTML version generated by hand and bundled in tarballs is much nicer
+  to look at than previous versions
+
+* improved: all php code is now formatted according to the PSR-2 standard
 
 
 XML-RPC for PHP version 3.0.0 - 2014/6/15
@@ -10,7 +101,8 @@ 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.
 
@@ -27,15 +119,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 <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 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
 
@@ -50,13 +146,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
@@ -152,7 +251,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?)
@@ -247,7 +346,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
@@ -324,9 +423,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
@@ -351,3 +450,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
+<xmlrpc@usefulinc.com>.
+
+
+XML-RPC for PHP version 1.0 beta 9
+
+I'm pleased to announce XML-RPC for PHP version 1.0 beta 9. This is
+is largely a bugfix release.
+
+It can be downloaded from http://xmlrpc.usefulinc.com/php.html
+
+Comprehensive documentation is available in the distribution, but you
+can also browse it at http://xmlrpc.usefulinc.com/doc/
+
+Bugfixes in this release include:
+
+ * Fixed string handling bug where characters between a </string>
+   and </value> tag were not ignored.
+
+ * Added in support for PHP's native boolean type.
+
+New features include:
+
+ * new getval() method (experimental only) which has support for
+   recreating nested arrays.
+ * fledgling unit test suite
+ * server.php has support for basic interop test suite
+
+The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
+
+Please test this as hard as possible and report bugs to the XML-RPC PHP
+mailing list, of which more details are available at
+http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
+
+
+XML-RPC for PHP version 1.0 beta 8
+
+I'm pleased to announce XML-RPC for PHP version 1.0 beta 8.
+
+This release fixes several bugs and adds a couple of new helper
+functions. The most critical change in this release is that you can no
+longer print debug info in comments inside a server method -- you must
+now use the new xmlrpc_debugmsg() function.
+
+It can be downloaded from http://xmlrpc.usefulinc.com/php.html
+
+Comprehensive documentation is available in the distribution, but you
+can also browse it at http://xmlrpc.usefulinc.com/doc/
+
+Bugfixes in this release include:
+
+ * fixed whitespace handling in values
+ * correct sending of Content-length from the server
+
+New features include:
+
+ * xmlrpc_debugmsg() method allows sending of debug info in comments in
+   the return payload from a server
+
+ * xmlrpc_encode() and xmlrpc_decode() translate between xmlrpcval
+   objects and PHP language arrays. They aren't suitable for all
+   datatypes, but can speed up coding in simple scenarios. Thanks to Dan
+   Libby for these.
+
+The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
+
+Please test this as hard as possible and report bugs to the XML-RPC PHP
+mailing list, of which more details are available at
+http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
+
+
+XML-RPC for PHP version 1.0 beta 7
+
+I'm pleased to announce XML-RPC for PHP version 1.0 beta 7. This is
+fixes some critical bugs that crept in. If it shows itself to be stable
+then it'll become the 1.0 release.
+
+It can be downloaded from http://xmlrpc.usefulinc.com/php.html
+
+Comprehensive documentation is available in the distribution, but you
+can also browse it at http://xmlrpc.usefulinc.com/doc/
+
+Bugfixes in this release include:
+
+ * Passing of booleans should now work as expected
+ * Dollar signs and backslashes in strings should pass OK
+ * addScalar() now works properly to append to array vals
+
+New features include:
+
+ * Added support for HTTP Basic authorization through the
+   xmlrpc_client::setCredentials method.
+
+ * Added test script and method for verifying correct passing of
+        booleans
+
+The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
+
+Please test this as hard as possible and report bugs to the XML-RPC PHP
+mailing list, of which more details are available at
+http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
+
+
+XML-RPC for PHP version 1.0 beta 6
+
+I'm pleased to announce XML-RPC for PHP version 1.0 beta 6. This is the
+final beta before the 1.0 release.
+
+It can be downloaded from http://xmlrpc.usefulinc.com/php.html
+
+Comprehensive documentation is available in the distribution, but you
+can also browse it at http://xmlrpc.usefulinc.com/doc/
+
+New features in this release include:
+
+ * Perl and Python test programs for the demo server
+ * Proper fault generation on a non-"200 OK" response from a remote host
+ * Bugfixed base64 decoding
+ * ISO8601 helper routines for translation to and from UNIX timestamps
+ * reorganization of code to allow eventual integration of alternative
+   transports
+
+The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
+
+Please test this as hard as possible and report bugs to the XML-RPC PHP
+mailing list, of which more details are available at
+http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
diff --git a/README b/README
deleted file mode 100644 (file)
index 8004813..0000000
--- a/README
+++ /dev/null
@@ -1,15 +0,0 @@
-NAME: XMLRPC for PHP
-
-DESCRIPTION: A php library for building xmlrpc clients and servers
-
-
-
-Installation instructions are in the INSTALL file.
-
-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
-
-The passphrase for the rsakey.pem certificate is 'test'.
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..304f080
--- /dev/null
+++ b/README.md
@@ -0,0 +1,38 @@
+XMLRPC for PHP
+==============
+A php library for building xml-rpc clients and servers.
+
+Installation
+------------
+The recommended way to install this library is using Composer.
+
+Detailed installation instructions are in the [INSTALL.md](INSTALL.md) file, along with system requirements listing.
+
+Documentation
+-------------
+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.
+
+*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)
+
+License
+-------
+Use of this software is subject to the terms in the [license.txt](license.txt) file
+
+SSL-certificate
+---------------
+The passphrase for the rsakey.pem certificate is 'test'.
+
+
+[![License](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/license)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
+[![Latest Stable Version](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/v/stable)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
+[![Total Downloads](https://poser.pugx.org/phpxmlrpc/phpxmlrpc/downloads)](https://packagist.org/packages/phpxmlrpc/phpxmlrpc)
+
+[![Build Status](https://travis-ci.org/gggeek/phpxmlrpc.svg?branch=php53)](https://travis-ci.org/gggeek/phpxmlrpc)
+[![Test Coverage](https://codeclimate.com/github/gggeek/phpxmlrpc/badges/coverage.svg)](https://codeclimate.com/github/gggeek/phpxmlrpc)
+[![Code Coverage](https://scrutinizer-ci.com/g/gggeek/phpxmlrpc/badges/coverage.png?b=php53)](https://scrutinizer-ci.com/g/gggeek/phpxmlrpc/?branch=php53)
index 20c31ec..58c3d40 100644 (file)
@@ -5,9 +5,38 @@
     "homepage": "http://gggeek.github.io/phpxmlrpc/",
     "keywords": [ "xmlrpc", "webservices" ],
     "require": {
-        "php": ">=5.1.0"
+        "php": ">=5.3.0",
+        "ext-xml": "*"
+    },
+    "require-dev": {
+        "phpunit/phpunit": ">=4.0.0",
+        "phpunit/phpunit-selenium": "*",
+        "codeclimate/php-test-reporter": "dev-master",
+        "ext-curl": "*",
+        "ext-mbstring": "*",
+        "indeyets/pake": "~1.99",
+        "phpdocumentor/phpdocumentor": "2.*",
+        "docbook/docbook-xsl": "~1.78"
+    },
+    "suggest": {
+        "ext-curl": "Needed for HTTPS and HTTP 1.1 support, NTLM Auth etc...",
+        "ext-zlib": "Needed for sending compressed requests and receiving compressed responses, if cURL is not available",
+        "ext-mbstring": "Needed to allow reception of requests/responses in character sets other than ASCII,LATIN-1,UTF-8"
     },
     "autoload": {
-        "classmap": [ "lib/xmlrpc.inc", "lib/xmlrpcs.inc" ]
-    }
-}
\ No newline at end of file
+        "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"
+                }
+            }
+        }
+    ]
+}
index f79aba0..0d0a649 100644 (file)
 <?php
 /**
  * @author Gaetano Giunta
- * @copyright (C) 2005-2014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @copyright (C) 2005-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
  *
  * @todo switch params for http compression from 0,1,2 to values to be used directly
  * @todo use ob_start to catch debug info and echo it AFTER method call results?
  * @todo be smarter in creating client stub for proxy/auth cases: only set appropriate property of client obj
  **/
 
+header('Content-Type: text/html; charset=utf-8');
+
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
-  <title>XMLRPC Debugger</title>
-  <meta name="robots" content="index,nofollow" />
-<style type="text/css">
-<!--
-body {border-top: 1px solid gray; padding: 1em; font-family: Verdana, Arial, Helvetica; font-size: 8pt;}
-h3 {font-size: 9.5pt;}
-h2 {font-size: 12pt;}
-.dbginfo {padding: 1em; background-color: #EEEEEE; border: 1px dashed silver; font-family: monospace;}
-#response {padding: 1em; margin-top: 1em; background-color: #DDDDDD; border: 1px solid gray; white-space: pre; font-family: monospace;}
-table {padding: 2px; margin-top: 1em;}
-th {background-color: navy; color: white; padding: 0.5em;}
-td {padding: 0.5em; font-family: monospace;}
-td form {margin: 0;}
-.oddrow {background-color: #EEEEEE;}
-.evidence {color: blue;}
-#phpcode { background-color: #EEEEEE; padding: 1em; margin-top: 1em;}
--->
-</style>
+    <title>XMLRPC Debugger</title>
+    <meta name="robots" content="index,nofollow"/>
+    <style type="text/css">
+        <!--
+        body {
+            border-top: 1px solid gray;
+            padding: 1em;
+            font-family: Verdana, Arial, Helvetica;
+            font-size: 8pt;
+        }
+
+        h3 {
+            font-size: 9.5pt;
+        }
+
+        h2 {
+            font-size: 12pt;
+        }
+
+        .dbginfo {
+            padding: 1em;
+            background-color: #EEEEEE;
+            border: 1px dashed silver;
+            font-family: monospace;
+        }
+
+        #response {
+            padding: 1em;
+            margin-top: 1em;
+            background-color: #DDDDDD;
+            border: 1px solid gray;
+            white-space: pre;
+            font-family: monospace;
+        }
+
+        table {
+            padding: 2px;
+            margin-top: 1em;
+        }
+
+        th {
+            background-color: navy;
+            color: white;
+            padding: 0.5em;
+        }
+
+        td {
+            padding: 0.5em;
+            font-family: monospace;
+        }
+
+        td form {
+            margin: 0;
+        }
+
+        .oddrow {
+            background-color: #EEEEEE;
+        }
+
+        .evidence {
+            color: blue;
+        }
+
+        #phpcode {
+            background-color: #EEEEEE;
+            padding: 1em;
+            margin-top: 1em;
+        }
+
+        -->
+    </style>
 </head>
 <body>
 <?php
 
-  include(dirname(__FILE__).'/common.php');
-  if ($action)
-  {
+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';
-    }
-    else
-    {
-      $clientclass = 'xmlrpc_client';
-      $msgclass = 'xmlrpcmsg';
-      $protoname = 'XMLRPC';
+    if ($timeout) {
+        set_time_limit($timeout + 10);
     }
 
-    if ($port != "")
-    {
-      $client = new $clientclass($path, $host, $port);
-      $server = "$host:$port$path";
+    if ($wstype == 1) {
+        @include 'jsonrpc.inc';
+        if (!class_exists('jsonrpc_client')) {
+            die('Error: to debug the jsonrpc protocol the jsonrpc.inc file is needed');
+        }
+        $clientClass = 'PhpJsRpc\Client';
+        $requestClass = 'PhpJsRpc\Request';
+        $protoName = 'JSONRPC';
     } else {
-      $client = new $clientclass($path, $host);
-      $server = "$host$path";
+        $clientClass = 'PhpXmlRpc\Client';
+        $requestClass = 'PhpXmlRpc\Request';
+        $protoName = 'XMLRPC';
     }
-    if ($protocol == 2)
-    {
-      $server = 'https://'.$server;
+
+    if ($port != "") {
+        $client = new $clientClass($path, $host, $port);
+        $server = "$host:$port$path";
+    } else {
+        $client = new $clientClass($path, $host);
+        $server = "$host$path";
     }
-    else
-    {
-      $server = 'http://'.$server;
+    if ($protocol == 2) {
+        $server = 'https://' . $server;
+    } else {
+        $server = 'http://' . $server;
     }
     if ($proxy != '') {
-      $pproxy = explode(':', $proxy);
-      if (count($pproxy) > 1)
-        $pport = $pproxy[1];
-      else
-        $pport = 8080;
-      $client->setProxy($pproxy[0], $pport, $proxyuser, $proxypwd);
+        $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');
-        }
         // fall thru intentionally
-      case 'describe':
-      case 'wrap':
-        $msg[0] = new $msgclass('system.methodHelp', null, $id);
-        $msg[0]->addparam(new xmlrpcval($method));
-        $msg[1] = new $msgclass('system.methodSignature', null, $id+1);
-        $msg[1]->addparam(new xmlrpcval($method));
-        $actionname = 'Description of method "'.$method.'"';
-        break;
-      case 'list':
-        $msg[0] = new $msgclass('system.listMethods', null, $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);
-        // 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 $requestClass('system.methodHelp', array(), $id);
+            $msg[0]->addparam(new PhpXmlRpc\Value($method));
+            $msg[1] = new $requestClass('system.methodSignature', array(), $id + 1);
+            $msg[1]->addparam(new PhpXmlRpc\Value($method));
+            $actionname = 'Description of method "' . $method . '"';
+            break;
+        case 'list':
+            $msg[0] = new $requestClass('system.listMethods', array(), $id);
+            $actionname = 'List of available methods';
+            break;
+        case 'execute':
+            if (!payload_is_safe($payload)) {
+                die("Tsk tsk tsk, please stop it or I will have to call in the cops!");
             }
-            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 $requestClass($method, array(), $id);
+            // hack! build xml payload by hand
+            if ($wstype == 1) {
+                $msg[0]->payload = "{\n" .
+                    '"method": "' . $method . "\",\n\"params\": [" .
+                    $payload .
+                    "\n],\n\"id\": ";
+                // fix: if user gave an empty string, use NULL, or we'll break json syntax
+                if ($id == "") {
+                    $msg[0]->payload .= "null\n}";
+                } else {
+                    if (is_numeric($id) || $id == 'false' || $id == 'true' || $id == 'null') {
+                        $msg[0]->payload .= "$id\n}";
+                    } else {
+                        $msg[0]->payload .= "\"$id\"\n}";
+                    }
+                }
+            } else {
+                $msg[0]->payload = $msg[0]->xml_header($inputcharset) .
+                    '<methodName>' . $method . "</methodName>\n<params>" .
+                    $payload .
+                    "</params>\n" . $msg[0]->xml_footer();
             }
-        }
-        else
-          $msg[0]->payload = $msg[0]->xml_header() .
-            '<methodName>' . $method . "</methodName>\n<params>" .
-            $payload .
-            "</params>\n" . $msg[0]->xml_footer();
-        $actionname = 'Execution of method '.$method;
-        break;
-      default: // give a warning
-        $actionname = '[ERROR: unknown action] "'.$action.'"';
+            $actionname = 'Execution of method ' . $method;
+            break;
+        default: // give a warning
+            $actionname = '[ERROR: unknown action] "' . $action . '"';
     }
 
     // Before calling execute, echo out brief description of action taken + date and time ???
     // this gives good user feedback for long-running methods...
-    echo '<h2>'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server)." ...</h2>\n";
+    echo '<h2>' . htmlspecialchars($actionname, ENT_COMPAT, $inputcharset) . ' on server ' . htmlspecialchars($server, ENT_COMPAT, $inputcharset) . " ...</h2>\n";
     flush();
 
     $response = null;
     // execute method(s)
-    if ($debug)
-      echo '<div class="dbginfo"><h2>Debug info:</h2>';  /// @todo use ob_start instead
+    if ($debug) {
+        echo '<div class="dbginfo"><h2>Debug info:</h2>';
+    }  /// @todo use ob_start instead
     $resp = array();
-    $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;
+    $time = microtime(true);
+    foreach ($msg as $message) {
+        // catch errors: for older xmlrpc libs, send does not return by ref
+        @$response = $client->send($message, $timeout, $httpprotocol);
+        $resp[] = $response;
+        if (!$response || $response->faultCode()) {
+            break;
+        }
     }
-    $mtime = explode(' ',microtime());
-    $time = (float)$mtime[0] + (float)$mtime[1] - $time;
-    if ($debug)
-      echo "</div>\n";
-
-    if ($response)
-    {
-
-    if ($response->faultCode())
-    {
-      // call failed! echo out error msg!
-      //echo '<h2>'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'</h2>';
-      echo "<h3>$protoname call FAILED!</h3>\n";
-      echo "<p>Fault code: [" . htmlspecialchars($response->faultCode()) .
-        "] Reason: '" . htmlspecialchars($response->faultString()) . "'</p>\n";
-      echo (strftime("%d/%b/%Y:%H:%M:%S\n"));
+    $time = microtime(true) - $time;
+    if ($debug) {
+        echo "</div>\n";
     }
-    else
-    {
-      // call succeeded: parse results
-      //echo '<h2>'.htmlspecialchars($actionname).' on server '.htmlspecialchars($server).'</h2>';
-      printf ("<h3>%s call(s) OK (%.2f secs.)</h3>\n", $protoname, $time);
-      echo (strftime("%d/%b/%Y:%H:%M:%S\n"));
-
-      switch ($action)
-      {
-        case 'list':
-
-        $v = $response->value();
-        if ($v->kindOf()=="array")
-        {
-          $max = $v->arraysize();
-          echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
-          echo "<thead>\n<tr><th>Method</th><th>Description</th></tr>\n</thead>\n<tbody>\n";
-          for($i=0; $i < $max; $i++)
-          {
-            $rec = $v->arraymem($i);
-            if ($i%2) $class=' class="oddrow"'; else $class = ' class="evenrow"';
-            echo ("<tr><td$class>".htmlspecialchars($rec->scalarval())."</td><td$class><form action=\"controller.php\" method=\"get\" target=\"frmcontroller\">".
-              "<input type=\"hidden\" name=\"host\" value=\"".htmlspecialchars($host)."\" />".
-              "<input type=\"hidden\" name=\"port\" value=\"".htmlspecialchars($port)."\" />".
-              "<input type=\"hidden\" name=\"path\" value=\"".htmlspecialchars($path)."\" />".
-              "<input type=\"hidden\" name=\"id\" value=\"".htmlspecialchars($id)."\" />".
-              "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />".
-              "<input type=\"hidden\" name=\"username\" value=\"".htmlspecialchars($username)."\" />".
-              "<input type=\"hidden\" name=\"password\" value=\"".htmlspecialchars($password)."\" />".
-              "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />".
-              "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />".
-              "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />".
-              "<input type=\"hidden\" name=\"cainfo\" value=\"".htmlspecialchars($cainfo)."\" />".
-              "<input type=\"hidden\" name=\"proxy\" value=\"".htmlspecialchars($proxy)."\" />".
-              "<input type=\"hidden\" name=\"proxyuser\" value=\"".htmlspecialchars($proxyuser)."\" />".
-              "<input type=\"hidden\" name=\"proxypwd\" value=\"".htmlspecialchars($proxypwd)."\" />".
-              "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />".
-              "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />".
-              "<input type=\"hidden\" name=\"clientcookies\" value=\"".htmlspecialchars($clientcookies)."\" />".
-              "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />".
-              "<input type=\"hidden\" name=\"timeout\" value=\"".htmlspecialchars($timeout)."\" />".
-              "<input type=\"hidden\" name=\"method\" value=\"".$rec->scalarval()."\" />".
-              "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />".
-              "<input type=\"hidden\" name=\"action\" value=\"describe\" />".
-              "<input type=\"hidden\" name=\"run\" value=\"now\" />".
-              "<input type=\"submit\" value=\"Describe\" /></form></td>");
-            //echo("</tr>\n");
-
-            // generate lo scheletro per il method payload per eventuali test
-            //$methodpayload="<methodCall>\n<methodName>".$rec->scalarval()."</methodName>\n<params>\n<param><value></value></param>\n</params>\n</methodCall>";
-
-            /*echo ("<form action=\"{$_SERVER['PHP_SELF']}\" method=\"get\"><td>".
-              "<input type=\"hidden\" name=\"host\" value=\"$host\" />".
-              "<input type=\"hidden\" name=\"port\" value=\"$port\" />".
-              "<input type=\"hidden\" name=\"path\" value=\"$path\" />".
-              "<input type=\"hidden\" name=\"method\" value=\"".$rec->scalarval()."\" />".
-              "<input type=\"hidden\" name=\"methodpayload\" value=\"$payload\" />".
-              "<input type=\"hidden\" name=\"action\" value=\"execute\" />".
-              "<input type=\"submit\" value=\"Test\" /></td></form>");*/
-            echo("</tr>\n");
-          }
-          echo "</tbody>\n</table>";
-        }
-          break;
 
-        case 'describe':
-
-        $r1 = $resp[0]->value();
-        $r2 = $resp[1]->value();
-
-        echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
-        echo "<thead>\n<tr><th>Method</th><th>".htmlspecialchars($method)."</th><th>&nbsp;</th><th>&nbsp;</th></tr>\n</thead>\n<tbody>\n";
-        $desc = htmlspecialchars($r1->scalarval());
-        if ($desc == "")
-          $desc = "-";
-        echo "<tr><td class=\"evenrow\">Description</td><td colspan=\"3\" class=\"evenrow\">$desc</td></tr>\n";
-        $payload="";
-        $alt_payload="";
-        if ($r2->kindOf()!="array")
-          echo "<tr><td class=\"oddrow\">Signature</td><td class=\"oddrow\">Unknown</td><td class=\"oddrow\">&nbsp;</td></tr>\n";
-        else
-        {
-          for($i=0; $i < $r2->arraysize(); $i++)
-          {
-            if ($i+1%2) $class=' class="oddrow"'; else $class = ' class="evenrow"';
-            echo "<tr><td$class>Signature&nbsp;".($i+1)."</td><td$class>";
-            $x = $r2->arraymem($i);
-            if ($x->kindOf()=="array")
-            {
-              $ret = $x->arraymem(0);
-              echo "<code>OUT:&nbsp;" . htmlspecialchars($ret->scalarval()) . "<br />IN: (";
-              if ($x->arraysize() > 1)
-              {
-                for($k = 1; $k < $x->arraysize(); $k++)
-                {
-                  $y = $x->arraymem($k);
-                  echo $y->scalarval();
-                  if ($wstype != 1)
-                  {
-                    $payload = $payload . '<param><value><'.htmlspecialchars($y->scalarval()).'></'.htmlspecialchars($y->scalarval())."></value></param>\n";
-                  }
-                  $alt_payload .= $y->scalarval();
-                  if ($k < $x->arraysize()-1)
-                  {
-                    $alt_payload .= ';';
-                    echo ", ";
-                  }
-                }
-              }
-              echo ")</code>";
+    if ($response) {
+        if ($response->faultCode()) {
+            // call failed! echo out error msg!
+            //echo '<h2>'.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'</h2>';
+            echo "<h3>$protoName call FAILED!</h3>\n";
+            echo "<p>Fault code: [" . htmlspecialchars($response->faultCode(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
+                "] Reason: '" . htmlspecialchars($response->faultString(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "'</p>\n";
+            echo(strftime("%d/%b/%Y:%H:%M:%S\n"));
+        } else {
+            // call succeeded: parse results
+            //echo '<h2>'.htmlspecialchars($actionname, ENT_COMPAT, $inputcharset).' on server '.htmlspecialchars($server, ENT_COMPAT, $inputcharset).'</h2>';
+            printf("<h3>%s call(s) OK (%.2f secs.)</h3>\n", $protoName, $time);
+            echo(strftime("%d/%b/%Y:%H:%M:%S\n"));
+
+            switch ($action) {
+                case 'list':
+
+                    $v = $response->value();
+                    if ($v->kindOf() == "array") {
+                        $max = $v->count();
+                        echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
+                        echo "<thead>\n<tr><th>Method ($max)</th><th>Description</th></tr>\n</thead>\n<tbody>\n";
+                        foreach($v as $i => $rec) {
+                            if ($i % 2) {
+                                $class = ' class="oddrow"';
+                            } else {
+                                $class = ' class="evenrow"';
+                            }
+                            echo("<tr><td$class>" . htmlspecialchars($rec->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "</td><td$class><form action=\"controller.php\" method=\"get\" target=\"frmcontroller\">" .
+                                "<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
+                                "<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
+                                "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
+                                "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
+                                "<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
+                                "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
+                                "<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
+                                "<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($rec->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "\" />" .
+                                "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
+                                "<input type=\"hidden\" name=\"action\" value=\"describe\" />" .
+                                "<input type=\"hidden\" name=\"run\" value=\"now\" />" .
+                                "<input type=\"submit\" value=\"Describe\" /></form></td>");
+                            //echo("</tr>\n");
+
+                            // generate the skeleton for method payload per possible tests
+                            //$methodpayload="<methodCall>\n<methodName>".$rec->scalarval()."</methodName>\n<params>\n<param><value></value></param>\n</params>\n</methodCall>";
+
+                            /*echo ("<form action=\"{$_SERVER['PHP_SELF']}\" method=\"get\"><td>".
+                              "<input type=\"hidden\" name=\"host\" value=\"$host\" />".
+                              "<input type=\"hidden\" name=\"port\" value=\"$port\" />".
+                              "<input type=\"hidden\" name=\"path\" value=\"$path\" />".
+                              "<input type=\"hidden\" name=\"method\" value=\"".$rec->scalarval()."\" />".
+                              "<input type=\"hidden\" name=\"methodpayload\" value=\"$payload\" />".
+                              "<input type=\"hidden\" name=\"action\" value=\"execute\" />".
+                              "<input type=\"submit\" value=\"Test\" /></td></form>");*/
+                            echo("</tr>\n");
+                        }
+                        echo "</tbody>\n</table>";
+                    }
+                    break;
+
+                case 'describe':
+
+                    $r1 = $resp[0]->value();
+                    $r2 = $resp[1]->value();
+
+                    echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";
+                    echo "<thead>\n<tr><th>Method</th><th>" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "</th><th>&nbsp;</th><th>&nbsp;</th></tr>\n</thead>\n<tbody>\n";
+                    $desc = htmlspecialchars($r1->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding);
+                    if ($desc == "") {
+                        $desc = "-";
+                    }
+                    echo "<tr><td class=\"evenrow\">Description</td><td colspan=\"3\" class=\"evenrow\">$desc</td></tr>\n";
+
+                    if ($r2->kindOf() != "array") {
+                        echo "<tr><td class=\"oddrow\">Signature</td><td class=\"oddrow\">Unknown</td><td class=\"oddrow\">&nbsp;</td></tr>\n";
+                    } else {
+                        foreach($r2 as $i => $x) {
+                            $payload = "";
+                            $alt_payload = "";
+                            if ($i + 1 % 2) {
+                                $class = ' class="oddrow"';
+                            } else {
+                                $class = ' class="evenrow"';
+                            }
+                            echo "<tr><td$class>Signature&nbsp;" . ($i + 1) . "</td><td$class>";
+                            if ($x->kindOf() == "array") {
+                                $ret = $x[0];
+                                echo "<code>OUT:&nbsp;" . htmlspecialchars($ret->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) . "<br />IN: (";
+                                if ($x->count() > 1) {
+                                    foreach($x as $k => $y) {
+                                        if ($k == 0) continue;
+                                        echo htmlspecialchars($y->scalarval(), ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding);
+                                        if ($wstype != 1) {
+                                            $type = $y->scalarval();
+                                            $payload .= '<param><value>';
+                                            switch($type) {
+                                                case 'undefined':
+                                                    break;
+                                                case 'null';
+                                                    $type = 'nil';
+                                                    // fall thru intentionally
+                                                default:
+                                                    $payload .= '<' .
+                                                        htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
+                                                        '></' . htmlspecialchars($type, ENT_COMPAT, \PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding) .
+                                                        '>';
+                                            }
+                                            $payload .= "</value></param>\n";
+                                        }
+                                        $alt_payload .= $y->scalarval();
+                                        if ($k < $x->count() - 1) {
+                                            $alt_payload .= ';';
+                                            echo ", ";
+                                        }
+                                    }
+                                }
+                                echo ")</code>";
+                            } else {
+                                echo 'Unknown';
+                            }
+                            echo '</td>';
+                            // button to test this method
+                            //$payload="<methodCall>\n<methodName>$method</methodName>\n<params>\n$payload</params>\n</methodCall>";
+                            echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">" .
+                                "<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
+                                "<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
+                                "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
+                                "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
+                                "<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
+                                "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
+                                "<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
+                                "<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"methodpayload\" value=\"" . htmlspecialchars($payload, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"altmethodpayload\" value=\"" . htmlspecialchars($alt_payload, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
+                                "<input type=\"hidden\" name=\"action\" value=\"execute\" />";
+                            if ($wstype != 1) {
+                                echo "<input type=\"submit\" value=\"Load method synopsis\" />";
+                            }
+                            echo "</form></td>\n";
+
+                            echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">" .
+                                "<input type=\"hidden\" name=\"host\" value=\"" . htmlspecialchars($host, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"port\" value=\"" . htmlspecialchars($port, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"path\" value=\"" . htmlspecialchars($path, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"id\" value=\"" . htmlspecialchars($id, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />" .
+                                "<input type=\"hidden\" name=\"username\" value=\"" . htmlspecialchars($username, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"password\" value=\"" . htmlspecialchars($password, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />" .
+                                "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />" .
+                                "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />" .
+                                "<input type=\"hidden\" name=\"cainfo\" value=\"" . htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxy\" value=\"" . htmlspecialchars($proxy, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxyuser\" value=\"" . htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"proxypwd\" value=\"" . htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />" .
+                                "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />" .
+                                "<input type=\"hidden\" name=\"clientcookies\" value=\"" . htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />" .
+                                "<input type=\"hidden\" name=\"timeout\" value=\"" . htmlspecialchars($timeout, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"method\" value=\"" . htmlspecialchars($method, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"methodsig\" value=\"" . $i . "\" />" .
+                                "<input type=\"hidden\" name=\"methodpayload\" value=\"" . htmlspecialchars($payload, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"altmethodpayload\" value=\"" . htmlspecialchars($alt_payload, ENT_COMPAT, $inputcharset) . "\" />" .
+                                "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />" .
+                                "<input type=\"hidden\" name=\"run\" value=\"now\" />" .
+                                "<input type=\"hidden\" name=\"action\" value=\"wrap\" />" .
+                                "<input type=\"submit\" value=\"Generate method call stub code\" />";
+                            echo "</form></td></tr>\n";
+                        }
+                    }
+                    echo "</tbody>\n</table>";
+
+                    break;
+
+                case 'wrap':
+                    $r1 = $resp[0]->value();
+                    $r2 = $resp[1]->value();
+                    if ($r2->kindOf() != "array" || $r2->count() <= $methodsig) {
+                        echo "Error: signature unknown\n";
+                    } else {
+                        $mdesc = $r1->scalarval();
+                        $encoder = new PhpXmlRpc\Encoder();
+                        $msig = $encoder->decode($r2);
+                        $msig = $msig[$methodsig];
+                        $proto = $protocol == 2 ? 'https' : $protocol == 1 ? 'http11' : '';
+                        if ($proxy == '' && $username == '' && !$requestcompression && !$responsecompression &&
+                            $clientcookies == ''
+                        ) {
+                            $opts = 1; // simple client copy in stub code
+                        } else {
+                            $opts = 0; // complete client copy in stub code
+                        }
+                        if ($wstype == 1) {
+                            $prefix = 'jsonrpc';
+                        } else {
+                            $prefix = 'xmlrpc';
+                        }
+                        $wrapper = new PhpXmlRpc\Wrapper();
+                        $code = $wrapper->buildWrapMethodSource($client, $method, array('timeout' => $timeout, 'protocol' => $proto, 'simple_client_copy' => $opts, 'prefix' => $prefix), str_replace('.', '_', $prefix . '_' . $method), $msig, $mdesc);
+                        //if ($code)
+                        //{
+                        echo "<div id=\"phpcode\">\n";
+                        highlight_string("<?php\n" . $code['docstring'] . $code['source'] . '?>');
+                        echo "\n</div>";
+                        //}
+                        //else
+                        //{
+                        //  echo 'Error while building php code stub...';
+                    }
+
+                    break;
+
+                case 'execute':
+                    echo '<div id="response"><h2>Response:</h2>' . htmlspecialchars($response->serialize()) . '</div>';
+                    break;
+
+                default: // give a warning
             }
-            else
-            {
-              echo 'Unknown';
-            }
-            echo '</td>';
-            //bottone per testare questo metodo
-            //$payload="<methodCall>\n<methodName>$method</methodName>\n<params>\n$payload</params>\n</methodCall>";
-            echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">".
-            "<input type=\"hidden\" name=\"host\" value=\"".htmlspecialchars($host)."\" />".
-            "<input type=\"hidden\" name=\"port\" value=\"".htmlspecialchars($port)."\" />".
-            "<input type=\"hidden\" name=\"path\" value=\"".htmlspecialchars($path)."\" />".
-            "<input type=\"hidden\" name=\"id\" value=\"".htmlspecialchars($id)."\" />".
-            "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />".
-            "<input type=\"hidden\" name=\"username\" value=\"".htmlspecialchars($username)."\" />".
-            "<input type=\"hidden\" name=\"password\" value=\"".htmlspecialchars($password)."\" />".
-            "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />".
-            "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />".
-            "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />".
-            "<input type=\"hidden\" name=\"cainfo\" value=\"".htmlspecialchars($cainfo)."\" />".
-            "<input type=\"hidden\" name=\"proxy\" value=\"".htmlspecialchars($proxy)."\" />".
-            "<input type=\"hidden\" name=\"proxyuser\" value=\"".htmlspecialchars($proxyuser)."\" />".
-            "<input type=\"hidden\" name=\"proxypwd\" value=\"".htmlspecialchars($proxypwd)."\" />".
-            "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />".
-            "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />".
-            "<input type=\"hidden\" name=\"clientcookies\" value=\"".htmlspecialchars($clientcookies)."\" />".
-            "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />".
-            "<input type=\"hidden\" name=\"timeout\" value=\"".htmlspecialchars($timeout)."\" />".
-            "<input type=\"hidden\" name=\"method\" value=\"".htmlspecialchars($method)."\" />".
-            "<input type=\"hidden\" name=\"methodpayload\" value=\"".htmlspecialchars($payload)."\" />".
-            "<input type=\"hidden\" name=\"altmethodpayload\" value=\"".htmlspecialchars($alt_payload)."\" />".
-            "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />".
-            "<input type=\"hidden\" name=\"action\" value=\"execute\" />";
-            if ($wstype != 1)
-              echo "<input type=\"submit\" value=\"Load method synopsis\" />";
-            echo "</form></td>\n";
-
-            echo "<td$class><form action=\"controller.php\" target=\"frmcontroller\" method=\"get\">".
-            "<input type=\"hidden\" name=\"host\" value=\"".htmlspecialchars($host)."\" />".
-            "<input type=\"hidden\" name=\"port\" value=\"".htmlspecialchars($port)."\" />".
-            "<input type=\"hidden\" name=\"path\" value=\"".htmlspecialchars($path)."\" />".
-            "<input type=\"hidden\" name=\"id\" value=\"".htmlspecialchars($id)."\" />".
-            "<input type=\"hidden\" name=\"debug\" value=\"$debug\" />".
-            "<input type=\"hidden\" name=\"username\" value=\"".htmlspecialchars($username)."\" />".
-            "<input type=\"hidden\" name=\"password\" value=\"".htmlspecialchars($password)."\" />".
-            "<input type=\"hidden\" name=\"authtype\" value=\"$authtype\" />".
-            "<input type=\"hidden\" name=\"verifyhost\" value=\"$verifyhost\" />".
-            "<input type=\"hidden\" name=\"verifypeer\" value=\"$verifypeer\" />".
-            "<input type=\"hidden\" name=\"cainfo\" value=\"".htmlspecialchars($cainfo)."\" />".
-            "<input type=\"hidden\" name=\"proxy\" value=\"".htmlspecialchars($proxy)."\" />".
-            "<input type=\"hidden\" name=\"proxyuser\" value=\"".htmlspecialchars($proxyuser)."\" />".
-            "<input type=\"hidden\" name=\"proxypwd\" value=\"".htmlspecialchars($proxypwd)."\" />".
-            "<input type=\"hidden\" name=\"responsecompression\" value=\"$responsecompression\" />".
-            "<input type=\"hidden\" name=\"requestcompression\" value=\"$requestcompression\" />".
-            "<input type=\"hidden\" name=\"clientcookies\" value=\"".htmlspecialchars($clientcookies)."\" />".
-            "<input type=\"hidden\" name=\"protocol\" value=\"$protocol\" />".
-            "<input type=\"hidden\" name=\"timeout\" value=\"".htmlspecialchars($timeout)."\" />".
-            "<input type=\"hidden\" name=\"method\" value=\"".htmlspecialchars($method)."\" />".
-            "<input type=\"hidden\" name=\"methodsig\" value=\"".$i."\" />".
-            "<input type=\"hidden\" name=\"methodpayload\" value=\"".htmlspecialchars($payload)."\" />".
-            "<input type=\"hidden\" name=\"altmethodpayload\" value=\"".htmlspecialchars($alt_payload)."\" />".
-            "<input type=\"hidden\" name=\"wstype\" value=\"$wstype\" />".
-            "<input type=\"hidden\" name=\"run\" value=\"now\" />".
-            "<input type=\"hidden\" name=\"action\" value=\"wrap\" />".
-            "<input type=\"submit\" value=\"Generate method call stub code\" />";
-            echo "</form></td></tr>\n";
-
-          }
-        }
-        echo "</tbody>\n</table>";
-
-          break;
-
-        case 'wrap':
-          $r1 = $resp[0]->value();
-          $r2 = $resp[1]->value();
-          if ($r2->kindOf()!="array" || $r2->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 "<div id=\"phpcode\">\n";
-            highlight_string("<?php\n".$code['docstring'].$code['source'].'?>');
-            echo "\n</div>";
-          //}
-          //else
-          //{
-          //  echo 'Error while building php code stub...';
-          }
-
-          break;
-
-        case 'execute':
-          echo '<div id="response"><h2>Response:</h2>'.htmlspecialchars($response->serialize()).'</div>';
-          break;
-
-        default: // give a warning
-      }
-    } // if !$response->faultCode()
+        } // if !$response->faultCode()
     } // if $response
-  }
-  else
-  {
+} else {
     // no action taken yet: give some instructions on debugger usage
-?>
-
-<h3>Instructions on usage of the debugger:</h3>
-<ol>
-<li>Run a 'list available methods' action against desired server</li>
-<li>If list of methods appears, click on 'describe method' for desired method</li>
-<li>To run method: click on 'load method synopsis' for desired method. This will load a skeleton for method call parameters in the form above. Complete all xmlrpc values with appropriate data and click 'Execute'</li>
-</ol>
+    ?>
+
+    <h3>Instructions on usage of the debugger</h3>
+    <ol>
+        <li>Run a 'list available methods' action against desired server</li>
+        <li>If list of methods appears, click on 'describe method' for desired method</li>
+        <li>To run method: click on 'load method synopsis' for desired method. This will load a skeleton for method call
+            parameters in the form above. Complete all xmlrpc values with appropriate data and click 'Execute'
+        </li>
+    </ol>
+    <?php
+    if (!extension_loaded('curl')) {
+        echo "<p class=\"evidence\">You will need to enable the CURL extension to use the HTTPS and HTTP 1.1 transports</p>\n";
+    }
+    ?>
+
+    <h3>Example</h3>
+    <p>
+        Server Address: phpxmlrpc.sourceforge.net<br/>
+        Path: /server.php
+    </p>
+
+    <h3>Notice</h3>
+    <p>all usernames and passwords entered on the above form will be written to the web server logs of this server. Use
+        with care.</p>
+
+    <h3>Changelog</h3>
+    <ul>
+        <li>2015-05-30: fix problems with generating method payloads for NIL and Undefined parameters</li>
+        <li>2015-04-19: fix problems with LATIN-1 characters in payload</li>
+        <li>2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id</li>
+        <li>2006-06-26: support building php code stub for calling remote methods</li>
+        <li>2006-05-25: better support for long running queries; check for no-curl installs</li>
+        <li>2006-05-02: added support for JSON-RPC. Note that many interesting json-rpc features are not implemented
+            yet, such as notifications or multicall.
+        </li>
+        <li>2006-04-22: added option for setting custom CA certs to verify peer with in SSLmode</li>
+        <li>2006-03-05: added option for setting Basic/Digest/NTLM auth type</li>
+        <li>2006-01-18: added option echoing to screen xmlrpc request before sending it ('More' debug)</li>
+        <li>2005-10-01: added option for setting cookies to be sent to server</li>
+        <li>2005-08-07: added switches for compression of requests and responses and http 1.1</li>
+        <li>2005-06-27: fixed possible security breach in parsing malformed xml</li>
+        <li>2005-06-24: fixed error with calling methods having parameters...</li>
+    </ul>
 <?php
-  if (!extension_loaded('curl'))
-  {
-      echo "<p class=\"evidence\">You will need to enable the CURL extension to use the HTTPS and HTTP 1.1 transports</p>\n";
-  }
-?>
 
-<h3>Example:</h3>
-<p>
-Server Address: phpxmlrpc.sourceforge.net<br/>
-Path: /server.php
-</p>
-
-<h3>Notice:</h3>
-<p>all usernames and passwords entered on the above form will be written to the web server logs of this server. Use with care.</p>
-
-<h3>Changelog</h3>
-<ul>
-<li>2007-02-20: add visual editor for method payload; allow strings, bools as jsonrpc msg id</li>
-<li>2006-06-26: support building php code stub for calling remote methods</li>
-<li>2006-05-25: better support for long running queries; check for no-curl installs</li>
-<li>2006-05-02: added support for JSON-RPC. Note that many interesting json-rpc features are not implemented yet, such as notifications or multicall.</li>
-<li>2006-04-22: added option for setting custom CA certs to verify peer with in SSLmode</li>
-<li>2006-03-05: added option for setting Basic/Digest/NTLM auth type</li>
-<li>2006-01-18: added option echoing to screen xmlrpc request before sending it ('More' debug)</li>
-<li>2005-10-01: added option for setting cookies to be sent to server</li>
-<li>2005-08-07: added switches for compression of requests and responses and http 1.1</li>
-<li>2005-06-27: fixed possible security breach in parsing malformed xml</li>
-<li>2005-06-24: fixed error with calling methods having parameters...</li>
-</ul>
-<?php
-  }
+}
 ?>
 </body>
 </html>
index adaf366..4026d60 100644 (file)
@@ -1,80 +1,89 @@
 <?php
 /**
  * @author Gaetano Giunta
- * @copyright (C) 2005-2014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @copyright (C) 2005-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ *
+ * Parses GET/POST variables
  *
  * @todo switch params for http compression from 0,1,2 to values to be used directly
  * @todo do some more sanitization of received parameters
  */
 
 // work around magic quotes
-  if (get_magic_quotes_gpc())
-  {
+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);
-  }
+}
 
+$preferredEncodings = 'UTF-8, ASCII, ISO-8859-1, UTF-7, EUC-JP, SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP';
+$inputcharset = mb_detect_encoding(urldecode($_SERVER['REQUEST_URI']), $preferredEncodings);
+if (isset($_GET['usepost']) && $_GET['usepost'] === 'true') {
+    $_GET = $_POST;
+    $inputcharset = mb_detect_encoding(implode('', $_GET), $preferredEncodings);
+}
 
-  if ( isset( $_GET['usepost'] ) && $_GET['usepost'] === 'true' )
-  {
-      $_GET = $_POST;
-  }
+/// @todo if $inputcharset is not UTF8, we should probably re-encode $_GET to make it UTF-8
 
 // recover input parameters
-  $debug = false;
-  $protocol = 0;
-  $run = false;
-  $wstype = 0;
-  $id = '';
-  if (isset($_GET['action']))
-  {
-    if (isset($_GET['wstype']) && $_GET['wstype'] == '1')
-    {
-      $wstype = 1;
-      if (isset($_GET['id']))
-        $id = $_GET['id'];
+$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'] : '';
     $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 = '';
     $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;
+}
index afb34ad..2fd4307 100644 (file)
 <?php
 /**
  * @author Gaetano Giunta
- * @copyright (C) 2005-2014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
+ * @copyright (C) 2005-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
  *
  * @todo add links to documentation from every option caption
  * @todo switch params for http compression from 0,1,2 to values to be used directly
  * @todo add a little bit more CSS formatting: we broke IE box model getting a width > 100%...
  * @todo add support for more options, such as ntlm auth to proxy, or request charset encoding
- *
  * @todo parse content of payload textarea to be fed to visual editor
  * @todo add http no-cache headers
  **/
 
-  include(dirname(__FILE__).'/common.php');
-  if ($action == '')
+// make sure we set the correct charset type for output, so that we can display all characters
+header('Content-Type: text/html; charset=utf-8');
+
+include __DIR__ . '/common.php';
+if ($action == '') {
     $action = 'list';
+}
 
-  // relative path to the visual xmlrpc editing dialog
-  $editorpath = '../../javascript/debugger/';
-  $editorlibs = '../../javascript/lib/';
+// relative path to the visual xmlrpc editing dialog
+$editorpath = '../../phpjsrpc/debugger/';
+$editorlibs = '../../phpjsrpc/lib/';
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
-<title>XMLRPC Debugger</title>
-<meta name="robots" content="index,nofollow" />
-<script type="text/javascript" language="Javascript">
-  if (window.name!='frmcontroller')
-    top.location.replace('index.php?run='+escape(self.location));
-</script>
-<!-- xmlrpc/jsonrpc base library -->
-<script type="text/javascript" src="<?php echo $editorlibs; ?>xmlrpc_lib.js"></script>
-<script type="text/javascript" src="<?php echo $editorlibs; ?>jsonrpc_lib.js"></script>
-<style type="text/css">
-<!--
-html {overflow: -moz-scrollbars-vertical;}
-body {padding: 0.5em; background-color: #EEEEEE; font-family: Verdana, Arial, Helvetica; font-size: 8pt;}
-h1 {font-size: 12pt; margin: 0.5em;}
-h2 {font-size: 10pt; display: inline; vertical-align: top;}
-table {border: 1px solid gray; margin-bottom: 0.5em; padding: 0.25em; width: 100%;}
-#methodpayload {display: inline;}
-td {vertical-align: top; font-family: Verdana, Arial, Helvetica; font-size: 8pt;}
-.labelcell {text-align: right;}
--->
-</style>
-<script language="JavaScript" type="text/javascript">
-<!--
-  function verifyserver()
-  {
-    if (document.frmaction.host.value == '')
-    {
-      alert('Please insert a server name or address');
-      return false;
-    }
-    if (document.frmaction.path.value == '')
-      document.frmaction.path.value = '/';
-    var action = '';
-    for (counter = 0; counter < document.frmaction.action.length; counter++)
-      if (document.frmaction.action[counter].checked)
-      {
-        action = document.frmaction.action[counter].value;
-      }
-    if (document.frmaction.method.value == '' && (action == 'execute' || action == 'wrap' || action == 'describe'))
-    {
-      alert('Please insert a method name');
-      return false;
-    }
-    if (document.frmaction.authtype.value != '1' && document.frmaction.username.value == '')
-    {
-      alert('No username for authenticating to server: authentication disabled');
-    }
-    return true;
-  }
+    <title>XMLRPC Debugger</title>
+    <meta name="robots" content="index,nofollow"/>
+    <script type="text/javascript" language="Javascript">
+        if (window.name != 'frmcontroller')
+            top.location.replace('index.php?run=' + escape(self.location));
+    </script>
+    <!-- xmlrpc/jsonrpc base library -->
+    <script type="text/javascript" src="<?php echo $editorlibs; ?>xmlrpc_lib.js"></script>
+    <script type="text/javascript" src="<?php echo $editorlibs; ?>jsonrpc_lib.js"></script>
+    <style type="text/css">
+        <!--
+        html {
+            overflow: -moz-scrollbars-vertical;
+        }
+
+        body {
+            padding: 0.5em;
+            background-color: #EEEEEE;
+            font-family: Verdana, Arial, Helvetica;
+            font-size: 8pt;
+        }
+
+        h1 {
+            font-size: 12pt;
+            margin: 0.5em;
+        }
+
+        h2 {
+            font-size: 10pt;
+            display: inline;
+            vertical-align: top;
+        }
+
+        table {
+            border: 1px solid gray;
+            margin-bottom: 0.5em;
+            padding: 0.25em;
+            width: 100%;
+        }
+
+        #methodpayload {
+            display: inline;
+        }
+
+        td {
+            vertical-align: top;
+            font-family: Verdana, Arial, Helvetica;
+            font-size: 8pt;
+        }
+
+        .labelcell {
+            text-align: right;
+        }
+
+        -->
+    </style>
+    <script language="JavaScript" type="text/javascript">
+        <!--
+        function verifyserver() {
+            if (document.frmaction.host.value == '') {
+                alert('Please insert a server name or address');
+                return false;
+            }
+            if (document.frmaction.path.value == '')
+                document.frmaction.path.value = '/';
+            var action = '';
+            for (counter = 0; counter < document.frmaction.action.length; counter++)
+                if (document.frmaction.action[counter].checked) {
+                    action = document.frmaction.action[counter].value;
+                }
+            if (document.frmaction.method.value == '' && (action == 'execute' || action == 'wrap' || action == 'describe')) {
+                alert('Please insert a method name');
+                return false;
+            }
+            if (document.frmaction.authtype.value != '1' && document.frmaction.username.value == '') {
+                alert('No username for authenticating to server: authentication disabled');
+            }
+            return true;
+        }
 
-  function switchaction()
-  {
-    // reset html layout depending on action to be taken
-    var action = '';
-    for (counter = 0; counter < document.frmaction.action.length; counter++)
-      if (document.frmaction.action[counter].checked)
-      {
-        action = document.frmaction.action[counter].value;
-      }
-    if (action == 'execute')
-    {
-      document.frmaction.methodpayload.disabled = false;
-      displaydialogeditorbtn(true);//if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
-      document.frmaction.method.disabled = false;
-      document.frmaction.methodpayload.rows = 10;
-    }
-    else
-    {
-      document.frmaction.methodpayload.rows = 1;
-      if (action == 'describe' || action == 'wrap')
-      {
-        document.frmaction.methodpayload.disabled = true;
-        displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = true;
-        document.frmaction.method.disabled = false;
-      }
-      else // list
-      {
-        document.frmaction.methodpayload.disabled = true;
-        displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
-        document.frmaction.method.disabled = true;
-      }
-    }
-  }
+        function switchaction() {
+            // reset html layout depending on action to be taken
+            var action = '';
+            for (counter = 0; counter < document.frmaction.action.length; counter++)
+                if (document.frmaction.action[counter].checked) {
+                    action = document.frmaction.action[counter].value;
+                }
+            if (action == 'execute') {
+                document.frmaction.methodpayload.disabled = false;
+                displaydialogeditorbtn(true);//if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
+                document.frmaction.method.disabled = false;
+                document.frmaction.methodpayload.rows = 10;
+            }
+            else {
+                document.frmaction.methodpayload.rows = 1;
+                if (action == 'describe' || action == 'wrap') {
+                    document.frmaction.methodpayload.disabled = true;
+                    displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = true;
+                    document.frmaction.method.disabled = false;
+                }
+                else // list
+                {
+                    document.frmaction.methodpayload.disabled = true;
+                    displaydialogeditorbtn(false); //if (document.getElementById('methodpayloadbtn') != undefined) document.getElementById('methodpayloadbtn').disabled = false;
+                    document.frmaction.method.disabled = true;
+                }
+            }
+        }
 
-  function switchssl()
-  {
-    if (document.frmaction.protocol.value != '2')
-    {
-      document.frmaction.verifypeer.disabled = true;
-      document.frmaction.verifyhost.disabled = true;
-      document.frmaction.cainfo.disabled = true;
-    }
-    else
-    {
-      document.frmaction.verifypeer.disabled = false;
-      document.frmaction.verifyhost.disabled = false;
-      document.frmaction.cainfo.disabled = false;
-    }
-  }
+        function switchssl() {
+            if (document.frmaction.protocol.value != '2') {
+                document.frmaction.verifypeer.disabled = true;
+                document.frmaction.verifyhost.disabled = true;
+                document.frmaction.cainfo.disabled = true;
+            }
+            else {
+                document.frmaction.verifypeer.disabled = false;
+                document.frmaction.verifyhost.disabled = false;
+                document.frmaction.cainfo.disabled = false;
+            }
+        }
 
-  function switchauth()
-  {
-    if (document.frmaction.protocol.value != '0')
-    {
-      document.frmaction.authtype.disabled = false;
-    }
-    else
-    {
-      document.frmaction.authtype.disabled = true;
-      document.frmaction.authtype.value = 1;
-    }
-  }
+        function switchauth() {
+            if (document.frmaction.protocol.value != '0') {
+                document.frmaction.authtype.disabled = false;
+            }
+            else {
+                document.frmaction.authtype.disabled = true;
+                document.frmaction.authtype.value = 1;
+            }
+        }
 
-  function swicthcainfo()
-  {
-    if (document.frmaction.verifypeer.checked == true)
-    {
-      document.frmaction.cainfo.disabled = false;
-    }
-    else
-    {
-      document.frmaction.cainfo.disabled = true;
-    }
-  }
+        function swicthcainfo() {
+            if (document.frmaction.verifypeer.checked == true) {
+                document.frmaction.cainfo.disabled = false;
+            }
+            else {
+                document.frmaction.cainfo.disabled = true;
+            }
+        }
 
-  function switchtransport(is_json)
-  {
-    if (is_json == 0)
-    {
-      document.getElementById("idcell").style.visibility = 'hidden';
-      document.frmjsonrpc.yes.checked = false;
-      document.frmxmlrpc.yes.checked = true;
-      document.frmaction.wstype.value="0";
-    }
-    else
-    {
-      document.getElementById("idcell").style.visibility = 'visible';
-      document.frmjsonrpc.yes.checked = true;
-      document.frmxmlrpc.yes.checked = false;
-      document.frmaction.wstype.value="1";
-    }
-  }
+        function switchtransport(is_json) {
+            if (is_json == 0) {
+                document.getElementById("idcell").style.visibility = 'hidden';
+                document.frmjsonrpc.yes.checked = false;
+                document.frmxmlrpc.yes.checked = true;
+                document.frmaction.wstype.value = "0";
+            }
+            else {
+                document.getElementById("idcell").style.visibility = 'visible';
+                document.frmjsonrpc.yes.checked = true;
+                document.frmxmlrpc.yes.checked = false;
+                document.frmaction.wstype.value = "1";
+            }
+        }
 
-  function displaydialogeditorbtn(show)
-  {
-    if (show && ((typeof base64_decode) == 'function'))
-    {
-         document.getElementById('methodpayloadbtn').innerHTML = '[<a href="#" onclick="activateeditor(); return false;">Edit</a>]';
-       }
-       else
-    {
-         document.getElementById('methodpayloadbtn').innerHTML = '';
-       }
-  }
+        function displaydialogeditorbtn(show) {
+            if (show && ((typeof base64_decode) == 'function')) {
+                document.getElementById('methodpayloadbtn').innerHTML = '[<a href="#" onclick="activateeditor(); return false;">Edit</a>]';
+            }
+            else {
+                document.getElementById('methodpayloadbtn').innerHTML = '';
+            }
+        }
 
-  function activateeditor()
-  {
-         var url = '<?php echo $editorpath; ?>visualeditor.php?params=<?php echo $alt_payload; ?>';
-         if (document.frmaction.wstype.value == "1")
-           url += '&type=jsonrpc';
-         var wnd = window.open(url, '_blank', 'width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=1');
-  }
+        function activateeditor() {
+            var url = '<?php echo $editorpath; ?>visualeditor.php?params=<?php echo $alt_payload; ?>';
+            if (document.frmaction.wstype.value == "1")
+                url += '&type=jsonrpc';
+            var wnd = window.open(url, '_blank', 'width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=1');
+        }
 
-  // if javascript version of the lib is found, allow it to send us params
-  function buildparams(base64data)
-  {
-    if (typeof base64_decode == 'function')
-    {
-         if (base64data == '0') // workaround for bug in base64_encode...
-           document.getElementById('methodpayload').value = '';
-         else
-        document.getElementById('methodpayload').value = base64_decode(base64data);
-    }
-  }
+        // 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';
-      }
-  }
+        // use GET for ease of refresh, switch to POST when payload is too big to fit in url (in IE: 2048 bytes! see http://support.microsoft.com/kb/q208427/)
+        function switchFormMethod() {
+            /// @todo use a more precise calculation, adding the rest of the fields to the actual generated url lenght
+            if (document.frmaction.methodpayload.value.length > 1536) {
+                document.frmaction.action = 'action.php?usepost=true';
+                document.frmaction.method = 'post';
+            }
+        }
 
-//-->
-</script>
+        //-->
+    </script>
 </head>
-<body onload="switchtransport(<?php echo $wstype;?>); switchaction(); switchssl(); switchauth(); swicthcainfo();<?php if ($run) echo ' document.forms[2].submit();'; ?>">
-<h1>XMLRPC <form name="frmxmlrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(0);"/></form>
-/<form name="frmjsonrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(1);"/></form>JSONRPC Debugger (based on the <a href="http://phpxmlrpc.sourceforge.net">PHP-XMLRPC</a> library)</h1>
-<form name="frmaction" method="get" action="action.php" target="frmaction" onSubmit="switchFormMethod();"
->
+<body
+    onload="switchtransport(<?php echo $wstype; ?>); switchaction(); switchssl(); switchauth(); swicthcainfo();<?php if ($run) {
+        echo ' document.forms[2].submit();';
+    } ?>">
+<h1>XMLRPC
+    <form name="frmxmlrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(0);"/></form>
+    /
+    <form name="frmjsonrpc" style="display: inline;" action="."><input name="yes" type="radio" onclick="switchtransport(1);"/></form>
+    JSONRPC Debugger (based on the <a href="http://gggeek.github.io/phpxmlrpc/">PHP-XMLRPC</a> library)
+</h1>
+<form name="frmaction" method="get" action="action.php" target="frmaction" onSubmit="switchFormMethod();">
 
-<table id="serverblock">
-<tr>
-<td><h2>Target server</h2></td>
-<td class="labelcell">Address:</td><td><input type="text" name="host" value="<?php echo htmlspecialchars($host); ?>" /></td>
-<td class="labelcell">Port:</td><td><input type="text" name="port" value="<?php echo htmlspecialchars($port); ?>" size="5" maxlength="5" /></td>
-<td class="labelcell">Path:</td><td><input type="text" name="path" value="<?php echo htmlspecialchars($path); ?>" /></td>
-</tr>
-</table>
+    <table id="serverblock">
+        <tr>
+            <td><h2>Target server</h2></td>
+            <td class="labelcell">Address:</td>
+            <td><input type="text" name="host" value="<?php echo htmlspecialchars($host, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Port:</td>
+            <td><input type="text" name="port" value="<?php echo htmlspecialchars($port, ENT_COMPAT, $inputcharset); ?>" size="5" maxlength="5"/>
+            </td>
+            <td class="labelcell">Path:</td>
+            <td><input type="text" name="path" value="<?php echo htmlspecialchars($path, ENT_COMPAT, $inputcharset); ?>"/></td>
+        </tr>
+    </table>
 
-<table id="actionblock">
-<tr>
-<td><h2>Action</h2></td>
-<td>List available methods<input type="radio" name="action" value="list"<?php if ($action=='list') echo ' checked="checked"'; ?> onclick="switchaction();" /></td>
-<td>Describe method<input type="radio" name="action" value="describe"<?php if ($action=='describe') echo ' checked="checked"'; ?> onclick="switchaction();" /></td>
-<td>Execute method<input type="radio" name="action" value="execute"<?php if ($action=='execute') echo ' checked="checked"'; ?> onclick="switchaction();" /></td>
-<td>Generate stub for method call<input type="radio" name="action" value="wrap"<?php if ($action=='wrap') echo ' checked="checked"'; ?> onclick="switchaction();" /></td>
-</tr>
-</table>
-<input type="hidden" name="methodsig" value="<?php echo htmlspecialchars($methodsig); ?>" />
+    <table id="actionblock">
+        <tr>
+            <td><h2>Action</h2></td>
+            <td>List available methods<input type="radio" name="action" value="list"<?php if ($action == 'list') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
+            <td>Describe method<input type="radio" name="action" value="describe"<?php if ($action == 'describe') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
+            <td>Execute method<input type="radio" name="action" value="execute"<?php if ($action == 'execute') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
+            <td>Generate stub for method call<input type="radio" name="action" value="wrap"<?php if ($action == 'wrap') { echo ' checked="checked"'; } ?> onclick="switchaction();"/></td>
+        </tr>
+    </table>
+    <input type="hidden" name="methodsig" value="<?php echo htmlspecialchars($methodsig, ENT_COMPAT, $inputcharset); ?>"/>
 
-<table id="methodblock">
-<tr>
-<td><h2>Method</h2></td>
-<td class="labelcell">Name:</td><td><input type="text" name="method" value="<?php echo htmlspecialchars($method); ?>" /></td>
-<td class="labelcell">Payload:<br/><div id="methodpayloadbtn"></div></td><td><textarea id="methodpayload" name="methodpayload" rows="1" cols="40"><?php echo htmlspecialchars($payload); ?></textarea></td>
-<td class="labelcell" id="idcell">Msg id: <input type="text" name="id" size="3" value="<?php echo htmlspecialchars($id); ?>"/></td>
-<td><input type="hidden" name="wstype" value="<?php echo $wstype;?>" />
-<input type="submit" value="Execute" onclick="return verifyserver();"/></td>
-</tr>
-</table>
+    <table id="methodblock">
+        <tr>
+            <td><h2>Method</h2></td>
+            <td class="labelcell">Name:</td>
+            <td><input type="text" name="method" value="<?php echo htmlspecialchars($method, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Payload:<br/>
+                <div id="methodpayloadbtn"></div>
+            </td>
+            <td><textarea id="methodpayload" name="methodpayload" rows="1" cols="40"><?php echo htmlspecialchars($payload, ENT_COMPAT, $inputcharset); ?></textarea></td>
+            <td class="labelcell" id="idcell">Msg id: <input type="text" name="id" size="3" value="<?php echo htmlspecialchars($id, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td><input type="hidden" name="wstype" value="<?php echo $wstype; ?>"/>
+                <input type="submit" value="Execute" onclick="return verifyserver();"/></td>
+        </tr>
+    </table>
 
-<table id="optionsblock">
-<tr>
-<td><h2>Client options</h2></td>
-<td class="labelcell">Show debug info:</td><td><select name="debug">
-<option value="0"<?php if ($debug == 0) echo ' selected="selected"'; ?>>No</option>
-<option value="1"<?php if ($debug == 1) echo ' selected="selected"'; ?>>Yes</option>
-<option value="2"<?php if ($debug == 2) echo ' selected="selected"'; ?>>More</option>
-</select>
-</td>
-<td class="labelcell">Timeout:</td><td><input type="text" name="timeout" size="3" value="<?php if ($timeout > 0) echo $timeout; ?>" /></td>
-<td class="labelcell">Protocol:</td><td><select name="protocol" onchange="switchssl(); switchauth(); swicthcainfo();">
-<option value="0"<?php if ($protocol == 0) echo ' selected="selected"'; ?>>HTTP 1.0</option>
-<option value="1"<?php if ($protocol == 1) echo ' selected="selected"'; ?>>HTTP 1.1</option>
-<option value="2"<?php if ($protocol == 2) echo ' selected="selected"'; ?>>HTTPS</option>
-</select></td>
-</tr>
-<tr>
-<td class="labelcell">AUTH:</td>
-<td class="labelcell">Username:</td><td><input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>" /></td>
-<td class="labelcell">Pwd:</td><td><input type="password" name="password" value="<?php echo htmlspecialchars($password); ?>" /></td>
-<td class="labelcell">Type</td><td><select name="authtype">
-<option value="1"<?php if ($authtype == 1) echo ' selected="selected"'; ?>>Basic</option>
-<option value="2"<?php if ($authtype == 2) echo ' selected="selected"'; ?>>Digest</option>
-<option value="8"<?php if ($authtype == 8) echo ' selected="selected"'; ?>>NTLM</option>
-</select></td>
-<td></td>
-</tr>
-<tr>
-<td class="labelcell">SSL:</td>
-<td class="labelcell">Verify Host's CN:</td><td><select name="verifyhost">
-<option value="0"<?php if ($verifyhost == 0) echo ' selected="selected"'; ?>>No</option>
-<option value="1"<?php if ($verifyhost == 1) echo ' selected="selected"'; ?>>Check CN existance</option>
-<option value="2"<?php if ($verifyhost == 2) echo ' selected="selected"'; ?>>Check CN match</option>
-</select></td>
-<td class="labelcell">Verify Cert:</td><td><input type="checkbox" value="1" name="verifypeer" onclick="swicthcainfo();"<?php if ($verifypeer) echo ' checked="checked"'; ?> /></td>
-<td class="labelcell">CA Cert file:</td><td><input type="text" name="cainfo" value="<?php echo htmlspecialchars($cainfo); ?>" /></td>
-</tr>
-<tr>
-<td class="labelcell">PROXY:</td>
-<td class="labelcell">Server:</td><td><input type="text" name="proxy" value="<?php echo htmlspecialchars($proxy); ?>" /></td>
-<td class="labelcell">Proxy user:</td><td><input type="text" name="proxyuser" value="<?php echo htmlspecialchars($proxyuser); ?>" /></td>
-<td class="labelcell">Proxy pwd:</td><td><input type="password" name="proxypwd" value="<?php echo htmlspecialchars($proxypwd); ?>" /></td>
-</tr>
-<tr>
-<td class="labelcell">COMPRESSION:</td>
-<td class="labelcell">Request:</td><td><select name="requestcompression">
-<option value="0"<?php if ($requestcompression == 0) echo ' selected="selected"'; ?>>None</option>
-<option value="1"<?php if ($requestcompression == 1) echo ' selected="selected"'; ?>>Gzip</option>
-<option value="2"<?php if ($requestcompression == 2) echo ' selected="selected"'; ?>>Deflate</option>
-</select></td>
-<td class="labelcell">Response:</td><td><select name="responsecompression">
-<option value="0"<?php if ($responsecompression == 0) echo ' selected="selected"'; ?>>None</option>
-<option value="1"<?php if ($responsecompression == 1) echo ' selected="selected"'; ?>>Gzip</option>
-<option value="2"<?php if ($responsecompression == 2) echo ' selected="selected"'; ?>>Deflate</option>
-<option value="3"<?php if ($responsecompression == 3) echo ' selected="selected"'; ?>>Any</option>
-</select></td>
-<td></td>
-</tr>
-<tr>
-<td class="labelcell">COOKIES:</td>
-<td colspan="4" class="labelcell"><input type="text" name="clientcookies" size="80" value="<?php echo htmlspecialchars($clientcookies); ?>" /></td>
-<td colspan="2">Format: 'cookie1=value1, cookie2=value2'</td>
-</tr>
-</table>
+    <table id="optionsblock">
+        <tr>
+            <td><h2>Client options</h2></td>
+            <td class="labelcell">Show debug info:</td>
+            <td><select name="debug">
+                    <option value="0"<?php if ($debug == 0) { echo ' selected="selected"'; } ?>>No</option>
+                    <option value="1"<?php if ($debug == 1) { echo ' selected="selected"'; } ?>>Yes</option>
+                    <option value="2"<?php if ($debug == 2) { echo ' selected="selected"'; } ?>>More</option>
+                </select>
+            </td>
+            <td class="labelcell">Timeout:</td>
+            <td><input type="text" name="timeout" size="3" value="<?php if ($timeout > 0) { echo $timeout; } ?>"/></td>
+            <td class="labelcell">Protocol:</td>
+            <td><select name="protocol" onchange="switchssl(); switchauth(); swicthcainfo();">
+                    <option value="0"<?php if ($protocol == 0) { echo ' selected="selected"'; } ?>>HTTP 1.0</option>
+                    <option value="1"<?php if ($protocol == 1) { echo ' selected="selected"'; } ?>>HTTP 1.1</option>
+                    <option value="2"<?php if ($protocol == 2) { echo ' selected="selected"'; } ?>>HTTPS</option>
+                </select></td>
+        </tr>
+        <tr>
+            <td class="labelcell">AUTH:</td>
+            <td class="labelcell">Username:</td>
+            <td><input type="text" name="username" value="<?php echo htmlspecialchars($username, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Pwd:</td>
+            <td><input type="password" name="password" value="<?php echo htmlspecialchars($password, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Type</td>
+            <td><select name="authtype">
+                    <option value="1"<?php if ($authtype == 1) { echo ' selected="selected"'; } ?>>Basic</option>
+                    <option value="2"<?php if ($authtype == 2) { echo ' selected="selected"'; } ?>>Digest</option>
+                    <option value="8"<?php if ($authtype == 8) { echo ' selected="selected"'; } ?>>NTLM</option>
+                </select></td>
+            <td></td>
+        </tr>
+        <tr>
+            <td class="labelcell">SSL:</td>
+            <td class="labelcell">Verify Host's CN:</td>
+            <td><select name="verifyhost">
+                    <option value="0"<?php if ($verifyhost == 0) { echo ' selected="selected"'; } ?>>No</option>
+                    <option value="1"<?php if ($verifyhost == 1) { echo ' selected="selected"'; } ?>>Check CN existence</option>
+                    <option value="2"<?php if ($verifyhost == 2) { echo ' selected="selected"'; } ?>>Check CN match</option>
+                </select></td>
+            <td class="labelcell">Verify Cert:</td>
+            <td><input type="checkbox" value="1" name="verifypeer" onclick="swicthcainfo();"<?php if ($verifypeer) { echo ' checked="checked"'; } ?> /></td>
+            <td class="labelcell">CA Cert file:</td>
+            <td><input type="text" name="cainfo" value="<?php echo htmlspecialchars($cainfo, ENT_COMPAT, $inputcharset); ?>"/></td>
+        </tr>
+        <tr>
+            <td class="labelcell">PROXY:</td>
+            <td class="labelcell">Server:</td>
+            <td><input type="text" name="proxy" value="<?php echo htmlspecialchars($proxy, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Proxy user:</td>
+            <td><input type="text" name="proxyuser" value="<?php echo htmlspecialchars($proxyuser, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td class="labelcell">Proxy pwd:</td>
+            <td><input type="password" name="proxypwd" value="<?php echo htmlspecialchars($proxypwd, ENT_COMPAT, $inputcharset); ?>"/></td>
+        </tr>
+        <tr>
+            <td class="labelcell">COMPRESSION:</td>
+            <td class="labelcell">Request:</td>
+            <td><select name="requestcompression">
+                    <option value="0"<?php if ($requestcompression == 0) { echo ' selected="selected"'; } ?>>None </option>
+                    <option value="1"<?php if ($requestcompression == 1) { echo ' selected="selected"'; } ?>>Gzip</option>
+                    <option value="2"<?php if ($requestcompression == 2) { echo ' selected="selected"'; } ?>>Deflate</option>
+                </select></td>
+            <td class="labelcell">Response:</td>
+            <td><select name="responsecompression">
+                    <option value="0"<?php if ($responsecompression == 0) { echo ' selected="selected"'; } ?>>None</option>
+                    <option value="1"<?php if ($responsecompression == 1) { echo ' selected="selected"'; } ?>>Gzip</option>
+                    <option value="2"<?php if ($responsecompression == 2) { echo ' selected="selected"'; } ?>>Deflate</option>
+                    <option value="3"<?php if ($responsecompression == 3) { echo ' selected="selected"'; } ?>>Any</option>
+                </select></td>
+            <td></td>
+        </tr>
+        <tr>
+            <td class="labelcell">COOKIES:</td>
+            <td colspan="4" class="labelcell"><input type="text" name="clientcookies" size="80" value="<?php echo htmlspecialchars($clientcookies, ENT_COMPAT, $inputcharset); ?>"/></td>
+            <td colspan="2">Format: 'cookie1=value1, cookie2=value2'</td>
+        </tr>
+    </table>
 
 </form>
 </body>
-</html>
\ No newline at end of file
+</html>
diff --git a/debugger/index.html b/debugger/index.html
deleted file mode 100644 (file)
index 87c75b9..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
-<html>
-<head>
-<title>XMLRPC Debugger</title>
-</head>
-<frameset rows="360,*">
-  <frame name="frmcontroller" src="controller.php" marginwidth="0" marginheight="0" frameborder="0" />
-  <frame name="frmaction" src="action.php" marginwidth="0" marginheight="0" frameborder="0" />
-</frameset>
-</html>
\ No newline at end of file
index 2f30c9f..eff10ea 100644 (file)
@@ -1,20 +1,21 @@
 <?php
-  $query = '';
-  if (isset($_GET['run']))
-  {
+$query = '';
+if (isset($_GET['run'])) {
     $path = parse_url($_GET['run']);
-    if (isset($path['query']))
-      $query = '?'.$path['query'];
-  }
+    if (isset($path['query'])) {
+        $query = '?' . $path['query'];
+    }
+}
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
 <html>
 <head>
-<title>XMLRPC Debugger</title>
+    <title>XMLRPC Debugger</title>
 </head>
 <frameset rows="360,*">
-  <frame name="frmcontroller" src="controller.php<?php echo htmlspecialchars($query); ?>" marginwidth="0" marginheight="0" frameborder="0" />
-  <frame name="frmaction" src="action.php" marginwidth="0" marginheight="0" frameborder="0" />
+    <frame name="frmcontroller" src="controller.php<?php echo htmlspecialchars($query); ?>" marginwidth="0"
+           marginheight="0" frameborder="0"/>
+    <frame name="frmaction" src="action.php" marginwidth="0" marginheight="0" frameborder="0"/>
 </frameset>
-</html>
\ No newline at end of file
+</html>
index 86febd1..90622d2 100644 (file)
@@ -1 +1,68 @@
-<html>\r<head><title>xmlrpc</title></head>\r<body>\r<h1>Agesort demo</h1>\r<h2>Send an array of 'name' => 'age' pairs to the server that will send it back sorted.</h2>\r<h3>The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs</h3>\r<p></p>\r<?php\rinclude("xmlrpc.inc");\r\r$inAr=array("Dave" => 24, "Edd" => 45, "Joe" => 37, "Fred" => 27);\rreset($inAr);\rprint "This is the input data:<br/><pre>";\rwhile (list($key, $val)=each($inAr)) {\r  print $key . ", " . $val . "\n";\r}\rprint "</pre>";\r\r// create parameters from the input array: an xmlrpc array of xmlrpc structs\r$p=array();\rforeach($inAr as $key => $val) {\r  $p[]=new xmlrpcval(array("name" => new xmlrpcval($key),\r                           "age" => new xmlrpcval($val, "int")), "struct");\r}\r$v=new xmlrpcval($p, "array");\rprint "Encoded into xmlrpc format it looks like this: <pre>\n" .  htmlentities($v->serialize()). "</pre>\n";\r\r// create client and message objects\r$f=new xmlrpcmsg('examples.sortByAge',  array($v));\r$c=new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80);\r\r// set maximum debug level, to have the complete communication printed to screen\r$c->setDebug(2);\r\r// send request\rprint "Now sending request (detailed debug info follows)";\r$r=&$c->send($f);\r\r// check response for errors, and take appropriate action\rif (!$r->faultCode()) {\r  print "The server gave me these results:<pre>";\r  $v=$r->value();\r  $max=$v->arraysize();\r  for($i=0; $i<$max; $i++) {\r    $rec=$v->arraymem($i);\r    $n=$rec->structmem("name");\r    $a=$rec->structmem("age");\r    print htmlspecialchars($n->scalarval()) . ", " . htmlspecialchars($a->scalarval()) . "\n";\r  }\r\r  print "<hr/>For nerds: I got this value back<br/><pre>" .\r    htmlentities($r->serialize()). "</pre><hr/>\n";\r} else {\r  print "An error occurred:<pre>";\r  print "Code: " . htmlspecialchars($r->faultCode()) .\r    "\nReason: '" . htmlspecialchars($r->faultString()).'\'</pre><hr/>';\r}\r\r?>\r</body>\r</html>\r
\ No newline at end of file
+<html>
+<head><title>xmlrpc - Agesort demo</title></head>
+<body>
+<h1>Agesort demo</h1>
+
+<h2>Send an array of 'name' => 'age' pairs to the server that will send it back sorted.</h2>
+
+<h3>The source code demonstrates basic lib usage, including handling of xmlrpc arrays and structs</h3>
+
+<p></p>
+<?php
+
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+$inAr = array("Dave" => 24, "Edd" => 45, "Joe" => 37, "Fred" => 27);
+print "This is the input data:<br/><pre>";
+foreach($inAr as $key => $val) {
+    print $key . ", " . $val . "\n";
+}
+print "</pre>";
+
+// create parameters from the input array: an xmlrpc array of xmlrpc structs
+$p = array();
+foreach ($inAr as $key => $val) {
+    $p[] = new PhpXmlRpc\Value(
+        array(
+            "name" => new PhpXmlRpc\Value($key),
+            "age" => new PhpXmlRpc\Value($val, "int")
+        ),
+        "struct"
+    );
+}
+$v = new PhpXmlRpc\Value($p, "array");
+print "Encoded into xmlrpc format it looks like this: <pre>\n" . htmlentities($v->serialize()) . "</pre>\n";
+
+// create client and message objects
+$req = new PhpXmlRpc\Request('examples.sortByAge', array($v));
+$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
+
+// set maximum debug level, to have the complete communication printed to screen
+$client->setDebug(2);
+
+// send request
+print "Now sending request (detailed debug info follows)";
+$resp = $client->send($req);
+
+// check response for errors, and take appropriate action
+if (!$resp->faultCode()) {
+    print "The server gave me these results:<pre>";
+    $value = $resp->value();
+    foreach ($value as $struct) {
+        $name = $struct["name"];
+        $age = $struct["age"];
+        print htmlspecialchars($name->scalarval()) . ", " . htmlspecialchars($age->scalarval()) . "\n";
+    }
+
+    print "<hr/>For nerds: I got this value back<br/><pre>" .
+        htmlentities($resp->serialize()) . "</pre><hr/>\n";
+} else {
+    print "An error occurred:<pre>";
+    print "Code: " . htmlspecialchars($resp->faultCode()) .
+        "\nReason: '" . htmlspecialchars($resp->faultString()) . '\'</pre><hr/>';
+}
+
+?>
+</body>
+</html>
diff --git a/demo/client/client.php b/demo/client/client.php
deleted file mode 100644 (file)
index 94b61ff..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-<html>
-<head><title>xmlrpc</title></head>
-<body>
-<h1>Getstatename demo</h1>
-<h2>Send a U.S. state number to the server and get back the state name</h2>
-<h3>The code demonstrates usage of the php_xmlrpc_encode function</h3>
-<?php
-       include("xmlrpc.inc");
-
-       // Play nice to PHP 5 installations with REGISTER_LONG_ARRAYS off
-       if(!isset($HTTP_POST_VARS) && isset($_POST))
-       {
-               $HTTP_POST_VARS = $_POST;
-       }
-
-       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 "<pre>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 "</pre><br/>State number " . $stateno . " is "
-                               . htmlspecialchars($v->scalarval()) . "<br/>";
-                       // print "<HR>I got this value back<BR><PRE>" .
-                       //  htmlentities($r->serialize()). "</PRE><HR>\n";
-               }
-               else
-               {
-                       print "An error occurred: ";
-                       print "Code: " . htmlspecialchars($r->faultCode())
-                               . " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
-               }
-       }
-       else
-       {
-               $stateno = "";
-       }
-
-       print "<form action=\"client.php\" method=\"POST\">
-<input name=\"stateno\" value=\"" . $stateno . "\"><input type=\"submit\" value=\"go\" name=\"submit\"></form>
-<p>Enter a state number to query its name</p>";
-
-?>
-</body>
-</html>
diff --git a/demo/client/comment.php b/demo/client/comment.php
deleted file mode 100644 (file)
index 5659fa1..0000000
+++ /dev/null
@@ -1,185 +0,0 @@
-<?php
-include("xmlrpc.inc");
-
-$mydir="/demo";
-
-// define some utility functions
-function bomb() { print "</body></html>"; exit(); }
-function dispatch($client, $method, $args) {
-       $msg=new xmlrpcmsg($method, $args);
-       $resp=$client->send($msg);
-       if (!$resp) { print "<p>IO error: ".$client->errstr."</p>"; bomb(); }
-       if ($resp->faultCode()) {
-               print "<p>There was an error: " . $resp->faultCode() . " " .
-                       $resp->faultString() . "</p>";
-               bomb();
-       }
-       return php_xmlrpc_decode($resp->value());
-}
-
-// create client for discussion server
-$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"];
-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"]))));
-
-       // 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
-
-?>
-<html><head><title>meerkat browser</title></head>
-<body bgcolor="#ffffff">
-<h2>Meerkat integration</h2>
-<?php
-@$catid=$_GET["catid"];
-if (@$_GET["oc"]==$catid)
-       @$chanid=$_GET["chanid"];
-else
-       $chanid=0;
-
-$client=new xmlrpc_client("/meerkat/xml-rpc/server.php",
-                                                                                                       "www.oreillynet.com", 80);
-
-if (@$_GET["comment"] &&
-               (!@$_GET["cdone"])) {
-       // we're making a comment on a story,
-       // so display a comment form
-?>
-<h3>Make a comment on the story</h3>
-<form method="post">
-<p>Your name:<br /><input type="text" size="30" name="name" /></p>
-<p>Your comment:<br /><textarea rows="5" cols="60"
-   name="commenttext"></textarea></p>
-<input type="submit" value="Send comment" />
-<input type="hidden" name="storyid"
-   value="<?php echo @$_GET["comment"];?>" />
-<input type="hidden" name="chanid"
-   value="<?php echo $chanid; ?>" />
-<input type="hidden" name="catid"
-   value="<?php echo $catid; ?>" />
-
-</form>
-<?php
-} else {
-       $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")));
-       }
-?>
-<form>
-<p>Subject area:<br />
-<select name="catid">
-<?php
-       if (!$catid)
-               print "<option value=\"0\">Choose a category</option>\n";
-       while(list($k,$v) = each($categories)) {
-               print "<option value=\"" . $v['id'] ."\"";
-               if ($v['id']==$catid) print " selected=\"selected\"";
-                       print ">". $v['title'] . "</option>\n";
-       }
-?>
-</select></p>
-<?php
-       if ($catid) {
-?>
-<p>News source:<br />
-<select name="chanid">
-<?php
-               if (!$chanid)
-                       print "<option value=\"0\">Choose a source</option>\n";
-               while(list($k,$v) = each($sources)) {
-                       print "<option value=\"" . $v['id'] ."\"";
-                       if ($v['id']==$chanid) print "\" selected=\"selected\"";
-                       print ">". $v['title'] . "</option>\n";
-               }
-?>
-</select>
-</p>
-
-<?php
-               } // end if ($catid)
-?>
-
-<p><input type="submit" value="Update" /></p>
-<input type="hidden" name="oc" value="<?php echo $catid; ?>" />
-</form>
-
-<?php
-        if ($chanid) {
-?>
-
-<h2>Stories available</h2>
-<table>
-<?php
-        while(list($k,$v) = each($stories)) {
-                print "<tr>";
-                print "<td><b>" . $v['title'] . "</b><br />";
-                print $v['description'] . "<br />";
-                print "<em><a target=\"_blank\" href=\"" .
-                        $v['link'] . "\">Read full story</a> ";
-                print "<a href=\"comment.php?catid=${catid}&chanid=${chanid}&" .
-                        "oc=${oc}&comment=" . $v['id'] . "\">Comment on this story</a>";
-                print "</em>";
-                print "</td>";
-                print "</tr>\n";
-                // now look for existing comments
-                $res=dispatch($dclient, "discuss.getComments",
-                                                       array(new xmlrpcval($v['id'])));
-                if (sizeof($res)>0) {
-                        print "<tr><td bgcolor=\"#dddddd\"><p><b><i>" .
-                                "Comments on this story:</i></b></p>";
-                        for($i=0; $i<sizeof($res); $i++) {
-                                $s=$res[$i];
-                                print "<p><b>From:</b> " . htmlentities($s['name']) . "<br />";
-                                print "<b>Comment:</b> " . htmlentities($s['comment']) . "</p>";
-                        }
-                        print "</td></tr>\n";
-                }
-                print "<tr><td><hr /></td></tr>\n";
-        }
-?>
-</table>
-
-<?php
-               } // end if ($chanid)
-} // end if comment
-?>
-<hr />
-<p>
-<a href="http://meerkat.oreillynet.com"><img align="right"
-       src="http://meerkat.oreillynet.com/icons/meerkat-powered.jpg"
-       height="31" width="88" alt="Meerkat powered, yeah!"
-       border="0" hspace="8" /></a>
-</p>
-</body>
-</html>
diff --git a/demo/client/getstatename.php b/demo/client/getstatename.php
new file mode 100644 (file)
index 0000000..69ce3e0
--- /dev/null
@@ -0,0 +1,43 @@
+<html>
+<head><title>xmlrpc - Getstatename demo</title></head>
+<body>
+<h1>Getstatename demo</h1>
+
+<h2>Send a U.S. state number to the server and get back the state name</h2>
+
+<h3>The code demonstrates usage of automatic encoding/decoding of php variables into xmlrpc values</h3>
+<?php
+
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+if (isset($_POST["stateno"]) && $_POST["stateno"] != "") {
+    $stateNo = (integer)$_POST["stateno"];
+    $encoder = new PhpXmlRpc\Encoder();
+    $req = new PhpXmlRpc\Request('examples.getStateName',
+        array($encoder->encode($stateNo))
+    );
+    print "Sending the following request:<pre>\n\n" . htmlentities($req->serialize()) . "\n\n</pre>Debug info of server data follows...\n\n";
+    $client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
+    $client->setDebug(1);
+    $r = $client->send($req);
+    if (!$r->faultCode()) {
+        $v = $r->value();
+        print "<br/>State number <b>" . $stateNo . "</b> is <b>"
+            . htmlspecialchars($encoder->decode($v)) . "</b><br/>";
+    } else {
+        print "An error occurred: ";
+        print "Code: " . htmlspecialchars($r->faultCode())
+            . " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
+    }
+} else {
+    $stateNo = "";
+}
+
+print "<form action=\"getstatename.php\" method=\"POST\">
+<input name=\"stateno\" value=\"" . $stateNo . "\"><input type=\"submit\" value=\"go\" name=\"submit\"></form>
+<p>Enter a state number to query its name</p>";
+
+?>
+</body>
+</html>
index 55dec8a..7870a94 100644 (file)
@@ -1 +1,86 @@
-<html>\r\r<head><title>xmlrpc</title></head>\r\r<body>\r\r<h1>Introspect demo</h1>\r\r<h2>Query server for available methods and their description</h2>\r\r<h3>The code demonstrates usage of multicall and introspection methods</h3>\r\r<?php\r\r  include("xmlrpc.inc");\r\r\r\r      function display_error($r)\r\r    {\r\r             print "An error occurred: ";\r\r          print "Code: " . $r->faultCode()\r\r                      . " Reason: '" .$r->faultString()."'<br/>";\r\r   }\r\r\r\r   // 'new style' client constuctor\r\r      $c = new xmlrpc_client("http://phpxmlrpc.sourceforge.net/server.php");\r\r        print "<h3>methods available at http://" . $c->server . $c->path .  "</h3>\n";\r\r\r\r      $m = new xmlrpcmsg('system.listMethods');\r\r     $r =& $c->send($m);\r\r   if($r->faultCode())\r\r   {\r\r             display_error($r);\r\r    }\r\r     else\r\r  {\r\r             $v=$r->value();\r\r               for($i=0; $i<$v->arraysize(); $i++)\r\r           {\r\r                     $mname=$v->arraymem($i);\r\r                      print "<h4>" . $mname->scalarval() . "</h4>\n";\r\r\r\r                     // build messages first, add params later\r\r                     $m1  = new xmlrpcmsg('system.methodHelp');\r\r                    $m2  = new xmlrpcmsg('system.methodSignature');\r\r                       $val = new xmlrpcval($mname->scalarval(), "string");\r\r                  $m1->addParam($val);\r\r                  $m2->addParam($val);\r\r\r\r                        // send multiple messages in one pass.\r\r                        // If server does not support multicall, client will fall back to 2 separate calls\r\r                    $ms = array($m1, $m2);\r\r                        $rs =& $c->send($ms);\r\r\r\r                       if($rs[0]->faultCode())\r\r                       {\r\r                             display_error($rs[0]);\r\r                        }\r\r                     else\r\r                  {\r\r                             $val=$rs[0]->value();\r\r                         $txt=$val->scalarval();\r\r                               if($txt != "")\r\r                                {\r\r                                     print "<h4>Documentation</h4><p>${txt}</p>\n";\r\r                                }\r\r                             else\r\r                          {\r\r                                     print "<p>No documentation available.</p>\n";\r\r                         }\r\r                     }\r\r\r\r                   if($rs[1]->faultCode())\r\r                       {\r\r                             display_error($rs[1]);\r\r                        }\r\r                     else\r\r                  {\r\r                             print "<h4>Signature</h4><p>\n";\r\r                              $val = $rs[1]->value();\r\r                               if($val->kindOf()=="array")\r\r                           {\r\r                                     for($j=0; $j<$val->arraysize(); $j++)\r\r                                 {\r\r                                             $x = $val->arraymem($j);\r\r                                              $ret = $x->arraymem(0);\r\r                                               print "<code>" . $ret->scalarval() . " "\r\r                                                      . $mname->scalarval() . "(";\r\r                                          if($x->arraysize()>1)\r\r                                         {\r\r                                                     for($k=1; $k<$x->arraysize(); $k++)\r\r                                                   {\r\r                                                             $y = $x->arraymem($k);\r\r                                                                print $y->scalarval();\r\r                                                                if($k < $x->arraysize()-1)\r\r                                                            {\r\r                                                                     print ", ";\r\r                                                           }\r\r                                                     }\r\r                                             }\r\r                                             print ")</code><br/>\n";\r\r                                      }\r\r                             }\r\r                             else\r\r                          {\r\r                                     print "Signature unknown\n";\r\r                          }\r\r                             print "</p>\n";\r\r                       }\r\r             }\r\r     }\r\r?>\r\r</body>\r\r</html>\r\r
\ No newline at end of file
+<html>
+<head><title>xmlrpc - Introspect demo</title></head>
+<body>
+<h1>Introspect demo</h1>
+<h2>Query server for available methods and their description</h2>
+<h3>The code demonstrates usage of multicall and introspection methods</h3>
+<?php
+
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+function display_error($r)
+{
+    print "An error occurred: ";
+    print "Code: " . $r->faultCode()
+        . " Reason: '" . $r->faultString() . "'<br/>";
+}
+
+$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
+
+// First off, let's retrieve the list of methods available on the remote server
+print "<h3>methods available at http://" . $client->server . $client->path . "</h3>\n";
+$req = new PhpXmlRpc\Request('system.listMethods');
+$resp = $client->send($req);
+
+if ($resp->faultCode()) {
+    display_error($resp);
+} else {
+    $v = $resp->value();
+
+    // Then, retrieve the signature and help text of each available method
+    foreach ($v as $methodName) {
+        print "<h4>" . $methodName->scalarval() . "</h4>\n";
+        // build messages first, add params later
+        $m1 = new PhpXmlRpc\Request('system.methodHelp');
+        $m2 = new PhpXmlRpc\Request('system.methodSignature');
+        $val = new PhpXmlRpc\Value($methodName->scalarval(), "string");
+        $m1->addParam($val);
+        $m2->addParam($val);
+        // Send multiple requests in one http call.
+        // If server does not support multicall, client will automatically fall back to 2 separate calls
+        $ms = array($m1, $m2);
+        $rs = $client->send($ms);
+        if ($rs[0]->faultCode()) {
+            display_error($rs[0]);
+        } else {
+            $val = $rs[0]->value();
+            $txt = $val->scalarval();
+            if ($txt != "") {
+                print "<h4>Documentation</h4><p>${txt}</p>\n";
+            } else {
+                print "<p>No documentation available.</p>\n";
+            }
+        }
+        if ($rs[1]->faultCode()) {
+            display_error($rs[1]);
+        } else {
+            print "<h4>Signature</h4><p>\n";
+            // note: using PhpXmlRpc\Encoder::decode() here would lead to cleaner code
+            $val = $rs[1]->value();
+            if ($val->kindOf() == "array") {
+                foreach ($val as $x) {
+                    $ret = $x[0];
+                    print "<code>" . $ret->scalarval() . " "
+                        . $methodName->scalarval() . "(";
+                    if ($x->count() > 1) {
+                        for ($k = 1; $k < $x->count(); $k++) {
+                            $y = $x[$k];
+                            print $y->scalarval();
+                            if ($k < $x->count() - 1) {
+                                print ", ";
+                            }
+                        }
+                    }
+                    print ")</code><br/>\n";
+                }
+            } else {
+                print "Signature unknown\n";
+            }
+            print "</p>\n";
+        }
+    }
+}
+?>
+</body>
+</html>
index 5f0916c..9486e09 100644 (file)
@@ -1,69 +1,66 @@
 <?php
 // Allow users to see the source of this file even if PHP is not configured for it
-if ((isset($HTTP_GET_VARS['showSource']) && $HTTP_GET_VARS['showSource']) ||
-       (isset($_GET['showSource']) && $_GET['showSource']))
-       { highlight_file(__FILE__); die(); }
+if (isset($_GET['showSource']) && $_GET['showSource']) {
+    highlight_file(__FILE__);
+    die();
+}
 ?>
 <html>
-<head><title>xmlrpc</title></head>
+<head><title>xmlrpc - Mail demo</title></head>
 <body>
 <h1>Mail demo</h1>
-<p>This form enables you to send mail via an XML-RPC server. For public use
-only the "Userland" server will work (see <a href="http://www.xmlrpc.com/discuss/msgReader$598">Dave Winer's message</a>).
-When you press <kbd>Send</kbd> this page will reload, showing you the XML-RPC request sent to the host server, the XML-RPC response received and the internal evaluation done by the PHP implementation.</p>
+
+<p>This form enables you to send mail via an XML-RPC server.
+    When you press <kbd>Send</kbd> this page will reload, showing you the XML-RPC request sent to the host server, the
+    XML-RPC response received and the internal evaluation done by the PHP implementation.</p>
+
 <p>You can find the source to this page here: <a href="mail.php?showSource=1">mail.php</a><br/>
-And the source to a functionally identical mail-by-XML-RPC server in the file <a href="../server/server.php?showSource=1">server.php</a> included with the library (look for the 'mail_send' method)</p>
+    And the source to a functionally identical mail-by-XML-RPC server in the file <a
+        href="../server/server.php?showSource=1">server.php</a> included with the library (look for the 'mail_send'
+    method)</p>
 <?php
-include("xmlrpc.inc");
 
-// Play nice to PHP 5 installations with REGISTER_LONG_ARRAYS off
-if (!isset($HTTP_POST_VARS) && isset($_POST))
-       $HTTP_POST_VARS = $_POST;
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
 
-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 (isset($_POST["mailto"]) && $_POST["mailto"]) {
+    $server = "http://phpxmlrpc.sourceforge.net/server.php";
+    $req = new PhpXmlRpc\Request('mail.send', array(
+        new PhpXmlRpc\Value($_POST["mailto"]),
+        new PhpXmlRpc\Value($_POST["mailsub"]),
+        new PhpXmlRpc\Value($_POST["mailmsg"]),
+        new PhpXmlRpc\Value($_POST["mailfrom"]),
+        new PhpXmlRpc\Value($_POST["mailcc"]),
+        new PhpXmlRpc\Value($_POST["mailbcc"]),
+        new PhpXmlRpc\Value("text/plain")
+    ));
 
-       $c=new xmlrpc_client($XP, $XS, 80);
-       $c->setDebug(2);
-       $r=&$c->send($f);
-       if (!$r->faultCode()) {
-               print "Mail sent OK<br/>\n";
-       } else {
-               print "<fonr color=\"red\">";
-               print "Mail send failed<br/>\n";
-               print "Fault: ";
-               print "Code: " . htmlspecialchars($r->faultCode()) .
-         " Reason: '" . htmlspecialchars($r->faultString()) . "'<br/>";
-               print "</font><br/>";
-       }
+    $client = new PhpXmlRpc\Client($server);
+    $client->setDebug(2);
+    $resp = $client->send($req);
+    if (!$resp->faultCode()) {
+        print "Mail sent OK<br/>\n";
+    } else {
+        print "<fonr color=\"red\">";
+        print "Mail send failed<br/>\n";
+        print "Fault: ";
+        print "Code: " . htmlspecialchars($resp->faultCode()) .
+            " Reason: '" . htmlspecialchars($resp->faultString()) . "'<br/>";
+        print "</font><br/>";
+    }
 }
 ?>
 <form method="POST">
-Server <select name="server"><option value="Userland">Userland</option>
-<option value="UsefulInc">UsefulInc private server</option></select>
-<hr/>
-From <input size="60" name="mailfrom" value=""/><br/>
-<hr/>
-To <input size="60" name="mailto" value=""/><br/>
-Cc <input size="60" name="mailcc" value=""/><br/>
-Bcc <input size="60" name="mailbcc" value=""/><br/>
-<hr/>
-Subject <input size="60" name="mailsub" value="A message from xmlrpc"/>
-<hr/>
-Body <textarea rows="7" cols="60" name="mailmsg">Your message here</textarea><br/>
-<input type="Submit" value="Send"/>
+    From <input size="60" name="mailfrom" value=""/><br/>
+    <hr/>
+    To <input size="60" name="mailto" value=""/><br/>
+    Cc <input size="60" name="mailcc" value=""/><br/>
+    Bcc <input size="60" name="mailbcc" value=""/><br/>
+    <hr/>
+    Subject <input size="60" name="mailsub" value="A message from xmlrpc"/>
+    <hr/>
+    Body <textarea rows="7" cols="60" name="mailmsg">Your message here</textarea><br/>
+    <input type="Submit" value="Send"/>
 </form>
 </body>
 </html>
diff --git a/demo/client/proxy.php b/demo/client/proxy.php
new file mode 100644 (file)
index 0000000..7173db0
--- /dev/null
@@ -0,0 +1,60 @@
+<html>
+<head><title>xmlrpc - Proxy demo</title></head>
+<body>
+<h1>proxy demo</h1>
+<h2>Query server using a 'proxy' object</h2>
+<h3>The code demonstrates usage for the terminally lazy. For a more complete proxy, look at at the Wrapper class</h3>
+<?php
+
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+class PhpXmlRpcProxy
+{
+    protected $client;
+    protected $prefix = 'examples.';
+
+    public function __construct(PhpXmlRpc\Client $client)
+    {
+        $this->client = $client;
+    }
+
+    /**
+     * Translates any method call to an xmlrpc call.
+     *
+     * @author Toth Istvan
+     *
+     * @param string $name remote function name. Will be prefixed
+     * @param array $arguments
+     *
+     * @return mixed
+     *
+     * @throws Exception
+     */
+    function __call($name, $arguments)
+    {
+        $encoder = new PhpXmlRpc\Encoder();
+        $valueArray = array();
+        foreach ($arguments as $parameter) {
+            $valueArray[] = $encoder->encode($parameter);
+        }
+
+        // just in case this was set to something else
+        $this->client->return_type = 'phpvals';
+
+        $resp = $this->client->send(new PhpXmlRpc\Request($this->prefix.$name, $valueArray));
+
+        if ($resp->faultCode()) {
+            throw new Exception($resp->faultString(), $resp->faultCode());
+        } else {
+            return $resp->value();
+        }
+    }
+
+}
+
+$stateNo = rand(1, 51);
+$proxy = new PhpXmlRpcProxy(new \PhpXmlRpc\Client('http://phpxmlrpc.sourceforge.net/server.php'));
+$stateName = $proxy->getStateName($stateNo);
+
+echo "State $stateNo is ".htmlspecialchars($stateName);
\ No newline at end of file
diff --git a/demo/client/simple_call.php b/demo/client/simple_call.php
deleted file mode 100644 (file)
index 9d47dc8..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-<?php
-/**
- * Helper function for the terminally lazy
- *
- * @copyright (c) 2006-2014 G. Giunta
- * @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;
-                       }
-
-                       $xmlrpcval_array = array();
-                       foreach($varargs as $parameter)
-                       {
-                               $xmlrpcval_array[] = php_xmlrpc_encode($parameter);
-                       }
-
-                       return $client->send(new xmlrpcmsg($remote_function_name, $xmlrpcval_array));
-               }
-       }
-?>
index 8b1ba48..5d33215 100644 (file)
@@ -1 +1,30 @@
-<html>\r\r<head><title>xmlrpc</title></head>\r\r<body>\r\r<h1>Which toolkit demo</h1>\r\r<h2>Query server for toolkit information</h2>\r\r<h3>The code demonstrates usage of the php_xmlrpc_decode function</h3>\r\r<?php\r\r        include("xmlrpc.inc");\r\r\r\r      $f = new xmlrpcmsg('interopEchoTests.whichToolkit', array());\r\r $c = new xmlrpc_client("/server.php", "phpxmlrpc.sourceforge.net", 80);\r\r       $r = $c->send($f);\r\r    if(!$r->faultCode())\r\r  {\r\r             $v = php_xmlrpc_decode($r->value());\r\r          print "<pre>";\r\r                print "name: " . htmlspecialchars($v["toolkitName"]) . "\n";\r\r          print "version: " . htmlspecialchars($v["toolkitVersion"]) . "\n";\r\r            print "docs: " . htmlspecialchars($v["toolkitDocsUrl"]) . "\n";\r\r               print "os: " . htmlspecialchars($v["toolkitOperatingSystem"]) . "\n";\r\r         print "</pre>";\r\r       }\r\r     else\r\r  {\r\r             print "An error occurred: ";\r\r          print "Code: " . htmlspecialchars($r->faultCode()) . " Reason: '" . htmlspecialchars($r->faultString()) . "'\n";\r\r      }\r\r?>\r\r</body>\r\r</html>\r\r
\ No newline at end of file
+<html>
+<head><title>xmlrpc - Which toolkit demo</title></head>
+<body>
+<h1>Which toolkit demo</h1>
+<h2>Query server for toolkit information</h2>
+<h3>The code demonstrates usage of the PhpXmlRpc\Encoder class</h3>
+<?php
+
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+$req = new PhpXmlRpc\Request('interopEchoTests.whichToolkit', array());
+$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
+$resp = $client->send($req);
+if (!$resp->faultCode()) {
+    $encoder = new PhpXmlRpc\Encoder();
+    $value = $encoder->decode($resp->value());
+    print "<pre>";
+    print "name: " . htmlspecialchars($value["toolkitName"]) . "\n";
+    print "version: " . htmlspecialchars($value["toolkitVersion"]) . "\n";
+    print "docs: " . htmlspecialchars($value["toolkitDocsUrl"]) . "\n";
+    print "os: " . htmlspecialchars($value["toolkitOperatingSystem"]) . "\n";
+    print "</pre>";
+} else {
+    print "An error occurred: ";
+    print "Code: " . htmlspecialchars($resp->faultCode()) . " Reason: '" . htmlspecialchars($resp->faultString()) . "'\n";
+}
+?>
+</body>
+</html>
index 458f668..c13c55d 100644 (file)
@@ -1,56 +1,53 @@
 <html>
-<head><title>xmlrpc</title></head>
+<head><title>xmlrpc - Webservice wrappper demo</title></head>
 <body>
 <h1>Webservice wrappper demo</h1>
+
 <h2>Wrap methods exposed by server into php functions</h2>
-<h3>The code demonstrates usage of the most automagic client usage possible:<br/>
-1) client that returns php values instead of xmlrpcval objects<br/>
-2) wrapping of remote methods into php functions
+
+<h3>The code demonstrates usage of some the most automagic client usage possible:<br/>
+    1) client that returns php values instead of xmlrpc value objects<br/>
+    2) wrapping of remote methods into php functions<br/>
+    See also proxy.php for an alternative take
 </h3>
 <?php
-       include("xmlrpc.inc");
-       include("xmlrpc_wrappers.inc");
 
-       $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 "<p>Server methods list could not be retrieved: error '".htmlspecialchars($r->faultString())."'</p>\n";
-       }
-       else
-       {
-               $testcase = '';
-               echo "<p>Server methods list retrieved, now wrapping it up...</p>\n<ul>\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 "<li>Remote server method ".htmlspecialchars($methodname)." wrapped into php function ".$funcname."</li>\n";
-                               }
-                               else
-                               {
-                                       echo "<li>Remote server method ".htmlspecialchars($methodname)." could not be wrapped!</li>\n";
-                               }
-                               if($methodname == 'examples.getStateName')
-                               {
-                                       $testcase = $funcname;
-                               }
-                       }
-               }
-               echo "</ul>\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);
-               }
-       }
+include_once __DIR__ . "/../../src/Autoloader.php";
+PhpXmlRpc\Autoloader::register();
+
+$client = new PhpXmlRpc\Client("http://phpxmlrpc.sourceforge.net/server.php");
+$client->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals
+$resp = $client->send(new PhpXmlRpc\Request('system.listMethods'));
+if ($resp->faultCode()) {
+    echo "<p>Server methods list could not be retrieved: error {$resp->faultCode()} '" . htmlspecialchars($resp->faultString()) . "'</p>\n";
+} else {
+    echo "<p>Server methods list retrieved, now wrapping it up...</p>\n<ul>\n";
+    flush();
+
+    $callable = false;
+    $wrapper = new PhpXmlRpc\Wrapper();
+    foreach ($resp->value() as $methodName) {
+        // $resp->value is an array of strings
+        if ($methodName == 'examples.getStateName') {
+            $callable = $wrapper->wrapXmlrpcMethod($client, $methodName);
+            if ($callable) {
+                echo "<li>Remote server method " . htmlspecialchars($methodName) . " wrapped into php function</li>\n";
+            } else {
+                echo "<li>Remote server method " . htmlspecialchars($methodName) . " could not be wrapped!</li>\n";
+            }
+            break;
+        }
+    }
+    echo "</ul>\n";
+    flush();
+
+    if ($callable) {
+        echo "Now testing function for remote method to convert U.S. state number into state name";
+        $stateNum = rand(1, 51);
+        // the 2nd parameter gets added to the closure - it is teh debug level to be used for the client
+        $stateName = $callable($stateNum, 2);
+    }
+}
 ?>
 </body>
 </html>
diff --git a/demo/client/zopetest.php b/demo/client/zopetest.php
deleted file mode 100644 (file)
index 7ecfeb5..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-<html>
-<head><title>xmlrpc</title></head>
-<body>
-<h1>Zope test demo</h1>
-<h3>The code demonstrates usage of basic authentication to connect to the server</h3>
-<?php
-       include("xmlrpc.inc");
-
-       $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()) . "<br/>";
-               print "<hr/>I got this value back<br/>pre>" .
-               htmlentities($r->serialize()). "</pre>\n";
-       }
-       else
-       {
-               print "An error occurred: ";
-               print "Code: " . htmlspecialchars($r->faultCode())
-                       . " Reason: '" . ($r->faultString()) . "'<br/>";
-       }
-?>
-</body>
-</html>
diff --git a/demo/demo1.txt b/demo/demo1.txt
deleted file mode 100644 (file)
index 2543c90..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0"?>
-          <methodResponse>
-             <params>
-                <param>
-                   <value>
-               <struct>
-<member><name>thearray</name>
-<value><array>
-<data>
-<value><string>ABCDEFHIJ</string></value>
-<value><int>1234</int></value>
-<value><boolean>1</boolean></value>
-</data>
-</array></value>
-</member>
-<member><name>theint</name>
-<value><int>23</int></value>
-</member>
-<member><name>thestring</name>
-<value><string>foobarwhizz</string></value>
-</member>
-<member><name>thestruct</name>
-<value><struct>
-<member><name>one</name>
-<value><int>1</int></value>
-</member>
-<member><name>two</name>
-<value><int>2</int></value>
-</member>
-</struct></value>
-</member>
-</struct>
-               </value>
-                   </param>
-                </params>
-             </methodResponse>
diff --git a/demo/demo1.xml b/demo/demo1.xml
new file mode 100644 (file)
index 0000000..eeb6a69
--- /dev/null
@@ -0,0 +1,60 @@
+<?xml version="1.0"?>
+<methodResponse>
+    <params>
+        <param>
+            <value>
+                <struct>
+                    <member>
+                        <name>thearray</name>
+                        <value>
+                            <array>
+                                <data>
+                                    <value>
+                                        <string>ABCDEFHIJ</string>
+                                    </value>
+                                    <value>
+                                        <int>1234</int>
+                                    </value>
+                                    <value>
+                                        <boolean>1</boolean>
+                                    </value>
+                                </data>
+                            </array>
+                        </value>
+                    </member>
+                    <member>
+                        <name>theint</name>
+                        <value>
+                            <int>23</int>
+                        </value>
+                    </member>
+                    <member>
+                        <name>thestring</name>
+                        <value>
+                            <string>foobarwhizz</string>
+                        </value>
+                    </member>
+                    <member>
+                        <name>thestruct</name>
+                        <value>
+                            <struct>
+                                <member>
+                                    <name>one</name>
+                                    <value>
+                                        <int>1</int>
+                                    </value>
+                                </member>
+                                <member>
+                                    <name>two</name>
+                                    <value>
+                                        <int>2</int>
+                                    </value>
+                                </member>
+                            </struct>
+                        </value>
+                    </member>
+                </struct>
+            </value>
+        </param>
+    </params>
+</methodResponse>
diff --git a/demo/demo2.txt b/demo/demo2.txt
deleted file mode 100644 (file)
index 2891422..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0"?>
-          <methodResponse>
-             <params>
-                <param>
-                   <value><string>South Dakota's own</string></value>
-                   </param>
-                </params>
-             </methodResponse>
diff --git a/demo/demo2.xml b/demo/demo2.xml
new file mode 100644 (file)
index 0000000..3289caf
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0"?>
+<methodResponse>
+    <params>
+        <param>
+            <value>
+                <string>South Dakota's own</string>
+            </value>
+        </param>
+    </params>
+</methodResponse>
diff --git a/demo/demo3.txt b/demo/demo3.txt
deleted file mode 100644 (file)
index 9247fca..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0"?>
-          <methodResponse>
-             <fault>
-                <value>
-                   <struct>
-                      <member>
-                         <name>faultCode</name>
-                         <value><int>4</int></value>
-                         </member>
-                      <member>
-                         <name>faultString</name>
-                         <value><string>Too many parameters.</string></value>
-                         </member>
-                      </struct>
-                   </value>
-                </fault>
-             </methodResponse>
diff --git a/demo/demo3.xml b/demo/demo3.xml
new file mode 100644 (file)
index 0000000..ed94aab
--- /dev/null
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+<methodResponse>
+    <fault>
+        <value>
+            <struct>
+                <member>
+                    <name>faultCode</name>
+                    <value>
+                        <int>4</int>
+                    </value>
+                </member>
+                <member>
+                    <name>faultString</name>
+                    <value>
+                        <string>Too many parameters.</string>
+                    </value>
+                </member>
+            </struct>
+        </value>
+    </fault>
+</methodResponse>
index 7072305..ac65209 100644 (file)
 <?php
 
-       include("xmlrpc.inc");
-       include("xmlrpcs.inc");
+include_once __DIR__ . "/../../vendor/autoload.php";
 
-       $addcomment_sig=array(array($xmlrpcInt, $xmlrpcString, $xmlrpcString, $xmlrpcString));
+use PhpXmlRpc\Value;
 
-       $addcomment_doc='Adds a comment to an item. The first parameter
+$addComment_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString));
+
+$addComment_doc = 'Adds a comment to an item. The first parameter
 is the item ID, the second the name of the commenter, and the third
 is the comment itself. Returns the number of comments against that
 ID.';
 
-       function addcomment($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);
-               $msgID = $n[0];
-               $name  = $n[1];
-               $comment = $n[2];
+function addComment($req)
+{
+    $err = "";
+    // since validation has already been carried out for us,
+    // we know we got exactly 3 string values
+    $encoder = new PhpXmlRpc\Encoder();
+    $n = $encoder->decode($req);
+    $msgID = $n[0];
+    $name = $n[1];
+    $comment = $n[2];
 
-               $dbh=dba_open("/tmp/comments.db", "c", "db2");
-               if($dbh)
-               {
-                       $countID="${msgID}_count";
-                       if(dba_exists($countID, $dbh))
-                       {
-                               $count=dba_fetch($countID, $dbh);
-                       }
-                       else
-                       {
-                               $count=0;
-                       }
-                       // add the new comment in
-                       dba_insert($msgID . "_comment_${count}", $comment, $dbh);
-                       dba_insert($msgID . "_name_${count}", $name, $dbh);
-                       $count++;
-                       dba_replace($countID, $count, $dbh);
-                       dba_close($dbh);
-               }
-               else
-               {
-                       $err="Unable to open comments database.";
-               }
-               // if we generated an error, create an error return response
-               if($err)
-               {
-                       return new xmlrpcresp(0, $xmlrpcerruser, $err);
-               }
-               else
-               {
-                       // otherwise, we create the right response
-                       // with the state name
-                       return new xmlrpcresp(new xmlrpcval($count, "int"));
-               }
-       }
+    $dbh = dba_open("/tmp/comments.db", "c", "db2");
+    if ($dbh) {
+        $countID = "${msgID}_count";
+        if (dba_exists($countID, $dbh)) {
+            $count = dba_fetch($countID, $dbh);
+        } else {
+            $count = 0;
+        }
+        // add the new comment in
+        dba_insert($msgID . "_comment_${count}", $comment, $dbh);
+        dba_insert($msgID . "_name_${count}", $name, $dbh);
+        $count++;
+        dba_replace($countID, $count, $dbh);
+        dba_close($dbh);
+    } else {
+        $err = "Unable to open comments database.";
+    }
+    // if we generated an error, create an error return response
+    if ($err) {
+        return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
+    } else {
+        // otherwise, we create the right response
+        return new PhpXmlRpc\Response(new PhpXmlRpc\Value($count, "int"));
+    }
+}
 
-       $getcomments_sig=array(array($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)
-       {
-               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));
-               }
-       }
+function getComments($req)
+{
+    $err = "";
+    $ra = array();
+    $encoder = new PhpXmlRpc\Encoder();
+    $msgID = $encoder->decode($req->getParam(0));
+    $dbh = dba_open("/tmp/comments.db", "r", "db2");
+    if ($dbh) {
+        $countID = "${msgID}_count";
+        if (dba_exists($countID, $dbh)) {
+            $count = dba_fetch($countID, $dbh);
+            for ($i = 0; $i < $count; $i++) {
+                $name = dba_fetch("${msgID}_name_${i}", $dbh);
+                $comment = dba_fetch("${msgID}_comment_${i}", $dbh);
+                // push a new struct onto the return array
+                $ra[] = array(
+                    "name" => $name,
+                    "comment" => $comment,
+                );
+            }
+        }
+    }
+    // if we generated an error, create an error return response
+    if ($err) {
+        return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
+    } else {
+        // otherwise, we create the right response
+        return new PhpXmlRpc\Response($encoder->encode($ra));
+    }
+}
 
-       $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
-               )
-       ));
-?>
+$srv = new PhpXmlRpc\Server(array(
+    "discuss.addComment" => array(
+        "function" => "addComment",
+        "signature" => $addComment_sig,
+        "docstring" => $addComment_doc,
+    ),
+    "discuss.getComments" => array(
+        "function" => "getComments",
+        "signature" => $getComments_sig,
+        "docstring" => $getComments_doc,
+    ),
+));
index 684be95..6e791f4 100644 (file)
@@ -2,84 +2,87 @@
 /**
  * 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
+ * @copyright (C) 2006-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
  */
 
-       include("xmlrpc.inc");
-       include("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)
-       * @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.
+ *
+ * DO NOT RUN AS IS IN PRODUCTION - this is an open relay !!!
+ *
+ * @param PhpXmlRpc\Request $req (see method docs below for a description of the expected parameters)
+ *
+ * @return PhpXmlRpc\Response
+ */
+function forward_request($req)
+{
+    $encoder = new \PhpXmlRpc\Encoder();
+
+    // create client
+    $timeout = 0;
+    $url = $encoder->decode($req->getParam(0));
+    $client = new PhpXmlRpc\Client($url);
+
+    if ($req->getNumParams() > 3) {
+        // we have to set some options onto the client.
+        // Note that if we do not untaint the received values, warnings might be generated...
+        $options = $encoder->decode($req->getParam(3));
+        foreach ($options as $key => $val) {
+            switch ($key) {
+                case 'Cookie':
+                    break;
+                case 'Credentials':
+                    break;
+                case 'RequestCompression':
+                    $client->setRequestCompression($val);
+                    break;
+                case 'SSLVerifyHost':
+                    $client->setSSLVerifyHost($val);
+                    break;
+                case 'SSLVerifyPeer':
+                    $client->setSSLVerifyPeer($val);
+                    break;
+                case 'Timeout':
+                    $timeout = (integer)$val;
+                    break;
+            } // switch
+        }
+    }
+
+    // build call for remote server
+    /// @todo find a way to forward client info (such as IP) to server, either
+    /// - as xml comments in the payload, or
+    /// - using std http header conventions, such as X-forwarded-for...
+    $reqMethod = $encoder->decode($req->getParam(1));
+    $pars = $req->getParam(2);
+    $req = new PhpXmlRpc\Request($reqMethod);
+    foreach ($pars as $par) {
+        $req->addParam($par);
+    }
 
-               // 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
+    PhpXmlRpc\Server::xmlrpc_debugmsg("Sending to server $url the payload: " . $req->serialize());
 
-               // 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);
-       }
+    return $client->send($req, $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 PhpXmlRpc\Server(
+    array(
+        'xmlrpcproxy.call' => array(
+            'function' => 'forward_request',
+            'signature' => array(
+                array('mixed', 'string', 'string', 'array'),
+                array('mixed', 'string', 'string', 'array', 'struct'),
+            ),
+            'docstring' => 'forwards xmlrpc calls to remote servers. Returns remote method\'s response. Accepts params: remote server url (might include basic auth credentials), method name, array of params, and (optionally) a struct containing call options',
+        ),
+    )
+);
index 45caf64..b18cf46 100644 (file)
  * is to be used for unit-testing the library.
  *
  * Please do not copy this file verbatim into your production server.
- *
  **/
 
 // give user a chance to see the source for this server instead of running the services
-if ($_SERVER['REQUEST_METHOD'] != 'POST' && isset($_GET['showSource']))
-{
-       highlight_file(__FILE__);
-       die();
-}
-
-       include("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
+if ($_SERVER['REQUEST_METHOD'] != 'POST' && isset($_GET['showSource'])) {
+    highlight_file(__FILE__);
+    die();
+}
+
+include_once __DIR__ . "/../../vendor/autoload.php";
+
+// out-of-band information: let the client manipulate the server operations.
+// we do this to help the testsuite script: do not reproduce in production!
+if (isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) {
+    $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = '/tmp/phpxmlrpc_coverage';
+    if (!is_dir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'])) {
+        mkdir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY']);
+    }
+
+    include_once __DIR__ . "/../../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/prepend.php";
+}
+
+use PhpXmlRpc\Value;
+
+/**
+ * Used to test usage of object methods in dispatch maps and in wrapper code.
+ */
+class xmlrpcServerMethodsContainer
+{
+    /**
+     * Method used to test logging of php warnings generated by user functions.
+     * @param PhpXmlRpc\Request $req
+     * @return PhpXmlRpc\Response
+     */
+    public function phpWarningGenerator($req)
+    {
+        $a = $undefinedVariable; // this triggers a warning in E_ALL mode, since $undefinedVariable is undefined
+        return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcBoolean));
+    }
+
+    /**
+     * Method used to test catching of exceptions in the server.
+     * @param PhpXmlRpc\Request $req
+     * @throws Exception
+     */
+    public function exceptionGenerator($req)
+    {
+        throw new Exception("it's just a test", 1);
+    }
+
+    /**
+     * @param string $msg
+     */
+    public function debugMessageGenerator($msg)
+    {
+        PhpXmlRpc\Server::xmlrpc_debugmsg($msg);
+    }
+
+    /**
+     * A PHP version of the state-number server. Send me an integer and i'll sell you a state.
+     * Used to test wrapping of PHP methods into xmlrpc methods.
+     *
+     * @param integer $num
+     * @return string
+     * @throws Exception
+     */
+    public static function findState($num)
+    {
+        return inner_findstate($num);
+    }
+
+    /**
+     * Returns an instance of stdClass.
+     * Used to test wrapping of PHP objects with class preservation
+     */
+    public function returnObject()
+    {
+        $obj = new stdClass();
+        $obj->hello = 'world';
+        return $obj;
+    }
+}
+
+// a PHP version of the state-number server
+// send me an integer and i'll sell you a state
+
+$stateNames = array(
+    "Alabama", "Alaska", "Arizona", "Arkansas", "California",
+    "Colorado", "Columbia", "Connecticut", "Delaware", "Florida",
+    "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
+    "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
+    "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada",
+    "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina",
+    "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
+    "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont",
+    "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming",
+);
+
+$findstate_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcInt));
+$findstate_doc = 'When passed an integer between 1 and 51 returns the
 name of a US state, where the integer is the index of that state name
 in an alphabetic order.';
 
+function findState($req)
+{
+    global $stateNames;
+
+    $err = "";
+    // get the first param
+    $sno = $req->getParam(0);
+
+    // param must be there and of the correct type: server object does the validation for us
+
+    // extract the value of the state number
+    $snv = $sno->scalarval();
+    // look it up in our array (zero-based)
+    if (isset($stateNames[$snv - 1])) {
+        $stateName = $stateNames[$snv - 1];
+    } else {
+        // not there, so complain
+        $err = "I don't have a state for the index '" . $snv . "'";
+    }
+
+    // if we generated an error, create an error return response
+    if ($err) {
+        return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
+    } else {
+        // otherwise, we create the right response with the state name
+        return new PhpXmlRpc\Response(new Value($stateName));
+    }
+}
+
+/**
+ * Inner code of the state-number server.
+ * Used to test wrapping of PHP functions into xmlrpc methods.
+ *
+ * @param integer $stateNo the state number
+ *
+ * @return string the name of the state (or error description)
+ *
+ * @throws Exception if state is not found
+ */
+function inner_findstate($stateNo)
+{
+    global $stateNames;
+
+    if (isset($stateNames[$stateNo - 1])) {
+        return $stateNames[$stateNo - 1];
+    } else {
+        // not, there so complain
+        throw new Exception("I don't have a state for the index '" . $stateNo . "'", PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser);
+    }
+}
+
+$wrapper = new PhpXmlRpc\Wrapper();
+
+$findstate2_sig = $wrapper->wrapPhpFunction('inner_findstate');
+
+$findstate3_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'));
+
+$obj = new xmlrpcServerMethodsContainer();
+$findstate4_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'));
+
+$findstate5_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true));
+eval($findstate5_sig['source']);
+
+$findstate6_sig = $wrapper->wrapPhpFunction('inner_findstate', '', array('return_source' => true));
+eval($findstate6_sig['source']);
+
+$findstate7_sig = $wrapper->wrapPhpFunction(array('xmlrpcServerMethodsContainer', 'findState'), '', array('return_source' => true));
+eval($findstate7_sig['source']);
+
+$obj = new xmlrpcServerMethodsContainer();
+$findstate8_sig = $wrapper->wrapPhpFunction(array($obj, 'findstate'), '', array('return_source' => true));
+eval($findstate8_sig['source']);
+
+$findstate9_sig = $wrapper->wrapPhpFunction('xmlrpcServerMethodsContainer::findState', '', array('return_source' => true));
+eval($findstate9_sig['source']);
+
+$findstate10_sig = array(
+    "function" => function ($req) { return findState($req); },
+    "signature" => $findstate_sig,
+    "docstring" => $findstate_doc,
+);
+
+$findstate11_sig = $wrapper->wrapPhpFunction(function ($stateNo) { return inner_findstate($stateNo); });
+
+$c = new xmlrpcServerMethodsContainer;
+$moreSignatures = $wrapper->wrapPhpClass($c, array('prefix' => 'tests.', 'method_type' => 'all'));
+
+$returnObj_sig =  $wrapper->wrapPhpFunction(array($c, 'returnObject'), '', array('encode_php_objs' => true));
+
+// used to test signatures with NULL params
+$findstate12_sig = array(
+    array(Value::$xmlrpcString, Value::$xmlrpcInt, Value::$xmlrpcNull),
+    array(Value::$xmlrpcString, Value::$xmlrpcNull, Value::$xmlrpcInt),
+);
+
+function findStateWithNulls($req)
+{
+    $a = $req->getParam(0);
+    $b = $req->getParam(1);
+
+    if ($a->scalartyp() == Value::$xmlrpcNull)
+        return new PhpXmlRpc\Response(new Value(inner_findstate($b->scalarval())));
+    else
+        return new PhpXmlRpc\Response(new Value(inner_findstate($a->scalarval())));
+}
+
+$addtwo_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt, Value::$xmlrpcInt));
+$addtwo_doc = 'Add two integers together and return the result';
+function addTwo($req)
+{
+    $s = $req->getParam(0);
+    $t = $req->getParam(1);
+
+    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcInt));
+}
 
-       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:
+$addtwodouble_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble, Value::$xmlrpcDouble));
+$addtwodouble_doc = 'Add two doubles together and return the result';
+function addTwoDouble($req)
+{
+    $s = $req->getParam(0);
+    $t = $req->getParam(1);
+
+    return new PhpXmlRpc\Response(new Value($s->scalarval() + $t->scalarval(), Value::$xmlrpcDouble));
+}
+
+$stringecho_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
+$stringecho_doc = 'Accepts a string parameter, returns the string.';
+function stringEcho($req)
+{
+    // just sends back a string
+    return new PhpXmlRpc\Response(new Value($req->getParam(0)->scalarval()));
+}
+
+$echoback_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
+$echoback_doc = 'Accepts a string parameter, returns the entire incoming payload';
+function echoBack($req)
+{
+    // just sends back a string with what i got sent to me, just escaped, that's all
+    $s = "I got the following message:\n" . $req->serialize();
+
+    return new PhpXmlRpc\Response(new Value($s));
+}
+
+$echosixtyfour_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcBase64));
+$echosixtyfour_doc = 'Accepts a base64 parameter and returns it decoded as a string';
+function echoSixtyFour($req)
+{
+    // Accepts an encoded value, but sends it back as a normal string.
+    // This is to test that base64 encoding is working as expected
+    $incoming = $req->getParam(0);
+
+    return new PhpXmlRpc\Response(new Value($incoming->scalarval(), Value::$xmlrpcString));
+}
+
+$bitflipper_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$bitflipper_doc = 'Accepts an array of booleans, and returns them inverted';
+function bitFlipper($req)
+{
+    $v = $req->getParam(0);
+    $rv = new Value(array(), Value::$xmlrpcArray);
+
+    foreach ($v as $b) {
+        if ($b->scalarval()) {
+            $rv[] = new Value(false, Value::$xmlrpcBoolean);
+        } else {
+            $rv[] = new Value(true, Value::$xmlrpcBoolean);
+        }
+    }
+
+    return new PhpXmlRpc\Response($rv);
+}
+
+// Sorting demo
+//
+// send me an array of structs thus:
+//
+// Dave 35
+// Edd  45
+// Fred 23
+// Barney 37
+//
+// and I'll return it to you in sorted order
+
+function agesorter_compare($a, $b)
+{
+    global $agesorter_arr;
+
+    // don't even ask me _why_ these come padded with hyphens, I couldn't tell you :p
+    $a = str_replace("-", "", $a);
+    $b = str_replace("-", "", $b);
+
+    if ($agesorter_arr[$a] == $agesorter_arr[$b]) {
+        return 0;
+    }
+
+    return ($agesorter_arr[$a] > $agesorter_arr[$b]) ? -1 : 1;
+}
+
+$agesorter_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$agesorter_doc = 'Send this method an array of [string, int] structs, eg:
 <pre>
  Dave   35
- Edd   45
+ Edd    45
  Fred   23
  Barney 37
 </pre>
 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 "<!-- found $max array elements -->\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)<br/>
+function ageSorter($req)
+{
+    global $agesorter_arr, $s;
+
+    PhpXmlRpc\Server::xmlrpc_debugmsg("Entering 'agesorter'");
+    // get the parameter
+    $sno = $req->getParam(0);
+    // error string for [if|when] things go wrong
+    $err = "";
+    $agar = array();
+
+    $max = $sno->count();
+    PhpXmlRpc\Server::xmlrpc_debugmsg("Found $max array elements");
+    foreach ($sno as $i => $rec) {
+        if ($rec->kindOf() != "struct") {
+            $err = "Found non-struct in array at element $i";
+            break;
+        }
+        // extract name and age from struct
+        $n = $rec["name"];
+        $a = $rec["age"];
+        // $n and $a are xmlrpcvals,
+        // so get the scalarval from them
+        $agar[$n->scalarval()] = $a->scalarval();
+    }
+
+    // create the output value
+    $v = new Value(array(), Value::$xmlrpcArray);
+
+    $agesorter_arr = $agar;
+    // hack, must make global as uksort() won't
+    // allow us to pass any other auxiliary information
+    uksort($agesorter_arr, 'agesorter_compare');
+    while (list($key, $val) = each($agesorter_arr)) {
+        // recreate each struct element
+        $v[] = new Value(
+            array(
+                "name" => new Value($key),
+                "age" => new Value($val, "int")
+            ),
+            Value::$xmlrpcStruct
+        );
+    }
+
+    if ($err) {
+        return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
+    } else {
+        return new PhpXmlRpc\Response($v);
+    }
+}
+
+// signature and instructions, place these in the dispatch map
+$mailsend_sig = array(array(
+    Value::$xmlrpcBoolean, Value::$xmlrpcString, Value::$xmlrpcString,
+    Value::$xmlrpcString, Value::$xmlrpcString, Value::$xmlrpcString,
+    Value::$xmlrpcString, Value::$xmlrpcString,
+));
+$mailsend_doc = 'mail.send(recipient, subject, text, sender, cc, bcc, mimetype)<br/>
 recipient, cc, and bcc are strings, comma-separated lists of email addresses, as described above.<br/>
 subject is a string, the subject of the message.<br/>
 sender is a string, it\'s the email address of the person sending the message. This string can not be
@@ -336,517 +383,599 @@ a comma-separated list, it must contain a single email address only.<br/>
 text is a string, it contains the body of the message.<br/>
 mimetype, a string, is a standard MIME type, for example, text/plain.
 ';
-       // WARNING; this functionality depends on the sendmail -t option
-       // it may not work with Windows machines properly; particularly
-       // the Bcc option. Sneak on your friends at your own risk!
-       function 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 <i4>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 &lt;i4&gt;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 &lt;i4&gt;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 &lt;, &gt;, &amp; \' and ".<BR>Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.';
-       function v1_countTheEntities($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
-
-       $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
+// WARNING; this functionality depends on the sendmail -t option
+// it may not work with Windows machines properly; particularly
+// the Bcc option. Sneak on your friends at your own risk!
+function mailSend($req)
+{
+    $err = "";
+
+    $mTo = $req->getParam(0);
+    $mSub = $req->getParam(1);
+    $mBody = $req->getParam(2);
+    $mFrom = $req->getParam(3);
+    $mCc = $req->getParam(4);
+    $mBcc = $req->getParam(5);
+    $mMime = $req->getParam(6);
+
+    if ($mTo->scalarval() == "") {
+        $err = "Error, no 'To' field specified";
+    }
+
+    if ($mFrom->scalarval() == "") {
+        $err = "Error, no 'From' field specified";
+    }
+
+    $msgHdr = "From: " . $mFrom->scalarval() . "\n";
+    $msgHdr .= "To: " . $mTo->scalarval() . "\n";
+
+    if ($mCc->scalarval() != "") {
+        $msgHdr .= "Cc: " . $mCc->scalarval() . "\n";
+    }
+    if ($mBcc->scalarval() != "") {
+        $msgHdr .= "Bcc: " . $mBcc->scalarval() . "\n";
+    }
+    if ($mMime->scalarval() != "") {
+        $msgHdr .= "Content-type: " . $mMime->scalarval() . "\n";
+    }
+    $msgHdr .= "X-Mailer: XML-RPC for PHP mailer 1.0";
+
+    if ($err == "") {
+        if (!mail("",
+            $mSub->scalarval(),
+            $mBody->scalarval(),
+            $msgHdr)
+        ) {
+            $err = "Error, could not send the mail.";
+        }
+    }
+
+    if ($err) {
+        return new PhpXmlRpc\Response(0, PhpXmlRpc\PhpXmlRpc::$xmlrpcerruser, $err);
+    } else {
+        return new PhpXmlRpc\Response(new Value(true, Value::$xmlrpcBoolean));
+    }
+}
+
+$getallheaders_sig = array(array(Value::$xmlrpcStruct));
+$getallheaders_doc = 'Returns a struct containing all the HTTP headers received with the request. Provides limited functionality with IIS';
+function getAllHeaders_xmlrpc($req)
+{
+    $encoder = new PhpXmlRpc\Encoder();
+
+    if (function_exists('getallheaders')) {
+        return new PhpXmlRpc\Response($encoder->encode(getallheaders()));
+    } else {
+        $headers = array();
+        // IIS: poor man's version of getallheaders
+        foreach ($_SERVER as $key => $val) {
+            if (strpos($key, 'HTTP_') === 0) {
+                $key = ucfirst(str_replace('_', '-', strtolower(substr($key, 5))));
+                $headers[$key] = $val;
+            }
+        }
+
+        return new PhpXmlRpc\Response($encoder->encode($headers));
+    }
+}
+
+$setcookies_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
+$setcookies_doc = 'Sends to client a response containing a single \'1\' digit, and sets to it http cookies as received in the request (array of structs describing a cookie)';
+function setCookies($req)
+{
+    $encoder = new PhpXmlRpc\Encoder();
+    $cookies = $req->getParam(0);
+    foreach ($cookies as $name => $value) {
+        $cookieDesc = $encoder->decode($value);
+        setcookie($name, @$cookieDesc['value'], @$cookieDesc['expires'], @$cookieDesc['path'], @$cookieDesc['domain'], @$cookieDesc['secure']);
+    }
+
+    return new PhpXmlRpc\Response(new Value(1, Value::$xmlrpcInt));
+}
+
+$getcookies_sig = array(array(Value::$xmlrpcStruct));
+$getcookies_doc = 'Sends to client a response containing all http cookies as received in the request (as struct)';
+function getCookies($req)
+{
+    $encoder = new PhpXmlRpc\Encoder();
+    return new PhpXmlRpc\Response($encoder->encode($_COOKIE));
+}
+
+$v1_arrayOfStructs_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcArray));
+$v1_arrayOfStructs_doc = 'This handler takes a single parameter, an array of structs, each of which contains at least three elements named moe, larry and curly, all <i4>s. Your handler must add all the struct elements named curly and return the result.';
+function v1_arrayOfStructs($req)
+{
+    $sno = $req->getParam(0);
+    $numCurly = 0;
+    foreach ($sno as $str) {
+        foreach ($str as $key => $val) {
+            if ($key == "curly") {
+                $numCurly += $val->scalarval();
+            }
+        }
+    }
+
+    return new PhpXmlRpc\Response(new Value($numCurly, Value::$xmlrpcInt));
+}
+
+$v1_easyStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
+$v1_easyStruct_doc = 'This handler takes a single parameter, a struct, containing at least three elements named moe, larry and curly, all &lt;i4&gt;s. Your handler must add the three numbers and return the result.';
+function v1_easyStruct($req)
+{
+    $sno = $req->getParam(0);
+    $moe = $sno["moe"];
+    $larry = $sno["larry"];
+    $curly = $sno["curly"];
+    $num = $moe->scalarval() + $larry->scalarval() + $curly->scalarval();
+
+    return new PhpXmlRpc\Response(new Value($num, Value::$xmlrpcInt));
+}
+
+$v1_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct));
+$v1_echoStruct_doc = 'This handler takes a single parameter, a struct. Your handler must return the struct.';
+function v1_echoStruct($req)
+{
+    $sno = $req->getParam(0);
+
+    return new PhpXmlRpc\Response($sno);
+}
+
+$v1_manyTypes_sig = array(array(
+    Value::$xmlrpcArray, Value::$xmlrpcInt, Value::$xmlrpcBoolean,
+    Value::$xmlrpcString, Value::$xmlrpcDouble, Value::$xmlrpcDateTime,
+    Value::$xmlrpcBase64,
+));
+$v1_manyTypes_doc = 'This handler takes six parameters, and returns an array containing all the parameters.';
+function v1_manyTypes($req)
+{
+    return new PhpXmlRpc\Response(new Value(
+        array(
+            $req->getParam(0),
+            $req->getParam(1),
+            $req->getParam(2),
+            $req->getParam(3),
+            $req->getParam(4),
+            $req->getParam(5)
+        ),
+        Value::$xmlrpcArray
+    ));
+}
+
+$v1_moderateSizeArrayCheck_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcArray));
+$v1_moderateSizeArrayCheck_doc = 'This handler takes a single parameter, which is an array containing between 100 and 200 elements. Each of the items is a string, your handler must return a string containing the concatenated text of the first and last elements.';
+function v1_moderateSizeArrayCheck($req)
+{
+    $ar = $req->getParam(0);
+    $sz = $ar->count();
+    $first = $ar[0];
+    $last = $ar[$sz - 1];
+
+    return new PhpXmlRpc\Response(new Value($first->scalarval() .
+        $last->scalarval(), Value::$xmlrpcString));
+}
+
+$v1_simpleStructReturn_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcInt));
+$v1_simpleStructReturn_doc = 'This handler takes one parameter, and returns a struct containing three elements, times10, times100 and times1000, the result of multiplying the number by 10, 100 and 1000.';
+function v1_simpleStructReturn($req)
+{
+    $sno = $req->getParam(0);
+    $v = $sno->scalarval();
+
+    return new PhpXmlRpc\Response(new Value(
+        array(
+            "times10" => new Value($v * 10, Value::$xmlrpcInt),
+            "times100" => new Value($v * 100, Value::$xmlrpcInt),
+            "times1000" => new Value($v * 1000, Value::$xmlrpcInt)
+        ),
+        Value::$xmlrpcStruct
+    ));
+}
+
+$v1_nestedStruct_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcStruct));
+$v1_nestedStruct_doc = 'This handler takes a single parameter, a struct, that models a daily calendar. At the top level, there is one struct for each year. Each year is broken down into months, and months into days. Most of the days are empty in the struct you receive, but the entry for April 1, 2000 contains a least three elements named moe, larry and curly, all &lt;i4&gt;s. Your handler must add the three numbers and return the result.';
+function v1_nestedStruct($req)
+{
+    $sno = $req->getParam(0);
+
+    $twoK = $sno["2000"];
+    $april = $twoK["04"];
+    $fools = $april["01"];
+    $curly = $fools["curly"];
+    $larry = $fools["larry"];
+    $moe = $fools["moe"];
+
+    return new PhpXmlRpc\Response(new Value($curly->scalarval() + $larry->scalarval() + $moe->scalarval(), Value::$xmlrpcInt));
+}
+
+$v1_countTheEntities_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcString));
+$v1_countTheEntities_doc = 'This handler takes a single parameter, a string, that contains any number of predefined entities, namely &lt;, &gt;, &amp; \' and ".<BR>Your handler must return a struct that contains five fields, all numbers: ctLeftAngleBrackets, ctRightAngleBrackets, ctAmpersands, ctApostrophes, ctQuotes.';
+function v1_countTheEntities($req)
+{
+    $sno = $req->getParam(0);
+    $str = $sno->scalarval();
+    $gt = 0;
+    $lt = 0;
+    $ap = 0;
+    $qu = 0;
+    $amp = 0;
+    for ($i = 0; $i < strlen($str); $i++) {
+        $c = substr($str, $i, 1);
+        switch ($c) {
+            case ">":
+                $gt++;
+                break;
+            case "<":
+                $lt++;
+                break;
+            case "\"":
+                $qu++;
+                break;
+            case "'":
+                $ap++;
+                break;
+            case "&":
+                $amp++;
+                break;
+            default:
+                break;
+        }
+    }
+
+    return new PhpXmlRpc\Response(new Value(
+        array(
+            "ctLeftAngleBrackets" => new Value($lt, Value::$xmlrpcInt),
+            "ctRightAngleBrackets" => new Value($gt, Value::$xmlrpcInt),
+            "ctAmpersands" => new Value($amp, Value::$xmlrpcInt),
+            "ctApostrophes" => new Value($ap, Value::$xmlrpcInt),
+            "ctQuotes" => new Value($qu, Value::$xmlrpcInt)
+        ),
+        Value::$xmlrpcStruct
+    ));
+}
+
+// trivial interop tests
+// http://www.xmlrpc.com/stories/storyReader$1636
+
+$i_echoString_sig = array(array(Value::$xmlrpcString, Value::$xmlrpcString));
+$i_echoString_doc = "Echoes string.";
+
+$i_echoStringArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$i_echoStringArray_doc = "Echoes string array.";
+
+$i_echoInteger_sig = array(array(Value::$xmlrpcInt, Value::$xmlrpcInt));
+$i_echoInteger_doc = "Echoes integer.";
+
+$i_echoIntegerArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$i_echoIntegerArray_doc = "Echoes integer array.";
+
+$i_echoFloat_sig = array(array(Value::$xmlrpcDouble, Value::$xmlrpcDouble));
+$i_echoFloat_doc = "Echoes float.";
+
+$i_echoFloatArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$i_echoFloatArray_doc = "Echoes float array.";
+
+$i_echoStruct_sig = array(array(Value::$xmlrpcStruct, Value::$xmlrpcStruct));
+$i_echoStruct_doc = "Echoes struct.";
+
+$i_echoStructArray_sig = array(array(Value::$xmlrpcArray, Value::$xmlrpcArray));
+$i_echoStructArray_doc = "Echoes struct array.";
+
+$i_echoValue_doc = "Echoes any value back.";
+$i_echoValue_sig = array(array(Value::$xmlrpcValue, Value::$xmlrpcValue));
+
+$i_echoBase64_sig = array(array(Value::$xmlrpcBase64, Value::$xmlrpcBase64));
+$i_echoBase64_doc = "Echoes base64.";
+
+$i_echoDate_sig = array(array(Value::$xmlrpcDateTime, Value::$xmlrpcDateTime));
+$i_echoDate_doc = "Echoes dateTime.";
+
+function i_echoParam($req)
+{
+    $s = $req->getParam(0);
+
+    return new PhpXmlRpc\Response($s);
+}
+
+function i_echoString($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoInteger($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoFloat($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoStruct($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoStringArray($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoIntegerArray($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoFloatArray($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoStructArray($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoValue($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoBase64($req)
+{
+    return i_echoParam($req);
+}
+
+function i_echoDate($req)
+{
+    return i_echoParam($req);
+}
+
+$i_whichToolkit_sig = array(array(Value::$xmlrpcStruct));
+$i_whichToolkit_doc = "Returns a struct containing the following strings: toolkitDocsUrl, toolkitName, toolkitVersion, toolkitOperatingSystem.";
+
+function i_whichToolkit($req)
+{
+    global $SERVER_SOFTWARE;
+    $ret = array(
+        "toolkitDocsUrl" => "http://phpxmlrpc.sourceforge.net/",
+        "toolkitName" => PhpXmlRpc\PhpXmlRpc::$xmlrpcName,
+        "toolkitVersion" => PhpXmlRpc\PhpXmlRpc::$xmlrpcVersion,
+        "toolkitOperatingSystem" => isset($SERVER_SOFTWARE) ? $SERVER_SOFTWARE : $_SERVER['SERVER_SOFTWARE'],
+    );
+
+    $encoder = new PhpXmlRpc\Encoder();
+    return new PhpXmlRpc\Response($encoder->encode($ret));
+}
+
+$object = new xmlrpcServerMethodsContainer();
+$signatures = array(
+    "examples.getStateName" => array(
+        "function" => "findState",
+        "signature" => $findstate_sig,
+        "docstring" => $findstate_doc,
+    ),
+    "examples.sortByAge" => array(
+        "function" => "ageSorter",
+        "signature" => $agesorter_sig,
+        "docstring" => $agesorter_doc,
+    ),
+    "examples.addtwo" => array(
+        "function" => "addTwo",
+        "signature" => $addtwo_sig,
+        "docstring" => $addtwo_doc,
+    ),
+    "examples.addtwodouble" => array(
+        "function" => "addTwoDouble",
+        "signature" => $addtwodouble_sig,
+        "docstring" => $addtwodouble_doc,
+    ),
+    "examples.stringecho" => array(
+        "function" => "stringEcho",
+        "signature" => $stringecho_sig,
+        "docstring" => $stringecho_doc,
+    ),
+    "examples.echo" => array(
+        "function" => "echoBack",
+        "signature" => $echoback_sig,
+        "docstring" => $echoback_doc,
+    ),
+    "examples.decode64" => array(
+        "function" => "echoSixtyFour",
+        "signature" => $echosixtyfour_sig,
+        "docstring" => $echosixtyfour_doc,
+    ),
+    "examples.invertBooleans" => array(
+        "function" => "bitFlipper",
+        "signature" => $bitflipper_sig,
+        "docstring" => $bitflipper_doc,
+    ),
+    // signature omitted on purpose
+    "tests.generatePHPWarning" => array(
+        "function" => array($object, "phpWarningGenerator"),
+    ),
+    // signature omitted on purpose
+    "tests.raiseException" => array(
+        "function" => array($object, "exceptionGenerator"),
+    ),
+    // Greek word 'kosme'. NB: NOT a valid ISO8859 string!
+    // NB: we can only register this when setting internal encoding to UTF-8, or it will break system.listMethods
+    "tests.utf8methodname." . 'κόσμε' => array(
+        "function" => "stringEcho",
+        "signature" => $stringecho_sig,
+        "docstring" => $stringecho_doc,
+    ),
+    /*"tests.iso88591methodname." . chr(224) . chr(252) . chr(232) => array(
+        "function" => "stringEcho",
+        "signature" => $stringecho_sig,
+        "docstring" => $stringecho_doc,
+    ),*/
+    "examples.getallheaders" => array(
+        "function" => 'getAllHeaders_xmlrpc',
+        "signature" => $getallheaders_sig,
+        "docstring" => $getallheaders_doc,
+    ),
+    "examples.setcookies" => array(
+        "function" => 'setCookies',
+        "signature" => $setcookies_sig,
+        "docstring" => $setcookies_doc,
+    ),
+    "examples.getcookies" => array(
+        "function" => 'getCookies',
+        "signature" => $getcookies_sig,
+        "docstring" => $getcookies_doc,
+    ),
+    "mail.send" => array(
+        "function" => "mailSend",
+        "signature" => $mailsend_sig,
+        "docstring" => $mailsend_doc,
+    ),
+    "validator1.arrayOfStructsTest" => array(
+        "function" => "v1_arrayOfStructs",
+        "signature" => $v1_arrayOfStructs_sig,
+        "docstring" => $v1_arrayOfStructs_doc,
+    ),
+    "validator1.easyStructTest" => array(
+        "function" => "v1_easyStruct",
+        "signature" => $v1_easyStruct_sig,
+        "docstring" => $v1_easyStruct_doc,
+    ),
+    "validator1.echoStructTest" => array(
+        "function" => "v1_echoStruct",
+        "signature" => $v1_echoStruct_sig,
+        "docstring" => $v1_echoStruct_doc,
+    ),
+    "validator1.manyTypesTest" => array(
+        "function" => "v1_manyTypes",
+        "signature" => $v1_manyTypes_sig,
+        "docstring" => $v1_manyTypes_doc,
+    ),
+    "validator1.moderateSizeArrayCheck" => array(
+        "function" => "v1_moderateSizeArrayCheck",
+        "signature" => $v1_moderateSizeArrayCheck_sig,
+        "docstring" => $v1_moderateSizeArrayCheck_doc,
+    ),
+    "validator1.simpleStructReturnTest" => array(
+        "function" => "v1_simpleStructReturn",
+        "signature" => $v1_simpleStructReturn_sig,
+        "docstring" => $v1_simpleStructReturn_doc,
+    ),
+    "validator1.nestedStructTest" => array(
+        "function" => "v1_nestedStruct",
+        "signature" => $v1_nestedStruct_sig,
+        "docstring" => $v1_nestedStruct_doc,
+    ),
+    "validator1.countTheEntities" => array(
+        "function" => "v1_countTheEntities",
+        "signature" => $v1_countTheEntities_sig,
+        "docstring" => $v1_countTheEntities_doc,
+    ),
+    "interopEchoTests.echoString" => array(
+        "function" => "i_echoString",
+        "signature" => $i_echoString_sig,
+        "docstring" => $i_echoString_doc,
+    ),
+    "interopEchoTests.echoStringArray" => array(
+        "function" => "i_echoStringArray",
+        "signature" => $i_echoStringArray_sig,
+        "docstring" => $i_echoStringArray_doc,
+    ),
+    "interopEchoTests.echoInteger" => array(
+        "function" => "i_echoInteger",
+        "signature" => $i_echoInteger_sig,
+        "docstring" => $i_echoInteger_doc,
+    ),
+    "interopEchoTests.echoIntegerArray" => array(
+        "function" => "i_echoIntegerArray",
+        "signature" => $i_echoIntegerArray_sig,
+        "docstring" => $i_echoIntegerArray_doc,
+    ),
+    "interopEchoTests.echoFloat" => array(
+        "function" => "i_echoFloat",
+        "signature" => $i_echoFloat_sig,
+        "docstring" => $i_echoFloat_doc,
+    ),
+    "interopEchoTests.echoFloatArray" => array(
+        "function" => "i_echoFloatArray",
+        "signature" => $i_echoFloatArray_sig,
+        "docstring" => $i_echoFloatArray_doc,
+    ),
+    "interopEchoTests.echoStruct" => array(
+        "function" => "i_echoStruct",
+        "signature" => $i_echoStruct_sig,
+        "docstring" => $i_echoStruct_doc,
+    ),
+    "interopEchoTests.echoStructArray" => array(
+        "function" => "i_echoStructArray",
+        "signature" => $i_echoStructArray_sig,
+        "docstring" => $i_echoStructArray_doc,
+    ),
+    "interopEchoTests.echoValue" => array(
+        "function" => "i_echoValue",
+        "signature" => $i_echoValue_sig,
+        "docstring" => $i_echoValue_doc,
+    ),
+    "interopEchoTests.echoBase64" => array(
+        "function" => "i_echoBase64",
+        "signature" => $i_echoBase64_sig,
+        "docstring" => $i_echoBase64_doc,
+    ),
+    "interopEchoTests.echoDate" => array(
+        "function" => "i_echoDate",
+        "signature" => $i_echoDate_sig,
+        "docstring" => $i_echoDate_doc,
+    ),
+    "interopEchoTests.whichToolkit" => array(
+        "function" => "i_whichToolkit",
+        "signature" => $i_whichToolkit_sig,
+        "docstring" => $i_whichToolkit_doc,
+    ),
+
+    'tests.getStateName.2' => $findstate2_sig,
+    'tests.getStateName.3' => $findstate3_sig,
+    'tests.getStateName.4' => $findstate4_sig,
+    'tests.getStateName.5' => $findstate5_sig,
+    'tests.getStateName.6' => $findstate6_sig,
+    'tests.getStateName.7' => $findstate7_sig,
+    'tests.getStateName.8' => $findstate8_sig,
+    'tests.getStateName.9' => $findstate9_sig,
+    'tests.getStateName.10' => $findstate10_sig,
+    'tests.getStateName.11' => $findstate11_sig,
+
+    'tests.getStateName.12' => array(
+        "function" => "findStateWithNulls",
+        "signature" => $findstate12_sig,
+        "docstring" => $findstate_doc,
+    ),
+
+    'tests.returnPhpObject' => $returnObj_sig,
+);
+
+$signatures = array_merge($signatures, $moreSignatures);
+
+// enable support for the NULL extension
+PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_extension = true;
+
+$s = new PhpXmlRpc\Server($signatures, false);
+$s->setdebug(3);
+$s->compress_response = true;
+
+// out-of-band information: let the client manipulate the server operations.
+// we do this to help the testsuite script: do not reproduce in production!
+if (isset($_GET['RESPONSE_ENCODING'])) {
+    $s->response_charset_encoding = $_GET['RESPONSE_ENCODING'];
+}
+if (isset($_GET['DETECT_ENCODINGS'])) {
+    PhpXmlRpc\PhpXmlRpc::$xmlrpc_detectencodings = $_GET['DETECT_ENCODINGS'];
+}
+if (isset($_GET['EXCEPTION_HANDLING'])) {
+    $s->exception_handling = $_GET['EXCEPTION_HANDLING'];
+}
+$s->service();
+// that should do all we need!
+
+// out-of-band information: let the client manipulate the server operations.
+// we do this to help the testsuite script: do not reproduce in production!
+if (isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && extension_loaded('xdebug')) {
+    include_once __DIR__ . "/../../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/append.php";
+}
index 3e7a401..b1ab3c0 100644 (file)
@@ -2,59 +2,60 @@
 <head><title>xmlrpc</title></head>
 <body>
 <?php
-       include("xmlrpc.inc");
-
-       $f = new xmlrpcmsg('examples.getStateName');
-
-       print "<h3>Testing value serialization</h3>\n";
-
-       $v = new xmlrpcval(23, "int");
-       print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
-       $v = new xmlrpcval("What are you saying? >> << &&");
-       print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
-
-       $v = new xmlrpcval(array(
-               new xmlrpcval("ABCDEFHIJ"),
-               new xmlrpcval(1234, 'int'),
-               new xmlrpcval(1, 'boolean')),
-               "array"
-       );
-
-       print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
-
-       $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 "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
-
-       $w = new xmlrpcval(array($v, new xmlrpcval("That was the struct!")), "array");
-
-       print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
-
-       $w = new xmlrpcval("Mary had a little lamb,
+
+include_once __DIR__ . "/../vendor/autoload.php";
+
+$req = new PhpXmlRpc\Request('examples.getStateName');
+
+print "<h3>Testing value serialization</h3>\n";
+
+$v = new PhpXmlRpc\Value(23, "int");
+print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
+$v = new PhpXmlRpc\Value("What are you saying? >> << &&");
+print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
+
+$v = new PhpXmlRpc\Value(array(
+    new PhpXmlRpc\Value("ABCDEFHIJ"),
+    new PhpXmlRpc\Value(1234, 'int'),
+    new PhpXmlRpc\Value(1, 'boolean'),),
+    "array"
+);
+
+print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
+
+$v = new PhpXmlRpc\Value(
+    array(
+        "thearray" => new PhpXmlRpc\Value(
+            array(
+                new PhpXmlRpc\Value("ABCDEFHIJ"),
+                new PhpXmlRpc\Value(1234, 'int'),
+                new PhpXmlRpc\Value(1, 'boolean'),
+                new PhpXmlRpc\Value(0, 'boolean'),
+                new PhpXmlRpc\Value(true, 'boolean'),
+                new PhpXmlRpc\Value(false, 'boolean'),
+            ),
+            "array"
+        ),
+        "theint" => new PhpXmlRpc\Value(23, 'int'),
+        "thestring" => new PhpXmlRpc\Value("foobarwhizz"),
+        "thestruct" => new PhpXmlRpc\Value(
+            array(
+                "one" => new PhpXmlRpc\Value(1, 'int'),
+                "two" => new PhpXmlRpc\Value(2, 'int'),
+            ),
+            "struct"
+        ),
+    ),
+    "struct"
+);
+
+print "<PRE>" . htmlentities($v->serialize()) . "</PRE>";
+
+$w = new PhpXmlRpc\Value(array($v, new PhpXmlRpc\Value("That was the struct!")), "array");
+
+print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
+
+$w = new PhpXmlRpc\Value("Mary had a little lamb,
 Whose fleece was white as snow,
 And everywhere that Mary went
 the lamb was sure to go.
@@ -63,29 +64,30 @@ Mary had a little lamb
 She tied it to a pylon
 Ten thousand volts went down its back
 And turned it into nylon", "base64"
-       );
-       print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
-       print "<PRE>Value of base64 string is: '" . $w->scalarval() . "'</PRE>";
+);
+print "<PRE>" . htmlentities($w->serialize()) . "</PRE>";
+print "<PRE>Value of base64 string is: '" . $w->scalarval() . "'</PRE>";
+
+$req->method('');
+$req->addParam(new PhpXmlRpc\Value("41", "int"));
 
-       $f->method('');
-       $f->addParam(new xmlrpcval("41", "int"));
+print "<h3>Testing request serialization</h3>\n";
+$op = $req->serialize();
+print "<PRE>" . htmlentities($op) . "</PRE>";
 
-       print "<h3>Testing request serialization</h3>\n";
-       $op = $f->serialize();
-       print "<PRE>" . htmlentities($op) . "</PRE>";
+print "<h3>Testing ISO date format</h3><pre>\n";
 
-       print "<h3>Testing ISO date format</h3><pre>\n";
+$t = time();
+$date = PhpXmlRpc\Helper\Date::iso8601Encode($t);
+print "Now is $t --> $date\n";
+print "Or in UTC, that is " . PhpXmlRpc\Helper\Date::iso8601Encode($t, 1) . "\n";
+$tb = PhpXmlRpc\Helper\Date::iso8601Decode($date);
+print "That is to say $date --> $tb\n";
+print "Which comes out at " . PhpXmlRpc\Helper\Date::iso8601Encode($tb) . "\n";
+print "Which was the time in UTC at " . PhpXmlRpc\Helper\Date::iso8601Encode($date, 1) . "\n";
 
-       $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 "</pre>\n";
 
-       print "</pre>\n";
 ?>
 </body>
 </html>
diff --git a/doc/.gitignore b/doc/.gitignore
deleted file mode 100644 (file)
index 898ede1..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-out/
-javadoc-out/
-xmlrpc_php.pdf
-xmlrpc_php.fo.xml
\ No newline at end of file
diff --git a/doc/Makefile b/doc/Makefile
deleted file mode 100644 (file)
index 5a77386..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-\r
-### USER EDITABLE VARS ###\r
-\r
-WEB=/var/www/xmlrpc/doc\r
-\r
-MKDIR=mkdir\r
-\r
-PHP=php\r
-\r
-FOP=fop\r
-\r
-PHPDOC=phpdoc\r
-\r
-\r
-#### DO NOT TOUCH FROM HERE ONWARDS ###\r
-\r
-install:\r
-       ${MKDIR} -p ${WEB}\r
-       cp *.html ${WEB}\r
-       cp *.css ${WEB}\r
-       cp *.gif ${WEB}\r
-       @echo HTML version of the manual has been installed to ${WEB}\r
-\r
-\r
-### the following targets are to be used for library development ###\r
-\r
-doc: out/index.html xmlrpc_php.pdf javadoc-out/index.html\r
-\r
-# tools currently used in building docs: php 5 with xsl extension, apache fop, phpdocumentor\r
-# alternatives include doxygen, jade, saxon, xsltproc etc...\r
-\r
-out/index.html xmlrpc_php.pdf: xmlrpc_php.xml\r
-       -${MKDIR} out\r
-# Jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g.\r
-#      jade -t xml -d custom.dsl xmlrpc_php.xml\r
-#\r
-# convertdoc command for xmlmind xxe editor\r
-#      convertdoc docb.toHTML xmlrpc_php.xml -u out\r
-#\r
-# saxon + xerces xml parser + saxon extensions + xslthl: adds a little syntax highligting\r
-# (bold and italics only, no color) for php source examples...\r
-#      java \\r
-#      -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 \\r
-#      -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \\r
-#      -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \\r
-#      -Dxslthl.config=file:///c:/htdocs/xmlrpc_cvs/docbook-xsl/highlighting/xslthl-config.xml \\r
-#      com.icl.saxon.StyleSheet -o xmlrpc_php.fo.xml xmlrpc_php.xml custom.fo.xsl use.extensions=1\r
-#\r
-#      custom php script that does the xslt magic\r
-       ${PHP} convert.php xmlrpc_php.xml custom.xsl out/\r
-#      post process html files to highlight php code samples\r
-       ${PHP} highlight.php out\r
-#      convert to fo and then to pdf using apache fop\r
-       ${PHP} convert.php xmlrpc_php.xml custom.fo.xsl xmlrpc_php.fo.xml\r
-       ${FOP} xmlrpc_php.fo.xml xmlrpc_php.pdf\r
-#      -rm xmlrpc_php.fo.xml\r
-\r
-javadoc-out/index.html: ../lib/xmlrpc.inc ../lib/xmlrpcs.inc ../lib/xmlrpc_wrappers.inc\r
-# generate docs out of javadoc via doxygen\r
-#      doxygen phpxmlrpc.dox\r
-#\r
-#      generate docs out of javadoc via phpdocumentor\r
-       ${PHP} ${PHPDOC} -f ../lib/xmlrpc.inc,../lib/xmlrpcs.inc,../lib/xmlrpc_wrappers.inc -t javadoc-out --title PHP-XMLRPC\r
-       -rm -rf javadoc-out/phpdoc-cache-*\r
-\r
-dist: doc\r
-       ${MKDIR} -p ../xmlrpc-${VERSION}/doc\r
-       -cp out/*.html ../xmlrpc-${VERSION}/doc\r
-       -cp out/*.css ../xmlrpc-${VERSION}/doc\r
-       -cp out/*.gif ../xmlrpc-${VERSION}/doc\r
-       -cp out/*.pdf ../xmlrpc-${VERSION}/doc\r
-       cp xmlrpc_php.xml ../xmlrpc-${VERSION}/doc\r
-       cp xmlrpc_php.pdf ../xmlrpc-${VERSION}/doc\r
-       cp Makefile ../xmlrpc-${VERSION}/doc\r
-\r
-clean:\r
-       -rm -f out/*.html\r
-       -rm -rf javadoc-out\r
-       -rm xmlrpc_php.fo.xml\r
-       -rm xmlrpc_php.pdf\r
diff --git a/doc/announce1_0.txt b/doc/announce1_0.txt
deleted file mode 100644 (file)
index a45b182..0000000
+++ /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
-<xmlrpc@usefulinc.com>.
diff --git a/doc/announce1_1.txt b/doc/announce1_1.txt
deleted file mode 100644 (file)
index db0a9fd..0000000
+++ /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 (file)
index 30c1d10..0000000
+++ /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 <xmlrpc@usefulinc.com>.
diff --git a/doc/announce1b7.txt b/doc/announce1b7.txt
deleted file mode 100644 (file)
index aceea29..0000000
+++ /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 <xmlrpc@usefulinc.com>.
diff --git a/doc/announce1b8.txt b/doc/announce1b8.txt
deleted file mode 100644 (file)
index d4db381..0000000
+++ /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 <xmlrpc@usefulinc.com>.
diff --git a/doc/announce1b9.txt b/doc/announce1b9.txt
deleted file mode 100644 (file)
index ad43a4e..0000000
+++ /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 </string>
-   and </value> tag were not ignored.
-
- * Added in support for PHP's native boolean type.
-
-New features include:
-
- * new getval() method (experimental only) which has support for
-   recreating nested arrays.
- * fledgling unit test suite
- * server.php has support for basic interop test suite
-
-The changelog is available at: http://xmlrpc.usefulinc.com/ChangeLog.txt
-
-Please test this as hard as possible and report bugs to the XML-RPC PHP
-mailing list, of which more details are available at
-http://xmlrpc.usefulinc.com/list.html, or to <xmlrpc@usefulinc.com>.
diff --git a/doc/api_changes_v4.md b/doc/api_changes_v4.md
new file mode 100644 (file)
index 0000000..7b04ecd
--- /dev/null
@@ -0,0 +1,237 @@
+API Changes between library versions 3 and 4
+============================================
+
+Class loading
+-------------
+
+It is not necessary any more to include the files xmlrpc.inc, xmlrpcs.inc and xmlrpc_wrappers.inc to have the
+library classes available.
+
+Instead, it is recommended to rely on class autoloading.
+* If you are using Composer, just install the library by declaring it as dependency for your project in composer.json 
+
+        "require": {
+            ...,
+            "phpxmlrpc/phpxmlrpc": "~4.0"
+        },
+       
+* If you do not use Composer, an autoloader for the library can be found in src/Atuloader.php.
+  The php example files in the demo/client folder do make use of it.
+  Example code to set up the autoloader:
+    
+        include_once <path to library> . "/src/Autoloader.php";
+        PhpXmlRpc\Autoloader::register();
+
+
+* If you still include manually xmlrpc.inc, xmlrpcs.inc or xmlrpc_wrappers.inc, you will not need to set up
+  class autoloading, as those files do include all the source files for the library classes
+
+
+New class naming
+----------------
+
+All classes have ben renamed, are now properly namespaced and follow the CamelCase naming convention.
+Existing class methods and members have been preserved; all new method names follow camelCase. 
+
+Conversion table:
+
+| Old class     | New class          | Notes                                 |
+| ------------- | ------------------ | ------------------------------------- |
+| xmlrpc_client | PhpXmlRpc\Client   |                                       |
+| xmlrpc_server | PhpXmlRpc\Server   | Removed method: echoInput             |
+| xmlrpcmsg     | PhpXmlRpc\Request  |                                       |
+| xmlrpcresp    | PhpXmlRpc\Response |                                       |
+| xmlrpcval     | PhpXmlRpc\Value    | Removed methods: serializeval, getval |
+
+
+New class methods
+-----------------
+
+In case you had extended the classes of the library and added methods to the subclasses, you might find that your
+implementation clashes with the new one if you implemented:
+
+
+| Class     | Method       | Notes                                   |
+| --------- | ------------ | --------------------------------------- |
+| xmlrpcval | count        | implements interface: Countable         |
+| xmlrpcval | getIterator  | implements interface: IteratorAggregate |
+| xmlrpcval | offsetExists | implements interface: ArrayAccess       |
+| xmlrpcval | offsetGet    | implements interface: ArrayAccess       |
+| xmlrpcval | offsetSet    | implements interface: ArrayAccess       |
+| xmlrpcval | offsetUnset  | implements interface: ArrayAccess       |
+
+
+Global variables cleanup
+------------------------
+
+All variables in the global scope have been moved into classes.
+
+Conversion table:
+
+| Old variable             | New variable                                | Notes     |
+| ------------------------ | ------------------------------------------- | --------- |
+| _xmlrpc_debuginfo        | PhpXmlRpc\Server::$_xmlrpc_debuginfo        | protected |
+| _xmlrpcs_capabilities    | NOT AVAILABLE YET                           |           |
+| _xmlrpcs_dmap            | NOT AVAILABLE YET                           |           |
+| _xmlrpcs_occurred_errors | PhpXmlRpc\Server::$_xmlrpcs_occurred_errors | protected |
+| _xmlrpcs_prev_ehandler   | PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler   | protected |
+| xmlrpcWPFObjHolder       | PhpXmlRpc\Wrapper::$objHolder               |           |
+| ...                      |                                             |           |
+
+
+Global functions cleanup
+------------------------
+
+Most functions in the global scope have been moved into classes.
+Some have been slightly changed.
+
+| Old function                     | New function                                | Notes                                                  |
+| -------------------------------- | ------------------------------------------- | ------------------------------------------------------ |
+| build_client_wrapper_code        | none                                        |                                                        |
+| build_remote_method_wrapper_code | PhpXmlRpc\Wrapper::buildWrapMethodSource    | signature changed                                      |
+| decode_chunked                   | PhpXmlRpc\Helper\Http::decodeChunked        |                                                        |
+| guess_encoding                   | PhpXmlRpc\Helper\XMLParser::guessEncoding   |                                                        |
+| has_encoding                     | PhpXmlRpc\Helper\XMLParser::hasEncoding     |                                                        |
+| is_valid_charset                 | PhpXmlRpc\Helper\Charset::isValidCharset    |                                                        |
+| 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
+---------------------------
+
+The default character set used by the library to deliver data to your app is now UTF8.
+It is also the character set that the library expects data from your app to be in (including method names).
+The value can be changed (to either US-ASCII or ISO-8859-1) by setting the desired value to
+    PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding
+
+Usage of closures for wrapping
+------------------------------
+
+...
+
+
+Differences in server behaviour
+-------------------------------
+
+The results for calls to system.listMethods and system.getCapabilities can not be set anymore via changes to
+global variables.
+
+
+Other
+-----
+
+* when serialize() is invoked on a response and its payload can not be serialized, an exception is thrown instead of
+  ending all execution
+
+* all error messages now mention the class and method which generated 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 when enabling 'compatibility mode'.
+
+### Default character set used for application data
+
+* when including the xmlrpc.inc file, the defalt character set used by the lib to give data to your app gets switched
+  back to ISO-8859-1, as it was in previous versions
+
+* if yor app used to change that value, you will need to add one line to your code, to make sure it is properly used
+
+        // code as was before
+        include('xmlrpc.inc');
+        $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
+        // new line needed now
+        PhpXmlRpc\PhpXmlRpc::importGlobals();
+
+### Usage of global variables
+
+* ALL global variables which existed after including xmlrpc.inc in version 3 still do exist after including it in v. 4
+* Code which relies on using (as in 'reading') their value will keep working unchanged
+
+* Changing the value of some of those variables does not have any effect anymore on library operation.
+  This is true for:
+
+        $GLOBALS['xmlrpcI4']
+        $GLOBALS['xmlrpcInt']
+        $GLOBALS['xmlrpcBoolean']
+        $GLOBALS['xmlrpcDouble']
+        $GLOBALS['xmlrpcString']
+        $GLOBALS['xmlrpcDatetTme']
+        $GLOBALS['xmlrpcBase64']
+        $GLOBALS['xmlrpcArray']
+        $GLOBALS['xmlrpcStruct']
+        $GLOBALS['xmlrpcValue']
+        $GLOBALS['xmlrpcNull']
+        $GLOBALS['xmlrpcTypes']
+        $GLOBALS['xmlrpc_valid_parents']
+        $GLOBALS['xml_iso88591_Entities']
+
+* Changing the value of the other global variables will still have an effect on operation of the library, but only after
+  a call to PhpXmlRpc::importGlobals()
+
+    Example:
+
+        // code as was before
+        include('xmlrpc.inc');
+        $GLOBALS['xmlrpc_null_apache_encoding'] = true;
+        // new line needed now
+        PhpXmlRpc\PhpXmlRpc::importGlobals();
+        
+    Alternative solution:
+    
+        include('xmlrpc.inc');
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_null_apache_encoding = true;
+
+* Not all variables which existed after including xmlrpcs.inc in version 3 are available
+
+    - $GLOBALS['_xmlrpcs_prev_ehandler'] has been replaced with protected static var PhpXmlRpc\Server::$_xmlrpcs_prev_ehandler
+        and is thus not available any more
+
+    - same for $GLOBALS['_xmlrpcs_occurred_errors']
+
+    - same for $GLOBALS['_xmlrpc_debuginfo']
+
+    - $GLOBALS['_xmlrpcs_capabilities'] and $GLOBALS['_xmlrpcs_dmap'] have been removed
+
+### Using typeof/class-name checks in your code
+
+* if you are checking the types of returned objects, your checks will most likely fail.
+  This is due to the fact that 'old' classes extend the 'new' versions, but library code that creates object
+  instances will return the new classes.
+
+    Example:
+        
+        is_a(php_xmlrpc_encode('hello world'), 'xmlrpcval') => false
+        is_a(php_xmlrpc_encode('hello world'), 'PhpXmlRpc\Value') => true
+
+### server behaviour can not be changed by setting global variables (the ones starting with _xmlrpcs_ )
+
+might be fixed later?
similarity index 90%
rename from doc/custom.fo.xsl
rename to doc/build/custom.fo.xsl
index f87d974..b1964c0 100644 (file)
-<?xml version='1.0'?>\r
-<xsl:stylesheet\r
-    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"\r
-       xmlns:fo="http://www.w3.org/1999/XSL/Format">\r
-<!--\r
- Customization xsl stylesheet for docbook to pdf transform\r
- @author Gaetano Giunta\r
- @copyright (c) 2007-2014 G. Giunta\r
- @license\r
- @todo make the xsl more dynamic: the path to import docbook.xsl could be f.e. rewritten/injected by the php user\r
--->\r
-\r
-\r
-<!-- import base stylesheet -->\r
-<xsl:import href="../../../tools/docbook-xsl/fo/docbook.xsl"/>\r
-\r
-\r
-<!-- customization vars -->\r
-<xsl:param name="fop1.extensions">1</xsl:param>\r
-<xsl:param name="draft.mode">no</xsl:param>\r
-<xsl:param name="funcsynopsis.style">ansi</xsl:param>\r
-<xsl:param name="id.warnings">0</xsl:param>\r
-<xsl:param name="highlight.source">1</xsl:param>\r
-<xsl:param name="highlight.default.language">php</xsl:param>\r
-<xsl:param name="paper.type">A4</xsl:param>\r
-<xsl:param name="shade.verbatim">1</xsl:param>\r
-\r
-<xsl:attribute-set name="verbatim.properties">\r
-  <xsl:attribute name="font-size">80%</xsl:attribute>\r
-</xsl:attribute-set>\r
-\r
-\r
-<!-- elements added / modified -->\r
-<xsl:template match="funcdef/function">\r
-  <xsl:choose>\r
-    <xsl:when test="$funcsynopsis.decoration != 0">\r
-      <fo:inline font-weight="bold">\r
-        <xsl:apply-templates/>\r
-      </fo:inline>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <xsl:apply-templates/>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-  <xsl:text> </xsl:text>\r
-</xsl:template>\r
-\r
-<xsl:template match="funcdef/type">\r
-  <xsl:apply-templates/>\r
-  <xsl:text> </xsl:text>\r
-</xsl:template>\r
-\r
-<xsl:template match="void">\r
-  <xsl:choose>\r
-    <xsl:when test="$funcsynopsis.style='ansi'">\r
-      <xsl:text>( void )</xsl:text>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <xsl:text>( )</xsl:text>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-</xsl:template>\r
-\r
-<xsl:template match="varargs">\r
-  <xsl:text>( ... )</xsl:text>\r
-</xsl:template>\r
-\r
-<xsl:template match="paramdef">\r
-  <xsl:variable name="paramnum">\r
-    <xsl:number count="paramdef" format="1"/>\r
-  </xsl:variable>\r
-  <xsl:if test="$paramnum=1">( </xsl:if>\r
-  <xsl:choose>\r
-    <xsl:when test="$funcsynopsis.style='ansi'">\r
-      <xsl:apply-templates/>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <xsl:apply-templates select="./parameter"/>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-  <xsl:choose>\r
-    <xsl:when test="following-sibling::paramdef">\r
-      <xsl:text>, </xsl:text>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <xsl:text> )</xsl:text>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-</xsl:template>\r
-\r
-<xsl:template match="paramdef/type">\r
-  <xsl:apply-templates/>\r
-  <xsl:text> </xsl:text>\r
-</xsl:template>\r
-\r
-<!-- default values for function parameters -->\r
-<xsl:template match="paramdef/initializer">\r
-  <xsl:text> = </xsl:text>\r
-  <xsl:apply-templates/>\r
-</xsl:template>\r
-\r
-\r
+<?xml version='1.0'?>
+<xsl:stylesheet
+    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
+    xmlns:fo="http://www.w3.org/1999/XSL/Format">
+<!--
+ Customization xsl stylesheet for docbook to pdf transform
+ @author Gaetano Giunta
+ @copyright (c) 2007-2015 G. Giunta
+ @license code licensed under the BSD License
+ @todo make the xsl more dynamic: the path to import docbook.xsl could be f.e. rewritten/injected by the php user
+-->
+
+
+<!-- import base stylesheet -->
+<xsl:import href="../../../../vendor/docbook/docbook-xsl/fo/docbook.xsl"/>
+
+
+<!-- customization vars -->
+<xsl:param name="fop1.extensions">1</xsl:param>
+<xsl:param name="draft.mode">no</xsl:param>
+<xsl:param name="funcsynopsis.style">ansi</xsl:param>
+<xsl:param name="id.warnings">0</xsl:param>
+<xsl:param name="highlight.source">1</xsl:param>
+<xsl:param name="highlight.default.language">php</xsl:param>
+<xsl:param name="paper.type">A4</xsl:param>
+<xsl:param name="shade.verbatim">1</xsl:param>
+
+<xsl:attribute-set name="verbatim.properties">
+  <xsl:attribute name="font-size">80%</xsl:attribute>
+</xsl:attribute-set>
+
+
+<!-- elements added / modified -->
+<xsl:template match="funcdef/function">
+  <xsl:choose>
+    <xsl:when test="$funcsynopsis.decoration != 0">
+      <fo:inline font-weight="bold">
+        <xsl:apply-templates/>
+      </fo:inline>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:apply-templates/>
+    </xsl:otherwise>
+  </xsl:choose>
+  <xsl:text> </xsl:text>
+</xsl:template>
+
+<xsl:template match="funcdef/type">
+  <xsl:apply-templates/>
+  <xsl:text> </xsl:text>
+</xsl:template>
+
+<xsl:template match="void">
+  <xsl:choose>
+    <xsl:when test="$funcsynopsis.style='ansi'">
+      <xsl:text>( void )</xsl:text>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:text>( )</xsl:text>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="varargs">
+  <xsl:text>( ... )</xsl:text>
+</xsl:template>
+
+<xsl:template match="paramdef">
+  <xsl:variable name="paramnum">
+    <xsl:number count="paramdef" format="1"/>
+  </xsl:variable>
+  <xsl:if test="$paramnum=1">( </xsl:if>
+  <xsl:choose>
+    <xsl:when test="$funcsynopsis.style='ansi'">
+      <xsl:apply-templates/>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:apply-templates select="./parameter"/>
+    </xsl:otherwise>
+  </xsl:choose>
+  <xsl:choose>
+    <xsl:when test="following-sibling::paramdef">
+      <xsl:text>, </xsl:text>
+    </xsl:when>
+    <xsl:otherwise>
+      <xsl:text> )</xsl:text>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<xsl:template match="paramdef/type">
+  <xsl:apply-templates/>
+  <xsl:text> </xsl:text>
+</xsl:template>
+
+<!-- default values for function parameters -->
+<xsl:template match="paramdef/initializer">
+  <xsl:text> = </xsl:text>
+  <xsl:apply-templates/>
+</xsl:template>
+
+
 </xsl:stylesheet>
\ No newline at end of file
similarity index 79%
rename from doc/custom.xsl
rename to doc/build/custom.xsl
index d38d2c7..c96cf55 100644 (file)
@@ -1,87 +1,91 @@
-<?xml version='1.0'?>\r
-<xsl:stylesheet\r
-    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">\r
-<!--\r
- Customization xsl stylesheet for docbook to chunked html transform\r
- @author Gaetano Giunta\r
- @copyright (c) 2007-2014 G. Giunta\r
- @license\r
- @todo make the xsl more dynamic: the path to import chunk.xsl could be f.e. rewritten/injected by the php user\r
--->\r
-\r
-\r
-<!-- import base stylesheet -->\r
-<xsl:import href="../../../tools/docbook-xsl/xhtml/chunk.xsl"/>\r
-\r
-\r
-<!-- customization vars -->\r
-<xsl:param name="draft.mode">no</xsl:param>\r
-<xsl:param name="funcsynopsis.style">ansi</xsl:param>\r
-<xsl:param name="html.stylesheet">xmlrpc.css</xsl:param>\r
-<xsl:param name="id.warnings">0</xsl:param>\r
-\r
-\r
-<!-- elements added / modified -->\r
-\r
-<!-- space between function name and opening parenthesis -->\r
-<xsl:template match="funcdef" mode="ansi-nontabular">\r
-  <code>\r
-    <xsl:apply-templates select="." mode="class.attribute"/>\r
-    <xsl:apply-templates mode="ansi-nontabular"/>\r
-    <xsl:text> ( </xsl:text>\r
-  </code>\r
-</xsl:template>\r
-\r
-<!-- space between return type and function name -->\r
-<xsl:template match="funcdef/type" mode="ansi-nontabular">\r
-  <xsl:apply-templates mode="ansi-nontabular"/>\r
-  <xsl:text> </xsl:text>\r
-</xsl:template>\r
-\r
-<!-- space between last param and closing parenthesis, remove tailing semicolon -->\r
-<xsl:template match="void" mode="ansi-nontabular">\r
-  <code>void )</code>\r
-</xsl:template>\r
-\r
-<xsl:template match="varargs" mode="ansi-nontabular">\r
-  <xsl:text>...</xsl:text>\r
-  <code> )</code>\r
-</xsl:template>\r
-\r
-<xsl:template match="paramdef" mode="ansi-nontabular">\r
-  <xsl:apply-templates mode="ansi-nontabular"/>\r
-  <xsl:choose>\r
-    <xsl:when test="following-sibling::*">\r
-      <xsl:text>, </xsl:text>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <code> )</code>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-</xsl:template>\r
-\r
-<!-- param types get code formatted (leave a space after type, as it is supposed to be before param name) -->\r
-<xsl:template match="paramdef/type" mode="ansi-nontabular">\r
-  <xsl:choose>\r
-    <xsl:when test="$funcsynopsis.decoration != 0">\r
-      <code>\r
-        <xsl:apply-templates mode="ansi-nontabular"/>\r
-      </code>\r
-    </xsl:when>\r
-    <xsl:otherwise>\r
-      <code>\r
-       <xsl:apply-templates mode="ansi-nontabular"/>\r
-      </code>\r
-    </xsl:otherwise>\r
-  </xsl:choose>\r
-  <xsl:text> </xsl:text>\r
-</xsl:template>\r
-\r
-<!-- default values for function parameters -->\r
-<xsl:template match="paramdef/initializer" mode="ansi-nontabular">\r
-  <xsl:text> = </xsl:text>\r
-  <xsl:apply-templates mode="ansi-nontabular"/>\r
-</xsl:template>\r
-\r
-\r
+<?xml version='1.0'?>
+<xsl:stylesheet
+    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+<!--
+ Customization xsl stylesheet for docbook to chunked html transform
+ @author Gaetano Giunta
+ @copyright (c) 2007-2015 G. Giunta
+ @license code licensed under the BSD License
+
+ @todo make the xsl more dynamic: the path to import chunk.xsl could be f.e. rewritten/injected by the php user.
+       This would be needed f.e. if the lib is installed as a dependency and is not the top-level composer project.
+       Note: according to http://stackoverflow.com/questions/9861355/using-dynamic-href-in-xslt-import-include this is
+       not easy to do - it would have to be done f.e. by the invoking php script...
+-->
+
+
+<!-- import base stylesheet -->
+<xsl:import href="../../../../vendor/docbook/docbook-xsl/xhtml/chunk.xsl"/>
+
+
+<!-- customization vars -->
+<xsl:param name="draft.mode">no</xsl:param>
+<xsl:param name="funcsynopsis.style">ansi</xsl:param>
+<xsl:param name="html.stylesheet">xmlrpc.css</xsl:param>
+<xsl:param name="id.warnings">0</xsl:param>
+
+
+<!-- elements added / modified -->
+
+<!-- space between function name and opening parenthesis -->
+<xsl:template match="funcdef" mode="ansi-nontabular">
+  <code>
+    <xsl:apply-templates select="." mode="class.attribute"/>
+    <xsl:apply-templates mode="ansi-nontabular"/>
+    <xsl:text> ( </xsl:text>
+  </code>
+</xsl:template>
+
+<!-- space between return type and function name -->
+<xsl:template match="funcdef/type" mode="ansi-nontabular">
+  <xsl:apply-templates mode="ansi-nontabular"/>
+  <xsl:text> </xsl:text>
+</xsl:template>
+
+<!-- space between last param and closing parenthesis, remove tailing semicolon -->
+<xsl:template match="void" mode="ansi-nontabular">
+  <code>void )</code>
+</xsl:template>
+
+<xsl:template match="varargs" mode="ansi-nontabular">
+  <xsl:text>...</xsl:text>
+  <code> )</code>
+</xsl:template>
+
+<xsl:template match="paramdef" mode="ansi-nontabular">
+  <xsl:apply-templates mode="ansi-nontabular"/>
+  <xsl:choose>
+    <xsl:when test="following-sibling::*">
+      <xsl:text>, </xsl:text>
+    </xsl:when>
+    <xsl:otherwise>
+      <code> )</code>
+    </xsl:otherwise>
+  </xsl:choose>
+</xsl:template>
+
+<!-- param types get code formatted (leave a space after type, as it is supposed to be before param name) -->
+<xsl:template match="paramdef/type" mode="ansi-nontabular">
+  <xsl:choose>
+    <xsl:when test="$funcsynopsis.decoration != 0">
+      <code>
+        <xsl:apply-templates mode="ansi-nontabular"/>
+      </code>
+    </xsl:when>
+    <xsl:otherwise>
+      <code>
+        <xsl:apply-templates mode="ansi-nontabular"/>
+      </code>
+    </xsl:otherwise>
+  </xsl:choose>
+  <xsl:text> </xsl:text>
+</xsl:template>
+
+<!-- default values for function parameters -->
+<xsl:template match="paramdef/initializer" mode="ansi-nontabular">
+  <xsl:text> = </xsl:text>
+  <xsl:apply-templates mode="ansi-nontabular"/>
+</xsl:template>
+
+
 </xsl:stylesheet>
\ No newline at end of file
diff --git a/doc/convert.php b/doc/convert.php
deleted file mode 100644 (file)
index 8e7f7f0..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-<?php
-/**
- * Script used to convert docbook source to human readable docs
- *
- * @copyright (c) 2007-2014 G. Giunta
- */
-
-if ($_SERVER['argc'] < 4)
-    die("Usage: php convert.php docbook.xml \path\\to\stylesheet.xsl output-dir|output_file\n");
-else
-    echo "Starting xsl conversion process...\n";
-
-$doc = $_SERVER['argv'][1];
-$xss = $_SERVER['argv'][2];
-
-if (!file_exists($doc))
-    die("KO: file $doc cannot be found\n");
-if (!file_exists($xss))
-    die("KO: file $xss cannot be found\n");
-
-// Load the XML source
-$xml = new DOMDocument;
-$xml->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
-{
-    $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";
-?>
\ No newline at end of file
diff --git a/doc/custom.dsl b/doc/custom.dsl
deleted file mode 100644 (file)
index b3b35ce..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE style-sheet PUBLIC "-//James Clark//DTD DSSSL Style Sheet//EN" [\r
-<!ENTITY dbstyle SYSTEM "/usr/lib/sgml/stylesheet/dsssl/docbook/nwalsh/html/docbook.dsl" CDATA DSSSL>\r
-]>\r
-\r
-<style-sheet>\r
-<style-specification use="docbook">\r
-<style-specification-body>\r
-\r
-(define %link-mailto-url%\r
-       "edd@usefulinc.com")\r
-\r
-(define %html-ext%\r
-       ".html")\r
-\r
-(define %use-id-as-filename%\r
-  #t)\r
-\r
-(define %root-filename%\r
-  "index")\r
-\r
-\r
-</style-specification-body>\r
-</style-specification>\r
-<external-specification id="docbook" document="dbstyle">\r
-</style-sheet>\r
diff --git a/doc/docbook-css/COPYING b/doc/docbook-css/COPYING
deleted file mode 100644 (file)
index d199ddc..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-Copyright (c) 2004 David Holroyd, and contributors.\r
-\r
-Permission to use, copy, modify and distribute this software and its\r
-documentation for any purpose and without fee is hereby granted in\r
-perpetuity, provided that the above copyright notice appear in all\r
-copies, and that both the copyright notice and this permission notice\r
-appear in supporting documentation. The contributors make no\r
-representations about the suitability of this software for any\r
-purpose. It is provided "as is" without express or implied warranty.\r
-\r
-THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS\r
-SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\r
-FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY\r
-SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER\r
-RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF\r
-CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\r
-CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r
diff --git a/doc/docbook-css/CREDITS b/doc/docbook-css/CREDITS
deleted file mode 100644 (file)
index 08d96c5..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-This stylesheet was writen by David Holroyd, with patches, suggestions,\r
-translations, and other help from these people:\r
-\r
-  David Leppik\r
-  Martin Gautier\r
-  Asia Magiera\r
-  Federico Koessler\r
-  Katie McSweenie\r
-\r
-Many thanks to all of them!\r
diff --git a/doc/docbook-css/core.css b/doc/docbook-css/core.css
deleted file mode 100644 (file)
index d9d4ba0..0000000
+++ /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/docbook-css/db-bindings.xml b/doc/docbook-css/db-bindings.xml
deleted file mode 100644 (file)
index cb575fd..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0"?>\r
-<bindings xmlns="http://www.mozilla.org/xbl"\r
-     xmlns:html="http://www.w3.org/1999/xhtml">\r
-  <binding id="ulink">\r
-    <handlers>\r
-      <handler event="click" button="0"\r
-               action="window.location=this.attributes.url.value;"/>\r
-      <handler event="mouseover"\r
-               action="window.status=this.attributes.url.value;"/>\r
-      <handler event="mouseout"\r
-               action="window.status=null;"/>\r
-    </handlers>\r
-  </binding>\r
-\r
-  <binding id="image">\r
-    <content>\r
-      <html:img xbl:inherits="src=fileref"/>\r
-    </content>\r
-\r
-    <implementation>\r
-      <constructor>\r
-       var img = document.getAnonymousNodes(this)[0];\r
-       var file = this.getAttribute("fileref");\r
-       // HACK: using img.src=file 'inline' doesn't seem to work\r
-       //       but it does when called from a setTimeout()\r
-       var f = function() { img.src = file; }\r
-       setTimeout(f, 0);\r
-      </constructor>\r
-    </implementation>\r
-  </binding>\r
-</bindings>\r
diff --git a/doc/docbook-css/driver.css b/doc/docbook-css/driver.css
deleted file mode 100644 (file)
index 1e7a2de..0000000
+++ /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 <ver> with the version number):
- *
- *   <?xml-stylesheet href="docbook-css-<ver>/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/docbook-css/l10n.css b/doc/docbook-css/l10n.css
deleted file mode 100644 (file)
index caeaa03..0000000
+++ /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/docbook-css/l10n/de.css b/doc/docbook-css/l10n/de.css
deleted file mode 100644 (file)
index 261be58..0000000
+++ /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/docbook-css/l10n/en.css b/doc/docbook-css/l10n/en.css
deleted file mode 100644 (file)
index 497e5f5..0000000
+++ /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/docbook-css/l10n/es.css b/doc/docbook-css/l10n/es.css
deleted file mode 100644 (file)
index 9b435fd..0000000
+++ /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/docbook-css/l10n/pl.css b/doc/docbook-css/l10n/pl.css
deleted file mode 100644 (file)
index 7e3504f..0000000
+++ /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/docbook-css/mozilla.css b/doc/docbook-css/mozilla.css
deleted file mode 100644 (file)
index 4f15519..0000000
+++ /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 <ulink>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/docbook-css/opera.css b/doc/docbook-css/opera.css
deleted file mode 100644 (file)
index a00a7c2..0000000
+++ /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/docbook-css/styles.css b/doc/docbook-css/styles.css
deleted file mode 100644 (file)
index fae29b7..0000000
+++ /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 <abstract> 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="emptytag"]:after {
-       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="sgmlcomment"]:after {
-       content: "-->";
-}
-
-sgmltag[class="xmlpi"]:before {
-       content: "<?";
-}
-sgmltag[class="xmlpi"]:after {
-       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 <member> 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 <title> */
-       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/docbook-css/tables.css b/doc/docbook-css/tables.css
deleted file mode 100644 (file)
index da148a3..0000000
+++ /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/docbook-css/xmlrpc.css b/doc/docbook-css/xmlrpc.css
deleted file mode 100644 (file)
index 08425ef..0000000
+++ /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/highlight.php b/doc/highlight.php
deleted file mode 100644 (file)
index eb8eacb..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-<?php
-/**
- * takes a dir as arg, highlights all php code found in html files inside
- *
- * @author Gaetano Giunta
- * @copyright (c) 2007-2014 G. Giunta
- */
-
-function highlight($file)
-{
-  $starttag = '<pre class="programlisting">';
-  $endtag = '</pre>';
-
-  $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);
-       }
-//var_dump($code);
-       $code = str_replace(array('&gt;', '&lt;'), array('>', '<'), $code);
-    $code = highlight_string('<?php '.$code, true);
-    $code = str_replace('<span style="color: #0000BB">&lt;?php&nbsp;<br />', '<span style="color: #0000BB">', $code);
-//echo($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);
-       }
-}
-
-?>
\ No newline at end of file
diff --git a/doc/manual/phpxmlrpc_manual.adoc b/doc/manual/phpxmlrpc_manual.adoc
new file mode 100644 (file)
index 0000000..7a8b880
--- /dev/null
@@ -0,0 +1,3122 @@
+= XML-RPC for PHP
+:revision: 4.0.0
+:keywords: xmlrpc, ,xml, rpc, webservices, http
+:toc: left
+:imagesdir: images
+:source-highlighter: highlightjs
+
+
+[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]
+
+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-&gt;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 &lt;, &gt;, ', ", &amp;, are encoded using their
+          entity reference as &amp;lt; &amp;gt; &amp;apos; &amp;quot; and
+          &amp;amp; All other characters outside of the ASCII range are
+          encoded using their character reference representation (e.g.
+          &amp;#200 for é). The XML-RPC spec recommends only encoding
+          ++&lt; &amp;++ 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-&gt;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-&gt;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-&gt;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-&gt;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-&gt;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-&gt;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('κόÏ\83με'); // 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 &lt;NIL/&gt; (and &lt;EX:NIL/&gt;) xmlrpc value, as
+        per the extension to the standard proposed here. This means that
+        &lt;NIL/&gt; and &lt;EX:NIL/&gt; 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
+        ++&lt;EX:NIL/&gt;++ tag instead of
+        ++&lt;NIL/&gt;++. 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
+        ++&lt;NIL/&gt;++ (or
+        ++&lt;EX:NIL/&gt;++, 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 '&lt;' character in
+      string values is encoded as '&amp;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-&gt;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 &lt;string/&gt;, serialize()
+      will output &lt;string&gt;&lt;/string&gt;), 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 &lt;ex:nil/&gt; 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 &lt;NIL/&gt; 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-&gt;service()
+            now returns a value: either the response payload or xmlrpcresp
+            object instance
+
+* Method
+            xmlrpc_server-&gt;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-&gt;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-&gt;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/xmlrpc_php.xml b/doc/xmlrpc_php.xml
deleted file mode 100644 (file)
index a37fc21..0000000
+++ /dev/null
@@ -1,4277 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?xml-stylesheet href="docbook-css/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</title>
-
-  <subtitle>version 3.0.0</subtitle>
-
-  <bookinfo>
-    <date>June 15, 2014</date>
-
-    <authorgroup>
-      <author>
-        <firstname>Edd</firstname>
-
-        <surname>Dumbill</surname>
-      </author>
-
-      <author>
-        <firstname>Gaetano</firstname>
-
-        <surname>Giunta</surname>
-      </author>
-
-      <author>
-        <firstname>Miles</firstname>
-
-        <surname>Lott</surname>
-      </author>
-
-      <author>
-        <firstname>Justin R.</firstname>
-
-        <surname>Miller</surname>
-      </author>
-
-      <author>
-        <firstname>Andres</firstname>
-
-        <surname>Salomon</surname>
-      </author>
-    </authorgroup>
-
-    <copyright>
-      <year>1999,2000,2001</year>
-
-      <holder>Edd Dumbill, Useful Information Company</holder>
-    </copyright>
-
-    <legalnotice>
-      <para>All rights reserved.</para>
-
-      <para>Redistribution and use in source and binary forms, with or without
-      modification, are permitted provided that the following conditions are
-      met:</para>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>Redistributions of source code must retain the above
-            copyright notice, this list of conditions and the following
-            disclaimer.</para>
-          </listitem>
-
-          <listitem>
-            <para>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.</para>
-          </listitem>
-
-          <listitem>
-            <para>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.</para>
-          </listitem>
-        </itemizedlist></para>
-
-      <para>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.</para>
-    </legalnotice>
-  </bookinfo>
-
-  <chapter id="introduction">
-    <title>Introduction</title>
-
-    <para>XML-RPC is a format devised by <ulink
-    url="http://www.userland.com/">Userland Software</ulink> for achieving
-    remote procedure call via XML using HTTP as the transport. XML-RPC has its
-    own web site, <ulink
-    url="http://www.xmlrpc.com/">www.xmlrpc.com</ulink></para>
-
-    <para>This collection of PHP classes provides a framework for writing
-    XML-RPC clients and servers in PHP.</para>
-
-    <para>Main goals of the project are ease of use, flexibility and
-    completeness.</para>
-
-    <para>The original author is Edd Dumbill of <ulink
-    url="http://usefulinc.com/">Useful Information Company</ulink>. As of the
-    1.0 stable release, the project was opened to wider involvement and moved
-    to <ulink
-    url="http://phpxmlrpc.sourceforge.net/">SourceForge</ulink>; later, to <ulink
-    url="https://github.com/">Github</ulink></para>
-
-    <para>A list of XML-RPC implementations for other languages such as Perl
-    and Python can be found on the <ulink
-    url="http://www.xmlrpc.com/">www.xmlrpc.com</ulink> site.</para>
-
-    <sect1>
-      <title>Acknowledgements</title>
-
-      <para>Daniel E. Baumann</para>
-
-      <para>James Bercegay</para>
-
-      <para>Leon Blackwell</para>
-
-      <para>Stephane Bortzmeyer</para>
-
-      <para>Daniel Convissor</para>
-
-      <para>Geoffrey T. Dairiki</para>
-
-      <para>Stefan Esser</para>
-
-      <para>James Flemer</para>
-
-      <para>Ernst de Haan</para>
-
-      <para>Tom Knight</para>
-
-      <para>Axel Kollmorgen</para>
-
-      <para>Peter Kocks</para>
-
-      <para>Daniel Krippner</para>
-
-      <para>S. Kuip</para>
-
-      <para>A. Lambert</para>
-
-      <para>Frederic Lecointre</para>
-
-      <para>Dan Libby</para>
-
-      <para>Arnaud Limbourg</para>
-
-      <para>Ernest MacDougal Campbell III</para>
-
-      <para>Lukasz Mach</para>
-
-      <para>Kjartan Mannes</para>
-
-      <para>Ben Margolin</para>
-
-      <para>Nicolay Mausz</para>
-
-      <para>Justin Miller</para>
-
-      <para>Jan Pfeifer</para>
-
-      <para>Giancarlo Pinerolo</para>
-
-      <para>Peter Russel</para>
-
-      <para>Jean-Jacques Sarton</para>
-
-      <para>Viliam Simko</para>
-
-      <para>Idan Sofer</para>
-
-      <para>Douglas Squirrel</para>
-
-      <para>Heiko Stübner</para>
-
-      <para>Anatoly Techtonik</para>
-
-      <para>Tommaso Trani</para>
-
-      <para>Eric van der Vlist</para>
-
-      <para>Christian Wenz</para>
-
-      <para>Jim Winstead</para>
-
-      <para>Przemyslaw Wroblewski</para>
-
-      <para>Bruno Zanetti Melotti</para>
-    </sect1>
-  </chapter>
-
-  <chapter id="news">
-    <title>What's new</title>
-
-    <para><emphasis>Note:</emphasis> 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.</para>
-
-    <sect1>
-      <title>3.0.0</title>
-
-      <para><emphasis>Note:</emphasis> 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.</para>
-
-      <para><itemizedlist>
-      <listitem>
-        <para>when using curl and keepalive, reset curl handle if we did not get back an http 200 response (eg a 302)</para>
-      </listitem>
-
-      <listitem>
-        <para>omit port on http 'Host' header if it is 80</para>
-      </listitem>
-
-      <listitem>
-        <para>test suite allows interrogating https servers ignoring their certs</para>
-      </listitem>
-
-      <listitem>
-        <para>method setAcceptedCompression was failing to disable reception of compressed responses if the
-         client supported them</para>
-      </listitem>
-
-      </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>3.0.0 beta</title>
-
-      <para>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.</para>
-
-      <para>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.</para>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>improved: removed all usage of php functions deprecated in
-            php 5.3, usage of assign-by-ref when creating new objects
-            etc...</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add support for the &lt;ex:nil/&gt; tag used by
-            the apache library, both in input and output</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add support for <classname>dateTime</classname>
-            objects in both in <function>php_xmlrpc_encode</function> and as
-            parameter for constructor of
-            <classname>xmlrpcval</classname></para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add support for timestamps as parameter for
-            constructor of <classname>xmlrpcval</classname></para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add option 'dates_as_objects' to
-            <function>php_xmlrpc_decode</function> to return
-            <classname>dateTime</classname> objects for xmlrpc
-            datetimes</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add new method
-            <methodname>SetCurlOptions</methodname> to
-            <classname>xmrlpc_client</classname> to allow extra flexibility in
-            tweaking http config, such as explicitly binding to an ip
-            address</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: add new method
-            <methodname>SetUserAgent</methodname> to
-            <classname>xmrlpc_client</classname> to to allow having different
-            user-agent http headers</para>
-          </listitem>
-
-          <listitem>
-            <para>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</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: allow servers in 'xmlrpcvals' mode to also
-            register plain php functions by defining them in the dispatch map
-            with an added option</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: catch exceptions thrown during execution of php
-            functions exposed as methods by the server</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: bad encoding if same object is encoded twice using
-            php_xmlrpc_encode</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.2.2</title>
-
-      <para><emphasis>Note:</emphasis> 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.</para>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>fixed: encoding of utf-8 characters outside of the BMP
-            plane</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: character set declarations surrounded by double
-            quotes were not recognized in http headers</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: be more tolerant in detection of charset in http
-            headers</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: fix detection of zlib.output_compression</para>
-          </listitem>
-
-          <listitem>
-            <para>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)</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: format floating point values using the correct
-            decimal separator even when php locale is set to one that uses
-            comma</para>
-          </listitem>
-
-          <listitem>
-            <para>fixed: improve robustness of the debugger when parsing weird
-            results from non-compliant servers</para>
-          </listitem>
-
-          <listitem>
-            <para>php warning when receiving 'false' in a bool value</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: allow the add_to_map server method to add docs for
-            single params too</para>
-          </listitem>
-
-          <listitem>
-            <para>improved: added the possibility to wrap for exposure as
-            xmlrpc methods plain php class methods, object methods and even
-            whole classes</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.2.1</title>
-
-      <itemizedlist>
-        <listitem>
-          <para>fixed: work aroung bug in php 5.2.2 which broke support of
-          HTTP_RAW_POST_DATA</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: is_dir parameter of setCaCertificate() method is
-          reversed</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: a php warning in xmlrpc_client creator method</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: parsing of '1e+1' as valid float</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: allow errorlevel 3 to work when prev. error handler was
-          a static method</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: usage of client::setcookie() for multiple cookies in
-          non-ssl mode</para>
-        </listitem>
-
-        <listitem>
-          <para>improved: support for CP1252 charset is not part or the
-          library but almost possible</para>
-        </listitem>
-
-        <listitem>
-          <para>improved: more info when curl is enabled and debug mode is
-          on</para>
-        </listitem>
-      </itemizedlist>
-    </sect1>
-
-    <sect1>
-      <title>2.2</title>
-
-      <itemizedlist>
-        <listitem>
-          <para>fixed: debugger errors on php installs with magic_quotes_gpc
-          on</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: support for https connections via proxy</para>
-        </listitem>
-
-        <listitem>
-          <para>fixed: wrap_xmlrpc_method() generated code failed to properly
-          encode php objects</para>
-        </listitem>
-
-        <listitem>
-          <para>improved: slightly faster encoding of data which is internally
-          UTF-8</para>
-        </listitem>
-
-        <listitem>
-          <para>improved: debugger always generates a 'null' id for jsonrpc if
-          user omits it</para>
-        </listitem>
-
-        <listitem>
-          <para>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)</para>
-        </listitem>
-
-        <listitem>
-          <para>new: support for the &lt;NIL/&gt; xmlrpc extension. see below
-          for more details</para>
-        </listitem>
-
-        <listitem>
-          <para>new: server support for the system.getCapabilities xmlrpc
-          extension</para>
-        </listitem>
-
-        <listitem>
-          <para>new: <function><link
-          linkend="wrap_xmlrpc_method">wrap_xmlrpc_method()</link></function>
-          accepts two new options: debug and return_on_fault</para>
-        </listitem>
-      </itemizedlist>
-    </sect1>
-
-    <sect1>
-      <title>2.1</title>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>The <function>wrap_php_function</function> and
-            <function>wrap_xmlrpc_method</function> functions have been moved
-            out of the base library file <filename>xmlrpc.inc</filename> into
-            a file of their own: <filename>xmlrpc_wrappers.inc</filename>. 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 <function>wrap_xmlrpc_method()</function> has been disabled
-            (but it can be optionally re-enabled). Both
-            <function>wrap_php_function()</function> and
-            <function>wrap_xmlrpc_method()</function> 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</para>
-          </listitem>
-
-          <listitem>
-            <para>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 <code>new xmlrpcval('true', 'boolean')</code>
-            is not supported anymore</para>
-          </listitem>
-
-          <listitem>
-            <para>The new function
-            <function>php_xmlrpc_decode_xml()</function> will take the xml
-            representation of either an xmlrpc request, response or single
-            value and return the corresponding php-xmlrpc object
-            instance</para>
-          </listitem>
-
-          <listitem>
-            <para>A new function <function>wrap_xmlrpc_server()</function>has
-            been added, to wrap all (or some) of the methods exposed by a
-            remote xmlrpc server into a php class</para>
-          </listitem>
-
-          <listitem>
-            <para>A new file has been added:
-            <filename>verify_compat.php</filename>, to help users diagnose the
-            level of compliance of their php installation with the
-            library</para>
-          </listitem>
-
-          <listitem>
-            <para>Restored compatibility with php 4.0.5 (for those poor souls
-            still stuck on it)</para>
-          </listitem>
-
-          <listitem>
-            <para>Method <methodname>xmlrpc_server-&gt;service()</methodname>
-            now returns a value: either the response payload or xmlrpcresp
-            object instance</para>
-          </listitem>
-
-          <listitem>
-            <para>Method
-            <methodname>xmlrpc_server-&gt;add_to_map()</methodname> now
-            accepts xmlrpc methods with no param definitions</para>
-          </listitem>
-
-          <listitem>
-            <para>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)</para>
-          </listitem>
-
-          <listitem>
-            <para>Full response payload is saved into xmlrpcresp object for
-            further debugging</para>
-          </listitem>
-
-          <listitem>
-            <para>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)</para>
-          </listitem>
-
-          <listitem>
-            <para>Stricter parsing of incoming xmlrpc messages: two more
-            invalid cases are now detected (double <literal>data</literal>
-            element inside <literal>array</literal> and
-            <literal>struct</literal>/<literal>array</literal> after scalar
-            inside <literal>value</literal> element)</para>
-          </listitem>
-
-          <listitem>
-            <para>More logging of errors in a lot of situations</para>
-          </listitem>
-
-          <listitem>
-            <para>Javadoc documentation of lib files (almost) complete</para>
-          </listitem>
-
-          <listitem>
-            <para>Many performance tweaks and code cleanups, plus the usual
-            crop of bugs fixed (see NEWS file for complete list of
-            bugs)</para>
-          </listitem>
-
-          <listitem>
-            <para>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)...</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.0 final</title>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>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</para>
-          </listitem>
-
-          <listitem>
-            <para>Added to the client class the possibility to specify
-            alternate certificate files/directories for authenticating the
-            peer with when using HTTPS communication</para>
-          </listitem>
-
-          <listitem>
-            <para>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)</para>
-          </listitem>
-
-          <listitem>
-            <para>The debugger has been upgraded to reflect the new client
-            capabilities</para>
-          </listitem>
-
-          <listitem>
-            <para>All known bugs have been squashed, and the lib is more
-            tolerant than ever of commonly-found mistakes</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.0 Release candidate 3</title>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>Added to server class the property
-            <property>functions_parameters_type</property>, 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)</para>
-          </listitem>
-
-          <listitem>
-            <para>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)</para>
-          </listitem>
-
-          <listitem>
-            <para>let php_xmlrpc_decode accept xmlrpcmsg objects as valid
-            input</para>
-          </listitem>
-
-          <listitem>
-            <para>'class::method' syntax is now accepted in the server
-            dispatch map</para>
-          </listitem>
-
-          <listitem>
-            <para><function>xmlrpc_clent::SetDebug()</function> accepts
-            integer values instead of a boolean value, with debugging level 2
-            adding to the information printed to screen the complete client
-            request</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.0 Release candidate 2</title>
-
-      <para><itemizedlist>
-          <listitem>
-            <para>Added a new property of the client object:
-            <code>xmlrpc_client-&gt;return_type</code>, 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.</para>
-          </listitem>
-
-          <listitem>
-            <para>Added in the extras dir. two new library file:
-            <filename>jsonrpc.inc</filename> and
-            <filename>jsonrpcs.inc</filename> containing new classes that
-            implement support for the json-rpc protocol (alpha quality
-            code)</para>
-          </listitem>
-
-          <listitem>
-            <para>Added a new client method: <code>setKey($key,
-            $keypass)</code> to be used in HTTPS connections</para>
-          </listitem>
-
-          <listitem>
-            <para>Added a new file containing some benchmarks in the testsuite
-            directory</para>
-          </listitem>
-        </itemizedlist></para>
-    </sect1>
-
-    <sect1>
-      <title>2.0 Release candidate 1</title>
-
-      <itemizedlist>
-        <listitem>
-          <para>Support for HTTP proxies (new method:
-          <code>xmlrpc_client::setProxy()</code>)</para>
-        </listitem>
-
-        <listitem>
-          <para>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:
-          <code>xmlrpc_client::setAcceptedCompression()</code>,
-          <code>xmlrpc_client::setRequestCompression()</code>). Note that the
-          ZLIB php extension needs to be enabled in PHP to support
-          compression.</para>
-        </listitem>
-
-        <listitem>
-          <para>Implement HTTP 1.1 connections, but only if CURL is enabled
-          (added an extra parameter to
-          <code>xmlrpc_client::xmlrpc_client</code> to set the desired HTTP
-          protocol at creation time and a new supported value for the last
-          parameter of <code>xmlrpc_client::send</code>, which now can be
-          safely omitted if it has been specified at creation time)</para>
-
-          <para>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.</para>
-        </listitem>
-
-        <listitem>
-          <para>Introduce support for cookies. Cookies to be sent to the
-          server with a request can be set using
-          <code>xmlrpc_client::setCookie()</code>, while cookies received from
-          the server are found in <code>xmlrpcresp::cookies()</code>. It is
-          left to the user to check for validity of received cookies and
-          decide whether they apply to successive calls or not.</para>
-        </listitem>
-
-        <listitem>
-          <para>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.</para>
-
-          <para>Supported encodings are US-ASCII, UTF-8 and ISO-8859-1.</para>
-        </listitem>
-
-        <listitem>
-          <para>Added one new xmlrpcmsg constructor syntax, allowing usage of
-          a single string with the complete URL of the target server</para>
-        </listitem>
-
-        <listitem>
-          <para>Convert xml-rpc boolean values into native php values instead
-          of 0 and 1</para>
-        </listitem>
-
-        <listitem>
-          <para>Force the <code>php_xmlrpc_encode</code> 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)</para>
-        </listitem>
-
-        <listitem>
-          <para>Prevent the <code>php_xmlrpc_encode</code> function from
-          further re-encoding any objects of class <code>xmlrpcval</code> that
-          are passed to it. This allows to call the function with arguments
-          consisting of mixed php values / xmlrpcval objects.</para>
-        </listitem>
-
-        <listitem>
-          <para>Allow a server to NOT respond to system.* method calls
-          (setting the <code>$server-&gt;allow_system_funcs</code>
-          property).</para>
-        </listitem>
-
-        <listitem>
-          <para>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: <code>xmlrpcval::structMemExists()</code></para>
-        </listitem>
-
-        <listitem>
-          <para>Expand methods <code>xmlrpcval::addArray</code>,
-          <code>addScalar</code> and <code>addStruct</code> allowing extra php
-          values to be added to xmlrpcval objects already formed.</para>
-        </listitem>
-
-        <listitem>
-          <para>Let the <code>xmlrpc_client::send</code> method accept an XML
-          string for sending instead of an xmlrpcmsg object, to facilitate
-          debugging and integration with the php native xmlrpc
-          extension</para>
-        </listitem>
-
-        <listitem>
-          <para>Extend the <code>php_xmlrpc_encode</code> and
-          <code>php_xmlrpc_decode</code> 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.</para>
-
-          <para>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 <code>php_xmlrpc_encode</code> and
-          <code>php_xmlrpc_decode</code>.</para>
-        </listitem>
-
-        <listitem>
-          <para>Extend the <code>php_xmlrpc_encode</code> function to allow
-          automatic serialization of iso8601-conforming php strings as
-          datetime.iso8601 xmlrpcvals, by usage of an optional
-          parameter</para>
-        </listitem>
-
-        <listitem>
-          <para>Added an automatic stub code generator for converting xmlrpc
-          methods to php functions and vice-versa.</para>
-
-          <para>This is done via two new functions:
-          <code>wrap_php_function</code> and <code>wrap_xmlrpc_method</code>,
-          and has many caveats, with php being a typeless language and
-          all...</para>
-
-          <para>With PHP versions lesser than 5.0.3 wrapping of php functions
-          into xmlrpc methods is not supported yet.</para>
-        </listitem>
-
-        <listitem>
-          <para>Allow object methods to be used in server dispatch map</para>
-        </listitem>
-
-        <listitem>
-          <para>Added a complete debugger solution, in the
-          <filename>debugger</filename> folder</para>
-        </listitem>
-
-        <listitem>
-          <para>Added configurable server-side debug messages, controlled by
-          the new method <code>xmlrpc_server::SetDebug()</code>. 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</para>
-        </listitem>
-
-        <listitem>
-          <para>New XML parsing code, yields smaller memory footprint and
-          faster execution times, not to mention complete elimination of the
-          dreaded <filename>eval()</filename> construct, so prone to code
-          injection exploits</para>
-        </listitem>
-
-        <listitem>
-          <para>Rewritten most of the error messages, making text more
-          explicative</para>
-        </listitem>
-      </itemizedlist>
-    </sect1>
-  </chapter>
-
-  <chapter id="requirements">
-    <title>System Requirements</title>
-
-    <para>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.</para>
-
-    <para>The <emphasis>minimum supported</emphasis> PHP version is
-    5.1.</para>
-
-    <para>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.</para>
-
-    <para>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.</para>
-  </chapter>
-
-  <chapter id="manifest">
-    <title>Files in the distribution</title>
-
-    <glosslist>
-      <glossentry>
-        <glossterm>lib/xmlrpc.inc</glossterm>
-
-        <glossdef>
-          <para>the XML-RPC classes. <function>include()</function> this in
-          your PHP files to use the classes.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>lib/xmlrpcs.inc</glossterm>
-
-        <glossdef>
-          <para>the XML-RPC server class. <function>include()</function> this
-          in addition to xmlrpc.inc to get server functionality</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>lib/xmlrpc_wrappers.inc</glossterm>
-
-        <glossdef>
-          <para>helper functions to "automagically" convert plain php
-          functions to xmlrpc services and vice versa</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/server/proxy.php</glossterm>
-
-        <glossdef>
-          <para>a sample server implementing xmlrpc proxy
-          functionality.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/server/server.php</glossterm>
-
-        <glossdef>
-          <para>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</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/client/client.php, demo/client/agesort.php,
-        demo/client/which.php</glossterm>
-
-        <glossdef>
-          <para>client code to exercise some of the functions in server.php,
-          including the <function>interopEchoTests.whichToolkit</function>
-          method.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/client/wrap.php</glossterm>
-
-        <glossdef>
-          <para>client code to illustrate 'wrapping' of remote methods into
-          php functions.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/client/introspect.php</glossterm>
-
-        <glossdef>
-          <para>client code to illustrate usage of introspection capabilities
-          offered by server.php.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/client/mail.php</glossterm>
-
-        <glossdef>
-          <para>client code to illustrate usage of an xmlrpc-to-email gateway
-          using Dave Winer's XML-RPC server at userland.com.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/client/zopetest.php</glossterm>
-
-        <glossdef>
-          <para>example client code that queries an xmlrpc server built in
-          Zope.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/vardemo.php</glossterm>
-
-        <glossdef>
-          <para>examples of how to construct xmlrpcval types</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/demo1.txt, demo/demo2.txt, demo/demo3.txt</glossterm>
-
-        <glossdef>
-          <para>XML-RPC responses captured in a file for testing purposes (you
-          can use these to test the
-          <function>xmlrpcmsg-&gt;parseResponse()</function> method).</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>demo/server/discuss.php,
-        demo/client/comment.php</glossterm>
-
-        <glossdef>
-          <para>Software used in the PHP chapter of <xref
-          linkend="jellyfish" /> to provide a comment server and allow the
-          attachment of comments to stories from Meerkat's data store.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>test/testsuite.php, test/parse_args.php</glossterm>
-
-        <glossdef>
-          <para>A unit test suite for this software package. If you do
-          development on this software, please consider submitting tests for
-          this suite.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>test/benchmark.php</glossterm>
-
-        <glossdef>
-          <para>A (very limited) benchmarking suite for this software package.
-          If you do development on this software, please consider submitting
-          benchmarks for this suite.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>test/phpunit.php, test/PHPUnit/*.php</glossterm>
-
-        <glossdef>
-          <para>An (incomplete) version PEAR's unit test framework for PHP.
-          The complete package can be found at <ulink
-          url="http://pear.php.net/package/PHPUnit">http://pear.php.net/package/PHPUnit</ulink></para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>test/verify_compat.php</glossterm>
-
-        <glossdef>
-          <para>Script designed to help the user to verify the level of
-          compatibility of the library with the current php install</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>extras/test.pl, extras/test.py</glossterm>
-
-        <glossdef>
-          <para>Perl and Python programs to exercise server.php to test that
-          some of the methods work.</para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>extras/workspace.testPhpServer.fttb</glossterm>
-
-        <glossdef>
-          <para>Frontier scripts to exercise the demo server. Thanks to Dave
-          Winer for permission to include these. See <ulink
-          url="http://www.xmlrpc.com/discuss/msgReader$853">Dave's
-          announcement of these.</ulink></para>
-        </glossdef>
-      </glossentry>
-
-      <glossentry>
-        <glossterm>extras/rsakey.pem</glossterm>
-
-        <glossdef>
-          <para>A test certificate key for the SSL support, which can be used
-          to generate dummy certificates. It has the passphrase "test."</para>
-        </glossdef>
-      </glossentry>
-    </glosslist>
-  </chapter>
-
-  <chapter id="bugs">
-    <title>Known bugs and limitations</title>
-
-    <para>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).</para>
-
-    <para>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 <xref
-    linkend="iso8601encode" /> and <xref linkend="iso8601decode" /> functions
-    to do the encoding and decoding for you.</para>
-
-    <para>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.</para>
-
-    <para>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 <xref linkend="xmlrpc-defencoding" /></para>
-
-    <para>Support for receiving from servers version 1 cookies (i.e.
-    conforming to RFC 2965) is quite incomplete, and might cause unforeseen
-    errors.</para>
-  </chapter>
-
-  <chapter id="support">
-    <title>Support</title>
-
-    <sect1>
-      <title>Online Support</title>
-
-      <para>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.</para>
-
-      <itemizedlist>
-        <listitem>
-          <para>The <emphasis>XML-RPC for PHP</emphasis> development is hosted
-          on <ulink
-          url="https://github.com/gggeek/phpxmlrpc">github.com/gggeek/phpxmlrpc</ulink>.
-          Bugs, feature requests and patches can be posted to the <ulink
-          url="https://github.com/gggeek/phpxmlrpc/issues">project's
-          website</ulink>.</para>
-        </listitem>
-
-        <listitem>
-          <para>The <emphasis>PHP XML-RPC interest mailing list</emphasis> is
-          run by the author. More details <ulink
-          url="http://lists.gnomehack.com/mailman/listinfo/phpxmlrpc">can be
-          found here</ulink>.</para>
-        </listitem>
-
-        <listitem>
-          <para>For more general XML-RPC questions, there is a Yahoo! Groups
-          <ulink url="http://groups.yahoo.com/group/xml-rpc/">XML-RPC mailing
-          list</ulink>.</para>
-        </listitem>
-
-        <listitem>
-          <para>The <ulink
-          url="http://www.xmlrpc.com/discuss">XML-RPC.com</ulink> discussion
-          group is a useful place to get help with using XML-RPC. This group
-          is also gatewayed into the Yahoo! Groups mailing list.</para>
-        </listitem>
-      </itemizedlist>
-    </sect1>
-
-    <sect1 id="jellyfish" xreflabel="The Jellyfish Book">
-      <title>The Jellyfish Book</title>
-
-      <para><graphic align="right" depth="190" fileref="progxmlrpc.s.gif"
-      format="GIF" width="145" />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.</para>
-
-      <para>Complete details of the book are <ulink
-      url="http://www.oreilly.com/catalog/progxmlrpc/">available from
-      O'Reilly's web site.</ulink></para>
-
-      <para>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
-      <ulink url="http://meerkat.oreillynet.com/">Meerkat</ulink> service in
-      order to allow commenting on news stories from around the Web.</para>
-
-      <para>If you've benefited from the effort that has been put into writing
-      this software, then please consider buying the book!</para>
-    </sect1>
-  </chapter>
-
-  <chapter id="apidocs">
-    <title>Class documentation</title>
-
-    <sect1 id="xmlrpcval" xreflabel="xmlrpcval">
-      <title>xmlrpcval</title>
-
-      <para>This is where a lot of the hard work gets done. This class enables
-      the creation and encapsulation of values for XML-RPC.</para>
-
-      <para>Ensure you've read the XML-RPC spec at <ulink
-      url="http://www.xmlrpc.com/stories/storyReader$7">http://www.xmlrpc.com/stories/storyReader$7</ulink>
-      before reading on as it will make things clearer.</para>
-
-      <para>The <classname>xmlrpcval</classname> class can store arbitrarily
-      complicated values using the following types: <literal>i4 int boolean
-      string double dateTime.iso8601 base64 array struct</literal>
-      <literal>null</literal>. You should refer to the <ulink
-      url="http://www.xmlrpc.com/spec">spec</ulink> for more information on
-      what each of these types mean.</para>
-
-      <sect2>
-        <title>Notes on types</title>
-
-        <sect3>
-          <title>int</title>
-
-          <para>The type <classname>i4</classname> is accepted as a synonym
-          for <classname>int</classname> when creating xmlrpcval objects. The
-          xml parsing code will always convert <classname>i4</classname> to
-          <classname>int</classname>: <classname>int</classname> is regarded
-          by this implementation as the canonical name for this type.</para>
-        </sect3>
-
-        <sect3>
-          <title>base64</title>
-
-          <para>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.</para>
-        </sect3>
-
-        <sect3>
-          <title>boolean</title>
-
-          <para>The php values <literal>true</literal> and
-          <literal>1</literal> map to <literal>true</literal>. All other
-          values (including the empty string) are converted to
-          <literal>false</literal>.</para>
-        </sect3>
-
-        <sect3>
-          <title>string</title>
-
-          <para>Characters &lt;, &gt;, ', ", &amp;, are encoded using their
-          entity reference as &amp;lt; &amp;gt; &amp;apos; &amp;quot; and
-          &amp;amp; All other characters outside of the ASCII range are
-          encoded using their character reference representation (e.g.
-          &amp;#200 for é). The XML-RPC spec recommends only encoding
-          <literal>&lt; &amp;</literal> but this implementation goes further,
-          for reasons explained by <ulink
-          url="http://www.w3.org/TR/REC-xml#syntax">the XML 1.0
-          recommendation</ulink>. In particular, using character reference
-          representation has the advantage of producing XML that is valid
-          independently of the charset encoding assumed.</para>
-        </sect3>
-
-        <sect3>
-          <title>null</title>
-
-          <para>There is no support for encoding <literal>null</literal>
-          values in the XML-RPC spec, but at least a couple of extensions (and
-          many toolkits) do support it. Before using <literal>null</literal>
-          values in your messages, make sure that the responding party accepts
-          them, and uses the same encoding convention (see ...).</para>
-        </sect3>
-      </sect2>
-
-      <sect2 id="xmlrpcval-creation" xreflabel="xmlrpcval constructors">
-        <title>Creation</title>
-
-        <para>The constructor is the normal way to create an
-        <classname>xmlrpcval</classname>. The constructor can take these
-        forms:</para>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type>new
-            <function>xmlrpcval</function></funcdef>
-
-            <void />
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type>new
-            <function>xmlrpcval</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$stringVal</parameter></paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type>new
-            <function>xmlrpcval</function></funcdef>
-
-            <paramdef><type>mixed</type><parameter>$scalarVal</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$scalartyp</parameter></paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type>new
-            <function>xmlrpcval</function></funcdef>
-
-            <paramdef><type>array</type><parameter>$arrayVal</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$arraytyp</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>The first constructor creates an empty value, which must be
-        altered using the methods <function>addScalar</function>,
-        <function>addArray</function> or <function>addStruct</function> before
-        it can be used.</para>
-
-        <para>The second constructor creates a simple string value.</para>
-
-        <para>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:
-        "<literal>int</literal>", "<literal>boolean</literal>",
-        "<literal>string</literal>", "<literal>double</literal>",
-        "<literal>dateTime.iso8601</literal>", "<literal>base64</literal>" or
-        "null".</para>
-
-        <para>Examples:</para>
-
-        <programlisting language="php">
-$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
-</programlisting>
-
-        <para>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 <classname>array</classname> or an associative
-        array in the case of a <classname>struct</classname>. The elements of
-        the array <emphasis>must be <classname>xmlrpcval</classname> objects
-        themselves</emphasis>.</para>
-
-        <para>The second parameter must be either "<literal>array</literal>"
-        or "<literal>struct</literal>".</para>
-
-        <para>Examples:</para>
-
-        <programlisting language="php">
-$myArray = new xmlrpcval(
-  array(
-    new xmlrpcval("Tom"),
-    new xmlrpcval("Dick"),
-    new xmlrpcval("Harry")
-  ),
-  "array");
-
-// recursive struct
-$myStruct = new xmlrpcval(
-  array(
-    "name" =&gt; new xmlrpcval("Tom", "string"),
-    "age" =&gt; new xmlrpcval(34, "int"),
-    "address" =&gt; new xmlrpcval(
-      array(
-        "street" =&gt; new xmlrpcval("Fifht Ave", "string"),
-        "city" =&gt; new xmlrpcval("NY", "string")
-      ),
-      "struct")
-  ),
-  "struct");
-</programlisting>
-
-        <para>See the file <literal>vardemo.php</literal> in this distribution
-        for more examples.</para>
-      </sect2>
-
-      <sect2 id="xmlrpcval-methods" xreflabel="xmlrpcval methods">
-        <title>Methods</title>
-
-        <sect3>
-          <title>addScalar</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>addScalar</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$stringVal</parameter></paramdef>
-            </funcprototype>
-
-            <funcprototype>
-              <funcdef><type>int</type><function>addScalar</function></funcdef>
-
-              <paramdef><type>mixed</type><parameter>$scalarVal</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$scalartyp</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <parameter>$val</parameter> is an empty
-          <classname>xmlrpcval</classname> this method makes it a scalar
-          value, and sets that value.</para>
-
-          <para>If <parameter>$val</parameter> is already a scalar value, then
-          no more scalars can be added and <literal>0</literal> is
-          returned.</para>
-
-          <para>If <parameter>$val</parameter> is an xmlrpcval of type array,
-          the php value <parameter>$scalarval</parameter> is added as its last
-          element.</para>
-
-          <para>If all went OK, <literal>1</literal> is returned, otherwise
-          <literal>0</literal>.</para>
-        </sect3>
-
-        <sect3>
-          <title>addArray</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>addArray</function></funcdef>
-
-              <paramdef><type>array</type><parameter>$arrayVal</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>The argument is a simple (numerically indexed) array. The
-          elements of the array <emphasis>must be
-          <classname>xmlrpcval</classname> objects
-          themselves</emphasis>.</para>
-
-          <para>Turns an empty <classname>xmlrpcval</classname> into an
-          <classname>array</classname> with contents as specified by
-          <parameter>$arrayVal</parameter>.</para>
-
-          <para>If <parameter>$val</parameter> is an xmlrpcval of type array,
-          the elements of <parameter>$arrayVal</parameter> are appended to the
-          existing ones.</para>
-
-          <para>See the fourth constructor form for more information.</para>
-
-          <para>If all went OK, <literal>1</literal> is returned, otherwise
-          <literal>0</literal>.</para>
-        </sect3>
-
-        <sect3>
-          <title>addStruct</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>addStruct</function></funcdef>
-
-              <paramdef><type>array</type><parameter>$assocArrayVal</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>The argument is an associative array. The elements of the
-          array <emphasis>must be <classname>xmlrpcval</classname> objects
-          themselves</emphasis>.</para>
-
-          <para>Turns an empty <classname>xmlrpcval</classname> into a
-          <classname>struct</classname> with contents as specified by
-          <parameter>$assocArrayVal</parameter>.</para>
-
-          <para>If <parameter>$val</parameter> is an xmlrpcval of type struct,
-          the elements of <parameter>$arrayVal</parameter> are merged with the
-          existing ones.</para>
-
-          <para>See the fourth constructor form for more information.</para>
-
-          <para>If all went OK, <literal>1</literal> is returned, otherwise
-          <literal>0</literal>.</para>
-        </sect3>
-
-        <sect3>
-          <title>kindOf</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>kindOf</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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.</para>
-        </sect3>
-
-        <sect3>
-          <title>serialize</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>serialize</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns a string containing the XML-RPC representation of this
-          value.</para>
-        </sect3>
-
-        <sect3>
-          <title>scalarVal</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>mixed</type><function>scalarVal</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <function>$val-&gt;kindOf() == "scalar"</function>, this
-          method returns the actual PHP-language value of the scalar (base 64
-          decoding is automatically handled here).</para>
-        </sect3>
-
-        <sect3>
-          <title>scalarTyp</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>scalarTyp</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <function>$val-&gt;kindOf() == "scalar"</function>, this
-          method returns a string denoting the type of the scalar. As
-          mentioned before, <literal>i4</literal> is always coerced to
-          <literal>int</literal>.</para>
-        </sect3>
-
-        <sect3>
-          <title>arrayMem</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcval</type><function>arrayMem</function></funcdef>
-
-              <paramdef><type>int</type><parameter>$n</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <function>$val-&gt;kindOf() == "array"</function>, returns
-          the <parameter>$n</parameter>th element in the array represented by
-          the value <parameter>$val</parameter>. The value returned is an
-          <classname>xmlrpcval</classname> object.</para>
-
-          <para><programlisting language="php">
-// iterating over values of an array object
-for ($i = 0; $i &lt; $val-&gt;arraySize(); $i++)
-{
-  $v = $val-&gt;arrayMem($i);
-  echo "Element $i of the array is of type ".$v-&gt;kindOf();
-}
-</programlisting></para>
-        </sect3>
-
-        <sect3>
-          <title>arraySize</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>arraySize</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <parameter>$val</parameter> is an
-          <classname>array</classname>, returns the number of elements in that
-          array.</para>
-        </sect3>
-
-        <sect3>
-          <title>structMem</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcval</type><function>structMem</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$memberName</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>If <function>$val-&gt;kindOf() == "struct"</function>, returns
-          the element called <parameter>$memberName</parameter> from the
-          struct represented by the value <parameter>$val</parameter>. The
-          value returned is an <classname>xmlrpcval</classname> object.</para>
-        </sect3>
-
-        <sect3>
-          <title>structEach</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>array</type><function>structEach</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns the next (key, value) pair from the struct, when
-          <parameter>$val</parameter> is a struct.
-          <parameter>$value</parameter> is an xmlrpcval itself. See also <xref
-          linkend="structreset" />.</para>
-
-          <para><programlisting language="php">
-// iterating over all values of a struct object
-$val-&gt;structreset();
-while (list($key, $v) = $val-&gt;structEach())
-{
-  echo "Element $key of the struct is of type ".$v-&gt;kindOf();
-}
-</programlisting></para>
-        </sect3>
-
-        <sect3 id="structreset" xreflabel="structreset()">
-          <title>structReset</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>structReset</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Resets the internal pointer for
-          <function>structEach()</function> to the beginning of the struct,
-          where <parameter>$val</parameter> is a struct.</para>
-        </sect3>
-
-        <sect3 id="structmemexists" xreflabel="structmemexists()">
-          <title>structMemExists</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>bool</type><function>structMemExsists</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$memberName</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns <constant>TRUE</constant> or
-          <constant>FALSE</constant> depending on whether a member of the
-          given name exists in the struct.</para>
-        </sect3>
-      </sect2>
-    </sect1>
-
-    <sect1 id="xmlrpcmsg" xreflabel="xmlrpcmsg">
-      <title>xmlrpcmsg</title>
-
-      <para>This class provides a representation for a request to an XML-RPC
-      server. A client sends an <classname>xmlrpcmsg</classname> to a server,
-      and receives back an <classname>xmlrpcresp</classname> (see <xref
-      linkend="xmlrpc-client-send" />).</para>
-
-      <sect2>
-        <title>Creation</title>
-
-        <para>The constructor takes the following forms:</para>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcmsg</type>new
-            <function>xmlrpcmsg</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$methodName</parameter></paramdef>
-
-            <paramdef><type>array</type><parameter>$parameterArray</parameter><initializer>null</initializer></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Where <parameter>methodName</parameter> is a string indicating
-        the name of the method you wish to invoke, and
-        <parameter>parameterArray</parameter> is a simple php
-        <classname>Array</classname> of <classname>xmlrpcval</classname>
-        objects. Here's an example message to the <emphasis>US state
-        name</emphasis> server:</para>
-
-        <programlisting language="php">
-$msg = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int")));
-</programlisting>
-
-        <para>This example requests the name of state number 23. For more
-        information on <classname>xmlrpcval</classname> objects, see <xref
-        linkend="xmlrpcval" />.</para>
-
-        <para>Note that the <parameter>parameterArray</parameter> parameter is
-        optional and can be omitted for methods that take no input parameters
-        or if you plan to add parameters one by one.</para>
-      </sect2>
-
-      <sect2>
-        <title>Methods</title>
-
-        <sect3>
-          <title>addParam</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>bool</type><function>addParam</function></funcdef>
-
-              <paramdef><type>xmlrpcval</type><parameter>$xmlrpcVal</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Adds the <classname>xmlrpcval</classname>
-          <parameter>xmlrpcVal</parameter> to the parameter list for this
-          method call. Returns TRUE or FALSE on error.</para>
-        </sect3>
-
-        <sect3>
-          <title>getNumParams</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>getNumParams</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns the number of parameters attached to this
-          message.</para>
-        </sect3>
-
-        <sect3>
-          <title>getParam</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcval</type><function>getParam</function></funcdef>
-
-              <paramdef><type>int</type><parameter>$n</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Gets the <parameter>n</parameter>th parameter in the message
-          (with the index zero-based). Use this method in server
-          implementations to retrieve the values sent by the client.</para>
-        </sect3>
-
-        <sect3>
-          <title>method</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>method</function></funcdef>
-
-              <void />
-            </funcprototype>
-
-            <funcprototype>
-              <funcdef><type>string</type><function>method</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$methName</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Gets or sets the method contained in the XML-RPC
-          message.</para>
-        </sect3>
-
-        <sect3>
-          <title>parseResponse</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcresp</type><function>parseResponse</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$xmlString</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Given an incoming XML-RPC server response contained in the
-          string <parameter>$xmlString</parameter>, this method constructs an
-          <classname>xmlrpcresp</classname> response object and returns it,
-          setting error codes as appropriate (see <xref
-          linkend="xmlrpc-client-send" />).</para>
-
-          <para>This method processes any HTTP/MIME headers it finds.</para>
-        </sect3>
-
-        <sect3>
-          <title>parseResponseFile</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcresp</type><function>parseResponseFile</function></funcdef>
-
-              <paramdef><type>file handle
-              resource</type><parameter>$fileHandle</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Given an incoming XML-RPC server response on the open file
-          handle <parameter>fileHandle</parameter>, this method reads all the
-          data it finds and passes it to
-          <function>parseResponse.</function></para>
-
-          <para>This method is useful to construct responses from pre-prepared
-          files (see files <literal>demo1.txt, demo2.txt, demo3.txt</literal>
-          in this distribution). It processes any HTTP headers it finds, and
-          does not close the file handle.</para>
-        </sect3>
-
-        <sect3>
-          <title>serialize</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string
-              </type><function>serialize</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns the an XML string representing the XML-RPC
-          message.</para>
-        </sect3>
-      </sect2>
-    </sect1>
-
-    <sect1 id="xmlrpc-client" xreflabel="xmlrpc_client">
-      <title>xmlrpc_client</title>
-
-      <para>This is the basic class used to represent a client of an XML-RPC
-      server.</para>
-
-      <sect2>
-        <title>Creation</title>
-
-        <para>The constructor accepts one of two possible syntaxes:</para>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpc_client</type>new
-            <function>xmlrpc_client</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$server_url</parameter></paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>xmlrpc_client</type>new
-            <function>xmlrpc_client</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$server_path</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$server_hostname</parameter></paramdef>
-
-            <paramdef><type>int</type><parameter>$server_port</parameter><initializer>80</initializer></paramdef>
-
-            <paramdef><type>string</type><parameter>$transport</parameter><initializer>'http'</initializer></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Here are a couple of usage examples of the first form:</para>
-
-        <programlisting language="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");
-</programlisting>
-
-        <para>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.</para>
-
-        <para>Here's another example client set up to query Userland's XML-RPC
-        server at <emphasis>betty.userland.com</emphasis>:</para>
-
-        <programlisting language="php">
-$client = new xmlrpc_client("/RPC2", "betty.userland.com", 80);
-</programlisting>
-
-        <para>The <parameter>server_port</parameter> parameter is optional,
-        and if omitted will default to 80 when using HTTP and 443 when using
-        HTTPS (see the <xref linkend="xmlrpc-client-send" /> method
-        below).</para>
-
-        <para>The <parameter>transport</parameter> parameter is optional, and
-        if omitted will default to 'http'. Allowed values are either
-        '<symbol>http'</symbol>, '<symbol>https</symbol>' or
-        '<symbol>http11'</symbol>. Its value can be overridden with every call
-        to the <methodname>send</methodname> method. See the
-        <methodname>send</methodname> method below for more details about the
-        meaning of the different values.</para>
-      </sect2>
-
-      <sect2>
-        <title>Methods</title>
-
-        <para>This class supports the following methods.</para>
-
-        <sect3 id="xmlrpc-client-send" xreflabel="xmlrpc_client-&gt;send">
-          <title>send</title>
-
-          <para>This method takes the forms:</para>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcresp</type><function>send</function></funcdef>
-
-              <paramdef><type>xmlrpcmsg</type><parameter>$xmlrpc_message</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$timeout</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$transport</parameter></paramdef>
-            </funcprototype>
-
-            <funcprototype>
-              <funcdef><type>array</type><function>send</function></funcdef>
-
-              <paramdef><type>array</type><parameter>$xmlrpc_messages</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$timeout</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$transport</parameter></paramdef>
-            </funcprototype>
-
-            <funcprototype>
-              <funcdef><type>xmlrpcresp</type><function>send</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$xml_payload</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$timeout</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$transport</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Where <parameter>xmlrpc_message</parameter> is an instance of
-          <classname>xmlrpcmsg</classname> (see <xref linkend="xmlrpcmsg" />),
-          and <parameter>response</parameter> is an instance of
-          <classname>xmlrpcresp</classname> (see <xref
-          linkend="xmlrpcresp" />).</para>
-
-          <para><parameter>If xmlrpc_messages</parameter> is an array of
-          message instances, <code>responses</code> will be an array of
-          response instances. The client will try to make use of a single
-          <code>system.multicall</code> xml-rpc method call to forward to the
-          server all the messages in a single HTTP round trip, unless
-          <code>$client-&gt;no_multicall</code> has been previously set to
-          <code>TRUE</code> (see the multicall method below), in which case
-          many consecutive xmlrpc requests will be sent.</para>
-
-          <para>The third syntax allows to build by hand (or any other means)
-          a complete xmlrpc request message, and send it to the server.
-          <parameter>xml_payload</parameter> 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 <ulink
-          url="http://www.php.net/xmlrpc">the php manual on
-          xmlrpc</ulink>).</para>
-
-          <para>The <parameter>timeout</parameter> is optional, and will be
-          set to <literal>0</literal> (wait for platform-specific predefined
-          timeout) if omitted. This timeout value is passed to
-          <function>fsockopen()</function>. It is also used for detecting
-          server timeouts during communication (i.e. if the server does not
-          send anything to the client for <parameter>timeout</parameter>
-          seconds, the connection will be closed).</para>
-
-          <para>The <parameter>transport</parameter> 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.</para>
-
-          <warning>
-            <para>PHP 4.0.6 has a bug which prevents SSL working.</para>
-          </warning>
-
-          <para>In addition to low-level errors, the XML-RPC server you were
-          querying may return an error in the
-          <classname>xmlrpcresp</classname> object. See <xref
-          linkend="xmlrpcresp" /> for details of how to handle these
-          errors.</para>
-        </sect3>
-
-        <sect3 id="multicall" xreflabel="xmlrpc_client-&gt;multicall">
-          <title>multiCall</title>
-
-          <para>This method takes the form:</para>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>array</type><function>multiCall</function></funcdef>
-
-              <paramdef><type>array</type><parameter>$messages</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$timeout</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$transport</parameter></paramdef>
-
-              <paramdef><type>bool</type><parameter>$fallback</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>This method is used to boxcar many method calls in a single
-          xml-rpc request. It will try first to make use of the
-          <code>system.multicall</code> xml-rpc method call, and fall back to
-          executing many separate requests if the server returns any
-          error.</para>
-
-          <para><parameter>msgs</parameter> is an array of
-          <classname>xmlrpcmsg</classname> objects (see <xref
-          linkend="xmlrpcmsg" />), and <parameter>response</parameter> is an
-          array of <classname>xmlrpcresp</classname> objects (see <xref
-          linkend="xmlrpcresp" />).</para>
-
-          <para>The <parameter>timeout</parameter> and
-          <parameter>transport</parameter> parameters are optional, and behave
-          as in the <methodname>send</methodname> method above.</para>
-
-          <para>The <parameter>fallback</parameter> parameter is optional, and
-          defaults to <constant>TRUE</constant>. When set to
-          <constant>FALSE</constant> 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.</para>
-        </sect3>
-
-        <sect3>
-          <title>setAcceptedCompression</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setAcceptedCompression</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$compressionmethod</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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
-          <parameter>compressionmethod</parameter> are: 'gzip', 'deflate',
-          'any' or null (with any meaning either gzip or deflate).</para>
-
-          <para>This requires the "zlib" extension to be enabled in your php
-          install. If it is, by default <classname>xmlrpc_client</classname>
-          instances will enable reception of compressed content.</para>
-        </sect3>
-
-        <sect3>
-          <title>setCaCertificate</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setCaCertificate</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$certificate</parameter></paramdef>
-
-              <paramdef><type>bool</type><parameter>$is_dir</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>This method sets an optional certificate to be used in
-          SSL-enabled communication to validate a remote server with (when the
-          <parameter>server_method</parameter> is set to 'https' in the
-          client's construction or in the send method and
-          <methodname>SetSSLVerifypeer</methodname> has been set to
-          <constant>TRUE</constant>).</para>
-
-          <para>The <parameter>certificate</parameter> parameter must be the
-          filename of a PEM formatted certificate, or a directory containing
-          multiple certificate files. The <parameter>is_dir</parameter>
-          parameter defaults to <constant>FALSE</constant>, set it to
-          <constant>TRUE</constant> to specify that
-          <parameter>certificate</parameter> indicates a directory instead of
-          a single file.</para>
-
-          <para>This requires the "curl" extension to be compiled into your
-          installation of PHP. For more details see the man page for the
-          <function>curl_setopt</function> function.</para>
-        </sect3>
-
-        <sect3>
-          <title>setCertificate</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setCertificate</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$certificate</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$passphrase</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>This method sets the optional certificate and passphrase used
-          in SSL-enabled communication with a remote server (when the
-          <parameter>server_method</parameter> is set to 'https' in the
-          client's construction or in the send method).</para>
-
-          <para>The <parameter>certificate</parameter> parameter must be the
-          filename of a PEM formatted certificate. The
-          <parameter>passphrase</parameter> parameter must contain the
-          password required to use the certificate.</para>
-
-          <para>This requires the "curl" extension to be compiled into your
-          installation of PHP. For more details see the man page for the
-          <function>curl_setopt</function> function.</para>
-
-          <para>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.</para>
-        </sect3>
-
-        <sect3>
-          <title>setCookie</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setCookie</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$name</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$value</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$path</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$domain</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$port</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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).</para>
-
-          <para><parameter>$value</parameter> is optional, and defaults to
-          null.</para>
-
-          <para><parameter>$path, $domain and $port</parameter> 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).</para>
-        </sect3>
-
-        <sect3>
-          <title>setCredentials</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setCredentials</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$username</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$password</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$authtype</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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
-          <constant>CURLAUTH_DIGEST</constant> and
-          <constant>CURLAUTH_NTLM</constant> as values for the authtype
-          parameter.</para>
-        </sect3>
-
-        <sect3>
-          <title>setCurlOptions</title>
-
-          <para><funcsynopsis>
-              <funcprototype>
-                <funcdef><type>void</type><function>setCurlOptions</function></funcdef>
-
-                <paramdef><type>array</type><parameter>$options</parameter></paramdef>
-              </funcprototype>
-            </funcsynopsis>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</para>
-        </sect3>
-
-        <sect3>
-          <title>setDebug</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setDebug</function></funcdef>
-
-              <paramdef><type>int</type><parameter>$debugLvl</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para><parameter>debugLvl</parameter> is either <literal>0,
-          1</literal> 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).</para>
-
-          <para>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.</para>
-
-          <para>This option can be very useful when debugging servers as it
-          allows you to see exactly what the client sends and the server
-          returns.</para>
-        </sect3>
-
-        <sect3>
-          <title>setKey</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setKey</function></funcdef>
-
-              <paramdef><type>int</type><parameter>$key</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$keypass</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>This method sets the optional certificate key and passphrase
-          used in SSL-enabled communication with a remote server (when the
-          <parameter>transport</parameter> is set to 'https' in the client's
-          construction or in the send method).</para>
-
-          <para>This requires the "curl" extension to be compiled into your
-          installation of PHP. For more details see the man page for the
-          <function>curl_setopt</function> function.</para>
-        </sect3>
-
-        <sect3>
-          <title>setProxy</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setProxy</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$proxyhost</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$proxyport</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$proxyusername</parameter></paramdef>
-
-              <paramdef><type>string</type><parameter>$proxypassword</parameter></paramdef>
-
-              <paramdef><type>int</type><parameter>$authtype</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>This method enables calling servers via an HTTP proxy. The
-          <parameter>proxyusername</parameter>,<parameter>
-          proxypassword</parameter> and <parameter>authtype</parameter>
-          parameters are optional. <parameter>Authtype</parameter> defaults to
-          <constant>CURLAUTH_BASIC</constant> (Basic authentication protocol);
-          the only other valid value is the constant
-          <constant>CURLAUTH_NTLM</constant>, and has effect only when the
-          client uses the HTTP 1.1 protocol.</para>
-
-          <para>NB: CURL versions before 7.11.10 cannot use a proxy to
-          communicate with https servers.</para>
-        </sect3>
-
-        <sect3>
-          <title>setRequestCompression</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setRequestCompression</function></funcdef>
-
-              <paramdef><type>string</type><parameter>$compressionmethod</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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 <parameter>compressionmethod</parameter> 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.</para>
-
-          <para>This requires the "zlib" extension to be enabled in your php
-          install.</para>
-        </sect3>
-
-        <sect3>
-          <title>setSSLVerifyHost</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setSSLVerifyHost</function></funcdef>
-
-              <paramdef><type>int</type><parameter>$i</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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.
-          <parameter><parameter>$i</parameter></parameter> 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.</para>
-        </sect3>
-
-        <sect3>
-          <title>setSSLVerifyPeer</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>void</type><function>setSSLVerifyPeer</function></funcdef>
-
-              <paramdef><type>bool</type><parameter>$i</parameter></paramdef>
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>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.
-          <parameter><parameter>$i</parameter></parameter> should be a boolean
-          value. Default value: <constant>TRUE</constant>. To specify custom
-          SSL certificates to validate the server with, use the
-          <methodname>setCaCertificate</methodname> method.</para>
-        </sect3>
-
-        <sect3>
-          <title>setUserAgent</title>
-
-          <para><funcsynopsis>
-              <funcprototype>
-                <funcdef><type>void</type><function>Useragent</function></funcdef>
-
-                <paramdef><type>string</type><parameter>$useragent</parameter></paramdef>
-              </funcprototype>
-            </funcsynopsis>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.</para>
-        </sect3>
-      </sect2>
-
-      <sect2>
-        <title>Variables</title>
-
-        <para>NB: direct manipulation of these variables is only recommended
-        for advanced users.</para>
-
-        <sect3>
-          <title>no_multicall</title>
-
-          <para>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.</para>
-        </sect3>
-
-        <sect3>
-          <title>request_charset_encoding</title>
-
-          <para>This is the charset encoding that will be used for serializing
-          request sent by the client.</para>
-
-          <para>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).</para>
-
-          <para>Valid values are 'US-ASCII', 'UTF-8' and 'ISO-8859-1'</para>
-        </sect3>
-
-        <sect3 id="return-type" xreflabel="return_type">
-          <title>return_type</title>
-
-          <para>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.</para>
-
-          <para>Example usage:</para>
-
-          <programlisting language="php">
-$client = new xmlrpc_client("phpxmlrpc.sourceforge.net/server.php");
-$client-&gt;return_type = 'phpvals';
-$message = new xmlrpcmsg("examples.getStateName", array(new xmlrpcval(23, "int")));
-$resp = $client-&gt;send($message);
-if ($resp-&gt;faultCode()) echo 'KO. Error: '.$resp-&gt;faultString(); else echo 'OK: got '.$resp-&gt;value();
-</programlisting>
-
-          <para>For more details about usage of the 'xml' value, see Appendix
-          A.</para>
-        </sect3>
-      </sect2>
-    </sect1>
-
-    <sect1 id="xmlrpcresp" xreflabel="xmlrpcresp">
-      <title>xmlrpcresp</title>
-
-      <para>This class is used to contain responses to XML-RPC requests. A
-      server method handler will construct an
-      <classname>xmlrpcresp</classname> and pass it as a return value. This
-      same value will be returned by the result of an invocation of the
-      <function>send</function> method of the
-      <classname>xmlrpc_client</classname> class.</para>
-
-      <sect2>
-        <title>Creation</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcresp</type>new
-            <function>xmlrpcresp</function></funcdef>
-
-            <paramdef><type>xmlrpcval</type><parameter>$xmlrpcval</parameter></paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>xmlrpcresp</type>new
-            <function>xmlrpcresp</function></funcdef>
-
-            <paramdef><parameter>0</parameter></paramdef>
-
-            <paramdef><type>int</type><parameter>$errcode</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$err_string</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>The first syntax is used when execution has happened without
-        difficulty: <parameter>$xmlrpcval</parameter> is an
-        <classname>xmlrpcval</classname> 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.</para>
-
-        <para>The second type of constructor is used in case of failure.
-        <parameter>errcode</parameter> and <parameter>err_string</parameter>
-        are used to provide indication of what has gone wrong. See <xref
-        linkend="xmlrpc-server" /> for more information on passing error
-        codes.</para>
-      </sect2>
-
-      <sect2>
-        <title>Methods</title>
-
-        <sect3>
-          <title>faultCode</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>int</type><function>faultCode</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns the integer fault code return from the XML-RPC
-          response. A zero value indicates success, any other value indicates
-          a failure response.</para>
-        </sect3>
-
-        <sect3>
-          <title>faultString</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>faultString</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns the human readable explanation of the fault indicated
-          by <function>$resp-&gt;faultCode</function>().</para>
-        </sect3>
-
-        <sect3>
-          <title>value</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>xmlrpcval</type><function>value</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns an <classname>xmlrpcval</classname> object containing
-          the return value sent by the server. If the response's
-          <function>faultCode</function> is non-zero then the value returned
-          by this method should not be used (it may not even be an
-          object).</para>
-
-          <para>Note: if the xmlrpcresp instance in question has been created
-          by an <classname>xmlrpc_client</classname> object whose
-          <varname>return_type</varname> was set to 'phpvals', then a plain
-          php value will be returned instead of an
-          <classname>xmlrpcval</classname> object. If the
-          <varname>return_type</varname> was set to 'xml', an xml string will
-          be returned (see the return_type member var above for more
-          details).</para>
-        </sect3>
-
-        <sect3>
-          <title>serialize</title>
-
-          <funcsynopsis>
-            <funcprototype>
-              <funcdef><type>string</type><function>serialize</function></funcdef>
-
-              <void />
-            </funcprototype>
-          </funcsynopsis>
-
-          <para>Returns an XML string representation of the response (xml
-          prologue not included).</para>
-        </sect3>
-      </sect2>
-    </sect1>
-
-    <sect1 id="xmlrpc-server" xreflabel="xmlrpc_server">
-      <title>xmlrpc_server</title>
-
-      <para>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:</para>
-
-      <programlisting language="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" =&gt; array("function" =&gt; "foo"),
-      "examples.myFunc2" =&gt; array("function" =&gt; "bar::foobar"),
-    ));
-</programlisting>
-
-      <para>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
-      <classname>xmlrpcresp</classname> object, that will be serialized back
-      to the caller.</para>
-
-      <sect2>
-        <title>Method handler functions</title>
-
-        <para>Both php functions and class methods can be registered as xmlrpc
-        method handlers.</para>
-
-        <para>The synopsis of a method handler function is:</para>
-
-        <para><synopsis>xmlrpcresp $resp = function (xmlrpcmsg $msg)</synopsis></para>
-
-        <para>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
-        <varname>exception_handling</varname> member variable (see
-        ...).</para>
-
-        <para>Note that if you implement a method with a name prefixed by
-        <code>system.</code> the handler function will be invoked by the
-        server with two parameters, the first being the server itself and the
-        second being the <classname>xmlrpcmsg</classname> object.</para>
-
-        <para>The same php function can be registered as handler of multiple
-        xmlrpc methods.</para>
-
-        <para>Here is a more detailed example of what the handler function
-        <function>foo</function> may do:</para>
-
-        <programlisting language="php">
-  function foo ($xmlrpcmsg) {
-    global $xmlrpcerruser; // import user errcode base value
-
-    $meth = $xmlrpcmsg-&gt;method(); // retrieve method name
-    $par = $xmlrpcmsg-&gt;getParam(0); // retrieve value of first parameter - assumes at least one param received
-    $val = $par-&gt;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"));
-    }
-  }
-</programlisting>
-
-        <para>See <filename>server.php</filename> in this distribution for
-        more examples of how to do this.</para>
-
-        <para>Since release 2.0RC3 there is a new, even simpler way of
-        registering php functions with the server. See section 5.7
-        below</para>
-      </sect2>
-
-      <sect2>
-        <title>The dispatch map</title>
-
-        <para>The first argument to the <function>xmlrpc_server</function>
-        constructor is an array, called the <emphasis>dispatch map</emphasis>.
-        In this array is the information the server needs to service the
-        XML-RPC methods you define.</para>
-
-        <para>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:</para>
-
-        <itemizedlist>
-          <listitem>
-            <para><function><literal>function</literal></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).</para>
-          </listitem>
-
-          <listitem>
-            <para><function><literal>signature</literal></function> - this
-            entry is an array containing the possible signatures (see <xref
-            linkend="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.</para>
-          </listitem>
-
-          <listitem>
-            <para><function><literal>docstring</literal></function> - this
-            entry is a string containing documentation for the method. The
-            documentation may contain HTML markup.</para>
-          </listitem>
-
-          <listitem>
-            <para><literal>signature_docs</literal> - this entry can be used
-            to provide documentation for the single parameters. It must match
-            in structure the 'signature' member. By default, only the
-            <classname>documenting_xmlrpc_server</classname> class in the
-            extras package will take advantage of this, since the
-            "system.methodHelp" protocol does not support documenting method
-            parameters individually.</para>
-          </listitem>
-
-          <listitem>
-            <para><literal>parameters_type</literal> - 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 <literal>phpvals</literal>.</para>
-          </listitem>
-        </itemizedlist>
-
-        <para>Look at the <filename>server.php</filename> example in the
-        distribution to see what a dispatch map looks like.</para>
-      </sect2>
-
-      <sect2 id="signatures" xreflabel="Signatures">
-        <title>Method signatures</title>
-
-        <para>A signature is a description of a method's return type and its
-        parameter types. A method may have more than one signature.</para>
-
-        <para>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 <programlisting
-        language="php">string examples.getStateName(int)
-</programlisting> has the signature <programlisting language="php">array($xmlrpcString, $xmlrpcInt)
-</programlisting> and, assuming that it is the only possible signature for the
-        method, it might be used like this in server creation: <programlisting
-        language="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" =&gt; array(
-    "function" =&gt; "findstate",
-    "signature" =&gt; $findstate_sig,
-    "docstring" =&gt; $findstate_doc
-  )));
-</programlisting></para>
-
-        <para>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.</para>
-
-        <para>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 <varname>$xmlrpcValue</varname>, which can be
-        used in method signatures as a placeholder for 'any xmlrpc
-        type':</para>
-
-        <para><programlisting language="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" =&gt; array(
-    "function" =&gt; "echoback",
-    "signature" =&gt; $echoback_sig, // this sig guarantees that the method handler will be called with one and only one parameter
-    "docstring" =&gt; $echoback_doc
-  )));
-</programlisting></para>
-
-        <para>Methods <methodname>system.listMethods</methodname>,
-        <methodname>system.methodHelp</methodname>,
-        <methodname>system.methodSignature</methodname> and
-        <methodname>system.multicall</methodname> are already defined by the
-        server, and should not be reimplemented (see Reserved Methods
-        below).</para>
-      </sect2>
-
-      <sect2>
-        <title>Delaying the server response</title>
-
-        <para>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 <literal>0</literal> this will have the desired
-        effect. You can then use the <function>service()</function> method of
-        the server class to service the request. For example:</para>
-
-        <programlisting language="php">
-$s = new xmlrpc_server($myDispMap, 0); // second parameter = 0 prevents automatic servicing of request
-
-// ... some code that does other stuff here
-
-$s-&gt;service();
-</programlisting>
-
-        <para>Note that the <methodname>service</methodname> 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.</para>
-
-        <para>To prevent the server from sending HTTP headers back to the
-        client, you can pass a second parameter with a value of
-        <literal>TRUE</literal> to the <methodname>service</methodname>
-        method. In this case, the response payload will be returned instead of
-        the response object.</para>
-
-        <para>Xmlrpc requests retrieved by other means than HTTP POST bodies
-        can also be processed. For example:</para>
-
-        <programlisting language="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-&gt;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
-</programlisting>
-      </sect2>
-
-      <sect2>
-        <title>Modifying the server behaviour</title>
-
-        <para>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)</para>
-
-        <sect3>
-          <title>setDebug()</title>
-
-          <para>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.</para>
-        </sect3>
-
-        <sect3>
-          <title>allow_system_funcs</title>
-
-          <para>Default_value: TRUE. When set to FALSE, disables support for
-          <methodname>System.xxx</methodname> functions in the server. It
-          might be useful e.g. if you do not wish the server to respond to
-          requests to <methodname>System.ListMethods</methodname>.</para>
-        </sect3>
-
-        <sect3>
-          <title>compress_response</title>
-
-          <para>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.</para>
-
-          <para>Note that the ZLIB php extension must be installed for this to
-          work. If it is, <varname>compress_response</varname> will default to
-          TRUE.</para>
-        </sect3>
-
-        <sect3>
-          <title>exception_handling</title>
-
-          <para>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</para>
-        </sect3>
-
-        <sect3>
-          <title>response_charset_encoding</title>
-
-          <para>Charset encoding to be used for response (only affects string
-          values).</para>
-
-          <para>If it can, the server will convert the generated response from
-          internal_encoding to the intended one.</para>
-
-          <para>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).</para>
-        </sect3>
-      </sect2>
-
-      <sect2>
-        <title>Fault reporting</title>
-
-        <para>Fault codes for your servers should start at the value indicated
-        by the global <literal>$xmlrpcerruser</literal> + 1.</para>
-
-        <para>Standard errors returned by the server include:</para>
-
-        <variablelist>
-          <varlistentry>
-            <term><literal>1</literal> <phrase>Unknown method</phrase></term>
-
-            <listitem>
-              <para>Returned if the server was asked to dispatch a method it
-              didn't know about</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>2</literal> <phrase>Invalid return
-            payload</phrase></term>
-
-            <listitem>
-              <para>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.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>3</literal> <phrase>Incorrect
-            parameters</phrase></term>
-
-            <listitem>
-              <para>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.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>4</literal> <phrase>Can't introspect: method
-            unknown</phrase></term>
-
-            <listitem>
-              <para>This error is generated by the builtin
-              <function>system.*</function> methods when any kind of
-              introspection is attempted on a method undefined by the
-              server.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>5</literal> <phrase>Didn't receive 200 OK from
-            remote server</phrase></term>
-
-            <listitem>
-              <para>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.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>6</literal> <phrase>No data received from
-            server</phrase></term>
-
-            <listitem>
-              <para>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.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>7</literal> <phrase>No SSL support compiled
-            in</phrase></term>
-
-            <listitem>
-              <para>This error is generated by the client when trying to send
-              a request with HTTPS and the CURL extension is not available to
-              PHP.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>8</literal> <phrase>CURL error</phrase></term>
-
-            <listitem>
-              <para>This error is generated by the client when trying to send
-              a request with HTTPS and the HTTPS communication fails.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>9-14</literal> <phrase>multicall
-            errors</phrase></term>
-
-            <listitem>
-              <para>These errors are generated by the server when something
-              fails inside a system.multicall request.</para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
-            <term><literal>100-</literal> <phrase>XML parse
-            errors</phrase></term>
-
-            <listitem>
-              <para>Returns 100 plus the XML parser error code for the fault
-              that occurred. The <function>faultString</function> returned
-              explains where the parse error was in the incoming XML
-              stream.</para>
-            </listitem>
-          </varlistentry>
-        </variablelist>
-      </sect2>
-
-      <sect2>
-        <title>'New style' servers</title>
-
-        <para>In the same spirit of simplification that inspired the
-        <varname>xmlrpc_client::return_type</varname> class variable, a new
-        class variable has been added to the server class:
-        <varname>functions_parameters_type</varname>. 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:<programlisting language="php">
-  function foo($usr_id, $out_lang='en') {
-    global $xmlrpcerruser;
-
-    ...
-
-    if ($someErrorCondition)
-      return new xmlrpcresp(0, $xmlrpcerruser+1, 'DOH!');
-    else
-      return array(
-        'name' =&gt; 'Joe',
-        'age' =&gt; 27,
-        'picture' =&gt; new xmlrpcval(file_get_contents($picOfTheGuy), 'base64')
-      );
-  }
-
-  $s = new xmlrpc_server(
-    array(
-      "examples.myFunc" =&gt; array(
-        "function" =&gt; "bar::foobar",
-        "signature" =&gt; array(
-          array($xmlrpcString, $xmlrpcInt),
-          array($xmlrpcString, $xmlrpcInt, $xmlrpcString)
-        )
-      )
-    ), false);
-  $s-&gt;functions_parameters_type = 'phpvals';
-  $s-&gt;service();
-</programlisting>There are a few things to keep in mind when using this
-        simplified syntax:</para>
-
-        <para>to return an xmlrpc error, the method handler function must
-        return an instance of <classname>xmlrpcresp</classname>. 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
-        <varname>exception_handling</varname> memeber var to 1;</para>
-
-        <para>to return a base64 value, the method handler function must
-        encode it on its own, creating an instance of an xmlrpcval
-        object;</para>
-
-        <para>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;</para>
-
-        <para>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;</para>
-
-        <para>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;</para>
-
-        <para>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.</para>
-      </sect2>
-    </sect1>
-  </chapter>
-
-  <chapter id="globalvars">
-    <title>Global variables</title>
-
-    <para>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.</para>
-
-    <sect1>
-      <title>"Constant" variables</title>
-
-      <sect2>
-        <title>$xmlrpcerruser</title>
-
-        <para><fieldsynopsis>
-            <varname>$xmlrpcerruser</varname>
-
-            <initializer>800</initializer>
-          </fieldsynopsis>The minimum value for errors reported by user
-        implemented XML-RPC servers. Error numbers lower than that are
-        reserved for library usage.</para>
-      </sect2>
-
-      <sect2>
-        <title>$xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble,
-        $xmlrpcString, $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray,
-        $xmlrpcStruct, $xmlrpcValue, $xmlrpcNull</title>
-
-        <para>For convenience the strings representing the XML-RPC types have
-        been encoded as global variables:<programlisting language="php">
-$xmlrpcI4="i4";
-$xmlrpcInt="int";
-$xmlrpcBoolean="boolean";
-$xmlrpcDouble="double";
-$xmlrpcString="string";
-$xmlrpcDateTime="dateTime.iso8601";
-$xmlrpcBase64="base64";
-$xmlrpcArray="array";
-$xmlrpcStruct="struct";
-$xmlrpcValue="undefined";
-$xmlrpcNull="null";
-</programlisting></para>
-      </sect2>
-
-      <sect2>
-        <title>$xmlrpcTypes, $xmlrpc_valid_parents, $xmlrpcerr, $xmlrpcstr,
-        $xmlrpcerrxml, $xmlrpc_backslash, $_xh, $xml_iso88591_Entities,
-        $xmlEntities, $xmlrpcs_capabilities</title>
-
-        <para>Reserved for internal usage.</para>
-      </sect2>
-    </sect1>
-
-    <sect1>
-      <title>Variables whose value can be modified</title>
-
-      <sect2 id="xmlrpc-defencoding" xreflabel="xmlrpc_defencoding">
-        <title xreflabel="">xmlrpc_defencoding</title>
-
-        <fieldsynopsis>
-          <varname>$xmlrpc_defencoding</varname>
-
-          <initializer>"UTF8"</initializer>
-        </fieldsynopsis>
-
-        <para>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).</para>
-
-        <para>Allowed values: <literal>"UTF8"</literal>,
-        <literal>"ISO-8859-1"</literal>, <literal>"ASCII".</literal></para>
-
-        <para>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.</para>
-      </sect2>
-
-      <sect2>
-        <title>xmlrpc_internalencoding</title>
-
-        <para><fieldsynopsis>
-            <varname>$xmlrpc_internalencoding</varname>
-
-            <initializer>"ISO-8859-1"</initializer>
-          </fieldsynopsis>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:</para>
-
-        <para><programlisting language="php">
-&lt;?php
-
-include('xmlrpc.inc');
-$xmlrpc_internalencoding = 'UTF-8'; // this has to be set after the inclusion above
-$v = new xmlrpcval('κόÏ\83με'); // This xmlrpc value will be correctly serialized as the greek word 'kosme'
-</programlisting></para>
-      </sect2>
-
-      <sect2>
-        <title>xmlrpcName</title>
-
-        <para><fieldsynopsis>
-            <varname>$xmlrpcName</varname>
-
-            <initializer>"XML-RPC for PHP"</initializer>
-          </fieldsynopsis>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.</para>
-      </sect2>
-
-      <sect2>
-        <title>xmlrpcVersion</title>
-
-        <para><fieldsynopsis>
-            <varname>$xmlrpcVersion</varname>
-
-            <initializer>"2.2"</initializer>
-          </fieldsynopsis>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.</para>
-      </sect2>
-
-      <sect2>
-        <title>xmlrpc_null_extension</title>
-
-        <para>When set to <constant>TRUE</constant>, the lib will enable
-        support for the &lt;NIL/&gt; (and &lt;EX:NIL/&gt;) xmlrpc value, as
-        per the extension to the standard proposed here. This means that
-        &lt;NIL/&gt; and &lt;EX:NIL/&gt; tags received will be parsed as valid
-        xmlrpc, and the corresponding xmlrpcvals will return "null" for
-        <methodname>scalarTyp()</methodname>.</para>
-      </sect2>
-
-      <sect2>
-        <title>xmlrpc_null_apache_encoding</title>
-
-        <para>When set to <literal>TRUE</literal>, php NULL values encoded
-        into <classname>xmlrpcval</classname> objects get serialized using the
-        <literal>&lt;EX:NIL/&gt;</literal> tag instead of
-        <literal>&lt;NIL/&gt;</literal>. Please note that both forms are
-        always accepted as input regardless of the value of this
-        variable.</para>
-      </sect2>
-    </sect1>
-  </chapter>
-
-  <chapter id="helpers">
-    <title>Helper functions</title>
-
-    <para>XML-RPC for PHP contains some helper functions which you can use to
-    make processing of XML-RPC requests easier.</para>
-
-    <sect1>
-      <title>Date functions</title>
-
-      <para>The XML-RPC specification has this to say on dates:</para>
-
-      <blockquote>
-        <para id="wrap_xmlrpc_method">Don't assume a timezone. It should be
-        specified by the server in its documentation what assumptions it makes
-        about timezones.</para>
-      </blockquote>
-
-      <para>Unfortunately, this means that date processing isn't
-      straightforward. Although XML-RPC uses ISO 8601 format dates, it doesn't
-      use the timezone specifier.</para>
-
-      <para>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.</para>
-
-      <para>For more information about dates, see <ulink
-      url="http://www.uic.edu/year2000/datefmt.html">ISO 8601: The Right
-      Format for Dates</ulink>, 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.</para>
-
-      <sect2 id="iso8601encode" xreflabel="iso8601_encode()">
-        <title>iso8601_encode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>string</type><function>iso8601_encode</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$time_t</parameter></paramdef>
-
-            <paramdef
-            choice="opt"><type>int</type><parameter>$utc</parameter><initializer>0</initializer></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Returns an ISO 8601 formatted date generated from the UNIX
-        timestamp <parameter>$time_t</parameter>, as returned by the PHP
-        function <function>time()</function>.</para>
-
-        <para>The argument <parameter>$utc</parameter> can be omitted, in
-        which case it defaults to <literal>0</literal>. If it is set to
-        <literal>1</literal>, then the function corrects the time passed in
-        for UTC. Example: if you're in the GMT-6:00 timezone and set
-        <parameter>$utc</parameter>, you will receive a date representation
-        six hours ahead of your local time.</para>
-
-        <para>The included demo program <filename>vardemo.php</filename>
-        includes a demonstration of this function.</para>
-      </sect2>
-
-      <sect2 id="iso8601decode" xreflabel="iso8601_decode()">
-        <title>iso8601_decode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>int</type><function>iso8601_decode</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$isoString</parameter></paramdef>
-
-            <paramdef><type>int</type><parameter>$utc</parameter><initializer>0</initializer></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Returns a UNIX timestamp from an ISO 8601 encoded time and date
-        string passed in. If <parameter>$utc</parameter> is
-        <literal>1</literal> then <parameter>$isoString</parameter> 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.</para>
-      </sect2>
-    </sect1>
-
-    <sect1 id="arrayuse">
-      <title>Easy use with nested PHP values</title>
-
-      <para>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
-      <type>int</type>, <type>double</type>, <type>string</type>,
-      <type>array</type>, <type>datetime</type> and <type>struct</type>
-      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.</para>
-
-      <para>These functions reside in <filename>xmlrpc.inc</filename>.</para>
-
-      <sect2 id="phpxmlrpcdecode">
-        <title>php_xmlrpc_decode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>mixed</type><function>php_xmlrpc_decode</function></funcdef>
-
-            <paramdef><type>xmlrpcval</type><parameter>$xmlrpc_val</parameter></paramdef>
-
-            <paramdef><type>array</type><parameter>$options</parameter></paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>array</type><function>php_xmlrpc_decode</function></funcdef>
-
-            <paramdef><type>xmlrpcmsg</type><parameter>$xmlrpcmsg_val</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$options</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Returns a native PHP value corresponding to the values found in
-        the <type>xmlrpcval</type> <parameter>$xmlrpc_val</parameter>,
-        translated into PHP types. Base-64 and datetime values are
-        automatically decoded to strings.</para>
-
-        <para>In the second form, returns an array containing the parameters
-        of the given
-        <parameter><classname>xmlrpcmsg</classname>_val</parameter>, decoded
-        to php types.</para>
-
-        <para>The <parameter>options</parameter> 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
-        <symbol>decode_php_objs</symbol> and
-        <literal>dates_as_objects</literal>. When the first is set, php
-        objects that have been converted to xml-rpc structs using the
-        <function>php_xmlrpc_encode</function> 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 <classname>dateTime</classname> objects
-        instead of strings.</para>
-
-        <para><emphasis><emphasis>WARNING</emphasis>:</emphasis> please take
-        extreme care before enabling the <symbol>decode_php_objs</symbol>
-        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.</para>
-
-        <para>Example:<programlisting language="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" =&gt; array(
-     "function" =&gt; "foo_wrapper",
-     "signatures" =&gt; ...
-  )));
-</programlisting></para>
-      </sect2>
-
-      <sect2 id="phpxmlrpcencode">
-        <title>php_xmlrpc_encode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type><function>php_xmlrpc_encode</function></funcdef>
-
-            <paramdef><type>mixed</type><parameter>$phpval</parameter></paramdef>
-
-            <paramdef><type>array</type><parameter>$options</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Returns an <type>xmlrpcval</type> object populated with the PHP
-        values in <parameter>$phpval</parameter>. 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.</para>
-
-        <para>The <parameter>options</parameter> 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
-        <symbol>encode_php_objs</symbol>, <literal>null_extension</literal>
-        and <symbol>auto_dates</symbol>.</para>
-
-        <para>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 <literal>NULL</literal> values to the
-        <literal>&lt;NIL/&gt;</literal> (or
-        <literal>&lt;EX:NIL/&gt;</literal>, see ...) tag. The last encodes any
-        string that matches the ISO8601 format into an XML-RPC
-        datetime.</para>
-
-        <para>Example:<programlisting language="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' =&gt; 666,
-  'second: an array' =&gt; array ('apple', 'orange', 'banana'),
-  'third: a base64 element' =&gt; new xmlrpcval('hello world', 'base64'),
-  'fourth: a datetime' =&gt; '20060107T01:53:00'
-  ), array('auto_dates'));
-</programlisting></para>
-      </sect2>
-
-      <sect2>
-        <title>php_xmlrpc_decode_xml</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcval | xmlrpcresp |
-            xmlrpcmsg</type><function>php_xmlrpc_decode_xml</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$xml</parameter></paramdef>
-
-            <paramdef><type>array</type><parameter>$options</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Decodes the xml representation of either an xmlrpc request,
-        response or single value, returning the corresponding php-xmlrpc
-        object, or <literal>FALSE</literal> in case of an error.</para>
-
-        <para>The <parameter>options</parameter> 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.</para>
-
-        <para>Example:<programlisting language="php">
-$text = '&lt;value&gt;&lt;array&gt;&lt;data&gt;&lt;value&gt;Hello world&lt;/value&gt;&lt;/data&gt;&lt;/array&gt;&lt;/value&gt;';
-$val = php_xmlrpc_decode_xml($text);
-if ($val) echo 'Found a value of type '.$val-&gt;kindOf(); else echo 'Found invalid xml';
-</programlisting></para>
-      </sect2>
-    </sect1>
-
-    <sect1>
-      <title>Automatic conversion of php functions into xmlrpc methods (and
-      vice versa)</title>
-
-      <para>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.</para>
-
-      <sect2>
-        <title>wrap_xmlrpc_method</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>string</type><function>wrap_xmlrpc_method</function></funcdef>
-
-            <paramdef>$client</paramdef>
-
-            <paramdef>$methodname</paramdef>
-
-            <paramdef>$extra_options</paramdef>
-          </funcprototype>
-
-          <funcprototype>
-            <funcdef><type>string</type><function>wrap_xmlrpc_method</function></funcdef>
-
-            <paramdef>$client</paramdef>
-
-            <paramdef>$methodname</paramdef>
-
-            <paramdef>$signum</paramdef>
-
-            <paramdef>$timeout</paramdef>
-
-            <paramdef>$protocol</paramdef>
-
-            <paramdef>$funcname</paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>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.</para>
-
-        <para>The second syntax is deprecated, and is listed here only for
-        backward compatibility.</para>
-
-        <para>The server must support the
-        <methodname>system.methodSignature</methodname> xmlrpc method call for
-        this function to work.</para>
-
-        <para>The <parameter>client</parameter> 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.</para>
-
-        <para>The optional parameters can be passed as array key,value pairs
-        in the <parameter>extra_options</parameter> param.</para>
-
-        <para>The <parameter>signum</parameter> optional param has the purpose
-        of indicating which method signature to use, if the given server
-        method has multiple signatures (defaults to 0).</para>
-
-        <para>The <parameter>timeout</parameter> and
-        <parameter>protocol</parameter> optional params are the same as in the
-        <methodname>xmlrpc_client::send()</methodname> method.</para>
-
-        <para>If set, the optional <parameter>new_function_name</parameter>
-        parameter indicates which name should be used for the generated
-        function. In case it is not set the function name will be
-        auto-generated.</para>
-
-        <para>If the <literal>return_source</literal> 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).</para>
-
-        <para>If the <literal>encode_php_objs</literal> 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.</para>
-
-        <para>If the <literal>decode_php_objs</literal> 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).</para>
-
-        <para><emphasis>Note that this might pose a security risk</emphasis>,
-        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.</para>
-
-        <para>In case of an error during generation of the wrapper function,
-        FALSE is returned, otherwise the name (or source code) of the new
-        function.</para>
-
-        <para>Known limitations: server must support
-        <methodname>system.methodsignature</methodname> 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.</para>
-
-        <para>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.</para>
-
-        <para>Example usage:</para>
-
-        <programlisting language="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-&gt;faultCode().'. Calling again with debug on';
-    $function($a, true);
-  }
-  else
-    echo "OK, state nr. $stateno is $statename";
-}
-</programlisting>
-      </sect2>
-
-      <sect2 id="wrap_php_function">
-        <title>wrap_php_function</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>array</type><function>wrap_php_function</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$funcname</parameter></paramdef>
-
-            <paramdef><type>string</type><parameter>$wrapper_function_name</parameter></paramdef>
-
-            <paramdef><type>array</type><parameter>$extra_options</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>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.</para>
-
-        <para>The optional <parameter>$wrapper_function_name</parameter>
-        specifies the name that will be used for the auto-generated
-        function.</para>
-
-        <para>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).</para>
-
-        <para>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.</para>
-
-        <para>If the <literal>return_source</literal> 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
-        <literal>source</literal> member of the returned array.</para>
-
-        <para>If the <literal>suppress_warnings</literal> 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.</para>
-
-        <para>If the <parameter>extra_options</parameter> array contains the
-        <literal>encode_php_objs</literal> 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.</para>
-
-        <para>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)</para>
-
-        <para>If the <literal>decode_php_objs</literal> 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).</para>
-
-        <para><emphasis>Note that this might pose a security risk</emphasis>,
-        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.</para>
-
-        <para>Example usage:</para>
-
-        <para><programlisting language="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);
-</programlisting></para>
-      </sect2>
-    </sect1>
-
-    <sect1 id="deprecated">
-      <title>Functions removed from the library</title>
-
-      <para>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.</para>
-
-      <para>To ease the transition to the new naming scheme and avoid breaking
-      existing implementations, the following scheme has been adopted:
-      <itemizedlist>
-          <listitem>
-            <para>If EPI-XMLRPC is not active in the current PHP installation,
-            the constant <literal>XMLRPC_EPI_ENABLED</literal> will be set to
-            <literal>'0'</literal></para>
-          </listitem>
-
-          <listitem>
-            <para>If EPI-XMLRPC is active in the current PHP installation, the
-            constant <literal>XMLRPC_EPI_ENABLED</literal> will be set to
-            <literal>'1'</literal></para>
-          </listitem>
-        </itemizedlist></para>
-
-      <para>The following documentation is kept for historical
-      reference:</para>
-
-      <sect2 id="xmlrpcdecode">
-        <title>xmlrpc_decode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>mixed</type><function>xmlrpc_decode</function></funcdef>
-
-            <paramdef><type>xmlrpcval</type><parameter>$xmlrpc_val</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Alias for php_xmlrpc_decode.</para>
-      </sect2>
-
-      <sect2 id="xmlrpcencode">
-        <title>xmlrpc_encode</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>xmlrpcval</type><function>xmlrpc_encode</function></funcdef>
-
-            <paramdef><type>mixed</type><parameter>$phpval</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Alias for php_xmlrpc_encode.</para>
-      </sect2>
-    </sect1>
-
-    <sect1 id="debugging">
-      <title>Debugging aids</title>
-
-      <sect2>
-        <title>xmlrpc_debugmsg</title>
-
-        <funcsynopsis>
-          <funcprototype>
-            <funcdef><type>void</type><function>xmlrpc_debugmsg</function></funcdef>
-
-            <paramdef><type>string</type><parameter>$debugstring</parameter></paramdef>
-          </funcprototype>
-        </funcsynopsis>
-
-        <para>Sends the contents of <parameter>$debugstring</parameter> 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.</para>
-
-        <para>Use this function in your methods so you can pass back
-        diagnostic information. It is only available from
-        <filename>xmlrpcs.inc</filename>.</para>
-      </sect2>
-    </sect1>
-  </chapter>
-
-  <chapter id="reserved" xreflabel="Reserved methods">
-    <title>Reserved methods</title>
-
-    <para>In order to extend the functionality offered by XML-RPC servers
-    without impacting on the protocol, reserved methods are supported in this
-    release.</para>
-
-    <para>All methods starting with <function>system.</function> are
-    considered reserved by the server. PHP for XML-RPC itself provides four
-    special methods, detailed in this chapter.</para>
-
-    <para>Note that all server objects will automatically respond to clients
-    querying these methods, unless the property
-    <property>allow_system_funcs</property> has been set to
-    <constant>false</constant> before calling the
-    <methodname>service()</methodname> method. This might pose a security risk
-    if the server is exposed to public access, e.g. on the internet.</para>
-
-    <sect1>
-      <title>system.getCapabilities</title>
-
-      <para></para>
-    </sect1>
-
-    <sect1>
-      <title>system.listMethods</title>
-
-      <para>This method may be used to enumerate the methods implemented by
-      the XML-RPC server.</para>
-
-      <para>The <function>system.listMethods</function> method requires no
-      parameters. It returns an array of strings, each of which is the name of
-      a method implemented by the server.</para>
-    </sect1>
-
-    <sect1 id="sysmethodsig">
-      <title>system.methodSignature</title>
-
-      <para>This method takes one parameter, the name of a method implemented
-      by the XML-RPC server.</para>
-
-      <para>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.</para>
-
-      <para>Multiple signatures (i.e. overloading) are permitted: this is the
-      reason that an array of signatures are returned by this method.</para>
-
-      <para>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".</para>
-
-      <para>For parameters that can be of more than one type, the "undefined"
-      string is supported.</para>
-
-      <para>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
-      <parameter>$resp</parameter> below is the response object from a method
-      call to <function>system.methodSignature</function>:</para>
-
-      <programlisting language="php">
-$v = $resp-&gt;value();
-if ($v-&gt;kindOf() != "array") {
-  // then the method did not have a signature defined
-}
-</programlisting>
-
-      <para>See the <filename>introspect.php</filename> demo included in this
-      distribution for an example of using this method.</para>
-    </sect1>
-
-    <sect1 id="sysmethhelp">
-      <title>system.methodHelp</title>
-
-      <para>This method takes one parameter, the name of a method implemented
-      by the XML-RPC server.</para>
-
-      <para>It returns a documentation string describing the use of that
-      method. If no such string is available, an empty string is
-      returned.</para>
-
-      <para>The documentation string may contain HTML markup.</para>
-    </sect1>
-
-    <sect1>
-      <title>system.multicall</title>
-
-      <para>This method takes one parameter, an array of 'request' struct
-      types. Each request struct must contain a
-      <parameter>methodName</parameter> member of type string and a
-      <parameter>params</parameter> member of type array, and corresponds to
-      the invocation of the corresponding method.</para>
-
-      <para>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.</para>
-    </sect1>
-  </chapter>
-
-  <chapter id="examples" xreflabel="Examples">
-    <title>Examples</title>
-
-    <para>The best examples are to be found in the sample files included with
-    the distribution. Some are included here.</para>
-
-    <sect1 id="statename">
-      <title>XML-RPC client: state name query</title>
-
-      <para>Code to get the corresponding state name from a number (1-50) from
-      the demo server available on SourceForge</para>
-
-      <programlisting language="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-&gt;send($m);
-  if (!$r-&gt;faultCode()) {
-      $v = $r-&gt;value();
-      print "State number " . htmlentities($HTTP_POST_VARS["stateno"]) . " is " .
-        htmlentities($v-&gt;scalarval()) . "&lt;BR&gt;";
-      print "&lt;HR&gt;I got this value back&lt;BR&gt;&lt;PRE&gt;" .
-        htmlentities($r-&gt;serialize()) . "&lt;/PRE&gt;&lt;HR&gt;\n";
-  } else {
-      print "Fault &lt;BR&gt;";
-      print "Code: " . htmlentities($r-&gt;faultCode()) . "&lt;BR&gt;" .
-            "Reason: '" . htmlentities($r-&gt;faultString()) . "'&lt;BR&gt;";
-  }
-</programlisting>
-    </sect1>
-
-    <sect1>
-      <title>Executing a multicall call</title>
-
-      <para>To be documented...</para>
-    </sect1>
-  </chapter>
-
-  <chapter id="faq">
-    <title>Frequently Asked Questions</title>
-
-    <sect1>
-      <title>How to send custom XML as payload of a method call</title>
-
-      <para>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.</para>
-
-      <para>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 '&lt;' character in
-      string values is encoded as '&amp;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).</para>
-    </sect1>
-
-    <sect1>
-      <title>Is there any limitation on the size of the requests / responses
-      that can be successfully sent?</title>
-
-      <para>Yes. But I have no hard figure to give; it most likely will depend
-      on the version of PHP in usage and its configuration.</para>
-
-      <para>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).</para>
-
-      <para>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.</para>
-
-      <para>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 <varname>xmlrpc_client::return_type</varname>
-      and <varname>xmlrpc_server::functions_parameters_type</varname> for more
-      details).</para>
-    </sect1>
-
-    <sect1>
-      <title>My server (client) returns an error whenever the client (server)
-      returns accented characters</title>
-
-      <para>To be documented...</para>
-    </sect1>
-
-    <sect1>
-      <title>How to enable long-lasting method calls</title>
-
-      <para>To be documented...</para>
-    </sect1>
-
-    <sect1>
-      <title>My client returns "XML-RPC Fault #2: Invalid return payload:
-      enable debugging to examine incoming payload": what should I do?</title>
-
-      <para>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.</para>
-
-      <para>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.</para>
-
-      <para>To find out what the server is really returning to your client,
-      you have to enable the debug mode of the client, using
-      $client-&gt;setdebug(1);</para>
-    </sect1>
-
-    <sect1>
-      <title>How can I save to a file the xml of the xmlrpc responses received
-      from servers?</title>
-
-      <para>If what you need is to save the responses received from the server
-      as xml, you have two options:</para>
-
-      <para>1- use the serialize() method on the response object.</para>
-
-      <programlisting language="php">
-$resp = $client-&gt;send($msg);
-if (!$resp-&gt;faultCode())
-  $data_to_be_saved = $resp-&gt;serialize();
-</programlisting>
-
-      <para>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 &lt;string/&gt;, serialize()
-      will output &lt;string&gt;&lt;/string&gt;), 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).</para>
-
-      <para>2 - set the client object to return the raw xml received instead
-      of the decoded objects:</para>
-
-      <programlisting language="php">
-$client = new xmlrpc_client($url);
-$client-&gt;return_type = 'xml';
-$resp = $client-&gt;send($msg);
-if (!$resp-&gt;faultCode())
-  $data_to_be_saved = $resp-&gt;value();
-</programlisting>
-
-      <para>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...</para>
-    </sect1>
-
-    <sect1>
-      <title>Can I use the ms windows character set?</title>
-
-      <para>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.</para>
-
-      <para>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.</para>
-
-      <para>To properly encode outgoing data that is natively in CP1252, you
-      will have to uncomment all relative code in the file
-      <filename>xmlrpc.inc</filename> (you can search for the string "1252"),
-      then set <code>$GLOBALS['xmlrpc_internalencoding']='CP1252';</code>
-      Please note that all incoming data will then be fed to your application
-      as UTF-8 to avoid any potential data loss.</para>
-    </sect1>
-
-    <sect1>
-      <title>Does the library support using cookies / http sessions?</title>
-
-      <para>In short: yes, but a little coding is needed to make it
-      happen.</para>
-
-      <para>The code below uses sessions to e.g. let the client store a value
-      on the server and retrieve it later.</para>
-
-      <para><programlisting>
-$resp = $client-&gt;send(new xmlrpcmsg('registervalue', array(new xmlrpcval('foo'), new xmlrpcval('bar'))));
-if (!$resp-&gt;faultCode())
-{
-  $cookies = $resp-&gt;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-&gt;setcookie('PHPSESSID', $session_id);
-    $val = $client-&gt;send(new xmlrpcmsg('getvalue', array(new xmlrpcval('foo')));
-  }
-}
-</programlisting>Server-side sessions are handled normally like in any other
-      php application. Please see the php manual for more information about
-      sessions.</para>
-
-      <para>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.</para>
-    </sect1>
-  </chapter>
-
-  <appendix id="integration">
-    <title>Integration with the PHP xmlrpc extension</title>
-
-    <para>To be documented more...</para>
-
-    <para>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</para>
-
-    <programlisting language="php">
-/*** client side ***/
-$c = new xmlrpc_client('http://phpxmlrpc.sourceforge.net/server.php');
-
-// tell the client to return raw xml as response value
-$c-&gt;return_type = 'xml';
-
-// let the native xmlrpc extension take care of encoding request parameters
-$r = $c-&gt;send(xmlrpc_encode_request('examples.getStateName', $_POST['stateno']));
-
-if ($r-&gt;faultCode())
-  // HTTP transport error
-  echo 'Got error '.$r-&gt;faultCode();
-else
-{
-  // HTTP request OK, but XML returned from server not parsed yet
-  $v = xmlrpc_decode($r-&gt;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);
-}
-</programlisting>
-  </appendix>
-
-  <appendix id="substitution">
-    <title>Substitution of the PHP xmlrpc extension</title>
-
-    <para>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).</para>
-
-    <para>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</para>
-  </appendix>
-
-  <appendix id="enough">
-    <title>'Enough of xmlrpcvals!': new style library usage</title>
-
-    <para>To be documented...</para>
-
-    <para>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</para>
-  </appendix>
-
-  <appendix id="debugger">
-    <title>Usage of the debugger</title>
-
-    <para>A webservice debugger is included in the library to help during
-    development and testing.</para>
-
-    <para>The interface should be self-explicative enough to need little
-    documentation.</para>
-
-    <para><graphic align="center" fileref="debugger.gif"
-    format="GIF" /></para>
-
-    <para>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.</para>
-
-    <para>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:</para>
-
-    <para><itemizedlist>
-        <listitem>
-          <para>to enable jsonrpc functionality, download the PHP-XMLRPC
-          EXTRAS package, and copy the file <filename>jsonrpc.inc</filename>
-          either to the same directory as the debugger or somewhere in your
-          php include path</para>
-        </listitem>
-      </itemizedlist><itemizedlist>
-        <listitem>
-          <para>to enable the visual value editing dialog, download the
-          JS-XMLRPC library, and copy somewhere in the web root files
-          <filename>visualeditor.php</filename>,
-          <filename>visualeditor.css</filename> and the folders
-          <filename>yui</filename> and <filename>img</filename>. Then edit the
-          debugger file <filename>controller.php</filename> and set
-          appropriately the variable <varname>$editorpath</varname>.</para>
-        </listitem>
-      </itemizedlist></para>
-  </appendix>
-</book>
-<!-- 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:
--->
index e5be7f7..0ae42fd 100644 (file)
-<?php\r
-// by Edd Dumbill (C) 1999-2002\r
-// <edd@usefulinc.com>\r
-\r
-// Copyright (c) 1999,2000,2002 Edd Dumbill.\r
-// All rights reserved.\r
-//\r
-// Redistribution and use in source and binary forms, with or without\r
-// modification, are permitted provided that the following conditions\r
-// are met:\r
-//\r
-//    * Redistributions of source code must retain the above copyright\r
-//      notice, this list of conditions and the following disclaimer.\r
-//\r
-//    * Redistributions in binary form must reproduce the above\r
-//      copyright notice, this list of conditions and the following\r
-//      disclaimer in the documentation and/or other materials provided\r
-//      with the distribution.\r
-//\r
-//    * Neither the name of the "XML-RPC for PHP" nor the names of its\r
-//      contributors may be used to endorse or promote products derived\r
-//      from this software without specific prior written permission.\r
-//\r
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r
-// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r
-// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r
-// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
-// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
-// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
-// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r
-// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r
-// OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-       if(!function_exists('xml_parser_create'))\r
-       {\r
-               // For PHP 4 onward, XML functionality is always compiled-in on windows:\r
-               // no more need to dl-open it. It might have been compiled out on *nix...\r
-               if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))\r
-               {\r
-                       dl('xml.so');\r
-               }\r
-       }\r
-\r
-       // G. Giunta 2005/01/29: declare global these variables,\r
-       // so that xmlrpc.inc will work even if included from within a function\r
-       // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.\r
-       $GLOBALS['xmlrpcI4']='i4';\r
-       $GLOBALS['xmlrpcInt']='int';\r
-       $GLOBALS['xmlrpcBoolean']='boolean';\r
-       $GLOBALS['xmlrpcDouble']='double';\r
-       $GLOBALS['xmlrpcString']='string';\r
-       $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';\r
-       $GLOBALS['xmlrpcBase64']='base64';\r
-       $GLOBALS['xmlrpcArray']='array';\r
-       $GLOBALS['xmlrpcStruct']='struct';\r
-       $GLOBALS['xmlrpcValue']='undefined';\r
-\r
-       $GLOBALS['xmlrpcTypes']=array(\r
-               $GLOBALS['xmlrpcI4']       => 1,\r
-               $GLOBALS['xmlrpcInt']      => 1,\r
-               $GLOBALS['xmlrpcBoolean']  => 1,\r
-               $GLOBALS['xmlrpcString']   => 1,\r
-               $GLOBALS['xmlrpcDouble']   => 1,\r
-               $GLOBALS['xmlrpcDateTime'] => 1,\r
-               $GLOBALS['xmlrpcBase64']   => 1,\r
-               $GLOBALS['xmlrpcArray']    => 2,\r
-               $GLOBALS['xmlrpcStruct']   => 3\r
-       );\r
-\r
-       $GLOBALS['xmlrpc_valid_parents'] = array(\r
-               'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),\r
-               'BOOLEAN' => array('VALUE'),\r
-               'I4' => array('VALUE'),\r
-               'INT' => array('VALUE'),\r
-               'STRING' => array('VALUE'),\r
-               'DOUBLE' => array('VALUE'),\r
-               'DATETIME.ISO8601' => array('VALUE'),\r
-               'BASE64' => array('VALUE'),\r
-               'MEMBER' => array('STRUCT'),\r
-               'NAME' => array('MEMBER'),\r
-               'DATA' => array('ARRAY'),\r
-               'ARRAY' => array('VALUE'),\r
-               'STRUCT' => array('VALUE'),\r
-               'PARAM' => array('PARAMS'),\r
-               'METHODNAME' => array('METHODCALL'),\r
-               'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),\r
-               'FAULT' => array('METHODRESPONSE'),\r
-               'NIL' => array('VALUE'), // only used when extension activated\r
-               'EX:NIL' => array('VALUE') // only used when extension activated\r
-       );\r
-\r
-       // define extra types for supporting NULL (useful for json or <NIL/>)\r
-       $GLOBALS['xmlrpcNull']='null';\r
-       $GLOBALS['xmlrpcTypes']['null']=1;\r
-\r
-       // Not in use anymore since 2.0. Shall we remove it?\r
-       /// @deprecated\r
-       $GLOBALS['xmlEntities']=array(\r
-               'amp'  => '&',\r
-               'quot' => '"',\r
-               'lt'   => '<',\r
-               'gt'   => '>',\r
-               'apos' => "'"\r
-       );\r
-\r
-       // tables used for transcoding different charsets into us-ascii xml\r
-\r
-       $GLOBALS['xml_iso88591_Entities']=array();\r
-       $GLOBALS['xml_iso88591_Entities']['in'] = array();\r
-       $GLOBALS['xml_iso88591_Entities']['out'] = array();\r
-       for ($i = 0; $i < 32; $i++)\r
-       {\r
-               $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);\r
-               $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';\r
-       }\r
-       for ($i = 160; $i < 256; $i++)\r
-       {\r
-               $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);\r
-               $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';\r
-       }\r
-\r
-       /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?\r
-       /// These will NOT be present in true ISO-8859-1, but will save the unwary\r
-       /// windows user from sending junk (though no luck when reciving them...)\r
-  /*\r
-       $GLOBALS['xml_cp1252_Entities']=array();\r
-       for ($i = 128; $i < 160; $i++)\r
-       {\r
-               $GLOBALS['xml_cp1252_Entities']['in'][] = chr($i);\r
-       }\r
-       $GLOBALS['xml_cp1252_Entities']['out'] = array(\r
-               '&#x20AC;', '?',        '&#x201A;', '&#x0192;',\r
-               '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',\r
-               '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',\r
-               '&#x0152;', '?',        '&#x017D;', '?',\r
-               '?',        '&#x2018;', '&#x2019;', '&#x201C;',\r
-               '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',\r
-               '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',\r
-               '&#x0153;', '?',        '&#x017E;', '&#x0178;'\r
-       );\r
-  */\r
-\r
-       $GLOBALS['xmlrpcerr'] = array(\r
-       'unknown_method'=>1,\r
-       'invalid_return'=>2,\r
-       'incorrect_params'=>3,\r
-       'introspect_unknown'=>4,\r
-       'http_error'=>5,\r
-       'no_data'=>6,\r
-       'no_ssl'=>7,\r
-       'curl_fail'=>8,\r
-       'invalid_request'=>15,\r
-       'no_curl'=>16,\r
-       'server_error'=>17,\r
-       'multicall_error'=>18,\r
-       'multicall_notstruct'=>9,\r
-       'multicall_nomethod'=>10,\r
-       'multicall_notstring'=>11,\r
-       'multicall_recursion'=>12,\r
-       'multicall_noparams'=>13,\r
-       'multicall_notarray'=>14,\r
-\r
-       'cannot_decompress'=>103,\r
-       'decompress_fail'=>104,\r
-       'dechunk_fail'=>105,\r
-       'server_cannot_decompress'=>106,\r
-       'server_decompress_fail'=>107\r
-       );\r
-\r
-       $GLOBALS['xmlrpcstr'] = array(\r
-       'unknown_method'=>'Unknown method',\r
-       'invalid_return'=>'Invalid return payload: enable debugging to examine incoming payload',\r
-       'incorrect_params'=>'Incorrect parameters passed to method',\r
-       'introspect_unknown'=>"Can't introspect: method unknown",\r
-       'http_error'=>"Didn't receive 200 OK from remote server.",\r
-       'no_data'=>'No data received from server.',\r
-       'no_ssl'=>'No SSL support compiled in.',\r
-       'curl_fail'=>'CURL error',\r
-       'invalid_request'=>'Invalid request payload',\r
-       'no_curl'=>'No CURL support compiled in.',\r
-       'server_error'=>'Internal server error',\r
-       'multicall_error'=>'Received from server invalid multicall response',\r
-       'multicall_notstruct'=>'system.multicall expected struct',\r
-       'multicall_nomethod'=>'missing methodName',\r
-       'multicall_notstring'=>'methodName is not a string',\r
-       'multicall_recursion'=>'recursive system.multicall forbidden',\r
-       'multicall_noparams'=>'missing params',\r
-       'multicall_notarray'=>'params is not an array',\r
-\r
-       'cannot_decompress'=>'Received from server compressed HTTP and cannot decompress',\r
-       'decompress_fail'=>'Received from server invalid compressed HTTP',\r
-       'dechunk_fail'=>'Received from server invalid chunked HTTP',\r
-       'server_cannot_decompress'=>'Received from client compressed HTTP request and cannot decompress',\r
-       'server_decompress_fail'=>'Received from client invalid compressed HTTP request'\r
-       );\r
-\r
-       // The charset encoding used by the server for received messages and\r
-       // by the client for received responses when received charset cannot be determined\r
-       // or is not supported\r
-       $GLOBALS['xmlrpc_defencoding']='UTF-8';\r
-\r
-       // The encoding used internally by PHP.\r
-       // String values received as xml will be converted to this, and php strings will be converted to xml\r
-       // as if having been coded with this\r
-       $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';\r
-\r
-       $GLOBALS['xmlrpcName']='XML-RPC for PHP';\r
-       $GLOBALS['xmlrpcVersion']='3.0.0';\r
-\r
-       // let user errors start at 800\r
-       $GLOBALS['xmlrpcerruser']=800;\r
-       // let XML parse errors start at 100\r
-       $GLOBALS['xmlrpcerrxml']=100;\r
-\r
-       // formulate backslashes for escaping regexp\r
-       // Not in use anymore since 2.0. Shall we remove it?\r
-       /// @deprecated\r
-       $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);\r
-\r
-       // set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values\r
-       $GLOBALS['xmlrpc_null_extension']=false;\r
-\r
-       // set to TRUE to enable encoding of php NULL values to <EX:NIL/> instead of <NIL/>\r
-       $GLOBALS['xmlrpc_null_apache_encoding']=false;\r
-    $GLOBALS['xmlrpc_null_apache_encoding_ns']='http://ws.apache.org/xmlrpc/namespaces/extensions';\r
-\r
-       // used to store state during parsing\r
-       // quick explanation of components:\r
-       //   ac - used to accumulate values\r
-       //   isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)\r
-       //   isf_reason - used for storing xmlrpcresp fault string\r
-       //   lv - used to indicate "looking for a value": implements\r
-       //        the logic to allow values with no types to be strings\r
-       //   params - used to store parameters in method calls\r
-       //   method - used to store method name\r
-       //   stack - array with genealogy of xml elements names:\r
-       //           used to validate nesting of xmlrpc elements\r
-       $GLOBALS['_xh']=null;\r
-\r
-       /**\r
-       * Convert a string to the correct XML representation in a target charset\r
-       * To help correct communication of non-ascii chars inside strings, regardless\r
-       * of the charset used when sending requests, parsing them, sending responses\r
-       * and parsing responses, an option is to convert all non-ascii chars present in the message\r
-       * into their equivalent 'charset entity'. Charset entities enumerated this way\r
-       * are independent of the charset encoding used to transmit them, and all XML\r
-       * parsers are bound to understand them.\r
-       * Note that in the std case we are not sending a charset encoding mime type\r
-       * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.\r
-       *\r
-       * @todo do a bit of basic benchmarking (strtr vs. str_replace)\r
-       * @todo make usage of iconv() or recode_string() or mb_string() where available\r
-       */\r
-       function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')\r
-       {\r
-               if ($src_encoding == '')\r
-               {\r
-                       // lame, but we know no better...\r
-                       $src_encoding = $GLOBALS['xmlrpc_internalencoding'];\r
-               }\r
-\r
-               switch(strtoupper($src_encoding.'_'.$dest_encoding))\r
-               {\r
-                       case 'ISO-8859-1_':\r
-                       case 'ISO-8859-1_US-ASCII':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);\r
-                               break;\r
-                       case 'ISO-8859-1_UTF-8':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               $escaped_data = utf8_encode($escaped_data);\r
-                               break;\r
-                       case 'ISO-8859-1_ISO-8859-1':\r
-                       case 'US-ASCII_US-ASCII':\r
-                       case 'US-ASCII_UTF-8':\r
-                       case 'US-ASCII_':\r
-                       case 'US-ASCII_ISO-8859-1':\r
-                       case 'UTF-8_UTF-8':\r
-                       //case 'CP1252_CP1252':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               break;\r
-                       case 'UTF-8_':\r
-                       case 'UTF-8_US-ASCII':\r
-                       case 'UTF-8_ISO-8859-1':\r
-       // NB: this will choke on invalid UTF-8, going most likely beyond EOF\r
-       $escaped_data = '';\r
-       // be kind to users creating string xmlrpcvals out of different php types\r
-       $data = (string) $data;\r
-       $ns = strlen ($data);\r
-       for ($nn = 0; $nn < $ns; $nn++)\r
-       {\r
-               $ch = $data[$nn];\r
-               $ii = ord($ch);\r
-               //1 7 0bbbbbbb (127)\r
-               if ($ii < 128)\r
-               {\r
-                       /// @todo shall we replace this with a (supposedly) faster str_replace?\r
-                       switch($ii){\r
-                               case 34:\r
-                                       $escaped_data .= '&quot;';\r
-                                       break;\r
-                               case 38:\r
-                                       $escaped_data .= '&amp;';\r
-                                       break;\r
-                               case 39:\r
-                                       $escaped_data .= '&apos;';\r
-                                       break;\r
-                               case 60:\r
-                                       $escaped_data .= '&lt;';\r
-                                       break;\r
-                               case 62:\r
-                                       $escaped_data .= '&gt;';\r
-                                       break;\r
-                               default:\r
-                                       $escaped_data .= $ch;\r
-                       } // switch\r
-               }\r
-               //2 11 110bbbbb 10bbbbbb (2047)\r
-               else if ($ii>>5 == 6)\r
-               {\r
-                       $b1 = ($ii & 31);\r
-                       $ii = ord($data[$nn+1]);\r
-                       $b2 = ($ii & 63);\r
-                       $ii = ($b1 * 64) + $b2;\r
-                       $ent = sprintf ('&#%d;', $ii);\r
-                       $escaped_data .= $ent;\r
-                       $nn += 1;\r
-               }\r
-               //3 16 1110bbbb 10bbbbbb 10bbbbbb\r
-               else if ($ii>>4 == 14)\r
-               {\r
-                       $b1 = ($ii & 15);\r
-                       $ii = ord($data[$nn+1]);\r
-                       $b2 = ($ii & 63);\r
-                       $ii = ord($data[$nn+2]);\r
-                       $b3 = ($ii & 63);\r
-                       $ii = ((($b1 * 64) + $b2) * 64) + $b3;\r
-                       $ent = sprintf ('&#%d;', $ii);\r
-                       $escaped_data .= $ent;\r
-                       $nn += 2;\r
-               }\r
-               //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb\r
-               else if ($ii>>3 == 30)\r
-               {\r
-                       $b1 = ($ii & 7);\r
-                       $ii = ord($data[$nn+1]);\r
-                       $b2 = ($ii & 63);\r
-                       $ii = ord($data[$nn+2]);\r
-                       $b3 = ($ii & 63);\r
-                       $ii = ord($data[$nn+3]);\r
-                       $b4 = ($ii & 63);\r
-                       $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;\r
-                       $ent = sprintf ('&#%d;', $ii);\r
-                       $escaped_data .= $ent;\r
-                       $nn += 3;\r
-               }\r
-       }\r
-                               break;\r
-/*\r
-                       case 'CP1252_':\r
-                       case 'CP1252_US-ASCII':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);\r
-                               $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
-                               break;\r
-                       case 'CP1252_UTF-8':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)\r
-                               $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
-                               $escaped_data = utf8_encode($escaped_data);\r
-                               break;\r
-                       case 'CP1252_ISO-8859-1':\r
-                               $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);\r
-                               // 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...\r
-                               $escaped_data = str_replace($GLOBALS['xml_cp1252_Entities']['in'], $GLOBALS['xml_cp1252_Entities']['out'], $escaped_data);\r
-                               break;\r
-*/\r
-                       default:\r
-                               $escaped_data = '';\r
-                               error_log("Converting from $src_encoding to $dest_encoding: not supported...");\r
-               }\r
-               return $escaped_data;\r
-       }\r
-\r
-       /// xml parser handler function for opening element tags\r
-       function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)\r
-       {\r
-               // if invalid xmlrpc already detected, skip all processing\r
-               if ($GLOBALS['_xh']['isf'] < 2)\r
-               {\r
-                       // check for correct element nesting\r
-                       // top level element can only be of 2 types\r
-                       /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:\r
-                       ///       there is only a single top level element in xml anyway\r
-                       if (count($GLOBALS['_xh']['stack']) == 0)\r
-                       {\r
-                               if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (\r
-                                       $name != 'VALUE' && !$accept_single_vals))\r
-                               {\r
-                                       $GLOBALS['_xh']['isf'] = 2;\r
-                                       $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';\r
-                                       return;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $GLOBALS['_xh']['rt'] = strtolower($name);\r
-                                       $GLOBALS['_xh']['rt'] = strtolower($name);\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               // not top level element: see if parent is OK\r
-                               $parent = end($GLOBALS['_xh']['stack']);\r
-                               if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))\r
-                               {\r
-                                       $GLOBALS['_xh']['isf'] = 2;\r
-                                       $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";\r
-                                       return;\r
-                               }\r
-                       }\r
-\r
-                       switch($name)\r
-                       {\r
-                               // optimize for speed switch cases: most common cases first\r
-                               case 'VALUE':\r
-                                       /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element\r
-                                       $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet\r
-                                       $GLOBALS['_xh']['ac']='';\r
-                                       $GLOBALS['_xh']['lv']=1;\r
-                                       $GLOBALS['_xh']['php_class']=null;\r
-                                       break;\r
-                               case 'I4':\r
-                               case 'INT':\r
-                               case 'STRING':\r
-                               case 'BOOLEAN':\r
-                               case 'DOUBLE':\r
-                               case 'DATETIME.ISO8601':\r
-                               case 'BASE64':\r
-                                       if ($GLOBALS['_xh']['vt']!='value')\r
-                                       {\r
-                                               //two data elements inside a value: an error occurred!\r
-                                               $GLOBALS['_xh']['isf'] = 2;\r
-                                               $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
-                                               return;\r
-                                       }\r
-                                       $GLOBALS['_xh']['ac']=''; // reset the accumulator\r
-                                       break;\r
-                               case 'STRUCT':\r
-                               case 'ARRAY':\r
-                                       if ($GLOBALS['_xh']['vt']!='value')\r
-                                       {\r
-                                               //two data elements inside a value: an error occurred!\r
-                                               $GLOBALS['_xh']['isf'] = 2;\r
-                                               $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
-                                               return;\r
-                                       }\r
-                                       // create an empty array to hold child values, and push it onto appropriate stack\r
-                                       $cur_val = array();\r
-                                       $cur_val['values'] = array();\r
-                                       $cur_val['type'] = $name;\r
-                                       // check for out-of-band information to rebuild php objs\r
-                                       // and in case it is found, save it\r
-                                       if (@isset($attrs['PHP_CLASS']))\r
-                                       {\r
-                                               $cur_val['php_class'] = $attrs['PHP_CLASS'];\r
-                                       }\r
-                                       $GLOBALS['_xh']['valuestack'][] = $cur_val;\r
-                                       $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next\r
-                                       break;\r
-                               case 'DATA':\r
-                                       if ($GLOBALS['_xh']['vt']!='data')\r
-                                       {\r
-                                               //two data elements inside a value: an error occurred!\r
-                                               $GLOBALS['_xh']['isf'] = 2;\r
-                                               $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";\r
-                                               return;\r
-                                       }\r
-                               case 'METHODCALL':\r
-                               case 'METHODRESPONSE':\r
-                               case 'PARAMS':\r
-                                       // valid elements that add little to processing\r
-                                       break;\r
-                               case 'METHODNAME':\r
-                               case 'NAME':\r
-                                       /// @todo we could check for 2 NAME elements inside a MEMBER element\r
-                                       $GLOBALS['_xh']['ac']='';\r
-                                       break;\r
-                               case 'FAULT':\r
-                                       $GLOBALS['_xh']['isf']=1;\r
-                                       break;\r
-                               case 'MEMBER':\r
-                                       $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\r
-                                       //$GLOBALS['_xh']['ac']='';\r
-                                       // Drop trough intentionally\r
-                               case 'PARAM':\r
-                                       // clear value type, so we can check later if no value has been passed for this param/member\r
-                                       $GLOBALS['_xh']['vt']=null;\r
-                                       break;\r
-                               case 'NIL':\r
-                               case 'EX:NIL':\r
-                                       if ($GLOBALS['xmlrpc_null_extension'])\r
-                                       {\r
-                                               if ($GLOBALS['_xh']['vt']!='value')\r
-                                               {\r
-                                                       //two data elements inside a value: an error occurred!\r
-                                                       $GLOBALS['_xh']['isf'] = 2;\r
-                                                       $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";\r
-                                                       return;\r
-                                               }\r
-                                               $GLOBALS['_xh']['ac']=''; // reset the accumulator\r
-                                               break;\r
-                                       }\r
-                                       // we do not support the <NIL/> extension, so\r
-                                       // drop through intentionally\r
-                               default:\r
-                                       /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!\r
-                                       $GLOBALS['_xh']['isf'] = 2;\r
-                                       $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";\r
-                                       break;\r
-                       }\r
-\r
-                       // Save current element name to stack, to validate nesting\r
-                       $GLOBALS['_xh']['stack'][] = $name;\r
-\r
-                       /// @todo optimization creep: move this inside the big switch() above\r
-                       if($name!='VALUE')\r
-                       {\r
-                               $GLOBALS['_xh']['lv']=0;\r
-                       }\r
-               }\r
-       }\r
-\r
-       /// Used in decoding xml chunks that might represent single xmlrpc values\r
-       function xmlrpc_se_any($parser, $name, $attrs)\r
-       {\r
-               xmlrpc_se($parser, $name, $attrs, true);\r
-       }\r
-\r
-       /// xml parser handler function for close element tags\r
-       function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)\r
-       {\r
-               if ($GLOBALS['_xh']['isf'] < 2)\r
-               {\r
-                       // push this element name from stack\r
-                       // NB: if XML validates, correct opening/closing is guaranteed and\r
-                       // we do not have to check for $name == $curr_elem.\r
-                       // we also checked for proper nesting at start of elements...\r
-                       $curr_elem = array_pop($GLOBALS['_xh']['stack']);\r
-\r
-                       switch($name)\r
-                       {\r
-                               case 'VALUE':\r
-                                       // This if() detects if no scalar was inside <VALUE></VALUE>\r
-                                       if ($GLOBALS['_xh']['vt']=='value')\r
-                                       {\r
-                                               $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
-                                               $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];\r
-                                       }\r
-\r
-                                       if ($rebuild_xmlrpcvals)\r
-                                       {\r
-                                               // build the xmlrpc val out of the data received, and substitute it\r
-                                               $temp = new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);\r
-                                               // in case we got info about underlying php class, save it\r
-                                               // in the object we're rebuilding\r
-                                               if (isset($GLOBALS['_xh']['php_class']))\r
-                                                       $temp->_php_class = $GLOBALS['_xh']['php_class'];\r
-                                               // check if we are inside an array or struct:\r
-                                               // if value just built is inside an array, let's move it into array on the stack\r
-                                               $vscount = count($GLOBALS['_xh']['valuestack']);\r
-                                               if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')\r
-                                               {\r
-                                                       $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $GLOBALS['_xh']['value'] = $temp;\r
-                                               }\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               /// @todo this needs to treat correctly php-serialized objects,\r
-                                               /// since std deserializing is done by php_xmlrpc_decode,\r
-                                               /// which we will not be calling...\r
-                                               if (isset($GLOBALS['_xh']['php_class']))\r
-                                               {\r
-                                               }\r
-\r
-                                               // check if we are inside an array or struct:\r
-                                               // if value just built is inside an array, let's move it into array on the stack\r
-                                               $vscount = count($GLOBALS['_xh']['valuestack']);\r
-                                               if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')\r
-                                               {\r
-                                                       $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];\r
-                                               }\r
-                                       }\r
-                                       break;\r
-                               case 'BOOLEAN':\r
-                               case 'I4':\r
-                               case 'INT':\r
-                               case 'STRING':\r
-                               case 'DOUBLE':\r
-                               case 'DATETIME.ISO8601':\r
-                               case 'BASE64':\r
-                                       $GLOBALS['_xh']['vt']=strtolower($name);\r
-                                       /// @todo: optimization creep - remove the if/elseif cycle below\r
-                                       /// since the case() in which we are already did that\r
-                                       if ($name=='STRING')\r
-                                       {\r
-                                               $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
-                                       }\r
-                                       elseif ($name=='DATETIME.ISO8601')\r
-                                       {\r
-                                               if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))\r
-                                               {\r
-                                                       error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);\r
-                                               }\r
-                                               $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];\r
-                                               $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];\r
-                                       }\r
-                                       elseif ($name=='BASE64')\r
-                                       {\r
-                                               /// @todo check for failure of base64 decoding / catch warnings\r
-                                               $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);\r
-                                       }\r
-                                       elseif ($name=='BOOLEAN')\r
-                                       {\r
-                                               // special case here: we translate boolean 1 or 0 into PHP\r
-                                               // constants true or false.\r
-                                               // Strings 'true' and 'false' are accepted, even though the\r
-                                               // spec never mentions them (see eg. Blogger api docs)\r
-                                               // NB: this simple checks helps a lot sanitizing input, ie no\r
-                                               // security problems around here\r
-                                               if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)\r
-                                               {\r
-                                                       $GLOBALS['_xh']['value']=true;\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       // log if receiveing something strange, even though we set the value to false anyway\r
-                                                       if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($GLOBALS['_xh']['ac'], 'false') != 0)\r
-                                                               error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);\r
-                                                       $GLOBALS['_xh']['value']=false;\r
-                                               }\r
-                                       }\r
-                                       elseif ($name=='DOUBLE')\r
-                                       {\r
-                                               // we have a DOUBLE\r
-                                               // we must check that only 0123456789-.<space> are characters here\r
-                                               // NOTE: regexp could be much stricter than this...\r
-                                               if (!preg_match('/^[+-eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))\r
-                                               {\r
-                                                       /// @todo: find a better way of throwing an error than this!\r
-                                                       error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);\r
-                                                       $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       // it's ok, add it on\r
-                                                       $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];\r
-                                               }\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               // we have an I4/INT\r
-                                               // we must check that only 0123456789-<space> are characters here\r
-                                               if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))\r
-                                               {\r
-                                                       /// @todo find a better way of throwing an error than this!\r
-                                                       error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);\r
-                                                       $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       // it's ok, add it on\r
-                                                       $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];\r
-                                               }\r
-                                       }\r
-                                       //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
-                                       $GLOBALS['_xh']['lv']=3; // indicate we've found a value\r
-                                       break;\r
-                               case 'NAME':\r
-                                       $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];\r
-                                       break;\r
-                               case 'MEMBER':\r
-                                       //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
-                                       // add to array in the stack the last element built,\r
-                                       // unless no VALUE was found\r
-                                       if ($GLOBALS['_xh']['vt'])\r
-                                       {\r
-                                               $vscount = count($GLOBALS['_xh']['valuestack']);\r
-                                               $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];\r
-                                       } else\r
-                                               error_log('XML-RPC: missing VALUE inside STRUCT in received xml');\r
-                                       break;\r
-                               case 'DATA':\r
-                                       //$GLOBALS['_xh']['ac']=''; // is this necessary?\r
-                                       $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty\r
-                                       break;\r
-                               case 'STRUCT':\r
-                               case 'ARRAY':\r
-                                       // fetch out of stack array of values, and promote it to current value\r
-                                       $curr_val = array_pop($GLOBALS['_xh']['valuestack']);\r
-                                       $GLOBALS['_xh']['value'] = $curr_val['values'];\r
-                                       $GLOBALS['_xh']['vt']=strtolower($name);\r
-                                       if (isset($curr_val['php_class']))\r
-                                       {\r
-                                               $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];\r
-                                       }\r
-                                       break;\r
-                               case 'PARAM':\r
-                                       // add to array of params the current value,\r
-                                       // unless no VALUE was found\r
-                                       if ($GLOBALS['_xh']['vt'])\r
-                                       {\r
-                                               $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];\r
-                                               $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];\r
-                                       }\r
-                                       else\r
-                                               error_log('XML-RPC: missing VALUE inside PARAM in received xml');\r
-                                       break;\r
-                               case 'METHODNAME':\r
-                                       $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);\r
-                                       break;\r
-                               case 'NIL':\r
-                               case 'EX:NIL':\r
-                                       if ($GLOBALS['xmlrpc_null_extension'])\r
-                                       {\r
-                                               $GLOBALS['_xh']['vt']='null';\r
-                                               $GLOBALS['_xh']['value']=null;\r
-                                               $GLOBALS['_xh']['lv']=3;\r
-                                               break;\r
-                                       }\r
-                                       // drop through intentionally if nil extension not enabled\r
-                               case 'PARAMS':\r
-                               case 'FAULT':\r
-                               case 'METHODCALL':\r
-                               case 'METHORESPONSE':\r
-                                       break;\r
-                               default:\r
-                                       // End of INVALID ELEMENT!\r
-                                       // shall we add an assert here for unreachable code???\r
-                                       break;\r
-                       }\r
-               }\r
-       }\r
-\r
-       /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values\r
-       function xmlrpc_ee_fast($parser, $name)\r
-       {\r
-               xmlrpc_ee($parser, $name, false);\r
-       }\r
-\r
-       /// xml parser handler function for character data\r
-       function xmlrpc_cd($parser, $data)\r
-       {\r
-               // skip processing if xml fault already detected\r
-               if ($GLOBALS['_xh']['isf'] < 2)\r
-               {\r
-                       // "lookforvalue==3" means that we've found an entire value\r
-                       // and should discard any further character data\r
-                       if($GLOBALS['_xh']['lv']!=3)\r
-                       {\r
-                               // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2\r
-                               //if($GLOBALS['_xh']['lv']==1)\r
-                               //{\r
-                                       // if we've found text and we're just in a <value> then\r
-                                       // say we've found a value\r
-                                       //$GLOBALS['_xh']['lv']=2;\r
-                               //}\r
-                               // we always initialize the accumulator before starting parsing, anyway...\r
-                               //if(!@isset($GLOBALS['_xh']['ac']))\r
-                               //{\r
-                               //      $GLOBALS['_xh']['ac'] = '';\r
-                               //}\r
-                               $GLOBALS['_xh']['ac'].=$data;\r
-                       }\r
-               }\r
-       }\r
-\r
-       /// xml parser handler function for 'other stuff', ie. not char data or\r
-       /// element start/end tag. In fact it only gets called on unknown entities...\r
-       function xmlrpc_dh($parser, $data)\r
-       {\r
-               // skip processing if xml fault already detected\r
-               if ($GLOBALS['_xh']['isf'] < 2)\r
-               {\r
-                       if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')\r
-                       {\r
-                               // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2\r
-                               //if($GLOBALS['_xh']['lv']==1)\r
-                               //{\r
-                               //      $GLOBALS['_xh']['lv']=2;\r
-                               //}\r
-                               $GLOBALS['_xh']['ac'].=$data;\r
-                       }\r
-               }\r
-               return true;\r
-       }\r
-\r
-       class xmlrpc_client\r
-       {\r
-               var $path;\r
-               var $server;\r
-               var $port=0;\r
-               var $method='http';\r
-               var $errno;\r
-               var $errstr;\r
-               var $debug=0;\r
-               var $username='';\r
-               var $password='';\r
-               var $authtype=1;\r
-               var $cert='';\r
-               var $certpass='';\r
-               var $cacert='';\r
-               var $cacertdir='';\r
-               var $key='';\r
-               var $keypass='';\r
-               var $verifypeer=true;\r
-               var $verifyhost=1;\r
-               var $no_multicall=false;\r
-               var $proxy='';\r
-               var $proxyport=0;\r
-               var $proxy_user='';\r
-               var $proxy_pass='';\r
-               var $proxy_authtype=1;\r
-               var $cookies=array();\r
-               var $extracurlopts=array();\r
-\r
-               /**\r
-               * List of http compression methods accepted by the client for responses.\r
-               * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib\r
-               *\r
-               * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since\r
-               * in those cases it will be up to CURL to decide the compression methods\r
-               * it supports. You might check for the presence of 'zlib' in the output of\r
-               * curl_version() to determine wheter compression is supported or not\r
-               */\r
-               var $accepted_compression = array();\r
-               /**\r
-               * Name of compression scheme to be used for sending requests.\r
-               * Either null, gzip or deflate\r
-               */\r
-               var $request_compression = '';\r
-               /**\r
-               * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:\r
-               * http://curl.haxx.se/docs/faq.html#7.3)\r
-               */\r
-               var $xmlrpc_curl_handle = null;\r
-               /// Whether to use persistent connections for http 1.1 and https\r
-               var $keepalive = false;\r
-               /// Charset encodings that can be decoded without problems by the client\r
-               var $accepted_charset_encodings = array();\r
-               /// Charset encoding to be used in serializing request. NULL = use ASCII\r
-               var $request_charset_encoding = '';\r
-               /**\r
-               * Decides the content of xmlrpcresp objects returned by calls to send()\r
-               * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'\r
-               */\r
-               var $return_type = 'xmlrpcvals';\r
-               /**\r
-               * Sent to servers in http headers\r
-               */\r
-               var $user_agent;\r
-\r
-               /**\r
-               * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php\r
-               * @param string $server the server name / ip address\r
-               * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used\r
-               * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed\r
-               */\r
-               function xmlrpc_client($path, $server='', $port='', $method='')\r
-               {\r
-                       // allow user to specify all params in $path\r
-                       if($server == '' and $port == '' and $method == '')\r
-                       {\r
-                               $parts = parse_url($path);\r
-                               $server = $parts['host'];\r
-                               $path = isset($parts['path']) ? $parts['path'] : '';\r
-                               if(isset($parts['query']))\r
-                               {\r
-                                       $path .= '?'.$parts['query'];\r
-                               }\r
-                               if(isset($parts['fragment']))\r
-                               {\r
-                                       $path .= '#'.$parts['fragment'];\r
-                               }\r
-                               if(isset($parts['port']))\r
-                               {\r
-                                       $port = $parts['port'];\r
-                               }\r
-                               if(isset($parts['scheme']))\r
-                               {\r
-                                       $method = $parts['scheme'];\r
-                               }\r
-                               if(isset($parts['user']))\r
-                               {\r
-                                       $this->username = $parts['user'];\r
-                               }\r
-                               if(isset($parts['pass']))\r
-                               {\r
-                                       $this->password = $parts['pass'];\r
-                               }\r
-                       }\r
-                       if($path == '' || $path[0] != '/')\r
-                       {\r
-                               $this->path='/'.$path;\r
-                       }\r
-                       else\r
-                       {\r
-                               $this->path=$path;\r
-                       }\r
-                       $this->server=$server;\r
-                       if($port != '')\r
-                       {\r
-                               $this->port=$port;\r
-                       }\r
-                       if($method != '')\r
-                       {\r
-                               $this->method=$method;\r
-                       }\r
-\r
-                       // if ZLIB is enabled, let the client by default accept compressed responses\r
-                       if(function_exists('gzinflate') || (\r
-                               function_exists('curl_init') && (($info = curl_version()) &&\r
-                               ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))\r
-                       ))\r
-                       {\r
-                               $this->accepted_compression = array('gzip', 'deflate');\r
-                       }\r
-\r
-                       // keepalives: enabled by default\r
-                       $this->keepalive = true;\r
-\r
-                       // by default the xml parser can support these 3 charset encodings\r
-                       $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');\r
-\r
-                       // initialize user_agent string\r
-                       $this->user_agent = $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'];\r
-               }\r
-\r
-               /**\r
-               * Enables/disables the echoing to screen of the xmlrpc responses received\r
-               * @param integer $in values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)\r
-               * @access public\r
-               */\r
-               function setDebug($in)\r
-               {\r
-                       $this->debug=$in;\r
-               }\r
-\r
-               /**\r
-               * Add some http BASIC AUTH credentials, used by the client to authenticate\r
-               * @param string $u username\r
-               * @param string $p password\r
-               * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)\r
-               * @access public\r
-               */\r
-               function setCredentials($u, $p, $t=1)\r
-               {\r
-                       $this->username=$u;\r
-                       $this->password=$p;\r
-                       $this->authtype=$t;\r
-               }\r
-\r
-               /**\r
-               * Add a client-side https certificate\r
-               * @param string $cert\r
-               * @param string $certpass\r
-               * @access public\r
-               */\r
-               function setCertificate($cert, $certpass)\r
-               {\r
-                       $this->cert = $cert;\r
-                       $this->certpass = $certpass;\r
-               }\r
-\r
-               /**\r
-               * Add a CA certificate to verify server with (see man page about\r
-               * CURLOPT_CAINFO for more details)\r
-               * @param string $cacert certificate file name (or dir holding certificates)\r
-               * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false\r
-               * @access public\r
-               */\r
-               function setCaCertificate($cacert, $is_dir=false)\r
-               {\r
-                       if ($is_dir)\r
-                       {\r
-                               $this->cacertdir = $cacert;\r
-                       }\r
-                       else\r
-                       {\r
-                               $this->cacert = $cacert;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Set attributes for SSL communication: private SSL key\r
-               * NB: does not work in older php/curl installs\r
-               * Thanks to Daniel Convissor\r
-               * @param string $key The name of a file containing a private SSL key\r
-               * @param string $keypass The secret password needed to use the private SSL key\r
-               * @access public\r
-               */\r
-               function setKey($key, $keypass)\r
-               {\r
-                       $this->key = $key;\r
-                       $this->keypass = $keypass;\r
-               }\r
-\r
-               /**\r
-               * Set attributes for SSL communication: verify server certificate\r
-               * @param bool $i enable/disable verification of peer certificate\r
-               * @access public\r
-               */\r
-               function setSSLVerifyPeer($i)\r
-               {\r
-                       $this->verifypeer = $i;\r
-               }\r
-\r
-               /**\r
-               * Set attributes for SSL communication: verify match of server cert w. hostname\r
-               * @param int $i\r
-               * @access public\r
-               */\r
-               function setSSLVerifyHost($i)\r
-               {\r
-                       $this->verifyhost = $i;\r
-               }\r
-\r
-               /**\r
-               * Set proxy info\r
-               * @param string $proxyhost\r
-               * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS\r
-               * @param string $proxyusername Leave blank if proxy has public access\r
-               * @param string $proxypassword Leave blank if proxy has public access\r
-               * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy\r
-               * @access public\r
-               */\r
-               function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)\r
-               {\r
-                       $this->proxy = $proxyhost;\r
-                       $this->proxyport = $proxyport;\r
-                       $this->proxy_user = $proxyusername;\r
-                       $this->proxy_pass = $proxypassword;\r
-                       $this->proxy_authtype = $proxyauthtype;\r
-               }\r
-\r
-               /**\r
-               * Enables/disables reception of compressed xmlrpc responses.\r
-               * Note that enabling reception of compressed responses merely adds some standard\r
-               * http headers to xmlrpc requests. It is up to the xmlrpc server to return\r
-               * compressed responses when receiving such requests.\r
-               * @param string $compmethod either 'gzip', 'deflate', 'any' or ''\r
-               * @access public\r
-               */\r
-               function setAcceptedCompression($compmethod)\r
-               {\r
-                       if ($compmethod == 'any')\r
-                               $this->accepted_compression = array('gzip', 'deflate');\r
-                       else\r
-                               if ($compmethod == false )\r
-                                       $this->accepted_compression = array();\r
-                               else\r
-                                       $this->accepted_compression = array($compmethod);\r
-               }\r
-\r
-               /**\r
-               * Enables/disables http compression of xmlrpc request.\r
-               * Take care when sending compressed requests: servers might not support them\r
-               * (and automatic fallback to uncompressed requests is not yet implemented)\r
-               * @param string $compmethod either 'gzip', 'deflate' or ''\r
-               * @access public\r
-               */\r
-               function setRequestCompression($compmethod)\r
-               {\r
-                       $this->request_compression = $compmethod;\r
-               }\r
-\r
-               /**\r
-               * Adds a cookie to list of cookies that will be sent to server.\r
-               * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:\r
-               * do not do it unless you know what you are doing\r
-               * @param string $name\r
-               * @param string $value\r
-               * @param string $path\r
-               * @param string $domain\r
-               * @param int $port\r
-               * @access public\r
-               *\r
-               * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)\r
-               */\r
-               function setCookie($name, $value='', $path='', $domain='', $port=null)\r
-               {\r
-                       $this->cookies[$name]['value'] = urlencode($value);\r
-                       if ($path || $domain || $port)\r
-                       {\r
-                               $this->cookies[$name]['path'] = $path;\r
-                               $this->cookies[$name]['domain'] = $domain;\r
-                               $this->cookies[$name]['port'] = $port;\r
-                               $this->cookies[$name]['version'] = 1;\r
-                       }\r
-                       else\r
-                       {\r
-                               $this->cookies[$name]['version'] = 0;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Directly set cURL options, for extra flexibility\r
-               * It allows eg. to bind client to a specific IP interface / address\r
-               * @param array $options\r
-               */\r
-               function SetCurlOptions( $options )\r
-               {\r
-                       $this->extracurlopts = $options;\r
-               }\r
-\r
-               /**\r
-               * Set user-agent string that will be used by this client instance\r
-               * in http headers sent to the server\r
-               */\r
-               function SetUserAgent( $agentstring )\r
-               {\r
-                       $this->user_agent = $agentstring;\r
-               }\r
-\r
-               /**\r
-               * Send an xmlrpc request\r
-               * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request\r
-               * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply\r
-               * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used\r
-               * @return xmlrpcresp\r
-               * @access public\r
-               */\r
-               function& send($msg, $timeout=0, $method='')\r
-               {\r
-                       // if user deos not specify http protocol, use native method of this client\r
-                       // (i.e. method set during call to constructor)\r
-                       if($method == '')\r
-                       {\r
-                               $method = $this->method;\r
-                       }\r
-\r
-                       if(is_array($msg))\r
-                       {\r
-                               // $msg is an array of xmlrpcmsg's\r
-                               $r = $this->multicall($msg, $timeout, $method);\r
-                               return $r;\r
-                       }\r
-                       elseif(is_string($msg))\r
-                       {\r
-                               $n = new xmlrpcmsg('');\r
-                               $n->payload = $msg;\r
-                               $msg = $n;\r
-                       }\r
-\r
-                       // where msg is an xmlrpcmsg\r
-                       $msg->debug=$this->debug;\r
-\r
-                       if($method == 'https')\r
-                       {\r
-                               $r =& $this->sendPayloadHTTPS(\r
-                                       $msg,\r
-                                       $this->server,\r
-                                       $this->port,\r
-                                       $timeout,\r
-                                       $this->username,\r
-                                       $this->password,\r
-                                       $this->authtype,\r
-                                       $this->cert,\r
-                                       $this->certpass,\r
-                                       $this->cacert,\r
-                                       $this->cacertdir,\r
-                                       $this->proxy,\r
-                                       $this->proxyport,\r
-                                       $this->proxy_user,\r
-                                       $this->proxy_pass,\r
-                                       $this->proxy_authtype,\r
-                                       $this->keepalive,\r
-                                       $this->key,\r
-                                       $this->keypass\r
-                               );\r
-                       }\r
-                       elseif($method == 'http11')\r
-                       {\r
-                               $r =& $this->sendPayloadCURL(\r
-                                       $msg,\r
-                                       $this->server,\r
-                                       $this->port,\r
-                                       $timeout,\r
-                                       $this->username,\r
-                                       $this->password,\r
-                                       $this->authtype,\r
-                                       null,\r
-                                       null,\r
-                                       null,\r
-                                       null,\r
-                                       $this->proxy,\r
-                                       $this->proxyport,\r
-                                       $this->proxy_user,\r
-                                       $this->proxy_pass,\r
-                                       $this->proxy_authtype,\r
-                                       'http',\r
-                                       $this->keepalive\r
-                               );\r
-                       }\r
-                       else\r
-                       {\r
-                               $r =& $this->sendPayloadHTTP10(\r
-                                       $msg,\r
-                                       $this->server,\r
-                                       $this->port,\r
-                                       $timeout,\r
-                                       $this->username,\r
-                                       $this->password,\r
-                                       $this->authtype,\r
-                                       $this->proxy,\r
-                                       $this->proxyport,\r
-                                       $this->proxy_user,\r
-                                       $this->proxy_pass,\r
-                                       $this->proxy_authtype\r
-                               );\r
-                       }\r
-\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,\r
-                       $username='', $password='', $authtype=1, $proxyhost='',\r
-                       $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)\r
-               {\r
-                       if($port==0)\r
-                       {\r
-                               $port=80;\r
-                       }\r
-\r
-                       // Only create the payload if it was not created previously\r
-                       if(empty($msg->payload))\r
-                       {\r
-                               $msg->createPayload($this->request_charset_encoding);\r
-                       }\r
-\r
-                       $payload = $msg->payload;\r
-                       // Deflate request body and set appropriate request headers\r
-                       if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))\r
-                       {\r
-                               if($this->request_compression == 'gzip')\r
-                               {\r
-                                       $a = @gzencode($payload);\r
-                                       if($a)\r
-                                       {\r
-                                               $payload = $a;\r
-                                               $encoding_hdr = "Content-Encoding: gzip\r\n";\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       $a = @gzcompress($payload);\r
-                                       if($a)\r
-                                       {\r
-                                               $payload = $a;\r
-                                               $encoding_hdr = "Content-Encoding: deflate\r\n";\r
-                                       }\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $encoding_hdr = '';\r
-                       }\r
-\r
-                       // thanks to Grant Rauscher <grant7@firstworld.net> for this\r
-                       $credentials='';\r
-                       if($username!='')\r
-                       {\r
-                               $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";\r
-                               if ($authtype != 1)\r
-                               {\r
-                                       error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported with HTTP 1.0');\r
-                               }\r
-                       }\r
-\r
-                       $accepted_encoding = '';\r
-                       if(is_array($this->accepted_compression) && count($this->accepted_compression))\r
-                       {\r
-                               $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";\r
-                       }\r
-\r
-                       $proxy_credentials = '';\r
-                       if($proxyhost)\r
-                       {\r
-                               if($proxyport == 0)\r
-                               {\r
-                                       $proxyport = 8080;\r
-                               }\r
-                               $connectserver = $proxyhost;\r
-                               $connectport = $proxyport;\r
-                               $uri = 'http://'.$server.':'.$port.$this->path;\r
-                               if($proxyusername != '')\r
-                               {\r
-                                       if ($proxyauthtype != 1)\r
-                                       {\r
-                                               error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported with HTTP 1.0');\r
-                                       }\r
-                                       $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $connectserver = $server;\r
-                               $connectport = $port;\r
-                               $uri = $this->path;\r
-                       }\r
-\r
-                       // Cookie generation, as per rfc2965 (version 1 cookies) or\r
-                       // netscape's rules (version 0 cookies)\r
-                       $cookieheader='';\r
-                       if (count($this->cookies))\r
-                       {\r
-                               $version = '';\r
-                               foreach ($this->cookies as $name => $cookie)\r
-                               {\r
-                                       if ($cookie['version'])\r
-                                       {\r
-                                               $version = ' $Version="' . $cookie['version'] . '";';\r
-                                               $cookieheader .= ' ' . $name . '="' . $cookie['value'] . '";';\r
-                                               if ($cookie['path'])\r
-                                                       $cookieheader .= ' $Path="' . $cookie['path'] . '";';\r
-                                               if ($cookie['domain'])\r
-                                                       $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';\r
-                                               if ($cookie['port'])\r
-                                                       $cookieheader .= ' $Port="' . $cookie['port'] . '";';\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $cookieheader .= ' ' . $name . '=' . $cookie['value'] . ";";\r
-                                       }\r
-                               }\r
-                               $cookieheader = 'Cookie:' . $version . substr($cookieheader, 0, -1) . "\r\n";\r
-                       }\r
-\r
-                       // omit port if 80\r
-                       $port = ($port == 80) ? '' : (':' . $port);\r
-\r
-                       $op= 'POST ' . $uri. " HTTP/1.0\r\n" .\r
-                               'User-Agent: ' . $this->user_agent . "\r\n" .\r
-                               'Host: '. $server . $port . "\r\n" .\r
-                               $credentials .\r
-                               $proxy_credentials .\r
-                               $accepted_encoding .\r
-                               $encoding_hdr .\r
-                               'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .\r
-                               $cookieheader .\r
-                               'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .\r
-                               strlen($payload) . "\r\n\r\n" .\r
-                               $payload;\r
-\r
-                       if($this->debug > 1)\r
-                       {\r
-                               print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";\r
-                               // let the client see this now in case http times out...\r
-                               flush();\r
-                       }\r
-\r
-                       if($timeout>0)\r
-                       {\r
-                               $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);\r
-                       }\r
-                       else\r
-                       {\r
-                               $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);\r
-                       }\r
-                       if($fp)\r
-                       {\r
-                               if($timeout>0 && function_exists('stream_set_timeout'))\r
-                               {\r
-                                       stream_set_timeout($fp, $timeout);\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $this->errstr='Connect error: '.$this->errstr;\r
-                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');\r
-                               return $r;\r
-                       }\r
-\r
-                       if(!fputs($fp, $op, strlen($op)))\r
-                       {\r
-                               fclose($fp);\r
-                               $this->errstr='Write error';\r
-                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);\r
-                               return $r;\r
-                       }\r
-                       else\r
-                       {\r
-                               // reset errno and errstr on successful socket connection\r
-                               $this->errstr = '';\r
-                       }\r
-                       // G. Giunta 2005/10/24: close socket before parsing.\r
-                       // should yield slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)\r
-                       $ipd='';\r
-                       do\r
-                       {\r
-                               // shall we check for $data === FALSE?\r
-                               // as per the manual, it signals an error\r
-                               $ipd.=fread($fp, 32768);\r
-                       } while(!feof($fp));\r
-                       fclose($fp);\r
-                       $r =& $msg->parseResponse($ipd, false, $this->return_type);\r
-                       return $r;\r
-\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',\r
-                       $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',\r
-                       $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,\r
-                       $keepalive=false, $key='', $keypass='')\r
-               {\r
-                       $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,\r
-                               $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,\r
-                               $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * Contributed by Justin Miller <justin@voxel.net>\r
-               * Requires curl to be built into PHP\r
-               * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!\r
-               * @access private\r
-               */\r
-               function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',\r
-                       $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',\r
-                       $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',\r
-                       $keepalive=false, $key='', $keypass='')\r
-               {\r
-                       if(!function_exists('curl_init'))\r
-                       {\r
-                               $this->errstr='CURL unavailable on this install';\r
-                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);\r
-                               return $r;\r
-                       }\r
-                       if($method == 'https')\r
-                       {\r
-                               if(($info = curl_version()) &&\r
-                                       ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))\r
-                               {\r
-                                       $this->errstr='SSL unavailable on this install';\r
-                                       $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);\r
-                                       return $r;\r
-                               }\r
-                       }\r
-\r
-                       if($port == 0)\r
-                       {\r
-                               if($method == 'http')\r
-                               {\r
-                                       $port = 80;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $port = 443;\r
-                               }\r
-                       }\r
-\r
-                       // Only create the payload if it was not created previously\r
-                       if(empty($msg->payload))\r
-                       {\r
-                               $msg->createPayload($this->request_charset_encoding);\r
-                       }\r
-\r
-                       // Deflate request body and set appropriate request headers\r
-                       $payload = $msg->payload;\r
-                       if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))\r
-                       {\r
-                               if($this->request_compression == 'gzip')\r
-                               {\r
-                                       $a = @gzencode($payload);\r
-                                       if($a)\r
-                                       {\r
-                                               $payload = $a;\r
-                                               $encoding_hdr = 'Content-Encoding: gzip';\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       $a = @gzcompress($payload);\r
-                                       if($a)\r
-                                       {\r
-                                               $payload = $a;\r
-                                               $encoding_hdr = 'Content-Encoding: deflate';\r
-                                       }\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $encoding_hdr = '';\r
-                       }\r
-\r
-                       if($this->debug > 1)\r
-                       {\r
-                               print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";\r
-                               // let the client see this now in case http times out...\r
-                               flush();\r
-                       }\r
-\r
-                       if(!$keepalive || !$this->xmlrpc_curl_handle)\r
-                       {\r
-                               $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);\r
-                               if($keepalive)\r
-                               {\r
-                                       $this->xmlrpc_curl_handle = $curl;\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $curl = $this->xmlrpc_curl_handle;\r
-                       }\r
-\r
-                       // results into variable\r
-                       curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);\r
-\r
-                       if($this->debug)\r
-                       {\r
-                               curl_setopt($curl, CURLOPT_VERBOSE, 1);\r
-                       }\r
-                       curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);\r
-                       // required for XMLRPC: post the data\r
-                       curl_setopt($curl, CURLOPT_POST, 1);\r
-                       // the data\r
-                       curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\r
-\r
-                       // return the header too\r
-                       curl_setopt($curl, CURLOPT_HEADER, 1);\r
-\r
-                       // NB: if we set an empty string, CURL will add http header indicating\r
-                       // ALL methods it is supporting. This is possibly a better option than\r
-                       // letting the user tell what curl can / cannot do...\r
-                       if(is_array($this->accepted_compression) && count($this->accepted_compression))\r
-                       {\r
-                               //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));\r
-                               // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
-                               if (count($this->accepted_compression) == 1)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);\r
-                               }\r
-                               else\r
-                                       curl_setopt($curl, CURLOPT_ENCODING, '');\r
-                       }\r
-                       // extra headers\r
-                       $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));\r
-                       // if no keepalive is wanted, let the server know it in advance\r
-                       if(!$keepalive)\r
-                       {\r
-                               $headers[] = 'Connection: close';\r
-                       }\r
-                       // request compression header\r
-                       if($encoding_hdr)\r
-                       {\r
-                               $headers[] = $encoding_hdr;\r
-                       }\r
-\r
-                       curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\r
-                       // timeout is borked\r
-                       if($timeout)\r
-                       {\r
-                               curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);\r
-                       }\r
-\r
-                       if($username && $password)\r
-                       {\r
-                               curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);\r
-                               if (defined('CURLOPT_HTTPAUTH'))\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);\r
-                               }\r
-                               else if ($authtype != 1)\r
-                               {\r
-                                       error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth is supported by the current PHP/curl install');\r
-                               }\r
-                       }\r
-\r
-                       if($method == 'https')\r
-                       {\r
-                               // set cert file\r
-                               if($cert)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_SSLCERT, $cert);\r
-                               }\r
-                               // set cert password\r
-                               if($certpass)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);\r
-                               }\r
-                               // whether to verify remote host's cert\r
-                               curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);\r
-                               // set ca certificates file/dir\r
-                               if($cacert)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_CAINFO, $cacert);\r
-                               }\r
-                               if($cacertdir)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);\r
-                               }\r
-                               // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
-                               if($key)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_SSLKEY, $key);\r
-                               }\r
-                               // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)\r
-                               if($keypass)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);\r
-                               }\r
-\r
-                // Upgrade transparently to more stringent check for versions of php which do not support otherwise.\r
-                // Doing it in constructor would be cleaner; doing it here saves us a couple of function calls\r
-                if($this->verifyhost == 1 && $info = curl_version() && version_compare($info['version'], '7.28.1') >= 0)\r
-                {\r
-                    $this->verifyhost = 2;\r
-                }\r
-                               // 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\r
-                               curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);\r
-                       }\r
-\r
-                       // proxy info\r
-                       if($proxyhost)\r
-                       {\r
-                               if($proxyport == 0)\r
-                               {\r
-                                       $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080\r
-                               }\r
-                               curl_setopt($curl, CURLOPT_PROXY, $proxyhost.':'.$proxyport);\r
-                               //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);\r
-                               if($proxyusername)\r
-                               {\r
-                                       curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);\r
-                                       if (defined('CURLOPT_PROXYAUTH'))\r
-                                       {\r
-                                               curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);\r
-                                       }\r
-                                       else if ($proxyauthtype != 1)\r
-                                       {\r
-                                               error_log('XML-RPC: '.__METHOD__.': warning. Only Basic auth to proxy is supported by the current PHP/curl install');\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       // NB: should we build cookie http headers by hand rather than let CURL do it?\r
-                       // the following code does not honour 'expires', 'path' and 'domain' cookie attributes\r
-                       // set to client obj the the user...\r
-                       if (count($this->cookies))\r
-                       {\r
-                               $cookieheader = '';\r
-                               foreach ($this->cookies as $name => $cookie)\r
-                               {\r
-                                       $cookieheader .= $name . '=' . $cookie['value'] . '; ';\r
-                               }\r
-                               curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));\r
-                       }\r
-\r
-                       foreach ($this->extracurlopts as $opt => $val)\r
-                       {\r
-                               curl_setopt($curl, $opt, $val);\r
-                       }\r
-\r
-                       $result = curl_exec($curl);\r
-\r
-                       if ($this->debug > 1)\r
-                       {\r
-                               print "<PRE>\n---CURL INFO---\n";\r
-                               foreach(curl_getinfo($curl) as $name => $val)\r
-                               {\r
-                                       if (is_array($val))\r
-                                       {\r
-                                               $val = implode("\n", $val);\r
-                                       }\r
-                                       print $name . ': ' . htmlentities($val) . "\n";\r
-                               }\r
-\r
-                               print "---END---\n</PRE>";\r
-                       }\r
-\r
-                       if(!$result) /// @todo we should use a better check here - what if we get back '' or '0'?\r
-                       {\r
-                               $this->errstr='no response';\r
-                               $resp=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));\r
-                               curl_close($curl);\r
-                               if($keepalive)\r
-                               {\r
-                                       $this->xmlrpc_curl_handle = null;\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               if(!$keepalive)\r
-                               {\r
-                                       curl_close($curl);\r
-                               }\r
-                               $resp =& $msg->parseResponse($result, true, $this->return_type);\r
-                // if we got back a 302, we can not reuse the curl handle for later calls\r
-                if($resp->faultCode() == $GLOBALS['xmlrpcerr']['http_error'] && $keepalive)\r
-                {\r
-                    curl_close($curl);\r
-                    $this->xmlrpc_curl_handle = null;\r
-                }\r
-                       }\r
-                       return $resp;\r
-               }\r
-\r
-               /**\r
-               * Send an array of request messages and return an array of responses.\r
-               * Unless $this->no_multicall has been set to true, it will try first\r
-               * to use one single xmlrpc call to server method system.multicall, and\r
-               * revert to sending many successive calls in case of failure.\r
-               * This failure is also stored in $this->no_multicall for subsequent calls.\r
-               * Unfortunately, there is no server error code universally used to denote\r
-               * the fact that multicall is unsupported, so there is no way to reliably\r
-               * distinguish between that and a temporary failure.\r
-               * If you are sure that server supports multicall and do not want to\r
-               * fallback to using many single calls, set the fourth parameter to FALSE.\r
-               *\r
-               * NB: trying to shoehorn extra functionality into existing syntax has resulted\r
-               * in pretty much convoluted code...\r
-               *\r
-               * @param array $msgs an array of xmlrpcmsg objects\r
-               * @param integer $timeout connection timeout (in seconds)\r
-               * @param string $method the http protocol variant to be used\r
-               * @param boolean fallback When true, upon receiving an error during multicall, multiple single calls will be attempted\r
-               * @return array\r
-               * @access public\r
-               */\r
-               function multicall($msgs, $timeout=0, $method='', $fallback=true)\r
-               {\r
-                       if ($method == '')\r
-                       {\r
-                               $method = $this->method;\r
-                       }\r
-                       if(!$this->no_multicall)\r
-                       {\r
-                               $results = $this->_try_multicall($msgs, $timeout, $method);\r
-                               if(is_array($results))\r
-                               {\r
-                                       // System.multicall succeeded\r
-                                       return $results;\r
-                               }\r
-                               else\r
-                               {\r
-                                       // either system.multicall is unsupported by server,\r
-                                       // or call failed for some other reason.\r
-                                       if ($fallback)\r
-                                       {\r
-                                               // Don't try it next time...\r
-                                               $this->no_multicall = true;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               if (is_a($results, 'xmlrpcresp'))\r
-                                               {\r
-                                                       $result = $results;\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $result = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               // override fallback, in case careless user tries to do two\r
-                               // opposite things at the same time\r
-                               $fallback = true;\r
-                       }\r
-\r
-                       $results = array();\r
-                       if ($fallback)\r
-                       {\r
-                               // system.multicall is (probably) unsupported by server:\r
-                               // emulate multicall via multiple requests\r
-                               foreach($msgs as $msg)\r
-                               {\r
-                                       $results[] =& $this->send($msg, $timeout, $method);\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               // user does NOT want to fallback on many single calls:\r
-                               // since we should always return an array of responses,\r
-                               // return an array with the same error repeated n times\r
-                               foreach($msgs as $msg)\r
-                               {\r
-                                       $results[] = $result;\r
-                               }\r
-                       }\r
-                       return $results;\r
-               }\r
-\r
-               /**\r
-               * Attempt to boxcar $msgs via system.multicall.\r
-               * Returns either an array of xmlrpcreponses, an xmlrpc error response\r
-               * or false (when received response does not respect valid multicall syntax)\r
-               * @access private\r
-               */\r
-               function _try_multicall($msgs, $timeout, $method)\r
-               {\r
-                       // Construct multicall message\r
-                       $calls = array();\r
-                       foreach($msgs as $msg)\r
-                       {\r
-                               $call['methodName'] = new xmlrpcval($msg->method(),'string');\r
-                               $numParams = $msg->getNumParams();\r
-                               $params = array();\r
-                               for($i = 0; $i < $numParams; $i++)\r
-                               {\r
-                                       $params[$i] = $msg->getParam($i);\r
-                               }\r
-                               $call['params'] = new xmlrpcval($params, 'array');\r
-                               $calls[] = new xmlrpcval($call, 'struct');\r
-                       }\r
-                       $multicall = new xmlrpcmsg('system.multicall');\r
-                       $multicall->addParam(new xmlrpcval($calls, 'array'));\r
-\r
-                       // Attempt RPC call\r
-                       $result =& $this->send($multicall, $timeout, $method);\r
-\r
-                       if($result->faultCode() != 0)\r
-                       {\r
-                               // call to system.multicall failed\r
-                               return $result;\r
-                       }\r
-\r
-                       // Unpack responses.\r
-                       $rets = $result->value();\r
-\r
-                       if ($this->return_type == 'xml')\r
-                       {\r
-                                       return $rets;\r
-                       }\r
-                       else if ($this->return_type == 'phpvals')\r
-                       {\r
-                               ///@todo test this code branch...\r
-                               $rets = $result->value();\r
-                               if(!is_array($rets))\r
-                               {\r
-                                       return false;           // bad return type from system.multicall\r
-                               }\r
-                               $numRets = count($rets);\r
-                               if($numRets != count($msgs))\r
-                               {\r
-                                       return false;           // wrong number of return values.\r
-                               }\r
-\r
-                               $response = array();\r
-                               for($i = 0; $i < $numRets; $i++)\r
-                               {\r
-                                       $val = $rets[$i];\r
-                                       if (!is_array($val)) {\r
-                                               return false;\r
-                                       }\r
-                                       switch(count($val))\r
-                                       {\r
-                                               case 1:\r
-                                                       if(!isset($val[0]))\r
-                                                       {\r
-                                                               return false;           // Bad value\r
-                                                       }\r
-                                                       // Normal return value\r
-                                                       $response[$i] = new xmlrpcresp($val[0], 0, '', 'phpvals');\r
-                                                       break;\r
-                                               case 2:\r
-                                                       ///     @todo remove usage of @: it is apparently quite slow\r
-                                                       $code = @$val['faultCode'];\r
-                                                       if(!is_int($code))\r
-                                                       {\r
-                                                               return false;\r
-                                                       }\r
-                                                       $str = @$val['faultString'];\r
-                                                       if(!is_string($str))\r
-                                                       {\r
-                                                               return false;\r
-                                                       }\r
-                                                       $response[$i] = new xmlrpcresp(0, $code, $str);\r
-                                                       break;\r
-                                               default:\r
-                                                       return false;\r
-                                       }\r
-                               }\r
-                               return $response;\r
-                       }\r
-                       else // return type == 'xmlrpcvals'\r
-                       {\r
-                               $rets = $result->value();\r
-                               if($rets->kindOf() != 'array')\r
-                               {\r
-                                       return false;           // bad return type from system.multicall\r
-                               }\r
-                               $numRets = $rets->arraysize();\r
-                               if($numRets != count($msgs))\r
-                               {\r
-                                       return false;           // wrong number of return values.\r
-                               }\r
-\r
-                               $response = array();\r
-                               for($i = 0; $i < $numRets; $i++)\r
-                               {\r
-                                       $val = $rets->arraymem($i);\r
-                                       switch($val->kindOf())\r
-                                       {\r
-                                               case 'array':\r
-                                                       if($val->arraysize() != 1)\r
-                                                       {\r
-                                                               return false;           // Bad value\r
-                                                       }\r
-                                                       // Normal return value\r
-                                                       $response[$i] = new xmlrpcresp($val->arraymem(0));\r
-                                                       break;\r
-                                               case 'struct':\r
-                                                       $code = $val->structmem('faultCode');\r
-                                                       if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')\r
-                                                       {\r
-                                                               return false;\r
-                                                       }\r
-                                                       $str = $val->structmem('faultString');\r
-                                                       if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')\r
-                                                       {\r
-                                                               return false;\r
-                                                       }\r
-                                                       $response[$i] = new xmlrpcresp(0, $code->scalarval(), $str->scalarval());\r
-                                                       break;\r
-                                               default:\r
-                                                       return false;\r
-                                       }\r
-                               }\r
-                               return $response;\r
-                       }\r
-               }\r
-       } // end class xmlrpc_client\r
-\r
-       class xmlrpcresp\r
-       {\r
-               var $val = 0;\r
-               var $valtyp;\r
-               var $errno = 0;\r
-               var $errstr = '';\r
-               var $payload;\r
-               var $hdrs = array();\r
-               var $_cookies = array();\r
-               var $content_type = 'text/xml';\r
-               var $raw_data = '';\r
-\r
-               /**\r
-               * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)\r
-               * @param integer $fcode set it to anything but 0 to create an error response\r
-               * @param string $fstr the error string, in case of an error response\r
-               * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'\r
-               *\r
-               * @todo add check that $val / $fcode / $fstr is of correct type???\r
-               * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain\r
-               * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...\r
-               */\r
-               function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')\r
-               {\r
-                       if($fcode != 0)\r
-                       {\r
-                               // error response\r
-                               $this->errno = $fcode;\r
-                               $this->errstr = $fstr;\r
-                               //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.\r
-                       }\r
-                       else\r
-                       {\r
-                               // successful response\r
-                               $this->val = $val;\r
-                               if ($valtyp == '')\r
-                               {\r
-                                       // user did not declare type of response value: try to guess it\r
-                                       if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))\r
-                                       {\r
-                                               $this->valtyp = 'xmlrpcvals';\r
-                                       }\r
-                                       else if (is_string($this->val))\r
-                                       {\r
-                                               $this->valtyp = 'xml';\r
-\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $this->valtyp = 'phpvals';\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       // user declares type of resp value: believe him\r
-                                       $this->valtyp = $valtyp;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Returns the error code of the response.\r
-               * @return integer the error code of this response (0 for not-error responses)\r
-               * @access public\r
-               */\r
-               function faultCode()\r
-               {\r
-                       return $this->errno;\r
-               }\r
-\r
-               /**\r
-               * Returns the error code of the response.\r
-               * @return string the error string of this response ('' for not-error responses)\r
-               * @access public\r
-               */\r
-               function faultString()\r
-               {\r
-                       return $this->errstr;\r
-               }\r
-\r
-               /**\r
-               * Returns the value received by the server.\r
-               * @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\r
-               * @access public\r
-               */\r
-               function value()\r
-               {\r
-                       return $this->val;\r
-               }\r
-\r
-               /**\r
-               * Returns an array with the cookies received from the server.\r
-               * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)\r
-               * with attributes being e.g. 'expires', 'path', domain'.\r
-               * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)\r
-               * are still present in the array. It is up to the user-defined code to decide\r
-               * how to use the received cookies, and whether they have to be sent back with the next\r
-               * request to the server (using xmlrpc_client::setCookie) or not\r
-               * @return array array of cookies received from the server\r
-               * @access public\r
-               */\r
-               function cookies()\r
-               {\r
-                       return $this->_cookies;\r
-               }\r
-\r
-               /**\r
-               * Returns xml representation of the response. XML prologue not included\r
-               * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed\r
-               * @return string the xml representation of the response\r
-               * @access public\r
-               */\r
-               function serialize($charset_encoding='')\r
-               {\r
-                       if ($charset_encoding != '')\r
-                               $this->content_type = 'text/xml; charset=' . $charset_encoding;\r
-                       else\r
-                               $this->content_type = 'text/xml';\r
-                       if ($GLOBALS['xmlrpc_null_apache_encoding'])\r
-                       {\r
-                               $result = "<methodResponse xmlns:ex=\"".$GLOBALS['xmlrpc_null_apache_encoding_ns']."\">\n";\r
-                       }\r
-                       else\r
-                       {\r
-                       $result = "<methodResponse>\n";\r
-                       }\r
-                       if($this->errno)\r
-                       {\r
-                               // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients\r
-                               // by xml-encoding non ascii chars\r
-                               $result .= "<fault>\n" .\r
-"<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .\r
-"</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .\r
-xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .\r
-"</struct>\n</value>\n</fault>";\r
-                       }\r
-                       else\r
-                       {\r
-                               if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))\r
-                               {\r
-                                       if (is_string($this->val) && $this->valtyp == 'xml')\r
-                                       {\r
-                                               $result .= "<params>\n<param>\n" .\r
-                                                       $this->val .\r
-                                                       "</param>\n</params>";\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               /// @todo try to build something serializable?\r
-                                               die('cannot serialize xmlrpcresp objects whose content is native php values');\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       $result .= "<params>\n<param>\n" .\r
-                                               $this->val->serialize($charset_encoding) .\r
-                                               "</param>\n</params>";\r
-                               }\r
-                       }\r
-                       $result .= "\n</methodResponse>";\r
-                       $this->payload = $result;\r
-                       return $result;\r
-               }\r
-       }\r
-\r
-       class xmlrpcmsg\r
-       {\r
-               var $payload;\r
-               var $methodname;\r
-               var $params=array();\r
-               var $debug=0;\r
-               var $content_type = 'text/xml';\r
-\r
-               /**\r
-               * @param string $meth the name of the method to invoke\r
-               * @param array $pars array of parameters to be passed to the method (xmlrpcval objects)\r
-               */\r
-               function xmlrpcmsg($meth, $pars=0)\r
-               {\r
-                       $this->methodname=$meth;\r
-                       if(is_array($pars) && count($pars)>0)\r
-                       {\r
-                               for($i=0; $i<count($pars); $i++)\r
-                               {\r
-                                       $this->addParam($pars[$i]);\r
-                               }\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function xml_header($charset_encoding='')\r
-               {\r
-                       if ($charset_encoding != '')\r
-                       {\r
-                               return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";\r
-                       }\r
-                       else\r
-                       {\r
-                               return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function xml_footer()\r
-               {\r
-                       return '</methodCall>';\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function kindOf()\r
-               {\r
-                       return 'msg';\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function createPayload($charset_encoding='')\r
-               {\r
-                       if ($charset_encoding != '')\r
-                               $this->content_type = 'text/xml; charset=' . $charset_encoding;\r
-                       else\r
-                               $this->content_type = 'text/xml';\r
-                       $this->payload=$this->xml_header($charset_encoding);\r
-                       $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";\r
-                       $this->payload.="<params>\n";\r
-                       for($i=0; $i<count($this->params); $i++)\r
-                       {\r
-                               $p=$this->params[$i];\r
-                               $this->payload.="<param>\n" . $p->serialize($charset_encoding) .\r
-                               "</param>\n";\r
-                       }\r
-                       $this->payload.="</params>\n";\r
-                       $this->payload.=$this->xml_footer();\r
-               }\r
-\r
-               /**\r
-               * Gets/sets the xmlrpc method to be invoked\r
-               * @param string $meth the method to be set (leave empty not to set it)\r
-               * @return string the method that will be invoked\r
-               * @access public\r
-               */\r
-               function method($meth='')\r
-               {\r
-                       if($meth!='')\r
-                       {\r
-                               $this->methodname=$meth;\r
-                       }\r
-                       return $this->methodname;\r
-               }\r
-\r
-               /**\r
-               * Returns xml representation of the message. XML prologue included\r
-               * @param string $charset_encoding\r
-               * @return string the xml representation of the message, xml prologue included\r
-               * @access public\r
-               */\r
-               function serialize($charset_encoding='')\r
-               {\r
-                       $this->createPayload($charset_encoding);\r
-                       return $this->payload;\r
-               }\r
-\r
-               /**\r
-               * Add a parameter to the list of parameters to be used upon method invocation\r
-               * @param xmlrpcval $par\r
-               * @return boolean false on failure\r
-               * @access public\r
-               */\r
-               function addParam($par)\r
-               {\r
-                       // add check: do not add to self params which are not xmlrpcvals\r
-                       if(is_object($par) && is_a($par, 'xmlrpcval'))\r
-                       {\r
-                               $this->params[]=$par;\r
-                               return true;\r
-                       }\r
-                       else\r
-                       {\r
-                               return false;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Returns the nth parameter in the message. The index zero-based.\r
-               * @param integer $i the index of the parameter to fetch (zero based)\r
-               * @return xmlrpcval the i-th parameter\r
-               * @access public\r
-               */\r
-               function getParam($i) { return $this->params[$i]; }\r
-\r
-               /**\r
-               * Returns the number of parameters in the messge.\r
-               * @return integer the number of parameters currently set\r
-               * @access public\r
-               */\r
-               function getNumParams() { return count($this->params); }\r
-\r
-               /**\r
-               * Given an open file handle, read all data available and parse it as axmlrpc response.\r
-               * NB: the file handle is not closed by this function.\r
-               * NNB: might have trouble in rare cases to work on network streams, as we\r
-               *      check for a read of 0 bytes instead of feof($fp).\r
-               *      But since checking for feof(null) returns false, we would risk an\r
-               *      infinite loop in that case, because we cannot trust the caller\r
-               *      to give us a valid pointer to an open file...\r
-               * @access public\r
-               * @param resource $fp stream pointer\r
-               * @return xmlrpcresp\r
-               * @todo add 2nd & 3rd param to be passed to ParseResponse() ???\r
-               */\r
-               function &parseResponseFile($fp)\r
-               {\r
-                       $ipd='';\r
-                       while($data=fread($fp, 32768))\r
-                       {\r
-                               $ipd.=$data;\r
-                       }\r
-                       //fclose($fp);\r
-                       $r =& $this->parseResponse($ipd);\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * Parses HTTP headers and separates them from data.\r
-               * @access private\r
-               */\r
-               function &parseResponseHeaders(&$data, $headers_processed=false)\r
-               {\r
-                               // Support "web-proxy-tunelling" connections for https through proxies\r
-                               if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))\r
-                               {\r
-                                       // Look for CR/LF or simple LF as line separator,\r
-                                       // (even though it is not valid http)\r
-                                       $pos = strpos($data,"\r\n\r\n");\r
-                                       if($pos || is_int($pos))\r
-                                       {\r
-                                               $bd = $pos+4;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $pos = strpos($data,"\n\n");\r
-                                               if($pos || is_int($pos))\r
-                                               {\r
-                                                       $bd = $pos+2;\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       // No separation between response headers and body: fault?\r
-                                                       $bd = 0;\r
-                                               }\r
-                                       }\r
-                                       if ($bd)\r
-                                       {\r
-                                               // this filters out all http headers from proxy.\r
-                                               // maybe we could take them into account, too?\r
-                                               $data = substr($data, $bd);\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');\r
-                                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');\r
-                                               return $r;\r
-                                       }\r
-                               }\r
-\r
-                               // Strip HTTP 1.1 100 Continue header if present\r
-                               while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))\r
-                               {\r
-                                       $pos = strpos($data, 'HTTP', 12);\r
-                                       // server sent a Continue header without any (valid) content following...\r
-                                       // give the client a chance to know it\r
-                                       if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5\r
-                                       {\r
-                                               break;\r
-                                       }\r
-                                       $data = substr($data, $pos);\r
-                               }\r
-                               if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))\r
-                               {\r
-                                       $errstr= substr($data, 0, strpos($data, "\n")-1);\r
-                                       error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);\r
-                                       $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');\r
-                                       return $r;\r
-                               }\r
-\r
-                               $GLOBALS['_xh']['headers'] = array();\r
-                               $GLOBALS['_xh']['cookies'] = array();\r
-\r
-                               // be tolerant to usage of \n instead of \r\n to separate headers and data\r
-                               // (even though it is not valid http)\r
-                               $pos = strpos($data,"\r\n\r\n");\r
-                               if($pos || is_int($pos))\r
-                               {\r
-                                       $bd = $pos+4;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $pos = strpos($data,"\n\n");\r
-                                       if($pos || is_int($pos))\r
-                                       {\r
-                                               $bd = $pos+2;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               // No separation between response headers and body: fault?\r
-                                               // we could take some action here instead of going on...\r
-                                               $bd = 0;\r
-                                       }\r
-                               }\r
-                               // be tolerant to line endings, and extra empty lines\r
-                               $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));\r
-                               while(list(,$line) = @each($ar))\r
-                               {\r
-                                       // take care of multi-line headers and cookies\r
-                                       $arr = explode(':',$line,2);\r
-                                       if(count($arr) > 1)\r
-                                       {\r
-                                               $header_name = strtolower(trim($arr[0]));\r
-                                               /// @todo some other headers (the ones that allow a CSV list of values)\r
-                                               /// do allow many values to be passed using multiple header lines.\r
-                                               /// We should add content to $GLOBALS['_xh']['headers'][$header_name]\r
-                                               /// instead of replacing it for those...\r
-                                               if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')\r
-                                               {\r
-                                                       if ($header_name == 'set-cookie2')\r
-                                                       {\r
-                                                               // version 2 cookies:\r
-                                                               // there could be many cookies on one line, comma separated\r
-                                                               $cookies = explode(',', $arr[1]);\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               $cookies = array($arr[1]);\r
-                                                       }\r
-                                                       foreach ($cookies as $cookie)\r
-                                                       {\r
-                                                               // glue together all received cookies, using a comma to separate them\r
-                                                               // (same as php does with getallheaders())\r
-                                                               if (isset($GLOBALS['_xh']['headers'][$header_name]))\r
-                                                                       $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);\r
-                                                               else\r
-                                                                       $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);\r
-                                                               // parse cookie attributes, in case user wants to correctly honour them\r
-                                                               // feature creep: only allow rfc-compliant cookie attributes?\r
-                                                               // @todo support for server sending multiple time cookie with same name, but using different PATHs\r
-                                                               $cookie = explode(';', $cookie);\r
-                                                               foreach ($cookie as $pos => $val)\r
-                                                               {\r
-                                                                       $val = explode('=', $val, 2);\r
-                                                                       $tag = trim($val[0]);\r
-                                                                       $val = trim(@$val[1]);\r
-                                                                       /// @todo with version 1 cookies, we should strip leading and trailing " chars\r
-                                                                       if ($pos == 0)\r
-                                                                       {\r
-                                                                               $cookiename = $tag;\r
-                                                                               $GLOBALS['_xh']['cookies'][$tag] = array();\r
-                                                                               $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);\r
-                                                                       }\r
-                                                                       else\r
-                                                                       {\r
-                                                                               if ($tag != 'value')\r
-                                                                               {\r
-                                                                                 $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;\r
-                                                                               }\r
-                                                                       }\r
-                                                               }\r
-                                                       }\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);\r
-                                               }\r
-                                       }\r
-                                       elseif(isset($header_name))\r
-                                       {\r
-                                               ///     @todo version1 cookies might span multiple lines, thus breaking the parsing above\r
-                                               $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);\r
-                                       }\r
-                               }\r
-\r
-                               $data = substr($data, $bd);\r
-\r
-                               if($this->debug && count($GLOBALS['_xh']['headers']))\r
-                               {\r
-                                       print '<PRE>';\r
-                                       foreach($GLOBALS['_xh']['headers'] as $header => $value)\r
-                                       {\r
-                                               print htmlentities("HEADER: $header: $value\n");\r
-                                       }\r
-                                       foreach($GLOBALS['_xh']['cookies'] as $header => $value)\r
-                                       {\r
-                                               print htmlentities("COOKIE: $header={$value['value']}\n");\r
-                                       }\r
-                                       print "</PRE>\n";\r
-                               }\r
-\r
-                               // if CURL was used for the call, http headers have been processed,\r
-                               // and dechunking + reinflating have been carried out\r
-                               if(!$headers_processed)\r
-                               {\r
-                                       // Decode chunked encoding sent by http 1.1 servers\r
-                                       if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')\r
-                                       {\r
-                                               if(!$data = decode_chunked($data))\r
-                                               {\r
-                                                       error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');\r
-                                                       $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);\r
-                                                       return $r;\r
-                                               }\r
-                                       }\r
-\r
-                                       // Decode gzip-compressed stuff\r
-                                       // code shamelessly inspired from nusoap library by Dietrich Ayala\r
-                                       if(isset($GLOBALS['_xh']['headers']['content-encoding']))\r
-                                       {\r
-                                               $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);\r
-                                               if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')\r
-                                               {\r
-                                                       // if decoding works, use it. else assume data wasn't gzencoded\r
-                                                       if(function_exists('gzinflate'))\r
-                                                       {\r
-                                                               if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))\r
-                                                               {\r
-                                                                       $data = $degzdata;\r
-                                                                       if($this->debug)\r
-                                                                       print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";\r
-                                                               }\r
-                                                               elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))\r
-                                                               {\r
-                                                                       $data = $degzdata;\r
-                                                                       if($this->debug)\r
-                                                                       print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";\r
-                                                               }\r
-                                                               else\r
-                                                               {\r
-                                                                       error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');\r
-                                                                       $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);\r
-                                                                       return $r;\r
-                                                               }\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');\r
-                                                               $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);\r
-                                                               return $r;\r
-                                                       }\r
-                                               }\r
-                                       }\r
-                               } // end of 'if needed, de-chunk, re-inflate response'\r
-\r
-                               // real stupid hack to avoid PHP complaining about returning NULL by ref\r
-                               $r = null;\r
-                               $r =& $r;\r
-                               return $r;\r
-               }\r
-\r
-               /**\r
-               * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.\r
-               * @param string $data the xmlrpc response, eventually including http headers\r
-               * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding\r
-               * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'\r
-               * @return xmlrpcresp\r
-               * @access public\r
-               */\r
-               function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')\r
-               {\r
-                       if($this->debug)\r
-                       {\r
-                               //by maHo, replaced htmlspecialchars with htmlentities\r
-                               print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";\r
-                       }\r
-\r
-                       if($data == '')\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': no response received from server.');\r
-                               $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);\r
-                               return $r;\r
-                       }\r
-\r
-                       $GLOBALS['_xh']=array();\r
-\r
-                       $raw_data = $data;\r
-                       // parse the HTTP headers of the response, if present, and separate them from data\r
-                       if(substr($data, 0, 4) == 'HTTP')\r
-                       {\r
-                               $r =& $this->parseResponseHeaders($data, $headers_processed);\r
-                               if ($r)\r
-                               {\r
-                                       // failed processing of HTTP response headers\r
-                                       // save into response obj the full payload received, for debugging\r
-                                       $r->raw_data = $data;\r
-                                       return $r;\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $GLOBALS['_xh']['headers'] = array();\r
-                               $GLOBALS['_xh']['cookies'] = array();\r
-                       }\r
-\r
-                       if($this->debug)\r
-                       {\r
-                               $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');\r
-                               if ($start)\r
-                               {\r
-                                       $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');\r
-                                       $end = strpos($data, '-->', $start);\r
-                                       $comments = substr($data, $start, $end-$start);\r
-                                       print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";\r
-                               }\r
-                       }\r
-\r
-                       // be tolerant of extra whitespace in response body\r
-                       $data = trim($data);\r
-\r
-                       /// @todo return an error msg if $data=='' ?\r
-\r
-                       // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)\r
-                       // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib\r
-                       $pos = strrpos($data, '</methodResponse>');\r
-                       if($pos !== false)\r
-                       {\r
-                               $data = substr($data, 0, $pos+17);\r
-                       }\r
-\r
-                       // if user wants back raw xml, give it to him\r
-                       if ($return_type == 'xml')\r
-                       {\r
-                               $r = new xmlrpcresp($data, 0, '', 'xml');\r
-                               $r->hdrs = $GLOBALS['_xh']['headers'];\r
-                               $r->_cookies = $GLOBALS['_xh']['cookies'];\r
-                               $r->raw_data = $raw_data;\r
-                               return $r;\r
-                       }\r
-\r
-                       // try to 'guestimate' the character encoding of the received response\r
-                       $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);\r
-\r
-                       $GLOBALS['_xh']['ac']='';\r
-                       //$GLOBALS['_xh']['qt']=''; //unused...\r
-                       $GLOBALS['_xh']['stack'] = array();\r
-                       $GLOBALS['_xh']['valuestack'] = array();\r
-                       $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc\r
-                       $GLOBALS['_xh']['isf_reason']='';\r
-                       $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'\r
-\r
-                       // if response charset encoding is not known / supported, try to use\r
-                       // the default encoding and parse the xml anyway, but log a warning...\r
-                       if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       // the following code might be better for mb_string enabled installs, but\r
-                       // makes the lib about 200% slower...\r
-                       //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received response: '.$resp_encoding);\r
-                               $resp_encoding = $GLOBALS['xmlrpc_defencoding'];\r
-                       }\r
-                       $parser = xml_parser_create($resp_encoding);\r
-                       xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
-                       // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell\r
-                       // the xml parser to give us back data in the expected charset.\r
-                       // What if internal encoding is not in one of the 3 allowed?\r
-                       // we use the broadest one, ie. utf8\r
-                       // This allows to send data which is native in various charset,\r
-                       // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding\r
-                       if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       {\r
-                               xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');\r
-                       }\r
-                       else\r
-                       {\r
-                               xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);\r
-                       }\r
-\r
-                       if ($return_type == 'phpvals')\r
-                       {\r
-                               xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');\r
-                       }\r
-                       else\r
-                       {\r
-                               xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');\r
-                       }\r
-\r
-                       xml_set_character_data_handler($parser, 'xmlrpc_cd');\r
-                       xml_set_default_handler($parser, 'xmlrpc_dh');\r
-\r
-                       // first error check: xml not well formed\r
-                       if(!xml_parse($parser, $data, count($data)))\r
-                       {\r
-                               // thanks to Peter Kocks <peter.kocks@baygate.com>\r
-                               if((xml_get_current_line_number($parser)) == 1)\r
-                               {\r
-                                       $errstr = 'XML error at line 1, check URL';\r
-                               }\r
-                               else\r
-                               {\r
-                                       $errstr = sprintf('XML error: %s at line %d, column %d',\r
-                                               xml_error_string(xml_get_error_code($parser)),\r
-                                               xml_get_current_line_number($parser), xml_get_current_column_number($parser));\r
-                               }\r
-                               error_log($errstr);\r
-                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');\r
-                               xml_parser_free($parser);\r
-                               if($this->debug)\r
-                               {\r
-                                       print $errstr;\r
-                               }\r
-                               $r->hdrs = $GLOBALS['_xh']['headers'];\r
-                               $r->_cookies = $GLOBALS['_xh']['cookies'];\r
-                               $r->raw_data = $raw_data;\r
-                               return $r;\r
-                       }\r
-                       xml_parser_free($parser);\r
-                       // second error check: xml well formed but not xml-rpc compliant\r
-                       if ($GLOBALS['_xh']['isf'] > 1)\r
-                       {\r
-                               if ($this->debug)\r
-                               {\r
-                                       /// @todo echo something for user?\r
-                               }\r
-\r
-                               $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],\r
-                               $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);\r
-                       }\r
-                       // third error check: parsing of the response has somehow gone boink.\r
-                       // NB: shall we omit this check, since we trust the parsing code?\r
-                       elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))\r
-                       {\r
-                               // something odd has happened\r
-                               // and it's time to generate a client side error\r
-                               // indicating something odd went on\r
-                               $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],\r
-                                       $GLOBALS['xmlrpcstr']['invalid_return']);\r
-                       }\r
-                       else\r
-                       {\r
-                               if ($this->debug)\r
-                               {\r
-                                       print "<PRE>---PARSED---\n";\r
-                                       // somehow htmlentities chokes on var_export, and some full html string...\r
-                                       //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));\r
-                                       print htmlspecialchars(var_export($GLOBALS['_xh']['value'], true));\r
-                                       print "\n---END---</PRE>";\r
-                               }\r
-\r
-                               // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.\r
-                               $v =& $GLOBALS['_xh']['value'];\r
-\r
-                               if($GLOBALS['_xh']['isf'])\r
-                               {\r
-                                       /// @todo we should test here if server sent an int and a string,\r
-                                       /// and/or coerce them into such...\r
-                                       if ($return_type == 'xmlrpcvals')\r
-                                       {\r
-                                               $errno_v = $v->structmem('faultCode');\r
-                                               $errstr_v = $v->structmem('faultString');\r
-                                               $errno = $errno_v->scalarval();\r
-                                               $errstr = $errstr_v->scalarval();\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $errno = $v['faultCode'];\r
-                                               $errstr = $v['faultString'];\r
-                                       }\r
-\r
-                                       if($errno == 0)\r
-                                       {\r
-                                               // FAULT returned, errno needs to reflect that\r
-                                               $errno = -1;\r
-                                       }\r
-\r
-                                       $r = new xmlrpcresp(0, $errno, $errstr);\r
-                               }\r
-                               else\r
-                               {\r
-                                       $r=new xmlrpcresp($v, 0, '', $return_type);\r
-                               }\r
-                       }\r
-\r
-                       $r->hdrs = $GLOBALS['_xh']['headers'];\r
-                       $r->_cookies = $GLOBALS['_xh']['cookies'];\r
-                       $r->raw_data = $raw_data;\r
-                       return $r;\r
-               }\r
-       }\r
-\r
-       class xmlrpcval\r
-       {\r
-               var $me=array();\r
-               var $mytype=0;\r
-               var $_php_class=null;\r
-\r
-               /**\r
-               * @param mixed $val\r
-               * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed\r
-               */\r
-               function xmlrpcval($val=-1, $type='')\r
-               {\r
-                       /// @todo: optimization creep - do not call addXX, do it all inline.\r
-                       /// downside: booleans will not be coerced anymore\r
-                       if($val!==-1 || $type!='')\r
-                       {\r
-                               // optimization creep: inlined all work done by constructor\r
-                               switch($type)\r
-                               {\r
-                                       case '':\r
-                                               $this->mytype=1;\r
-                                               $this->me['string']=$val;\r
-                                               break;\r
-                                       case 'i4':\r
-                                       case 'int':\r
-                                       case 'double':\r
-                                       case 'string':\r
-                                       case 'boolean':\r
-                                       case 'dateTime.iso8601':\r
-                                       case 'base64':\r
-                                       case 'null':\r
-                                               $this->mytype=1;\r
-                                               $this->me[$type]=$val;\r
-                                               break;\r
-                                       case 'array':\r
-                                               $this->mytype=2;\r
-                                               $this->me['array']=$val;\r
-                                               break;\r
-                                       case 'struct':\r
-                                               $this->mytype=3;\r
-                                               $this->me['struct']=$val;\r
-                                               break;\r
-                                       default:\r
-                                               error_log("XML-RPC: ".__METHOD__.": not a known type ($type)");\r
-                               }\r
-                               /*if($type=='')\r
-                               {\r
-                                       $type='string';\r
-                               }\r
-                               if($GLOBALS['xmlrpcTypes'][$type]==1)\r
-                               {\r
-                                       $this->addScalar($val,$type);\r
-                               }\r
-                               elseif($GLOBALS['xmlrpcTypes'][$type]==2)\r
-                               {\r
-                                       $this->addArray($val);\r
-                               }\r
-                               elseif($GLOBALS['xmlrpcTypes'][$type]==3)\r
-                               {\r
-                                       $this->addStruct($val);\r
-                               }*/\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Add a single php value to an (unitialized) xmlrpcval\r
-               * @param mixed $val\r
-               * @param string $type\r
-               * @return int 1 or 0 on failure\r
-               */\r
-               function addScalar($val, $type='string')\r
-               {\r
-                       $typeof=@$GLOBALS['xmlrpcTypes'][$type];\r
-                       if($typeof!=1)\r
-                       {\r
-                               error_log("XML-RPC: ".__METHOD__.": not a scalar type ($type)");\r
-                               return 0;\r
-                       }\r
-\r
-                       // coerce booleans into correct values\r
-                       // NB: we should either do it for datetimes, integers and doubles, too,\r
-                       // or just plain remove this check, implemented on booleans only...\r
-                       if($type==$GLOBALS['xmlrpcBoolean'])\r
-                       {\r
-                               if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))\r
-                               {\r
-                                       $val=true;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $val=false;\r
-                               }\r
-                       }\r
-\r
-                       switch($this->mytype)\r
-                       {\r
-                               case 1:\r
-                                       error_log('XML-RPC: '.__METHOD__.': scalar xmlrpcval can have only one value');\r
-                                       return 0;\r
-                               case 3:\r
-                                       error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval');\r
-                                       return 0;\r
-                               case 2:\r
-                                       // we're adding a scalar value to an array here\r
-                                       //$ar=$this->me['array'];\r
-                                       //$ar[]=new xmlrpcval($val, $type);\r
-                                       //$this->me['array']=$ar;\r
-                                       // Faster (?) avoid all the costly array-copy-by-val done here...\r
-                                       $this->me['array'][]=new xmlrpcval($val, $type);\r
-                                       return 1;\r
-                               default:\r
-                                       // a scalar, so set the value and remember we're scalar\r
-                                       $this->me[$type]=$val;\r
-                                       $this->mytype=$typeof;\r
-                                       return 1;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Add an array of xmlrpcval objects to an xmlrpcval\r
-               * @param array $vals\r
-               * @return int 1 or 0 on failure\r
-               * @access public\r
-               *\r
-               * @todo add some checking for $vals to be an array of xmlrpcvals?\r
-               */\r
-               function addArray($vals)\r
-               {\r
-                       if($this->mytype==0)\r
-                       {\r
-                               $this->mytype=$GLOBALS['xmlrpcTypes']['array'];\r
-                               $this->me['array']=$vals;\r
-                               return 1;\r
-                       }\r
-                       elseif($this->mytype==2)\r
-                       {\r
-                               // we're adding to an array here\r
-                               $this->me['array'] = array_merge($this->me['array'], $vals);\r
-                               return 1;\r
-                       }\r
-                       else\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');\r
-                               return 0;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Add an array of named xmlrpcval objects to an xmlrpcval\r
-               * @param array $vals\r
-               * @return int 1 or 0 on failure\r
-               * @access public\r
-               *\r
-               * @todo add some checking for $vals to be an array?\r
-               */\r
-               function addStruct($vals)\r
-               {\r
-                       if($this->mytype==0)\r
-                       {\r
-                               $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];\r
-                               $this->me['struct']=$vals;\r
-                               return 1;\r
-                       }\r
-                       elseif($this->mytype==3)\r
-                       {\r
-                               // we're adding to a struct here\r
-                               $this->me['struct'] = array_merge($this->me['struct'], $vals);\r
-                               return 1;\r
-                       }\r
-                       else\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': already initialized as a [' . $this->kindOf() . ']');\r
-                               return 0;\r
-                       }\r
-               }\r
-\r
-               // poor man's version of print_r ???\r
-               // DEPRECATED!\r
-               function dump($ar)\r
-               {\r
-                       foreach($ar as $key => $val)\r
-                       {\r
-                               echo "$key => $val<br />";\r
-                               if($key == 'array')\r
-                               {\r
-                                       while(list($key2, $val2) = each($val))\r
-                                       {\r
-                                               echo "-- $key2 => $val2<br />";\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Returns a string containing "struct", "array" or "scalar" describing the base type of the value\r
-               * @return string\r
-               * @access public\r
-               */\r
-               function kindOf()\r
-               {\r
-                       switch($this->mytype)\r
-                       {\r
-                               case 3:\r
-                                       return 'struct';\r
-                                       break;\r
-                               case 2:\r
-                                       return 'array';\r
-                                       break;\r
-                               case 1:\r
-                                       return 'scalar';\r
-                                       break;\r
-                               default:\r
-                                       return 'undef';\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function serializedata($typ, $val, $charset_encoding='')\r
-               {\r
-                       $rs='';\r
-                       switch(@$GLOBALS['xmlrpcTypes'][$typ])\r
-                       {\r
-                               case 1:\r
-                                       switch($typ)\r
-                                       {\r
-                                               case $GLOBALS['xmlrpcBase64']:\r
-                                                       $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcBoolean']:\r
-                                                       $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcString']:\r
-                                                       // G. Giunta 2005/2/13: do NOT use htmlentities, since\r
-                                                       // it will produce named html entities, which are invalid xml\r
-                                                       $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcInt']:\r
-                                               case $GLOBALS['xmlrpcI4']:\r
-                                                       $rs.="<${typ}>".(int)$val."</${typ}>";\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcDouble']:\r
-                                                       // avoid using standard conversion of float to string because it is locale-dependent,\r
-                                                       // and also because the xmlrpc spec forbids exponential notation.\r
-                                                       // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.\r
-                                                       // The code below tries its best at keeping max precision while avoiding exp notation,\r
-                                                       // but there is of course no limit in the number of decimal places to be used...\r
-                                                       $rs.="<${typ}>".preg_replace('/\\.?0+$/','',number_format((double)$val, 128, '.', ''))."</${typ}>";\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcDateTime']:\r
-                                                       if (is_string($val))\r
-                                                       {\r
-                                                               $rs.="<${typ}>${val}</${typ}>";\r
-                                                       }\r
-                                                       else if(is_a($val, 'DateTime'))\r
-                                                       {\r
-                                                               $rs.="<${typ}>".$val->format('Ymd\TH:i:s')."</${typ}>";\r
-                                                       }\r
-                                                       else if(is_int($val))\r
-                                                       {\r
-                                                               $rs.="<${typ}>".strftime("%Y%m%dT%H:%M:%S", $val)."</${typ}>";\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               // not really a good idea here: but what shall we output anyway? left for backward compat...\r
-                                                               $rs.="<${typ}>${val}</${typ}>";\r
-                                                       }\r
-                                                       break;\r
-                                               case $GLOBALS['xmlrpcNull']:\r
-                                                       if ($GLOBALS['xmlrpc_null_apache_encoding'])\r
-                                                       {\r
-                                                               $rs.="<ex:nil/>";\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               $rs.="<nil/>";\r
-                                                       }\r
-                                                       break;\r
-                                               default:\r
-                                                       // no standard type value should arrive here, but provide a possibility\r
-                                                       // for xmlrpcvals of unknown type...\r
-                                                       $rs.="<${typ}>${val}</${typ}>";\r
-                                       }\r
-                                       break;\r
-                               case 3:\r
-                                       // struct\r
-                                       if ($this->_php_class)\r
-                                       {\r
-                                               $rs.='<struct php_class="' . $this->_php_class . "\">\n";\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $rs.="<struct>\n";\r
-                                       }\r
-                                       foreach($val as $key2 => $val2)\r
-                                       {\r
-                                               $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";\r
-                                               //$rs.=$this->serializeval($val2);\r
-                                               $rs.=$val2->serialize($charset_encoding);\r
-                                               $rs.="</member>\n";\r
-                                       }\r
-                                       $rs.='</struct>';\r
-                                       break;\r
-                               case 2:\r
-                                       // array\r
-                                       $rs.="<array>\n<data>\n";\r
-                                       for($i=0; $i<count($val); $i++)\r
-                                       {\r
-                                               //$rs.=$this->serializeval($val[$i]);\r
-                                               $rs.=$val[$i]->serialize($charset_encoding);\r
-                                       }\r
-                                       $rs.="</data>\n</array>";\r
-                                       break;\r
-                               default:\r
-                                       break;\r
-                       }\r
-                       return $rs;\r
-               }\r
-\r
-               /**\r
-               * Returns xml representation of the value. XML prologue not included\r
-               * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed\r
-               * @return string\r
-               * @access public\r
-               */\r
-               function serialize($charset_encoding='')\r
-               {\r
-                       // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...\r
-                       //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))\r
-                       //{\r
-                               reset($this->me);\r
-                               list($typ, $val) = each($this->me);\r
-                               return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";\r
-                       //}\r
-               }\r
-\r
-               // DEPRECATED\r
-               function serializeval($o)\r
-               {\r
-                       // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...\r
-                       //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))\r
-                       //{\r
-                               $ar=$o->me;\r
-                               reset($ar);\r
-                               list($typ, $val) = each($ar);\r
-                               return '<value>' . $this->serializedata($typ, $val) . "</value>\n";\r
-                       //}\r
-               }\r
-\r
-               /**\r
-               * Checks whether a struct member with a given name is present.\r
-               * Works only on xmlrpcvals of type struct.\r
-               * @param string $m the name of the struct member to be looked up\r
-               * @return boolean\r
-               * @access public\r
-               */\r
-               function structmemexists($m)\r
-               {\r
-                       return array_key_exists($m, $this->me['struct']);\r
-               }\r
-\r
-               /**\r
-               * Returns the value of a given struct member (an xmlrpcval object in itself).\r
-               * Will raise a php warning if struct member of given name does not exist\r
-               * @param string $m the name of the struct member to be looked up\r
-               * @return xmlrpcval\r
-               * @access public\r
-               */\r
-               function structmem($m)\r
-               {\r
-                       return $this->me['struct'][$m];\r
-               }\r
-\r
-               /**\r
-               * Reset internal pointer for xmlrpcvals of type struct.\r
-               * @access public\r
-               */\r
-               function structreset()\r
-               {\r
-                       reset($this->me['struct']);\r
-               }\r
-\r
-               /**\r
-               * Return next member element for xmlrpcvals of type struct.\r
-               * @return xmlrpcval\r
-               * @access public\r
-               */\r
-               function structeach()\r
-               {\r
-                       return each($this->me['struct']);\r
-               }\r
-\r
-               // DEPRECATED! this code looks like it is very fragile and has not been fixed\r
-               // for a long long time. Shall we remove it for 2.0?\r
-               function getval()\r
-               {\r
-                       // UNSTABLE\r
-                       reset($this->me);\r
-                       list($a,$b)=each($this->me);\r
-                       // contributed by I Sofer, 2001-03-24\r
-                       // add support for nested arrays to scalarval\r
-                       // i've created a new method here, so as to\r
-                       // preserve back compatibility\r
-\r
-                       if(is_array($b))\r
-                       {\r
-                               @reset($b);\r
-                               while(list($id,$cont) = @each($b))\r
-                               {\r
-                                       $b[$id] = $cont->scalarval();\r
-                               }\r
-                       }\r
-\r
-                       // add support for structures directly encoding php objects\r
-                       if(is_object($b))\r
-                       {\r
-                               $t = get_object_vars($b);\r
-                               @reset($t);\r
-                               while(list($id,$cont) = @each($t))\r
-                               {\r
-                                       $t[$id] = $cont->scalarval();\r
-                               }\r
-                               @reset($t);\r
-                               while(list($id,$cont) = @each($t))\r
-                               {\r
-                                       @$b->$id = $cont;\r
-                               }\r
-                       }\r
-                       // end contrib\r
-                       return $b;\r
-               }\r
-\r
-               /**\r
-               * Returns the value of a scalar xmlrpcval\r
-               * @return mixed\r
-               * @access public\r
-               */\r
-               function scalarval()\r
-               {\r
-                       reset($this->me);\r
-                       list(,$b)=each($this->me);\r
-                       return $b;\r
-               }\r
-\r
-               /**\r
-               * Returns the type of the xmlrpcval.\r
-               * For integers, 'int' is always returned in place of 'i4'\r
-               * @return string\r
-               * @access public\r
-               */\r
-               function scalartyp()\r
-               {\r
-                       reset($this->me);\r
-                       list($a,)=each($this->me);\r
-                       if($a==$GLOBALS['xmlrpcI4'])\r
-                       {\r
-                               $a=$GLOBALS['xmlrpcInt'];\r
-                       }\r
-                       return $a;\r
-               }\r
-\r
-               /**\r
-               * Returns the m-th member of an xmlrpcval of struct type\r
-               * @param integer $m the index of the value to be retrieved (zero based)\r
-               * @return xmlrpcval\r
-               * @access public\r
-               */\r
-               function arraymem($m)\r
-               {\r
-                       return $this->me['array'][$m];\r
-               }\r
-\r
-               /**\r
-               * Returns the number of members in an xmlrpcval of array type\r
-               * @return integer\r
-               * @access public\r
-               */\r
-               function arraysize()\r
-               {\r
-                       return count($this->me['array']);\r
-               }\r
-\r
-               /**\r
-               * Returns the number of members in an xmlrpcval of struct type\r
-               * @return integer\r
-               * @access public\r
-               */\r
-               function structsize()\r
-               {\r
-                       return count($this->me['struct']);\r
-               }\r
-       }\r
-\r
-\r
-       // date helpers\r
-\r
-       /**\r
-       * Given a timestamp, return the corresponding ISO8601 encoded string.\r
-       *\r
-       * Really, timezones ought to be supported\r
-       * but the XML-RPC spec says:\r
-       *\r
-       * "Don't assume a timezone. It should be specified by the server in its\r
-       * documentation what assumptions it makes about timezones."\r
-       *\r
-       * These routines always assume localtime unless\r
-       * $utc is set to 1, in which case UTC is assumed\r
-       * and an adjustment for locale is made when encoding\r
-       *\r
-       * @param int $timet (timestamp)\r
-       * @param int $utc (0 or 1)\r
-       * @return string\r
-       */\r
-       function iso8601_encode($timet, $utc=0)\r
-       {\r
-               if(!$utc)\r
-               {\r
-                       $t=strftime("%Y%m%dT%H:%M:%S", $timet);\r
-               }\r
-               else\r
-               {\r
-                       if(function_exists('gmstrftime'))\r
-                       {\r
-                               // gmstrftime doesn't exist in some versions\r
-                               // of PHP\r
-                               $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);\r
-                       }\r
-                       else\r
-                       {\r
-                               $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));\r
-                       }\r
-               }\r
-               return $t;\r
-       }\r
-\r
-       /**\r
-       * Given an ISO8601 date string, return a timet in the localtime, or UTC\r
-       * @param string $idate\r
-       * @param int $utc either 0 or 1\r
-       * @return int (datetime)\r
-       */\r
-       function iso8601_decode($idate, $utc=0)\r
-       {\r
-               $t=0;\r
-               if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))\r
-               {\r
-                       if($utc)\r
-                       {\r
-                               $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);\r
-                       }\r
-                       else\r
-                       {\r
-                               $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);\r
-                       }\r
-               }\r
-               return $t;\r
-       }\r
-\r
-       /**\r
-       * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.\r
-       *\r
-       * Works with xmlrpc message objects as input, too.\r
-       *\r
-       * Given proper options parameter, can rebuild generic php object instances\r
-       * (provided those have been encoded to xmlrpc format using a corresponding\r
-       * option in php_xmlrpc_encode())\r
-       * PLEASE NOTE that rebuilding php objects involves calling their constructor function.\r
-       * This means that the remote communication end can decide which php code will\r
-       * get executed on your server, leaving the door possibly open to 'php-injection'\r
-       * style of attacks (provided you have some classes defined on your server that\r
-       * might wreak havoc if instances are built outside an appropriate context).\r
-       * Make sure you trust the remote server/client before eanbling this!\r
-       *\r
-       * @author Dan Libby (dan@libby.com)\r
-       *\r
-       * @param xmlrpcval $xmlrpc_val\r
-       * @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\r
-       * @return mixed\r
-       */\r
-       function php_xmlrpc_decode($xmlrpc_val, $options=array())\r
-       {\r
-               switch($xmlrpc_val->kindOf())\r
-               {\r
-                       case 'scalar':\r
-                               if (in_array('extension_api', $options))\r
-                               {\r
-                                       reset($xmlrpc_val->me);\r
-                                       list($typ,$val) = each($xmlrpc_val->me);\r
-                                       switch ($typ)\r
-                                       {\r
-                                               case 'dateTime.iso8601':\r
-                                                       $xmlrpc_val->scalar = $val;\r
-                                                       $xmlrpc_val->xmlrpc_type = 'datetime';\r
-                                                       $xmlrpc_val->timestamp = iso8601_decode($val);\r
-                                                       return $xmlrpc_val;\r
-                                               case 'base64':\r
-                                                       $xmlrpc_val->scalar = $val;\r
-                                                       $xmlrpc_val->type = $typ;\r
-                                                       return $xmlrpc_val;\r
-                                               default:\r
-                                                       return $xmlrpc_val->scalarval();\r
-                                       }\r
-                               }\r
-                               if (in_array('dates_as_objects', $options) && $xmlrpc_val->scalartyp() == 'dateTime.iso8601')\r
-                               {\r
-                                       // we return a Datetime object instead of a string\r
-                                       // since now the constructor of xmlrpcval accepts safely strings, ints and datetimes,\r
-                                       // we cater to all 3 cases here\r
-                                       $out = $xmlrpc_val->scalarval();\r
-                                       if (is_string($out))\r
-                                       {\r
-                                               $out = strtotime($out);\r
-                                       }\r
-                                       if (is_int($out))\r
-                                       {\r
-                                               $result = new Datetime();\r
-                                               $result->setTimestamp($out);\r
-                                               return $result;\r
-                                       }\r
-                                       elseif (is_a($out, 'Datetime'))\r
-                                       {\r
-                                               return $out;\r
-                                       }\r
-                               }\r
-                               return $xmlrpc_val->scalarval();\r
-                       case 'array':\r
-                               $size = $xmlrpc_val->arraysize();\r
-                               $arr = array();\r
-                               for($i = 0; $i < $size; $i++)\r
-                               {\r
-                                       $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);\r
-                               }\r
-                               return $arr;\r
-                       case 'struct':\r
-                               $xmlrpc_val->structreset();\r
-                               // If user said so, try to rebuild php objects for specific struct vals.\r
-                               /// @todo should we raise a warning for class not found?\r
-                               // shall we check for proper subclass of xmlrpcval instead of\r
-                               // presence of _php_class to detect what we can do?\r
-                               if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''\r
-                                       && class_exists($xmlrpc_val->_php_class))\r
-                               {\r
-                                       $obj = @new $xmlrpc_val->_php_class;\r
-                                       while(list($key,$value)=$xmlrpc_val->structeach())\r
-                                       {\r
-                                               $obj->$key = php_xmlrpc_decode($value, $options);\r
-                                       }\r
-                                       return $obj;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $arr = array();\r
-                                       while(list($key,$value)=$xmlrpc_val->structeach())\r
-                                       {\r
-                                               $arr[$key] = php_xmlrpc_decode($value, $options);\r
-                                       }\r
-                                       return $arr;\r
-                               }\r
-                       case 'msg':\r
-                               $paramcount = $xmlrpc_val->getNumParams();\r
-                               $arr = array();\r
-                               for($i = 0; $i < $paramcount; $i++)\r
-                               {\r
-                                       $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));\r
-                               }\r
-                               return $arr;\r
-                       }\r
-       }\r
-\r
-       // This constant left here only for historical reasons...\r
-       // it was used to decide if we have to define xmlrpc_encode on our own, but\r
-       // we do not do it anymore\r
-       if(function_exists('xmlrpc_decode'))\r
-       {\r
-               define('XMLRPC_EPI_ENABLED','1');\r
-       }\r
-       else\r
-       {\r
-               define('XMLRPC_EPI_ENABLED','0');\r
-       }\r
-\r
-       /**\r
-       * Takes native php types and encodes them into xmlrpc PHP object format.\r
-       * It will not re-encode xmlrpcval objects.\r
-       *\r
-       * Feature creep -- could support more types via optional type argument\r
-       * (string => datetime support has been added, ??? => base64 not yet)\r
-       *\r
-       * If given a proper options parameter, php object instances will be encoded\r
-       * into 'special' xmlrpc values, that can later be decoded into php objects\r
-       * by calling php_xmlrpc_decode() with a corresponding option\r
-       *\r
-       * @author Dan Libby (dan@libby.com)\r
-       *\r
-       * @param mixed $php_val the value to be converted into an xmlrpcval object\r
-       * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'\r
-       * @return xmlrpcval\r
-       */\r
-       function php_xmlrpc_encode($php_val, $options=array())\r
-       {\r
-               $type = gettype($php_val);\r
-               switch($type)\r
-               {\r
-                       case 'string':\r
-                               if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))\r
-                                       $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);\r
-                               else\r
-                                       $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);\r
-                               break;\r
-                       case 'integer':\r
-                               $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);\r
-                               break;\r
-                       case 'double':\r
-                               $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);\r
-                               break;\r
-                               // <G_Giunta_2001-02-29>\r
-                               // Add support for encoding/decoding of booleans, since they are supported in PHP\r
-                       case 'boolean':\r
-                               $xmlrpc_val = new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);\r
-                               break;\r
-                               // </G_Giunta_2001-02-29>\r
-                       case 'array':\r
-                               // PHP arrays can be encoded to either xmlrpc structs or arrays,\r
-                               // depending on wheter they are hashes or plain 0..n integer indexed\r
-                               // A shorter one-liner would be\r
-                               // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));\r
-                               // but execution time skyrockets!\r
-                               $j = 0;\r
-                               $arr = array();\r
-                               $ko = false;\r
-                               foreach($php_val as $key => $val)\r
-                               {\r
-                                       $arr[$key] = php_xmlrpc_encode($val, $options);\r
-                                       if(!$ko && $key !== $j)\r
-                                       {\r
-                                               $ko = true;\r
-                                       }\r
-                                       $j++;\r
-                               }\r
-                               if($ko)\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);\r
-                               }\r
-                               break;\r
-                       case 'object':\r
-                               if(is_a($php_val, 'xmlrpcval'))\r
-                               {\r
-                                       $xmlrpc_val = $php_val;\r
-                               }\r
-                               else if(is_a($php_val, 'DateTime'))\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval($php_val->format('Ymd\TH:i:s'), $GLOBALS['xmlrpcStruct']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       $arr = array();\r
-                                       reset($php_val);\r
-                                       while(list($k,$v) = each($php_val))\r
-                                       {\r
-                                               $arr[$k] = php_xmlrpc_encode($v, $options);\r
-                                       }\r
-                                       $xmlrpc_val = new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);\r
-                                       if (in_array('encode_php_objs', $options))\r
-                                       {\r
-                                               // let's save original class name into xmlrpcval:\r
-                                               // might be useful later on...\r
-                                               $xmlrpc_val->_php_class = get_class($php_val);\r
-                                       }\r
-                               }\r
-                               break;\r
-                       case 'NULL':\r
-                               if (in_array('extension_api', $options))\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcString']);\r
-                               }\r
-                               else if (in_array('null_extension', $options))\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval('', $GLOBALS['xmlrpcNull']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval();\r
-                               }\r
-                               break;\r
-                       case 'resource':\r
-                               if (in_array('extension_api', $options))\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       $xmlrpc_val = new xmlrpcval();\r
-                               }\r
-                       // catch "user function", "unknown type"\r
-                       default:\r
-                               // giancarlo pinerolo <ping@alt.it>\r
-                               // it has to return\r
-                               // an empty object in case, not a boolean.\r
-                               $xmlrpc_val = new xmlrpcval();\r
-                               break;\r
-                       }\r
-                       return $xmlrpc_val;\r
-       }\r
-\r
-       /**\r
-       * Convert the xml representation of a method response, method request or single\r
-       * xmlrpc value into the appropriate object (a.k.a. deserialize)\r
-       * @param string $xml_val\r
-       * @param array $options\r
-       * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp\r
-       */\r
-       function php_xmlrpc_decode_xml($xml_val, $options=array())\r
-       {\r
-               $GLOBALS['_xh'] = array();\r
-               $GLOBALS['_xh']['ac'] = '';\r
-               $GLOBALS['_xh']['stack'] = array();\r
-               $GLOBALS['_xh']['valuestack'] = array();\r
-               $GLOBALS['_xh']['params'] = array();\r
-               $GLOBALS['_xh']['pt'] = array();\r
-               $GLOBALS['_xh']['isf'] = 0;\r
-               $GLOBALS['_xh']['isf_reason'] = '';\r
-               $GLOBALS['_xh']['method'] = false;\r
-               $GLOBALS['_xh']['rt'] = '';\r
-               /// @todo 'guestimate' encoding\r
-               $parser = xml_parser_create();\r
-               xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
-               // What if internal encoding is not in one of the 3 allowed?\r
-               // we use the broadest one, ie. utf8!\r
-               if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-               {\r
-                       xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');\r
-               }\r
-               else\r
-               {\r
-                       xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);\r
-               }\r
-               xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');\r
-               xml_set_character_data_handler($parser, 'xmlrpc_cd');\r
-               xml_set_default_handler($parser, 'xmlrpc_dh');\r
-               if(!xml_parse($parser, $xml_val, 1))\r
-               {\r
-                       $errstr = sprintf('XML error: %s at line %d, column %d',\r
-                                               xml_error_string(xml_get_error_code($parser)),\r
-                                               xml_get_current_line_number($parser), xml_get_current_column_number($parser));\r
-                       error_log($errstr);\r
-                       xml_parser_free($parser);\r
-                       return false;\r
-               }\r
-               xml_parser_free($parser);\r
-               if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???\r
-               {\r
-                       error_log($GLOBALS['_xh']['isf_reason']);\r
-                       return false;\r
-               }\r
-               switch ($GLOBALS['_xh']['rt'])\r
-               {\r
-                       case 'methodresponse':\r
-                               $v =& $GLOBALS['_xh']['value'];\r
-                               if ($GLOBALS['_xh']['isf'] == 1)\r
-                               {\r
-                                       $vc = $v->structmem('faultCode');\r
-                                       $vs = $v->structmem('faultString');\r
-                                       $r = new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());\r
-                               }\r
-                               else\r
-                               {\r
-                                       $r = new xmlrpcresp($v);\r
-                               }\r
-                               return $r;\r
-                       case 'methodcall':\r
-                               $m = new xmlrpcmsg($GLOBALS['_xh']['method']);\r
-                               for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)\r
-                               {\r
-                                       $m->addParam($GLOBALS['_xh']['params'][$i]);\r
-                               }\r
-                               return $m;\r
-                       case 'value':\r
-                               return $GLOBALS['_xh']['value'];\r
-                       default:\r
-                               return false;\r
-               }\r
-       }\r
-\r
-       /**\r
-       * decode a string that is encoded w/ "chunked" transfer encoding\r
-       * as defined in rfc2068 par. 19.4.6\r
-       * code shamelessly stolen from nusoap library by Dietrich Ayala\r
-       *\r
-       * @param string $buffer the string to be decoded\r
-       * @return string\r
-       */\r
-       function decode_chunked($buffer)\r
-       {\r
-               // length := 0\r
-               $length = 0;\r
-               $new = '';\r
-\r
-               // read chunk-size, chunk-extension (if any) and crlf\r
-               // get the position of the linebreak\r
-               $chunkend = strpos($buffer,"\r\n") + 2;\r
-               $temp = substr($buffer,0,$chunkend);\r
-               $chunk_size = hexdec( trim($temp) );\r
-               $chunkstart = $chunkend;\r
-               while($chunk_size > 0)\r
-               {\r
-                       $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);\r
-\r
-                       // just in case we got a broken connection\r
-                       if($chunkend == false)\r
-                       {\r
-                               $chunk = substr($buffer,$chunkstart);\r
-                               // append chunk-data to entity-body\r
-                               $new .= $chunk;\r
-                               $length += strlen($chunk);\r
-                               break;\r
-                       }\r
-\r
-                       // read chunk-data and crlf\r
-                       $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);\r
-                       // append chunk-data to entity-body\r
-                       $new .= $chunk;\r
-                       // length := length + chunk-size\r
-                       $length += strlen($chunk);\r
-                       // read chunk-size and crlf\r
-                       $chunkstart = $chunkend + 2;\r
-\r
-                       $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;\r
-                       if($chunkend == false)\r
-                       {\r
-                               break; //just in case we got a broken connection\r
-                       }\r
-                       $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);\r
-                       $chunk_size = hexdec( trim($temp) );\r
-                       $chunkstart = $chunkend;\r
-               }\r
-               return $new;\r
-       }\r
-\r
-       /**\r
-       * xml charset encoding guessing helper function.\r
-       * Tries to determine the charset encoding of an XML chunk received over HTTP.\r
-       * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,\r
-       * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,\r
-       * which will be most probably using UTF-8 anyway...\r
-       *\r
-       * @param string $httpheader the http Content-type header\r
-       * @param string $xmlchunk xml content buffer\r
-       * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)\r
-       * @return string\r
-       *\r
-       * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!\r
-       */\r
-       function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)\r
-       {\r
-               // discussion: see http://www.yale.edu/pclt/encoding/\r
-               // 1 - test if encoding is specified in HTTP HEADERS\r
-\r
-               //Details:\r
-               // LWS:           (\13\10)?( |\t)+\r
-               // token:         (any char but excluded stuff)+\r
-               // quoted string: " (any char but double quotes and cointrol chars)* "\r
-               // header:        Content-type = ...; charset=value(; ...)*\r
-               //   where value is of type token, no LWS allowed between 'charset' and value\r
-               // Note: we do not check for invalid chars in VALUE:\r
-               //   this had better be done using pure ereg as below\r
-               // Note 2: we might be removing whitespace/tabs that ought to be left in if\r
-               //   the received charset is a quoted string. But nobody uses such charset names...\r
-\r
-               /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?\r
-               $matches = array();\r
-               if(preg_match('/;\s*charset\s*=([^;]+)/i', $httpheader, $matches))\r
-               {\r
-                       return strtoupper(trim($matches[1], " \t\""));\r
-               }\r
-\r
-               // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern\r
-               //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)\r
-               //     NOTE: actually, according to the spec, even if we find the BOM and determine\r
-               //     an encoding, we should check if there is an encoding specified\r
-               //     in the xml declaration, and verify if they match.\r
-               /// @todo implement check as described above?\r
-               /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)\r
-               if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))\r
-               {\r
-                       return 'UCS-4';\r
-               }\r
-               elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))\r
-               {\r
-                       return 'UTF-16';\r
-               }\r
-               elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))\r
-               {\r
-                       return 'UTF-8';\r
-               }\r
-\r
-               // 3 - test if encoding is specified in the xml declaration\r
-               // Details:\r
-               // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+\r
-               // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*\r
-               if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".\r
-                       '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",\r
-                       $xmlchunk, $matches))\r
-               {\r
-                       return strtoupper(substr($matches[2], 1, -1));\r
-               }\r
-\r
-               // 4 - if mbstring is available, let it do the guesswork\r
-               // NB: we favour finding an encoding that is compatible with what we can process\r
-               if(extension_loaded('mbstring'))\r
-               {\r
-                       if($encoding_prefs)\r
-                       {\r
-                               $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);\r
-                       }\r
-                       else\r
-                       {\r
-                               $enc = mb_detect_encoding($xmlchunk);\r
-                       }\r
-                       // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...\r
-                       // IANA also likes better US-ASCII, so go with it\r
-                       if($enc == 'ASCII')\r
-                       {\r
-                               $enc = 'US-'.$enc;\r
-                       }\r
-                       return $enc;\r
-               }\r
-               else\r
-               {\r
-                       // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?\r
-                       // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types\r
-                       // this should be the standard. And we should be getting text/xml as request and response.\r
-                       // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...\r
-                       return $GLOBALS['xmlrpc_defencoding'];\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Checks if a given charset encoding is present in a list of encodings or\r
-       * if it is a valid subset of any encoding in the list\r
-       * @param string $encoding charset to be tested\r
-       * @param mixed $validlist comma separated list of valid charsets (or array of charsets)\r
-       * @return bool\r
-       */\r
-       function is_valid_charset($encoding, $validlist)\r
-       {\r
-               $charset_supersets = array(\r
-                       'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',\r
-                               'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',\r
-                               'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',\r
-                               'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',\r
-                               'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')\r
-               );\r
-               if (is_string($validlist))\r
-                       $validlist = explode(',', $validlist);\r
-               if (@in_array(strtoupper($encoding), $validlist))\r
-                       return true;\r
-               else\r
-               {\r
-                       if (array_key_exists($encoding, $charset_supersets))\r
-                               foreach ($validlist as $allowed)\r
-                                       if (in_array($allowed, $charset_supersets[$encoding]))\r
-                                               return true;\r
-                       return false;\r
-               }\r
-       }\r
-\r
-?>
\ No newline at end of file
+<?php
+// by Edd Dumbill (C) 1999-2002
+// <edd@usefulinc.com>
+
+// Copyright (c) 1999,2000,2002 Edd Dumbill.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//    * Redistributions of source code must retain the above copyright
+//      notice, this list of conditions and the following disclaimer.
+//
+//    * Redistributions in binary form must reproduce the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer in the documentation and/or other materials provided
+//      with the distribution.
+//
+//    * Neither the name of the "XML-RPC for PHP" nor the names of its
+//      contributors may be used to endorse or promote products derived
+//      from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+// OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/******************************************************************************
+ *
+ * *** DEPRECATED ***
+ *
+ * This file is only used to insure backwards compatibility
+ * with the API of the library <= rev. 3
+ *
+ * If it is included, the library will work without any further autoloading
+ *****************************************************************************/
+
+include_once(__DIR__.'/../src/PhpXmlRpc.php');
+include_once(__DIR__.'/../src/Value.php');
+include_once(__DIR__.'/../src/Request.php');
+include_once(__DIR__.'/../src/Response.php');
+include_once(__DIR__.'/../src/Client.php');
+include_once(__DIR__.'/../src/Encoder.php');
+include_once(__DIR__.'/../src/Helper/Charset.php');
+include_once(__DIR__.'/../src/Helper/Date.php');
+include_once(__DIR__.'/../src/Helper/Http.php');
+include_once(__DIR__.'/../src/Helper/Logger.php');
+include_once(__DIR__.'/../src/Helper/XMLParser.php');
+
+
+/* Expose the global variables which used to be defined */
+PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1'; // old default
+PhpXmlRpc\PhpXmlRpc::exportGlobals();
+
+/* some stuff deprecated enough that we do not want to put it in the new lib version */
+
+/// @deprecated
+$GLOBALS['xmlEntities'] = array(
+    'amp'  => '&',
+    'quot' => '"',
+    'lt'   => '<',
+    'gt'   => '>',
+    'apos' => "'"
+);
+
+// formulate backslashes for escaping regexp
+// Not in use anymore since 2.0. Shall we remove it?
+/// @deprecated
+$GLOBALS['xmlrpc_backslash'] = chr(92).chr(92);
+
+/* Expose with the old names the classes which have been namespaced */
+
+class xmlrpcval extends PhpXmlRpc\Value
+{
+    /**
+     * @deprecated
+     * @param xmlrpcval $o
+     * @return string
+     */
+    public function serializeval($o)
+    {
+        // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
+        //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
+        //{
+        $ar = $o->me;
+        reset($ar);
+        list($typ, $val) = each($ar);
+
+        return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
+        //}
+    }
+
+    /**
+     * @deprecated this code looks like it is very fragile and has not been fixed
+     * for a long long time. Shall we remove it for 2.0?
+     */
+    public function getval()
+    {
+        // UNSTABLE
+        reset($this->me);
+        list($a, $b) = each($this->me);
+        // contributed by I Sofer, 2001-03-24
+        // add support for nested arrays to scalarval
+        // i've created a new method here, so as to
+        // preserve back compatibility
+
+        if (is_array($b)) {
+            @reset($b);
+            while (list($id, $cont) = @each($b)) {
+                $b[$id] = $cont->scalarval();
+            }
+        }
+
+        // add support for structures directly encoding php objects
+        if (is_object($b)) {
+            $t = get_object_vars($b);
+            @reset($t);
+            while (list($id, $cont) = @each($t)) {
+                $t[$id] = $cont->scalarval();
+            }
+            @reset($t);
+            while (list($id, $cont) = @each($t)) {
+                @$b->$id = $cont;
+            }
+        }
+        // end contrib
+        return $b;
+    }
+
+}
+
+class xmlrpcmsg extends PhpXmlRpc\Request
+{
+}
+
+class xmlrpcresp extends PhpXmlRpc\Response
+{
+}
+
+class xmlrpc_client extends PhpXmlRpc\Client
+{
+}
+
+/* Expose as global functions the ones which are now class methods */
+
+/// Wrong speling, but we are adamant on backwards compatibility!
+function xmlrpc_encode_entitites($data, $srcEncoding='', $destEncoding='')
+{
+    return PhpXmlRpc\Helper\Charset::instance()->encodeEntitites($data, $srcEncoding, $destEncoding);
+}
+
+function iso8601_encode($timeT, $utc=0)
+{
+    return PhpXmlRpc\Helper\Date::iso8601Encode($timeT, $utc);
+}
+
+function iso8601_decode($iDate, $utc=0)
+{
+    return PhpXmlRpc\Helper\Date::iso8601Decode($iDate, $utc);
+}
+
+function decode_chunked($buffer)
+{
+    return PhpXmlRpc\Helper\Http::decodeChunked($buffer);
+}
+
+function php_xmlrpc_decode($xmlrpcVal, $options=array())
+{
+    $encoder = new PhpXmlRpc\Encoder();
+    return $encoder->decode($xmlrpcVal, $options);
+}
+
+function php_xmlrpc_encode($phpVal, $options=array())
+{
+    $encoder = new PhpXmlRpc\Encoder();
+    return $encoder->encode($phpVal, $options);
+}
+
+function php_xmlrpc_decode_xml($xmlVal, $options=array())
+{
+    $encoder = new PhpXmlRpc\Encoder();
+    return $encoder->decodeXml($xmlVal, $options);
+}
+
+function guess_encoding($httpHeader='', $xmlChunk='', $encodingPrefs=null)
+{
+    return PhpXmlRpc\Helper\XMLParser::guessEncoding($httpHeader, $xmlChunk, $encodingPrefs);
+}
+
+function has_encoding($xmlChunk)
+{
+    return PhpXmlRpc\Helper\XMLParser::hasEncoding($xmlChunk);
+}
+
+function is_valid_charset($encoding, $validList)
+{
+    return PhpXmlRpc\Helper\Charset::instance()->isValidCharset($encoding, $validList);
+}
index b2c6611..3c2390a 100644 (file)
-<?php\r
-/**\r
- * PHP-XMLRPC "wrapper" functions\r
- * Generate stubs to transparently access xmlrpc methods as php functions and viceversa\r
- *\r
- * @author Gaetano Giunta\r
- * @copyright (C) 2006-2014 G. Giunta\r
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt\r
- *\r
- * @todo separate introspection from code generation for func-2-method wrapping\r
- * @todo use some better templating system for code generation?\r
- * @todo implement method wrapping with preservation of php objs in calls\r
- * @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)\r
- * @todo implement self-parsing of php code for PHP <= 4\r
- */\r
-\r
-       // requires: xmlrpc.inc\r
-\r
-       /**\r
-       * Given a string defining a php type or phpxmlrpc type (loosely defined: strings\r
-       * accepted come from javadoc blocks), return corresponding phpxmlrpc type.\r
-       * NB: for php 'resource' types returns empty string, since resources cannot be serialized;\r
-       * for php class names returns 'struct', since php objects can be serialized as xmlrpc structs\r
-       * for php arrays always return array, even though arrays sometiles serialize as json structs\r
-       * @param string $phptype\r
-       * @return string\r
-       */\r
-       function php_2_xmlrpc_type($phptype)\r
-       {\r
-               switch(strtolower($phptype))\r
-               {\r
-                       case 'string':\r
-                               return $GLOBALS['xmlrpcString'];\r
-                       case 'integer':\r
-                       case $GLOBALS['xmlrpcInt']: // 'int'\r
-                       case $GLOBALS['xmlrpcI4']:\r
-                               return $GLOBALS['xmlrpcInt'];\r
-                       case 'double':\r
-                               return $GLOBALS['xmlrpcDouble'];\r
-                       case 'boolean':\r
-                               return $GLOBALS['xmlrpcBoolean'];\r
-                       case 'array':\r
-                               return $GLOBALS['xmlrpcArray'];\r
-                       case 'object':\r
-                               return $GLOBALS['xmlrpcStruct'];\r
-                       case $GLOBALS['xmlrpcBase64']:\r
-                       case $GLOBALS['xmlrpcStruct']:\r
-                               return strtolower($phptype);\r
-                       case 'resource':\r
-                               return '';\r
-                       default:\r
-                               if(class_exists($phptype))\r
-                               {\r
-                                       return $GLOBALS['xmlrpcStruct'];\r
-                               }\r
-                               else\r
-                               {\r
-                                       // unknown: might be any 'extended' xmlrpc type\r
-                                       return $GLOBALS['xmlrpcValue'];\r
-                               }\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Given a string defining a phpxmlrpc type return corresponding php type.\r
-       * @param string $xmlrpctype\r
-       * @return string\r
-       */\r
-       function xmlrpc_2_php_type($xmlrpctype)\r
-       {\r
-               switch(strtolower($xmlrpctype))\r
-               {\r
-                       case 'base64':\r
-                       case 'datetime.iso8601':\r
-                       case 'string':\r
-                               return $GLOBALS['xmlrpcString'];\r
-                       case 'int':\r
-                       case 'i4':\r
-                               return 'integer';\r
-                       case 'struct':\r
-                       case 'array':\r
-                               return 'array';\r
-                       case 'double':\r
-                               return 'float';\r
-                       case 'undefined':\r
-                               return 'mixed';\r
-                       case 'boolean':\r
-                       case 'null':\r
-                       default:\r
-                               // unknown: might be any xmlrpc type\r
-                               return strtolower($xmlrpctype);\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Given a user-defined PHP function, create a PHP 'wrapper' function that can\r
-       * be exposed as xmlrpc method from an xmlrpc_server object and called from remote\r
-       * clients (as well as its corresponding signature info).\r
-       *\r
-       * Since php is a typeless language, to infer types of input and output parameters,\r
-       * it relies on parsing the javadoc-style comment block associated with the given\r
-       * function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)\r
-       * in the @param tag is also allowed, if you need the php function to receive/send\r
-       * data in that particular format (note that base64 encoding/decoding is transparently\r
-       * carried out by the lib, while datetime vals are passed around as strings)\r
-       *\r
-       * Known limitations:\r
-       * - only works for user-defined functions, not for PHP internal functions\r
-       *   (reflection does not support retrieving number/type of params for those)\r
-       * - functions returning php objects will generate special xmlrpc responses:\r
-       *   when the xmlrpc decoding of those responses is carried out by this same lib, using\r
-       *   the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.\r
-       *   In short: php objects can be serialized, too (except for their resource members),\r
-       *   using this function.\r
-       *   Other libs might choke on the very same xml that will be generated in this case\r
-       *   (i.e. it has a nonstandard attribute on struct element tags)\r
-       * - usage of javadoc @param tags using param names in a different order from the\r
-       *   function prototype is not considered valid (to be fixed?)\r
-       *\r
-       * Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'\r
-       * php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)\r
-       * is by making use of the functions_parameters_type class member.\r
-       *\r
-       * @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\r
-       * @param string $newfuncname (optional) name for function to be created\r
-       * @param array $extra_options (optional) array of options for conversion. valid values include:\r
-       *        bool  return_source when true, php code w. function definition will be returned, not evaluated\r
-       *        bool  encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects\r
-       *        bool  decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---\r
-       *        bool  suppress_warnings  remove from produced xml any runtime warnings due to the php function being invoked\r
-       * @return false on error, or an array containing the name of the new php function,\r
-       *         its signature and docs, to be used in the server dispatch map\r
-       *\r
-       * @todo decide how to deal with params passed by ref: bomb out or allow?\r
-       * @todo finish using javadoc info to build method sig if all params are named but out of order\r
-       * @todo add a check for params of 'resource' type\r
-       * @todo add some trigger_errors / error_log when returning false?\r
-       * @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...\r
-       * @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?\r
-       * @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster\r
-       * @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?\r
-       */\r
-       function wrap_php_function($funcname, $newfuncname='', $extra_options=array())\r
-       {\r
-               $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;\r
-               $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';\r
-               $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;\r
-               $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;\r
-               $catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';\r
-\r
-               $exists = false;\r
-           if (is_string($funcname) && strpos($funcname, '::') !== false)\r
-           {\r
-               $funcname = explode('::', $funcname);\r
-           }\r
-        if(is_array($funcname))\r
-        {\r
-            if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0])))\r
-            {\r
-                       error_log('XML-RPC: syntax for function to be wrapped is wrong');\r
-                       return false;\r
-            }\r
-            if(is_string($funcname[0]))\r
-            {\r
-                $plainfuncname = implode('::', $funcname);\r
-            }\r
-            elseif(is_object($funcname[0]))\r
-            {\r
-                $plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];\r
-            }\r
-            $exists = method_exists($funcname[0], $funcname[1]);\r
-        }\r
-        else\r
-        {\r
-            $plainfuncname = $funcname;\r
-            $exists = function_exists($funcname);\r
-        }\r
-\r
-               if(!$exists)\r
-               {\r
-                       error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname);\r
-                       return false;\r
-               }\r
-               else\r
-               {\r
-                       // determine name of new php function\r
-                       if($newfuncname == '')\r
-                       {\r
-                               if(is_array($funcname))\r
-                               {\r
-                               if(is_string($funcname[0]))\r
-                                       $xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);\r
-                               else\r
-                                       $xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1];\r
-                               }\r
-                               else\r
-                               {\r
-                                       $xmlrpcfuncname = "{$prefix}_$funcname";\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $xmlrpcfuncname = $newfuncname;\r
-                       }\r
-                       while($buildit && function_exists($xmlrpcfuncname))\r
-                       {\r
-                               $xmlrpcfuncname .= 'x';\r
-                       }\r
-\r
-                       // start to introspect PHP code\r
-                       if(is_array($funcname))\r
-                       {\r
-                       $func = new ReflectionMethod($funcname[0], $funcname[1]);\r
-                       if($func->isPrivate())\r
-                       {\r
-                               error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-                       if($func->isProtected())\r
-                       {\r
-                               error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-                       if($func->isConstructor())\r
-                       {\r
-                               error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-                if($func->isDestructor())\r
-                       {\r
-                               error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-                       if($func->isAbstract())\r
-                       {\r
-                               error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-                /// @todo add more checks for static vs. nonstatic?\r
-            }\r
-                       else\r
-                       {\r
-                       $func = new ReflectionFunction($funcname);\r
-            }\r
-                       if($func->isInternal())\r
-                       {\r
-                               // Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs\r
-                               // instead of getparameters to fully reflect internal php functions ?\r
-                               error_log('XML-RPC: function to be wrapped is internal: '.$plainfuncname);\r
-                               return false;\r
-                       }\r
-\r
-                       // retrieve parameter names, types and description from javadoc comments\r
-\r
-                       // function description\r
-                       $desc = '';\r
-                       // type of return val: by default 'any'\r
-                       $returns = $GLOBALS['xmlrpcValue'];\r
-                       // desc of return val\r
-                       $returnsDocs = '';\r
-                       // type + name of function parameters\r
-                       $paramDocs = array();\r
-\r
-                       $docs = $func->getDocComment();\r
-                       if($docs != '')\r
-                       {\r
-                               $docs = explode("\n", $docs);\r
-                               $i = 0;\r
-                               foreach($docs as $doc)\r
-                               {\r
-                                       $doc = trim($doc, " \r\t/*");\r
-                                       if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)\r
-                                       {\r
-                                               if($desc)\r
-                                               {\r
-                                                       $desc .= "\n";\r
-                                               }\r
-                                               $desc .= $doc;\r
-                                       }\r
-                                       elseif(strpos($doc, '@param') === 0)\r
-                                       {\r
-                                               // syntax: @param type [$name] desc\r
-                                               if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches))\r
-                                               {\r
-                                                       if(strpos($matches[1], '|'))\r
-                                                       {\r
-                                                               //$paramDocs[$i]['type'] = explode('|', $matches[1]);\r
-                                                               $paramDocs[$i]['type'] = 'mixed';\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               $paramDocs[$i]['type'] = $matches[1];\r
-                                                       }\r
-                                                       $paramDocs[$i]['name'] = trim($matches[2]);\r
-                                                       $paramDocs[$i]['doc'] = $matches[3];\r
-                                               }\r
-                                               $i++;\r
-                                       }\r
-                                       elseif(strpos($doc, '@return') === 0)\r
-                                       {\r
-                                               // syntax: @return type desc\r
-                                               //$returns = preg_split('/\s+/', $doc);\r
-                                               if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))\r
-                                               {\r
-                                                       $returns = php_2_xmlrpc_type($matches[1]);\r
-                                                       if(isset($matches[2]))\r
-                                                       {\r
-                                                               $returnsDocs = $matches[2];\r
-                                                       }\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       // execute introspection of actual function prototype\r
-                       $params = array();\r
-                       $i = 0;\r
-                       foreach($func->getParameters() as $paramobj)\r
-                       {\r
-                               $params[$i] = array();\r
-                               $params[$i]['name'] = '$'.$paramobj->getName();\r
-                               $params[$i]['isoptional'] = $paramobj->isOptional();\r
-                               $i++;\r
-                       }\r
-\r
-\r
-                       // start  building of PHP code to be eval'd\r
-                       $innercode = '';\r
-                       $i = 0;\r
-                       $parsvariations = array();\r
-                       $pars = array();\r
-                       $pnum = count($params);\r
-                       foreach($params as $param)\r
-                       {\r
-                               if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name']))\r
-                               {\r
-                                       // param name from phpdoc info does not match param definition!\r
-                                       $paramDocs[$i]['type'] = 'mixed';\r
-                               }\r
-\r
-                               if($param['isoptional'])\r
-                               {\r
-                                       // this particular parameter is optional. save as valid previous list of parameters\r
-                                       $innercode .= "if (\$paramcount > $i) {\n";\r
-                                       $parsvariations[] = $pars;\r
-                               }\r
-                               $innercode .= "\$p$i = \$msg->getParam($i);\n";\r
-                               if ($decode_php_objects)\r
-                               {\r
-                                       $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";\r
-                               }\r
-                               else\r
-                               {\r
-                                       $innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";\r
-                               }\r
-\r
-                               $pars[] = "\$p$i";\r
-                               $i++;\r
-                               if($param['isoptional'])\r
-                               {\r
-                                       $innercode .= "}\n";\r
-                               }\r
-                               if($i == $pnum)\r
-                               {\r
-                                       // last allowed parameters combination\r
-                                       $parsvariations[] = $pars;\r
-                               }\r
-                       }\r
-\r
-                       $sigs = array();\r
-                       $psigs = array();\r
-                       if(count($parsvariations) == 0)\r
-                       {\r
-                               // only known good synopsis = no parameters\r
-                               $parsvariations[] = array();\r
-                               $minpars = 0;\r
-                       }\r
-                       else\r
-                       {\r
-                               $minpars = count($parsvariations[0]);\r
-                       }\r
-\r
-                       if($minpars)\r
-                       {\r
-                               // add to code the check for min params number\r
-                               // NB: this check needs to be done BEFORE decoding param values\r
-                               $innercode = "\$paramcount = \$msg->getNumParams();\n" .\r
-                               "if (\$paramcount < $minpars) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . $innercode;\r
-                       }\r
-                       else\r
-                       {\r
-                               $innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;\r
-                       }\r
-\r
-                       $innercode .= "\$np = false;\n";\r
-                       // since there are no closures in php, if we are given an object instance,\r
-            // we store a pointer to it in a global var...\r
-                       if ( is_array($funcname) && is_object($funcname[0]) )\r
-                       {\r
-                           $GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0];\r
-                           $innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";\r
-                           $realfuncname = '$obj->'.$funcname[1];\r
-                       }\r
-                       else\r
-                       {\r
-                       $realfuncname = $plainfuncname;\r
-            }\r
-                       foreach($parsvariations as $pars)\r
-                       {\r
-                               $innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";\r
-                               // build a 'generic' signature (only use an appropriate return type)\r
-                               $sig = array($returns);\r
-                               $psig = array($returnsDocs);\r
-                               for($i=0; $i < count($pars); $i++)\r
-                               {\r
-                                       if (isset($paramDocs[$i]['type']))\r
-                                       {\r
-                                               $sig[] = php_2_xmlrpc_type($paramDocs[$i]['type']);\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $sig[] = $GLOBALS['xmlrpcValue'];\r
-                                       }\r
-                                       $psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';\r
-                               }\r
-                               $sigs[] = $sig;\r
-                               $psigs[] = $psig;\r
-                       }\r
-                       $innercode .= "\$np = true;\n";\r
-                       $innercode .= "if (\$np) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n";\r
-                       //$innercode .= "if (\$_xmlrpcs_error_occurred) return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";\r
-                       $innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";\r
-                       if($returns == $GLOBALS['xmlrpcDateTime'] || $returns == $GLOBALS['xmlrpcBase64'])\r
-                       {\r
-                               $innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";\r
-                       }\r
-                       else\r
-                       {\r
-                               if ($encode_php_objects)\r
-                                       $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";\r
-                               else\r
-                                       $innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";\r
-                       }\r
-                       // shall we exclude functions returning by ref?\r
-                       // if($func->returnsReference())\r
-                       //      return false;\r
-                       $code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";\r
-                       //print_r($code);\r
-                       if ($buildit)\r
-                       {\r
-                               $allOK = 0;\r
-                               eval($code.'$allOK=1;');\r
-                               // alternative\r
-                               //$xmlrpcfuncname = create_function('$m', $innercode);\r
-\r
-                               if(!$allOK)\r
-                               {\r
-                                       error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$plainfuncname);\r
-                                       return false;\r
-                               }\r
-                       }\r
-\r
-                       /// @todo examine if $paramDocs matches $parsvariations and build array for\r
-                       /// usage as method signature, plus put together a nice string for docs\r
-\r
-                       $ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);\r
-                       return $ret;\r
-               }\r
-       }\r
-\r
-    /**\r
-    * Given a user-defined PHP class or php object, map its methods onto a list of\r
-       * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server\r
-       * object and called from remote clients (as well as their corresponding signature info).\r
-       *\r
-    * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class\r
-    * @param array $extra_options see the docs for wrap_php_method for more options\r
-    *        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\r
-    * @return array or false on failure\r
-    *\r
-    * @todo get_class_methods will return both static and non-static methods.\r
-    *       we have to differentiate the action, depending on wheter we recived a class name or object\r
-    */\r
-    function wrap_php_class($classname, $extra_options=array())\r
-    {\r
-               $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';\r
-               $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';\r
-\r
-        $result = array();\r
-               $mlist = get_class_methods($classname);\r
-               foreach($mlist as $mname)\r
-               {\r
-               if ($methodfilter == '' || preg_match($methodfilter, $mname))\r
-                       {\r
-                       // echo $mlist."\n";\r
-                       $func = new ReflectionMethod($classname, $mname);\r
-                       if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract())\r
-                       {\r
-                               if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||\r
-                               (!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))))\r
-                       {\r
-                        $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);\r
-                        if ( $methodwrap )\r
-                        {\r
-                            $result[$methodwrap['function']] = $methodwrap['function'];\r
-                        }\r
-                    }\r
-                       }\r
-                       }\r
-               }\r
-        return $result;\r
-    }\r
-\r
-       /**\r
-       * Given an xmlrpc client and a method name, register a php wrapper function\r
-       * that will call it and return results using native php types for both\r
-       * params and results. The generated php function will return an xmlrpcresp\r
-       * object for failed xmlrpc calls\r
-       *\r
-       * Known limitations:\r
-       * - server must support system.methodsignature for the wanted xmlrpc method\r
-       * - for methods that expose many signatures, only one can be picked (we\r
-       *   could in principle check if signatures differ only by number of params\r
-       *   and not by type, but it would be more complication than we can spare time)\r
-       * - nested xmlrpc params: the caller of the generated php function has to\r
-       *   encode on its own the params passed to the php function if these are structs\r
-       *   or arrays whose (sub)members include values of type datetime or base64\r
-       *\r
-       * Notes: the connection properties of the given client will be copied\r
-       * and reused for the connection used during the call to the generated\r
-       * php function.\r
-       * Calling the generated php function 'might' be slow: a new xmlrpc client\r
-       * is created on every invocation and an xmlrpc-connection opened+closed.\r
-       * An extra 'debug' param is appended to param list of xmlrpc method, useful\r
-       * for debugging purposes.\r
-       *\r
-       * @param xmlrpc_client $client     an xmlrpc client set up correctly to communicate with target server\r
-       * @param string        $methodname the xmlrpc method to be mapped to a php function\r
-       * @param array         $extra_options array of options that specify conversion details. valid options include\r
-       *        integer       signum      the index of the method signature to use in mapping (if method exposes many sigs)\r
-       *        integer       timeout     timeout (in secs) to be used when executing function/calling remote method\r
-       *        string        protocol    'http' (default), 'http11' or 'https'\r
-       *        string        new_function_name the name of php function to create. If unspecified, lib will pick an appropriate name\r
-       *        string        return_source if true return php code w. function definition instead fo function name\r
-       *        bool          encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects\r
-       *        bool          decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---\r
-       *        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\r
-       *        bool          debug        set it to 1 or 2 to see debug results of querying server for method synopsis\r
-       * @return string                   the name of the generated php function (or false) - OR AN ARRAY...\r
-       */\r
-       function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')\r
-       {\r
-               // mind numbing: let caller use sane calling convention (as per javadoc, 3 params),\r
-               // OR the 2.0 calling convention (no options) - we really love backward compat, don't we?\r
-               if (!is_array($extra_options))\r
-               {\r
-                       $signum = $extra_options;\r
-                       $extra_options = array();\r
-               }\r
-               else\r
-               {\r
-                       $signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;\r
-                       $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;\r
-                       $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';\r
-                       $newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';\r
-               }\r
-               //$encode_php_objects = in_array('encode_php_objects', $extra_options);\r
-               //$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :\r
-               //      in_array('build_class_code', $extra_options) ? 2 : 0;\r
-\r
-               $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;\r
-               $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;\r
-               // it seems like the meaning of 'simple_client_copy' here is swapped wrt client_copy_mode later on...\r
-               $simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;\r
-               $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;\r
-               $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';\r
-               if (isset($extra_options['return_on_fault']))\r
-               {\r
-                       $decode_fault = true;\r
-                       $fault_response = $extra_options['return_on_fault'];\r
-               }\r
-               else\r
-               {\r
-                       $decode_fault = false;\r
-                       $fault_response = '';\r
-               }\r
-               $debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;\r
-\r
-               $msgclass = $prefix.'msg';\r
-               $valclass = $prefix.'val';\r
-               $decodefunc = 'php_'.$prefix.'_decode';\r
-\r
-               $msg = new $msgclass('system.methodSignature');\r
-               $msg->addparam(new $valclass($methodname));\r
-               $client->setDebug($debug);\r
-               $response =& $client->send($msg, $timeout, $protocol);\r
-               if($response->faultCode())\r
-               {\r
-                       error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);\r
-                       return false;\r
-               }\r
-               else\r
-               {\r
-                       $msig = $response->value();\r
-                       if ($client->return_type != 'phpvals')\r
-                       {\r
-                               $msig = $decodefunc($msig);\r
-                       }\r
-                       if(!is_array($msig) || count($msig) <= $signum)\r
-                       {\r
-                               error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);\r
-                               return false;\r
-                       }\r
-                       else\r
-                       {\r
-                               // pick a suitable name for the new function, avoiding collisions\r
-                               if($newfuncname != '')\r
-                               {\r
-                                       $xmlrpcfuncname = $newfuncname;\r
-                               }\r
-                               else\r
-                               {\r
-                                       // take care to insure that methodname is translated to valid\r
-                                       // php function name\r
-                                       $xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),\r
-                                               array('_', ''), $methodname);\r
-                               }\r
-                               while($buildit && function_exists($xmlrpcfuncname))\r
-                               {\r
-                                       $xmlrpcfuncname .= 'x';\r
-                               }\r
-\r
-                               $msig = $msig[$signum];\r
-                               $mdesc = '';\r
-                               // if in 'offline' mode, get method description too.\r
-                               // in online mode, favour speed of operation\r
-                               if(!$buildit)\r
-                               {\r
-                                       $msg = new $msgclass('system.methodHelp');\r
-                                       $msg->addparam(new $valclass($methodname));\r
-                                       $response =& $client->send($msg, $timeout, $protocol);\r
-                                       if (!$response->faultCode())\r
-                                       {\r
-                                               $mdesc = $response->value();\r
-                                               if ($client->return_type != 'phpvals')\r
-                                               {\r
-                                                       $mdesc = $mdesc->scalarval();\r
-                                               }\r
-                                       }\r
-                               }\r
-\r
-                               $results = build_remote_method_wrapper_code($client, $methodname,\r
-                                       $xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,\r
-                                       $prefix, $decode_php_objects, $encode_php_objects, $decode_fault,\r
-                                       $fault_response);\r
-\r
-                               //print_r($code);\r
-                               if ($buildit)\r
-                               {\r
-                                       $allOK = 0;\r
-                                       eval($results['source'].'$allOK=1;');\r
-                                       // alternative\r
-                                       //$xmlrpcfuncname = create_function('$m', $innercode);\r
-                                       if($allOK)\r
-                                       {\r
-                                               return $xmlrpcfuncname;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);\r
-                                               return false;\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       $results['function'] = $xmlrpcfuncname;\r
-                                       return $results;\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Similar to wrap_xmlrpc_method, but will generate a php class that wraps\r
-       * all xmlrpc methods exposed by the remote server as own methods.\r
-       * For more details see wrap_xmlrpc_method.\r
-       * @param xmlrpc_client $client the client obj all set to query the desired server\r
-       * @param array $extra_options list of options for wrapped code\r
-       * @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)\r
-       */\r
-       function wrap_xmlrpc_server($client, $extra_options=array())\r
-       {\r
-               $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';\r
-               //$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;\r
-               $timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;\r
-               $protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';\r
-               $newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';\r
-               $encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;\r
-               $decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;\r
-               $verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;\r
-               $buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;\r
-               $prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';\r
-\r
-               $msgclass = $prefix.'msg';\r
-               //$valclass = $prefix.'val';\r
-               $decodefunc = 'php_'.$prefix.'_decode';\r
-\r
-               $msg = new $msgclass('system.listMethods');\r
-               $response =& $client->send($msg, $timeout, $protocol);\r
-               if($response->faultCode())\r
-               {\r
-                       error_log('XML-RPC: could not retrieve method list from remote server');\r
-                       return false;\r
-               }\r
-               else\r
-               {\r
-                       $mlist = $response->value();\r
-                       if ($client->return_type != 'phpvals')\r
-                       {\r
-                               $mlist = $decodefunc($mlist);\r
-                       }\r
-                       if(!is_array($mlist) || !count($mlist))\r
-                       {\r
-                               error_log('XML-RPC: could not retrieve meaningful method list from remote server');\r
-                               return false;\r
-                       }\r
-                       else\r
-                       {\r
-                               // pick a suitable name for the new function, avoiding collisions\r
-                               if($newclassname != '')\r
-                               {\r
-                                       $xmlrpcclassname = $newclassname;\r
-                               }\r
-                               else\r
-                               {\r
-                                       $xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),\r
-                                               array('_', ''), $client->server).'_client';\r
-                               }\r
-                               while($buildit && class_exists($xmlrpcclassname))\r
-                               {\r
-                                       $xmlrpcclassname .= 'x';\r
-                               }\r
-\r
-                               /// @todo add function setdebug() to new class, to enable/disable debugging\r
-                               $source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";\r
-                               $source .= "function $xmlrpcclassname()\n{\n";\r
-                               $source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix);\r
-                               $source .= "\$this->client =& \$client;\n}\n\n";\r
-                               $opts = array('simple_client_copy' => 2, 'return_source' => true,\r
-                                       'timeout' => $timeout, 'protocol' => $protocol,\r
-                                       'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,\r
-                                       'decode_php_objs' => $decode_php_objects\r
-                                       );\r
-                               /// @todo build javadoc for class definition, too\r
-                               foreach($mlist as $mname)\r
-                               {\r
-                                       if ($methodfilter == '' || preg_match($methodfilter, $mname))\r
-                                       {\r
-                                               $opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),\r
-                                                       array('_', ''), $mname);\r
-                                               $methodwrap = wrap_xmlrpc_method($client, $mname, $opts);\r
-                                               if ($methodwrap)\r
-                                               {\r
-                                                       if (!$buildit)\r
-                                                       {\r
-                                                               $source .= $methodwrap['docstring'];\r
-                                                       }\r
-                                                       $source .= $methodwrap['source']."\n";\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       error_log('XML-RPC: will not create class method to wrap remote method '.$mname);\r
-                                               }\r
-                                       }\r
-                               }\r
-                               $source .= "}\n";\r
-                               if ($buildit)\r
-                               {\r
-                                       $allOK = 0;\r
-                                       eval($source.'$allOK=1;');\r
-                                       // alternative\r
-                                       //$xmlrpcfuncname = create_function('$m', $innercode);\r
-                                       if($allOK)\r
-                                       {\r
-                                               return $xmlrpcclassname;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);\r
-                                               return false;\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-       * Given the necessary info, build php code that creates a new function to\r
-       * invoke a remote xmlrpc method.\r
-       * Take care that no full checking of input parameters is done to ensure that\r
-       * valid php code is emitted.\r
-       * Note: real spaghetti code follows...\r
-       * @access private\r
-       */\r
-       function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,\r
-               $msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',\r
-               $decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,\r
-               $fault_response='')\r
-       {\r
-               $code = "function $xmlrpcfuncname (";\r
-               if ($client_copy_mode < 2)\r
-               {\r
-                       // client copy mode 0 or 1 == partial / full client copy in emitted code\r
-                       $innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix);\r
-                       $innercode .= "\$client->setDebug(\$debug);\n";\r
-                       $this_ = '';\r
-               }\r
-               else\r
-               {\r
-                       // client copy mode 2 == no client copy in emitted code\r
-                       $innercode = '';\r
-                       $this_ = 'this->';\r
-               }\r
-               $innercode .= "\$msg = new {$prefix}msg('$methodname');\n";\r
-\r
-               if ($mdesc != '')\r
-               {\r
-                       // take care that PHP comment is not terminated unwillingly by method description\r
-                       $mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";\r
-               }\r
-               else\r
-               {\r
-                       $mdesc = "/**\nFunction $xmlrpcfuncname\n";\r
-               }\r
-\r
-               // param parsing\r
-               $plist = array();\r
-               $pcount = count($msig);\r
-               for($i = 1; $i < $pcount; $i++)\r
-               {\r
-                       $plist[] = "\$p$i";\r
-                       $ptype = $msig[$i];\r
-                       if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||\r
-                               $ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')\r
-                       {\r
-                               // only build directly xmlrpcvals when type is known and scalar\r
-                               $innercode .= "\$p$i = new {$prefix}val(\$p$i, '$ptype');\n";\r
-                       }\r
-                       else\r
-                       {\r
-                               if ($encode_php_objects)\r
-                               {\r
-                                       $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";\r
-                               }\r
-                               else\r
-                               {\r
-                                       $innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n";\r
-                               }\r
-                       }\r
-                       $innercode .= "\$msg->addparam(\$p$i);\n";\r
-                       $mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n";\r
-               }\r
-               if ($client_copy_mode < 2)\r
-               {\r
-                       $plist[] = '$debug=0';\r
-                       $mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";\r
-               }\r
-               $plist = implode(', ', $plist);\r
-               $mdesc .= '* @return '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";\r
-\r
-               $innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n";\r
-               if ($decode_fault)\r
-               {\r
-                       if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))\r
-                       {\r
-                               $respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";\r
-                       }\r
-                       else\r
-                       {\r
-                               $respcode = var_export($fault_response, true);\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       $respcode = '$res';\r
-               }\r
-               if ($decode_php_objects)\r
-               {\r
-                       $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";\r
-               }\r
-               else\r
-               {\r
-                       $innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";\r
-               }\r
-\r
-               $code = $code . $plist. ") {\n" . $innercode . "\n}\n";\r
-\r
-               return array('source' => $code, 'docstring' => $mdesc);\r
-       }\r
-\r
-       /**\r
-       * Given necessary info, generate php code that will rebuild a client object\r
-       * Take care that no full checking of input parameters is done to ensure that\r
-       * valid php code is emitted.\r
-       * @access private\r
-       */\r
-       function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')\r
-       {\r
-               $code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).\r
-                       "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";\r
-\r
-               // copy all client fields to the client that will be generated runtime\r
-               // (this provides for future expansion or subclassing of client obj)\r
-               if ($verbatim_client_copy)\r
-               {\r
-                       foreach($client as $fld => $val)\r
-                       {\r
-                               if($fld != 'debug' && $fld != 'return_type')\r
-                               {\r
-                                       $val = var_export($val, true);\r
-                                       $code .= "\$client->$fld = $val;\n";\r
-                               }\r
-                       }\r
-               }\r
-               // only make sure that client always returns the correct data type\r
-               $code .= "\$client->return_type = '{$prefix}vals';\n";\r
-               //$code .= "\$client->setDebug(\$debug);\n";\r
-               return $code;\r
-       }\r
-?>
\ No newline at end of file
+<?php
+
+/******************************************************************************
+ *
+ * *** DEPRECATED ***
+ *
+ * This file is only used to insure backwards compatibility
+ * with the API of the library <= rev. 3
+ *****************************************************************************/
+
+include_once(__DIR__.'/../src/Wrapper.php');
+
+/* Expose as global functions the ones which are now class methods */
+
+/**
+ * @see PhpXmlRpc\Wrapper::php_2_xmlrpc_type
+ * @param string $phpType
+ * @return string
+ */
+function php_2_xmlrpc_type($phpType)
+{
+    $wrapper = new PhpXmlRpc\Wrapper();
+    return $wrapper->php2XmlrpcType($phpType);
+}
+
+/**
+ * @see PhpXmlRpc\Wrapper::xmlrpc_2_php_type
+ * @param string $xmlrpcType
+ * @return string
+ */
+function xmlrpc_2_php_type($xmlrpcType)
+{
+    $wrapper = new PhpXmlRpc\Wrapper();
+    return $wrapper->xmlrpc2PhpType($xmlrpcType);
+}
+
+/**
+ * @see PhpXmlRpc\Wrapper::wrap_php_function
+ * @param callable $funcName
+ * @param string $newFuncName
+ * @param array $extraOptions
+ * @return array|false
+ */
+function wrap_php_function($funcName, $newFuncName='', $extraOptions=array())
+{
+    $wrapper = new PhpXmlRpc\Wrapper();
+    if (!isset($extraOptions['return_source'])  || $extraOptions['return_source'] == false) {
+        // backwards compat: return string instead of callable
+        $extraOptions['return_source'] = true;
+        $wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions);
+        eval($wrapped['source']);
+    } else {
+        $wrapped = $wrapper->wrapPhpFunction($funcName, $newFuncName, $extraOptions);
+    }
+    return $wrapped;
+}
+
+/**
+ * NB: this function returns an array in a format which is unsuitable for direct use in the server dispatch map, unlike
+ * PhpXmlRpc\Wrapper::wrapPhpClass. This behaviour might seem like a bug, but has been kept for backwards compatibility.
+ *
+ * @see PhpXmlRpc\Wrapper::wrap_php_class
+ * @param string|object $className
+ * @param array $extraOptions
+ * @return array|false
+ */
+function wrap_php_class($className, $extraOptions=array())
+{
+    $wrapper = new PhpXmlRpc\Wrapper();
+    $fix = false;
+    if (!isset($extraOptions['return_source'])  || $extraOptions['return_source'] == false) {
+        // backwards compat: return string instead of callable
+        $extraOptions['return_source'] = true;
+        $fix = true;
+    }
+    $wrapped = $wrapper->wrapPhpClass($className, $extraOptions);
+    foreach($wrapped as $name => $value) {
+        if ($fix) {
+            eval($value['source']);
+        }
+        $wrapped[$name] = $value['function'];
+    }
+    return $wrapped;
+}
+
+/**
+ * @see PhpXmlRpc\Wrapper::wrapXmlrpcMethod
+ * @param xmlrpc_client $client
+ * @param string $methodName
+ * @param int|array $extraOptions the usage of an int as signature number is deprecated, use an option in $extraOptions
+ * @param int $timeout            deprecated, use an option in $extraOptions
+ * @param string $protocol        deprecated, use an option in $extraOptions
+ * @param string $newFuncName     deprecated, use an option in $extraOptions
+ * @return array|callable|false
+ */
+function wrap_xmlrpc_method($client, $methodName, $extraOptions=0, $timeout=0, $protocol='', $newFuncName='')
+{
+    if (!is_array($extraOptions))
+    {
+        $sigNum = $extraOptions;
+        $extraOptions = array(
+            'signum' => $sigNum,
+            'timeout' => $timeout,
+            'protocol' => $protocol,
+            'new_function_name' => $newFuncName
+        );
+    }
+
+    $wrapper = new PhpXmlRpc\Wrapper();
+
+    if (!isset($extraOptions['return_source'])  || $extraOptions['return_source'] == false) {
+        // backwards compat: return string instead of callable
+        $extraOptions['return_source'] = true;
+        $wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions);
+        eval($wrapped['source']);
+        $wrapped = $wrapped['function'];
+    } else {
+        $wrapped = $wrapper->wrapXmlrpcMethod($client, $methodName, $extraOptions);
+    }
+    return $wrapped;
+}
+
+/**
+ * @see PhpXmlRpc\Wrapper::wrap_xmlrpc_server
+ * @param xmlrpc_client $client
+ * @param array $extraOptions
+ * @return mixed
+ */
+function wrap_xmlrpc_server($client, $extraOptions=array())
+{
+    $wrapper = new PhpXmlRpc\Wrapper();
+    return $wrapper->wrapXmlrpcServer($client, $extraOptions);
+}
+
+/**
+ * Given the necessary info, build php code that creates a new function to invoke a remote xmlrpc method.
+ * Take care that no full checking of input parameters is done to ensure that valid php code is emitted.
+ * Only kept for backwards compatibility
+ * Note: real spaghetti code follows...
+ *
+ * @deprecated
+ */
+function build_remote_method_wrapper_code($client, $methodName, $xmlrpcFuncName,
+     $mSig, $mDesc = '', $timeout = 0, $protocol = '', $clientCopyMode = 0, $prefix = 'xmlrpc',
+     $decodePhpObjects = false, $encodePhpObjects = false, $decodeFault = false,
+     $faultResponse = '', $namespace = '\\PhpXmlRpc\\')
+{
+    $code = "function $xmlrpcFuncName (";
+    if ($clientCopyMode < 2) {
+        // client copy mode 0 or 1 == partial / full client copy in emitted code
+        $innerCode = build_client_wrapper_code($client, $clientCopyMode, $prefix, $namespace);
+        $innerCode .= "\$client->setDebug(\$debug);\n";
+        $this_ = '';
+    } else {
+        // client copy mode 2 == no client copy in emitted code
+        $innerCode = '';
+        $this_ = 'this->';
+    }
+    $innerCode .= "\$req = new {$namespace}Request('$methodName');\n";
+
+    if ($mDesc != '') {
+        // take care that PHP comment is not terminated unwillingly by method description
+        $mDesc = "/**\n* " . str_replace('*/', '* /', $mDesc) . "\n";
+    } else {
+        $mDesc = "/**\nFunction $xmlrpcFuncName\n";
+    }
+
+    // param parsing
+    $innerCode .= "\$encoder = new {$namespace}Encoder();\n";
+    $plist = array();
+    $pCount = count($mSig);
+    for ($i = 1; $i < $pCount; $i++) {
+        $plist[] = "\$p$i";
+        $pType = $mSig[$i];
+        if ($pType == 'i4' || $pType == 'int' || $pType == 'boolean' || $pType == 'double' ||
+            $pType == 'string' || $pType == 'dateTime.iso8601' || $pType == 'base64' || $pType == 'null'
+        ) {
+            // only build directly xmlrpc values when type is known and scalar
+            $innerCode .= "\$p$i = new {$namespace}Value(\$p$i, '$pType');\n";
+        } else {
+            if ($encodePhpObjects) {
+                $innerCode .= "\$p$i = \$encoder->encode(\$p$i, array('encode_php_objs'));\n";
+            } else {
+                $innerCode .= "\$p$i = \$encoder->encode(\$p$i);\n";
+            }
+        }
+        $innerCode .= "\$req->addparam(\$p$i);\n";
+        $mDesc .= '* @param ' . xmlrpc_2_php_type($pType) . " \$p$i\n";
+    }
+    if ($clientCopyMode < 2) {
+        $plist[] = '$debug=0';
+        $mDesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
+    }
+    $plist = implode(', ', $plist);
+    $mDesc .= '* @return ' . xmlrpc_2_php_type($mSig[0]) . " (or an {$namespace}Response obj instance if call fails)\n*/\n";
+
+    $innerCode .= "\$res = \${$this_}client->send(\$req, $timeout, '$protocol');\n";
+    if ($decodeFault) {
+        if (is_string($faultResponse) && ((strpos($faultResponse, '%faultCode%') !== false) || (strpos($faultResponse, '%faultString%') !== false))) {
+            $respCode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '" . str_replace("'", "''", $faultResponse) . "')";
+        } else {
+            $respCode = var_export($faultResponse, true);
+        }
+    } else {
+        $respCode = '$res';
+    }
+    if ($decodePhpObjects) {
+        $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value(), array('decode_php_objs'));";
+    } else {
+        $innerCode .= "if (\$res->faultcode()) return $respCode; else return \$encoder->decode(\$res->value());";
+    }
+
+    $code = $code . $plist . ") {\n" . $innerCode . "\n}\n";
+
+    return array('source' => $code, 'docstring' => $mDesc);
+}
+
+/**
+ * @deprecated
+ */
+function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
+{
+    $code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).
+        "', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
+
+    // copy all client fields to the client that will be generated runtime
+    // (this provides for future expansion or subclassing of client obj)
+    if ($verbatim_client_copy)
+    {
+        foreach($client as $fld => $val)
+        {
+            if($fld != 'debug' && $fld != 'return_type')
+            {
+                $val = var_export($val, true);
+                $code .= "\$client->$fld = $val;\n";
+            }
+        }
+    }
+    // only make sure that client always returns the correct data type
+    $code .= "\$client->return_type = '{$prefix}vals';\n";
+    //$code .= "\$client->setDebug(\$debug);\n";
+    return $code;
+}
index 180595c..71cde1f 100644 (file)
-<?php\r
-// by Edd Dumbill (C) 1999-2002\r
-// <edd@usefulinc.com>\r
-\r
-// Copyright (c) 1999,2000,2002 Edd Dumbill.\r
-// All rights reserved.\r
-//\r
-// Redistribution and use in source and binary forms, with or without\r
-// modification, are permitted provided that the following conditions\r
-// are met:\r
-//\r
-//    * Redistributions of source code must retain the above copyright\r
-//      notice, this list of conditions and the following disclaimer.\r
-//\r
-//    * Redistributions in binary form must reproduce the above\r
-//      copyright notice, this list of conditions and the following\r
-//      disclaimer in the documentation and/or other materials provided\r
-//      with the distribution.\r
-//\r
-//    * Neither the name of the "XML-RPC for PHP" nor the names of its\r
-//      contributors may be used to endorse or promote products derived\r
-//      from this software without specific prior written permission.\r
-//\r
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r
-// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r
-// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r
-// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
-// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
-// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
-// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r
-// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r
-// OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-       // XML RPC Server class\r
-       // requires: xmlrpc.inc\r
-\r
-       $GLOBALS['xmlrpcs_capabilities'] = array(\r
-               // xmlrpc spec: always supported\r
-               'xmlrpc' => new xmlrpcval(array(\r
-                       'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'),\r
-                       'specVersion' => new xmlrpcval(1, 'int')\r
-               ), 'struct'),\r
-               // if we support system.xxx functions, we always support multicall, too...\r
-               // Note that, as of 2006/09/17, the following URL does not respond anymore\r
-               'system.multicall' => new xmlrpcval(array(\r
-                       'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),\r
-                       'specVersion' => new xmlrpcval(1, 'int')\r
-               ), 'struct'),\r
-               // introspection: version 2! we support 'mixed', too\r
-               'introspection' => new xmlrpcval(array(\r
-                       'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),\r
-                       'specVersion' => new xmlrpcval(2, 'int')\r
-               ), 'struct')\r
-       );\r
-\r
-       /* Functions that implement system.XXX methods of xmlrpc servers */\r
-       $_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct']));\r
-       $_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';\r
-       $_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec'));\r
-       function _xmlrpcs_getCapabilities($server, $m=null)\r
-       {\r
-               $outAr = $GLOBALS['xmlrpcs_capabilities'];\r
-               // NIL extension\r
-               if ($GLOBALS['xmlrpc_null_extension']) {\r
-                       $outAr['nil'] = new xmlrpcval(array(\r
-                               'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),\r
-                               'specVersion' => new xmlrpcval(1, 'int')\r
-                       ), 'struct');\r
-               }\r
-               return new xmlrpcresp(new xmlrpcval($outAr, 'struct'));\r
-       }\r
-\r
-       // listMethods: signature was either a string, or nothing.\r
-       // The useless string variant has been removed\r
-       $_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray']));\r
-       $_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch';\r
-       $_xmlrpcs_listMethods_sdoc=array(array('list of method names'));\r
-       function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing\r
-       {\r
-\r
-               $outAr=array();\r
-               foreach($server->dmap as $key => $val)\r
-               {\r
-                       $outAr[]=new xmlrpcval($key, 'string');\r
-               }\r
-               if($server->allow_system_funcs)\r
-               {\r
-                       foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val)\r
-                       {\r
-                               $outAr[]=new xmlrpcval($key, 'string');\r
-                       }\r
-               }\r
-               return new xmlrpcresp(new xmlrpcval($outAr, 'array'));\r
-       }\r
-\r
-       $_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString']));\r
-       $_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)';\r
-       $_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described'));\r
-       function _xmlrpcs_methodSignature($server, $m)\r
-       {\r
-               // let accept as parameter both an xmlrpcval or string\r
-               if (is_object($m))\r
-               {\r
-                       $methName=$m->getParam(0);\r
-                       $methName=$methName->scalarval();\r
-               }\r
-               else\r
-               {\r
-                       $methName=$m;\r
-               }\r
-               if(strpos($methName, "system.") === 0)\r
-               {\r
-                       $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;\r
-               }\r
-               else\r
-               {\r
-                       $dmap=$server->dmap; $sysCall=0;\r
-               }\r
-               if(isset($dmap[$methName]))\r
-               {\r
-                       if(isset($dmap[$methName]['signature']))\r
-                       {\r
-                               $sigs=array();\r
-                               foreach($dmap[$methName]['signature'] as $inSig)\r
-                               {\r
-                                       $cursig=array();\r
-                                       foreach($inSig as $sig)\r
-                                       {\r
-                                               $cursig[]=new xmlrpcval($sig, 'string');\r
-                                       }\r
-                                       $sigs[]=new xmlrpcval($cursig, 'array');\r
-                               }\r
-                               $r=new xmlrpcresp(new xmlrpcval($sigs, 'array'));\r
-                       }\r
-                       else\r
-                       {\r
-                               // NB: according to the official docs, we should be returning a\r
-                               // "none-array" here, which means not-an-array\r
-                               $r=new xmlrpcresp(new xmlrpcval('undef', 'string'));\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       $r=new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);\r
-               }\r
-               return $r;\r
-       }\r
-\r
-       $_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString']));\r
-       $_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string';\r
-       $_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described'));\r
-       function _xmlrpcs_methodHelp($server, $m)\r
-       {\r
-               // let accept as parameter both an xmlrpcval or string\r
-               if (is_object($m))\r
-               {\r
-                       $methName=$m->getParam(0);\r
-                       $methName=$methName->scalarval();\r
-               }\r
-               else\r
-               {\r
-                       $methName=$m;\r
-               }\r
-               if(strpos($methName, "system.") === 0)\r
-               {\r
-                       $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;\r
-               }\r
-               else\r
-               {\r
-                       $dmap=$server->dmap; $sysCall=0;\r
-               }\r
-               if(isset($dmap[$methName]))\r
-               {\r
-                       if(isset($dmap[$methName]['docstring']))\r
-                       {\r
-                               $r=new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string');\r
-                       }\r
-                       else\r
-                       {\r
-                               $r=new xmlrpcresp(new xmlrpcval('', 'string'));\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       $r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);\r
-               }\r
-               return $r;\r
-       }\r
-\r
-       $_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray']));\r
-       $_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';\r
-       $_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"'));\r
-       function _xmlrpcs_multicall_error($err)\r
-       {\r
-               if(is_string($err))\r
-               {\r
-                       $str = $GLOBALS['xmlrpcstr']["multicall_${err}"];\r
-                       $code = $GLOBALS['xmlrpcerr']["multicall_${err}"];\r
-               }\r
-               else\r
-               {\r
-                       $code = $err->faultCode();\r
-                       $str = $err->faultString();\r
-               }\r
-               $struct = array();\r
-               $struct['faultCode'] = new xmlrpcval($code, 'int');\r
-               $struct['faultString'] = new xmlrpcval($str, 'string');\r
-               return new xmlrpcval($struct, 'struct');\r
-       }\r
-\r
-       function _xmlrpcs_multicall_do_call($server, $call)\r
-       {\r
-               if($call->kindOf() != 'struct')\r
-               {\r
-                       return _xmlrpcs_multicall_error('notstruct');\r
-               }\r
-               $methName = @$call->structmem('methodName');\r
-               if(!$methName)\r
-               {\r
-                       return _xmlrpcs_multicall_error('nomethod');\r
-               }\r
-               if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string')\r
-               {\r
-                       return _xmlrpcs_multicall_error('notstring');\r
-               }\r
-               if($methName->scalarval() == 'system.multicall')\r
-               {\r
-                       return _xmlrpcs_multicall_error('recursion');\r
-               }\r
-\r
-               $params = @$call->structmem('params');\r
-               if(!$params)\r
-               {\r
-                       return _xmlrpcs_multicall_error('noparams');\r
-               }\r
-               if($params->kindOf() != 'array')\r
-               {\r
-                       return _xmlrpcs_multicall_error('notarray');\r
-               }\r
-               $numParams = $params->arraysize();\r
-\r
-               $msg = new xmlrpcmsg($methName->scalarval());\r
-               for($i = 0; $i < $numParams; $i++)\r
-               {\r
-                       if(!$msg->addParam($params->arraymem($i)))\r
-                       {\r
-                               $i++;\r
-                               return _xmlrpcs_multicall_error(new xmlrpcresp(0,\r
-                                       $GLOBALS['xmlrpcerr']['incorrect_params'],\r
-                                       $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i));\r
-                       }\r
-               }\r
-\r
-               $result = $server->execute($msg);\r
-\r
-               if($result->faultCode() != 0)\r
-               {\r
-                       return _xmlrpcs_multicall_error($result);               // Method returned fault.\r
-               }\r
-\r
-               return new xmlrpcval(array($result->value()), 'array');\r
-       }\r
-\r
-       function _xmlrpcs_multicall_do_call_phpvals($server, $call)\r
-       {\r
-               if(!is_array($call))\r
-               {\r
-                       return _xmlrpcs_multicall_error('notstruct');\r
-               }\r
-               if(!array_key_exists('methodName', $call))\r
-               {\r
-                       return _xmlrpcs_multicall_error('nomethod');\r
-               }\r
-               if (!is_string($call['methodName']))\r
-               {\r
-                       return _xmlrpcs_multicall_error('notstring');\r
-               }\r
-               if($call['methodName'] == 'system.multicall')\r
-               {\r
-                       return _xmlrpcs_multicall_error('recursion');\r
-               }\r
-               if(!array_key_exists('params', $call))\r
-               {\r
-                       return _xmlrpcs_multicall_error('noparams');\r
-               }\r
-               if(!is_array($call['params']))\r
-               {\r
-                       return _xmlrpcs_multicall_error('notarray');\r
-               }\r
-\r
-               // this is a real dirty and simplistic hack, since we might have received a\r
-               // base64 or datetime values, but they will be listed as strings here...\r
-               $numParams = count($call['params']);\r
-               $pt = array();\r
-               foreach($call['params'] as $val)\r
-                       $pt[] = php_2_xmlrpc_type(gettype($val));\r
-\r
-               $result = $server->execute($call['methodName'], $call['params'], $pt);\r
-\r
-               if($result->faultCode() != 0)\r
-               {\r
-                       return _xmlrpcs_multicall_error($result);               // Method returned fault.\r
-               }\r
-\r
-               return new xmlrpcval(array($result->value()), 'array');\r
-       }\r
-\r
-       function _xmlrpcs_multicall($server, $m)\r
-       {\r
-               $result = array();\r
-               // let accept a plain list of php parameters, beside a single xmlrpc msg object\r
-               if (is_object($m))\r
-               {\r
-                       $calls = $m->getParam(0);\r
-                       $numCalls = $calls->arraysize();\r
-                       for($i = 0; $i < $numCalls; $i++)\r
-                       {\r
-                               $call = $calls->arraymem($i);\r
-                               $result[$i] = _xmlrpcs_multicall_do_call($server, $call);\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       $numCalls=count($m);\r
-                       for($i = 0; $i < $numCalls; $i++)\r
-                       {\r
-                               $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);\r
-                       }\r
-               }\r
-\r
-               return new xmlrpcresp(new xmlrpcval($result, 'array'));\r
-       }\r
-\r
-       $GLOBALS['_xmlrpcs_dmap']=array(\r
-               'system.listMethods' => array(\r
-                       'function' => '_xmlrpcs_listMethods',\r
-                       'signature' => $_xmlrpcs_listMethods_sig,\r
-                       'docstring' => $_xmlrpcs_listMethods_doc,\r
-                       'signature_docs' => $_xmlrpcs_listMethods_sdoc),\r
-               'system.methodHelp' => array(\r
-                       'function' => '_xmlrpcs_methodHelp',\r
-                       'signature' => $_xmlrpcs_methodHelp_sig,\r
-                       'docstring' => $_xmlrpcs_methodHelp_doc,\r
-                       'signature_docs' => $_xmlrpcs_methodHelp_sdoc),\r
-               'system.methodSignature' => array(\r
-                       'function' => '_xmlrpcs_methodSignature',\r
-                       'signature' => $_xmlrpcs_methodSignature_sig,\r
-                       'docstring' => $_xmlrpcs_methodSignature_doc,\r
-                       'signature_docs' => $_xmlrpcs_methodSignature_sdoc),\r
-               'system.multicall' => array(\r
-                       'function' => '_xmlrpcs_multicall',\r
-                       'signature' => $_xmlrpcs_multicall_sig,\r
-                       'docstring' => $_xmlrpcs_multicall_doc,\r
-                       'signature_docs' => $_xmlrpcs_multicall_sdoc),\r
-               'system.getCapabilities' => array(\r
-                       'function' => '_xmlrpcs_getCapabilities',\r
-                       'signature' => $_xmlrpcs_getCapabilities_sig,\r
-                       'docstring' => $_xmlrpcs_getCapabilities_doc,\r
-                       'signature_docs' => $_xmlrpcs_getCapabilities_sdoc)\r
-       );\r
-\r
-       $GLOBALS['_xmlrpcs_occurred_errors'] = '';\r
-       $GLOBALS['_xmlrpcs_prev_ehandler'] = '';\r
-\r
-       /**\r
-       * Error handler used to track errors that occur during server-side execution of PHP code.\r
-       * This allows to report back to the client whether an internal error has occurred or not\r
-       * using an xmlrpc response object, instead of letting the client deal with the html junk\r
-       * that a PHP execution error on the server generally entails.\r
-       *\r
-       * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.\r
-       *\r
-       */\r
-       function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)\r
-       {\r
-               // obey the @ protocol\r
-               if (error_reporting() == 0)\r
-                       return;\r
-\r
-               //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)\r
-               if($errcode != E_STRICT)\r
-               {\r
-                       $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n";\r
-               }\r
-               // Try to avoid as much as possible disruption to the previous error handling\r
-               // mechanism in place\r
-               if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')\r
-               {\r
-                       // The previous error handler was the default: all we should do is log error\r
-                       // to the default error log (if level high enough)\r
-                       if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))\r
-                       {\r
-                               error_log($errstring);\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       // Pass control on to previous error handler, trying to avoid loops...\r
-                       if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler')\r
-                       {\r
-                               // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers\r
-                               if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))\r
-                               {\r
-                                       // the following works both with static class methods and plain object methods as error handler\r
-                                       call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context));\r
-                               }\r
-                               else\r
-                               {\r
-                                       $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       $GLOBALS['_xmlrpc_debuginfo']='';\r
-\r
-       /**\r
-       * Add a string to the debug info that can be later seralized by the server\r
-       * as part of the response message.\r
-       * Note that for best compatibility, the debug string should be encoded using\r
-       * the $GLOBALS['xmlrpc_internalencoding'] character set.\r
-       * @param string $m\r
-       * @access public\r
-       */\r
-       function xmlrpc_debugmsg($m)\r
-       {\r
-               $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n";\r
-       }\r
-\r
-       class xmlrpc_server\r
-       {\r
-               /**\r
-               * Array defining php functions exposed as xmlrpc methods by this server\r
-               * @access private\r
-               */\r
-               var $dmap=array();\r
-               /**\r
-               * Defines how functions in dmap will be invoked: either using an xmlrpc msg object\r
-               * or plain php values.\r
-               * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'\r
-               */\r
-               var $functions_parameters_type='xmlrpcvals';\r
-               /**\r
-               * Option used for fine-tuning the encoding the php values returned from\r
-               * functions registered in the dispatch map when the functions_parameters_types\r
-               * member is set to 'phpvals'\r
-               * @see php_xmlrpc_encode for a list of values\r
-               */\r
-               var $phpvals_encoding_options = array( 'auto_dates' );\r
-               /// 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\r
-               var $debug = 1;\r
-               /**\r
-               * Controls behaviour of server when invoked user function throws an exception:\r
-               * 0 = catch it and return an 'internal error' xmlrpc response (default)\r
-               * 1 = catch it and return an xmlrpc response with the error corresponding to the exception\r
-               * 2 = allow the exception to float to the upper layers\r
-               */\r
-               var $exception_handling = 0;\r
-               /**\r
-               * When set to true, it will enable HTTP compression of the response, in case\r
-               * the client has declared its support for compression in the request.\r
-               */\r
-               var $compress_response = false;\r
-               /**\r
-               * List of http compression methods accepted by the server for requests.\r
-               * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib\r
-               */\r
-               var $accepted_compression = array();\r
-               /// shall we serve calls to system.* methods?\r
-               var $allow_system_funcs = true;\r
-               /// list of charset encodings natively accepted for requests\r
-               var $accepted_charset_encodings = array();\r
-               /**\r
-               * charset encoding to be used for response.\r
-               * NB: if we can, we will convert the generated response from internal_encoding to the intended one.\r
-               * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),\r
-               * null (leave unspecified in response, convert output stream to US_ASCII),\r
-               * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),\r
-               * 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).\r
-               * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)\r
-               */\r
-               var $response_charset_encoding = '';\r
-               /**\r
-               * Storage for internal debug info\r
-               * @access private\r
-               */\r
-               var $debug_info = '';\r
-               /**\r
-               * Extra data passed at runtime to method handling functions. Used only by EPI layer\r
-               */\r
-               var $user_data = null;\r
-\r
-               /**\r
-               * @param array $dispmap the dispatch map with definition of exposed services\r
-               * @param boolean $servicenow set to false to prevent the server from running upon construction\r
-               */\r
-               function xmlrpc_server($dispMap=null, $serviceNow=true)\r
-               {\r
-                       // if ZLIB is enabled, let the server by default accept compressed requests,\r
-                       // and compress responses sent to clients that support them\r
-                       if(function_exists('gzinflate'))\r
-                       {\r
-                               $this->accepted_compression = array('gzip', 'deflate');\r
-                               $this->compress_response = true;\r
-                       }\r
-\r
-                       // by default the xml parser can support these 3 charset encodings\r
-                       $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');\r
-\r
-                       // dispMap is a dispatch array of methods\r
-                       // mapped to function names and signatures\r
-                       // if a method\r
-                       // doesn't appear in the map then an unknown\r
-                       // method error is generated\r
-                       /* milosch - changed to make passing dispMap optional.\r
-                        * instead, you can use the class add_to_map() function\r
-                        * to add functions manually (borrowed from SOAPX4)\r
-                        */\r
-                       if($dispMap)\r
-                       {\r
-                               $this->dmap = $dispMap;\r
-                               if($serviceNow)\r
-                               {\r
-                                       $this->service();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Set debug level of server.\r
-               * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)\r
-               * 0 = no debug info,\r
-               * 1 = msgs set from user with debugmsg(),\r
-               * 2 = add complete xmlrpc request (headers and body),\r
-               * 3 = add also all processing warnings happened during method processing\r
-               * (NB: this involves setting a custom error handler, and might interfere\r
-               * with the standard processing of the php function exposed as method. In\r
-               * particular, triggering an USER_ERROR level error will not halt script\r
-               * execution anymore, but just end up logged in the xmlrpc response)\r
-               * Note that info added at level 2 and 3 will be base64 encoded\r
-               * @access public\r
-               */\r
-               function setDebug($in)\r
-               {\r
-                       $this->debug=$in;\r
-               }\r
-\r
-               /**\r
-               * Return a string with the serialized representation of all debug info\r
-               * @param string $charset_encoding the target charset encoding for the serialization\r
-               * @return string an XML comment (or two)\r
-               */\r
-               function serializeDebug($charset_encoding='')\r
-               {\r
-                       // Tough encoding problem: which internal charset should we assume for debug info?\r
-                       // It might contain a copy of raw data received from client, ie with unknown encoding,\r
-                       // intermixed with php generated data and user generated data...\r
-                       // so we split it: system debug is base 64 encoded,\r
-                       // user debug info should be encoded by the end user using the INTERNAL_ENCODING\r
-                       $out = '';\r
-                       if ($this->debug_info != '')\r
-                       {\r
-                               $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n".base64_encode($this->debug_info)."\n-->\n";\r
-                       }\r
-                       if($GLOBALS['_xmlrpc_debuginfo']!='')\r
-                       {\r
-\r
-                               $out .= "<!-- DEBUG INFO:\n" . xmlrpc_encode_entitites(str_replace('--', '_-', $GLOBALS['_xmlrpc_debuginfo']), $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n-->\n";\r
-                               // NB: a better solution MIGHT be to use CDATA, but we need to insert it\r
-                               // into return payload AFTER the beginning tag\r
-                               //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n";\r
-                       }\r
-                       return $out;\r
-               }\r
-\r
-               /**\r
-               * Execute the xmlrpc request, printing the response\r
-               * @param string $data the request body. If null, the http POST request will be examined\r
-               * @return xmlrpcresp the response object (usually not used by caller...)\r
-               * @access public\r
-               */\r
-               function service($data=null, $return_payload=false)\r
-               {\r
-                       if ($data === null)\r
-                       {\r
-                               // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA\r
-                $data = file_get_contents('php://input');\r
-                       }\r
-                       $raw_data = $data;\r
-\r
-                       // reset internal debug info\r
-                       $this->debug_info = '';\r
-\r
-                       // Echo back what we received, before parsing it\r
-                       if($this->debug > 1)\r
-                       {\r
-                               $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");\r
-                       }\r
-\r
-                       $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);\r
-                       if (!$r)\r
-                       {\r
-                               $r=$this->parseRequest($data, $req_charset);\r
-                       }\r
-\r
-                       // save full body of request into response, for more debugging usages\r
-                       $r->raw_data = $raw_data;\r
-\r
-                       if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors'])\r
-                       {\r
-                               $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .\r
-                                       $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++");\r
-                       }\r
-\r
-                       $payload=$this->xml_header($resp_charset);\r
-                       if($this->debug > 0)\r
-                       {\r
-                               $payload = $payload . $this->serializeDebug($resp_charset);\r
-                       }\r
-\r
-                       // G. Giunta 2006-01-27: do not create response serialization if it has\r
-                       // already happened. Helps building json magic\r
-                       if (empty($r->payload))\r
-                       {\r
-                               $r->serialize($resp_charset);\r
-                       }\r
-                       $payload = $payload . $r->payload;\r
-\r
-                       if ($return_payload)\r
-                       {\r
-                               return $payload;\r
-                       }\r
-\r
-                       // if we get a warning/error that has output some text before here, then we cannot\r
-                       // add a new header. We cannot say we are sending xml, either...\r
-                       if(!headers_sent())\r
-                       {\r
-                               header('Content-Type: '.$r->content_type);\r
-                               // we do not know if client actually told us an accepted charset, but if he did\r
-                               // we have to tell him what we did\r
-                               header("Vary: Accept-Charset");\r
-\r
-                               // http compression of output: only\r
-                               // if we can do it, and we want to do it, and client asked us to,\r
-                               // and php ini settings do not force it already\r
-                               $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');\r
-                               if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''\r
-                                       && $php_no_self_compress)\r
-                               {\r
-                                       if(strpos($resp_encoding, 'gzip') !== false)\r
-                                       {\r
-                                               $payload = gzencode($payload);\r
-                                               header("Content-Encoding: gzip");\r
-                                               header("Vary: Accept-Encoding");\r
-                                       }\r
-                                       elseif (strpos($resp_encoding, 'deflate') !== false)\r
-                                       {\r
-                                               $payload = gzcompress($payload);\r
-                                               header("Content-Encoding: deflate");\r
-                                               header("Vary: Accept-Encoding");\r
-                                       }\r
-                               }\r
-\r
-                               // do not ouput content-length header if php is compressing output for us:\r
-                               // it will mess up measurements\r
-                               if($php_no_self_compress)\r
-                               {\r
-                                       header('Content-Length: ' . (int)strlen($payload));\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages');\r
-                       }\r
-\r
-                       print $payload;\r
-\r
-                       // return request, in case subclasses want it\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * Add a method to the dispatch map\r
-               * @param string $methodname the name with which the method will be made available\r
-               * @param string $function the php function that will get invoked\r
-               * @param array $sig the array of valid method signatures\r
-               * @param string $doc method documentation\r
-               * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)\r
-               * @access public\r
-               */\r
-               function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false)\r
-               {\r
-                       $this->dmap[$methodname] = array(\r
-                               'function'      => $function,\r
-                               'docstring' => $doc\r
-                       );\r
-                       if ($sig)\r
-                       {\r
-                               $this->dmap[$methodname]['signature'] = $sig;\r
-                       }\r
-                       if ($sigdoc)\r
-                       {\r
-                               $this->dmap[$methodname]['signature_docs'] = $sigdoc;\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Verify type and number of parameters received against a list of known signatures\r
-               * @param array $in array of either xmlrpcval objects or xmlrpc type definitions\r
-               * @param array $sig array of known signatures to match against\r
-               * @return array\r
-               * @access private\r
-               */\r
-               function verifySignature($in, $sig)\r
-               {\r
-                       // check each possible signature in turn\r
-                       if (is_object($in))\r
-                       {\r
-                               $numParams = $in->getNumParams();\r
-                       }\r
-                       else\r
-                       {\r
-                               $numParams = count($in);\r
-                       }\r
-                       foreach($sig as $cursig)\r
-                       {\r
-                               if(count($cursig)==$numParams+1)\r
-                               {\r
-                                       $itsOK=1;\r
-                                       for($n=0; $n<$numParams; $n++)\r
-                                       {\r
-                                               if (is_object($in))\r
-                                               {\r
-                                                       $p=$in->getParam($n);\r
-                                                       if($p->kindOf() == 'scalar')\r
-                                                       {\r
-                                                               $pt=$p->scalartyp();\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               $pt=$p->kindOf();\r
-                                                       }\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...\r
-                                               }\r
-\r
-                                               // param index is $n+1, as first member of sig is return type\r
-                                               if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue'])\r
-                                               {\r
-                                                       $itsOK=0;\r
-                                                       $pno=$n+1;\r
-                                                       $wanted=$cursig[$n+1];\r
-                                                       $got=$pt;\r
-                                                       break;\r
-                                               }\r
-                                       }\r
-                                       if($itsOK)\r
-                                       {\r
-                                               return array(1,'');\r
-                                       }\r
-                               }\r
-                       }\r
-                       if(isset($wanted))\r
-                       {\r
-                               return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");\r
-                       }\r
-                       else\r
-                       {\r
-                               return array(0, "No method signature matches number of parameters");\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * Parse http headers received along with xmlrpc request. If needed, inflate request\r
-               * @return mixed null on success or an xmlrpcresp\r
-               * @access private\r
-               */\r
-               function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)\r
-               {\r
-                       // check if $_SERVER is populated: it might have been disabled via ini file\r
-                       // (this is true even when in CLI mode)\r
-                       if (count($_SERVER) == 0)\r
-                       {\r
-                               error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');\r
-                       }\r
-\r
-                       if($this->debug > 1)\r
-                       {\r
-                               if(function_exists('getallheaders'))\r
-                               {\r
-                                       $this->debugmsg(''); // empty line\r
-                                       foreach(getallheaders() as $name => $val)\r
-                                       {\r
-                                               $this->debugmsg("HEADER: $name: $val");\r
-                                       }\r
-                               }\r
-\r
-                       }\r
-\r
-                       if(isset($_SERVER['HTTP_CONTENT_ENCODING']))\r
-                       {\r
-                               $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);\r
-                       }\r
-                       else\r
-                       {\r
-                               $content_encoding = '';\r
-                       }\r
-\r
-                       // check if request body has been compressed and decompress it\r
-                       if($content_encoding != '' && strlen($data))\r
-                       {\r
-                               if($content_encoding == 'deflate' || $content_encoding == 'gzip')\r
-                               {\r
-                                       // if decoding works, use it. else assume data wasn't gzencoded\r
-                                       if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))\r
-                                       {\r
-                                               if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))\r
-                                               {\r
-                                                       $data = $degzdata;\r
-                                                       if($this->debug > 1)\r
-                                                       {\r
-                                                               $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");\r
-                                                       }\r
-                                               }\r
-                                               elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))\r
-                                               {\r
-                                                       $data = $degzdata;\r
-                                                       if($this->debug > 1)\r
-                                                               $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']);\r
-                                                       return $r;\r
-                                               }\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');\r
-                                               $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']);\r
-                                               return $r;\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       // check if client specified accepted charsets, and if we know how to fulfill\r
-                       // the request\r
-                       if ($this->response_charset_encoding == 'auto')\r
-                       {\r
-                               $resp_encoding = '';\r
-                               if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))\r
-                               {\r
-                                       // here we should check if we can match the client-requested encoding\r
-                                       // with the encodings we know we can generate.\r
-                                       /// @todo we should parse q=0.x preferences instead of getting first charset specified...\r
-                                       $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));\r
-                                       // Give preference to internal encoding\r
-                                       $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII');\r
-                                       foreach ($known_charsets as $charset)\r
-                                       {\r
-                                               foreach ($client_accepted_charsets as $accepted)\r
-                                                       if (strpos($accepted, $charset) === 0)\r
-                                                       {\r
-                                                               $resp_encoding = $charset;\r
-                                                               break;\r
-                                                       }\r
-                                               if ($resp_encoding)\r
-                                                       break;\r
-                                       }\r
-                               }\r
-                       }\r
-                       else\r
-                       {\r
-                               $resp_encoding = $this->response_charset_encoding;\r
-                       }\r
-\r
-                       if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))\r
-                       {\r
-                               $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];\r
-                       }\r
-                       else\r
-                       {\r
-                               $resp_compression = '';\r
-                       }\r
-\r
-                       // 'guestimate' request encoding\r
-                       /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???\r
-                       $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',\r
-                               $data);\r
-\r
-                       return null;\r
-               }\r
-\r
-               /**\r
-               * Parse an xml chunk containing an xmlrpc request and execute the corresponding\r
-               * php function registered with the server\r
-               * @param string $data the xml request\r
-               * @param string $req_encoding (optional) the charset encoding of the xml request\r
-               * @return xmlrpcresp\r
-               * @access private\r
-               */\r
-               function parseRequest($data, $req_encoding='')\r
-               {\r
-                       // 2005/05/07 commented and moved into caller function code\r
-                       //if($data=='')\r
-                       //{\r
-                       //      $data=$GLOBALS['HTTP_RAW_POST_DATA'];\r
-                       //}\r
-\r
-                       // G. Giunta 2005/02/13: we do NOT expect to receive html entities\r
-                       // so we do not try to convert them into xml character entities\r
-                       //$data = xmlrpc_html_entity_xlate($data);\r
-\r
-                       $GLOBALS['_xh']=array();\r
-                       $GLOBALS['_xh']['ac']='';\r
-                       $GLOBALS['_xh']['stack']=array();\r
-                       $GLOBALS['_xh']['valuestack'] = array();\r
-                       $GLOBALS['_xh']['params']=array();\r
-                       $GLOBALS['_xh']['pt']=array();\r
-                       $GLOBALS['_xh']['isf']=0;\r
-                       $GLOBALS['_xh']['isf_reason']='';\r
-                       $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not\r
-                       $GLOBALS['_xh']['rt']='';\r
-\r
-                       // decompose incoming XML into request structure\r
-                       if ($req_encoding != '')\r
-                       {\r
-                               if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                               // the following code might be better for mb_string enabled installs, but\r
-                               // makes the lib about 200% slower...\r
-                               //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                               {\r
-                                       error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding);\r
-                                       $req_encoding = $GLOBALS['xmlrpc_defencoding'];\r
-                               }\r
-                               /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,\r
-                               // the encoding is not UTF8 and there are non-ascii chars in the text...\r
-                               /// @todo use an empty string for php 5 ???\r
-                               $parser = xml_parser_create($req_encoding);\r
-                       }\r
-                       else\r
-                       {\r
-                               $parser = xml_parser_create();\r
-                       }\r
-\r
-                       xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);\r
-                       // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell\r
-                       // the xml parser to give us back data in the expected charset\r
-                       // What if internal encoding is not in one of the 3 allowed?\r
-                       // we use the broadest one, ie. utf8\r
-                       // This allows to send data which is native in various charset,\r
-                       // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding\r
-                       if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))\r
-                       {\r
-                               xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');\r
-                       }\r
-                       else\r
-                       {\r
-                               xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);\r
-                       }\r
-\r
-                       if ($this->functions_parameters_type != 'xmlrpcvals')\r
-                               xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');\r
-                       else\r
-                               xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');\r
-                       xml_set_character_data_handler($parser, 'xmlrpc_cd');\r
-                       xml_set_default_handler($parser, 'xmlrpc_dh');\r
-                       if(!xml_parse($parser, $data, 1))\r
-                       {\r
-                               // return XML error as a faultCode\r
-                               $r=new xmlrpcresp(0,\r
-                               $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser),\r
-                               sprintf('XML error: %s at line %d, column %d',\r
-                                       xml_error_string(xml_get_error_code($parser)),\r
-                                       xml_get_current_line_number($parser), xml_get_current_column_number($parser)));\r
-                               xml_parser_free($parser);\r
-                       }\r
-                       elseif ($GLOBALS['_xh']['isf'])\r
-                       {\r
-                               xml_parser_free($parser);\r
-                               $r=new xmlrpcresp(0,\r
-                                       $GLOBALS['xmlrpcerr']['invalid_request'],\r
-                                       $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']);\r
-                       }\r
-                       else\r
-                       {\r
-                               xml_parser_free($parser);\r
-                               // small layering violation in favor of speed and memory usage:\r
-                               // we should allow the 'execute' method handle this, but in the\r
-                               // most common scenario (xmlrpcvals type server with some methods\r
-                               // registered as phpvals) that would mean a useless encode+decode pass\r
-                               if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals')))\r
-                               {\r
-                                       if($this->debug > 1)\r
-                                       {\r
-                                               $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++");\r
-                                       }\r
-                                       $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       // build an xmlrpcmsg object with data parsed from xml\r
-                                       $m=new xmlrpcmsg($GLOBALS['_xh']['method']);\r
-                                       // now add parameters in\r
-                                       for($i=0; $i<count($GLOBALS['_xh']['params']); $i++)\r
-                                       {\r
-                                               $m->addParam($GLOBALS['_xh']['params'][$i]);\r
-                                       }\r
-\r
-                                       if($this->debug > 1)\r
-                                       {\r
-                                               $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");\r
-                                       }\r
-                                       $r = $this->execute($m);\r
-                               }\r
-                       }\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * Execute a method invoked by the client, checking parameters used\r
-               * @param mixed $m either an xmlrpcmsg obj or a method name\r
-               * @param array $params array with method parameters as php types (if m is method name only)\r
-               * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)\r
-               * @return xmlrpcresp\r
-               * @access private\r
-               */\r
-               function execute($m, $params=null, $paramtypes=null)\r
-               {\r
-                       if (is_object($m))\r
-                       {\r
-                               $methName = $m->method();\r
-                       }\r
-                       else\r
-                       {\r
-                               $methName = $m;\r
-                       }\r
-                       $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);\r
-                       $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap;\r
-\r
-                       if(!isset($dmap[$methName]['function']))\r
-                       {\r
-                               // No such method\r
-                               return new xmlrpcresp(0,\r
-                                       $GLOBALS['xmlrpcerr']['unknown_method'],\r
-                                       $GLOBALS['xmlrpcstr']['unknown_method']);\r
-                       }\r
-\r
-                       // Check signature\r
-                       if(isset($dmap[$methName]['signature']))\r
-                       {\r
-                               $sig = $dmap[$methName]['signature'];\r
-                               if (is_object($m))\r
-                               {\r
-                                       list($ok, $errstr) = $this->verifySignature($m, $sig);\r
-                               }\r
-                               else\r
-                               {\r
-                                       list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);\r
-                               }\r
-                               if(!$ok)\r
-                               {\r
-                                       // Didn't match.\r
-                                       return new xmlrpcresp(\r
-                                               0,\r
-                                               $GLOBALS['xmlrpcerr']['incorrect_params'],\r
-                                               $GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}"\r
-                                       );\r
-                               }\r
-                       }\r
-\r
-                       $func = $dmap[$methName]['function'];\r
-                       // let the 'class::function' syntax be accepted in dispatch maps\r
-                       if(is_string($func) && strpos($func, '::'))\r
-                       {\r
-                               $func = explode('::', $func);\r
-                       }\r
-                       // verify that function to be invoked is in fact callable\r
-                       if(!is_callable($func))\r
-                       {\r
-                               error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");\r
-                               return new xmlrpcresp(\r
-                                       0,\r
-                                       $GLOBALS['xmlrpcerr']['server_error'],\r
-                                       $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"\r
-                               );\r
-                       }\r
-\r
-                       // If debug level is 3, we should catch all errors generated during\r
-                       // processing of user function, and log them as part of response\r
-                       if($this->debug > 2)\r
-                       {\r
-                               $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');\r
-                       }\r
-                       try\r
-                       {\r
-                               // Allow mixed-convention servers\r
-                               if (is_object($m))\r
-                               {\r
-                                       if($sysCall)\r
-                                       {\r
-                                               $r = call_user_func($func, $this, $m);\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               $r = call_user_func($func, $m);\r
-                                       }\r
-                                       if (!is_a($r, 'xmlrpcresp'))\r
-                                       {\r
-                                               error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object");\r
-                                               if (is_a($r, 'xmlrpcval'))\r
-                                               {\r
-                                                       $r = new xmlrpcresp($r);\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $r = new xmlrpcresp(\r
-                                                               0,\r
-                                                               $GLOBALS['xmlrpcerr']['server_error'],\r
-                                                               $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object"\r
-                                                       );\r
-                                               }\r
-                                       }\r
-                               }\r
-                               else\r
-                               {\r
-                                       // call a 'plain php' function\r
-                                       if($sysCall)\r
-                                       {\r
-                                               array_unshift($params, $this);\r
-                                               $r = call_user_func_array($func, $params);\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               // 3rd API convention for method-handling functions: EPI-style\r
-                                               if ($this->functions_parameters_type == 'epivals')\r
-                                               {\r
-                                                       $r = call_user_func_array($func, array($methName, $params, $this->user_data));\r
-                                                       // mimic EPI behaviour: if we get an array that looks like an error, make it\r
-                                                       // an eror response\r
-                                                       if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))\r
-                                                       {\r
-                                                               $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']);\r
-                                                       }\r
-                                                       else\r
-                                                       {\r
-                                                               // functions using EPI api should NOT return resp objects,\r
-                                                               // so make sure we encode the return type correctly\r
-                                                               $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api')));\r
-                                                       }\r
-                                               }\r
-                                               else\r
-                                               {\r
-                                                       $r = call_user_func_array($func, $params);\r
-                                               }\r
-                                       }\r
-                                       // the return type can be either an xmlrpcresp object or a plain php value...\r
-                                       if (!is_a($r, 'xmlrpcresp'))\r
-                                       {\r
-                                               // what should we assume here about automatic encoding of datetimes\r
-                                               // and php classes instances???\r
-                                               $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options));\r
-                                       }\r
-                               }\r
-                       }\r
-                       catch(Exception $e)\r
-                       {\r
-                               // (barring errors in the lib) an uncatched exception happened\r
-                               // in the called function, we wrap it in a proper error-response\r
-                               switch($this->exception_handling)\r
-                               {\r
-                                       case 2:\r
-                                               throw $e;\r
-                                               break;\r
-                                       case 1:\r
-                                               $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage());\r
-                                               break;\r
-                                       default:\r
-                                               $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']);\r
-                               }\r
-                       }\r
-                       if($this->debug > 2)\r
-                       {\r
-                               // note: restore the error handler we found before calling the\r
-                               // user func, even if it has been changed inside the func itself\r
-                               if($GLOBALS['_xmlrpcs_prev_ehandler'])\r
-                               {\r
-                                       set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);\r
-                               }\r
-                               else\r
-                               {\r
-                                       restore_error_handler();\r
-                               }\r
-                       }\r
-                       return $r;\r
-               }\r
-\r
-               /**\r
-               * add a string to the 'internal debug message' (separate from 'user debug message')\r
-               * @param string $string\r
-               * @access private\r
-               */\r
-               function debugmsg($string)\r
-               {\r
-                       $this->debug_info .= $string."\n";\r
-               }\r
-\r
-               /**\r
-               * @access private\r
-               */\r
-               function xml_header($charset_encoding='')\r
-               {\r
-                       if ($charset_encoding != '')\r
-                       {\r
-                               return "<?xml version=\"1.0\" encoding=\"$charset_encoding\"?" . ">\n";\r
-                       }\r
-                       else\r
-                       {\r
-                               return "<?xml version=\"1.0\"?" . ">\n";\r
-                       }\r
-               }\r
-\r
-               /**\r
-               * A debugging routine: just echoes back the input packet as a string value\r
-               * DEPRECATED!\r
-               */\r
-               function echoInput()\r
-               {\r
-                       $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));\r
-                       print $r->serialize();\r
-               }\r
-       }\r
-?>
\ No newline at end of file
+<?php
+// by Edd Dumbill (C) 1999-2002
+// <edd@usefulinc.com>
+
+// Copyright (c) 1999,2000,2002 Edd Dumbill.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//    * Redistributions of source code must retain the above copyright
+//      notice, this list of conditions and the following disclaimer.
+//
+//    * Redistributions in binary form must reproduce the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer in the documentation and/or other materials provided
+//      with the distribution.
+//
+//    * Neither the name of the "XML-RPC for PHP" nor the names of its
+//      contributors may be used to endorse or promote products derived
+//      from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+// OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/******************************************************************************
+ *
+ * *** DEPRECATED ***
+ *
+ * This file is only used to insure backwards compatibility
+ * with the API of the library <= rev. 3
+ *****************************************************************************/
+
+include_once(__DIR__.'/../src/Server.php');
+
+class xmlrpc_server extends PhpXmlRpc\Server
+{
+    /**
+     * A debugging routine: just echoes back the input packet as a string value
+     * @deprecated
+     */
+    public function echoInput()
+    {
+        $r = new Response(new PhpXmlRpc\Value("'Aha said I: '" . file_get_contents('php://input'), 'string'));
+        print $r->serialize();
+    }
+}
+
+/* Expose as global functions the ones which are now class methods */
+
+/**
+ * @see PhpXmlRpc\Server::xmlrpc_debugmsg
+ * @param string $m
+ */
+function xmlrpc_debugmsg($m)
+{
+    PhpXmlRpc\Server::xmlrpc_debugmsg($m);
+}
+
+function _xmlrpcs_getCapabilities($server, $m=null)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_getCapabilities($server, $m);
+}
+
+$_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray']));
+$_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch';
+$_xmlrpcs_listMethods_sdoc=array(array('list of method names'));
+function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
+{
+    return PhpXmlRpc\Server::_xmlrpcs_listMethods($server, $m);
+}
+
+$_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString']));
+$_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)';
+$_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described'));
+function _xmlrpcs_methodSignature($server, $m)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_methodSignature($server, $m);
+}
+
+$_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString']));
+$_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string';
+$_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described'));
+function _xmlrpcs_methodHelp($server, $m)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_methodHelp($server, $m);
+}
+
+function _xmlrpcs_multicall_error($err)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_multicall_error($err);
+}
+
+function _xmlrpcs_multicall_do_call($server, $call)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call($server, $call);
+}
+
+function _xmlrpcs_multicall_do_call_phpvals($server, $call)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_multicall_do_call_phpvals($server, $call);
+}
+
+$_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray']));
+$_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';
+$_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"'));
+function _xmlrpcs_multicall($server, $m)
+{
+    return PhpXmlRpc\Server::_xmlrpcs_multicall($server, $m);
+}
diff --git a/license.txt b/license.txt
new file mode 100644 (file)
index 0000000..37313ac
--- /dev/null
@@ -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/pakefile.php b/pakefile.php
new file mode 100644 (file)
index 0000000..74bcba8
--- /dev/null
@@ -0,0 +1,380 @@
+<?php
+/**
+ * Makefile for phpxmlrpc library.
+ * To be used with the Pake tool: https://github.com/indeyets/pake/wiki
+ *
+ * @copyright (c) 2015 G. Giunta
+ *
+ * @todo !important allow user to specify location of docbook xslt instead of the one installed via composer
+ */
+
+namespace PhpXmlRpc {
+
+class Builder
+{
+    protected static $buildDir = 'build';
+    protected static $libVersion;
+    protected static $tools = array(
+        'asciidoctor' => 'asciidoctor',
+        'fop' => 'fop',
+        'php' => 'php',
+        'zip' => 'zip',
+    );
+    protected static $options = array(
+        'repo' => 'https://github.com/gggeek/phpxmlrpc',
+        'branch' => 'php53'
+    );
+
+    public static function libVersion()
+    {
+        if (self::$libVersion == null)
+            throw new \Exception('Missing library version argument');
+        return self::$libVersion;
+    }
+
+    public static function buildDir()
+    {
+        return self::$buildDir;
+    }
+
+    public static function workspaceDir()
+    {
+        return self::buildDir().'/workspace';
+    }
+
+    /// most likely things will break if this one is moved outside of BuildDir
+    public static function distDir()
+    {
+        return self::buildDir().'/xmlrpc-'.self::libVersion();
+    }
+
+    /// these will be generated in BuildDir
+    public static function distFiles()
+    {
+        return array(
+            'xmlrpc-'.self::libVersion().'.tar.gz',
+            'xmlrpc-'.self::libVersion().'.zip',
+        );
+    }
+
+    public static function getOpts($args=array(), $cliOpts=array())
+    {
+        if (count($args) > 0)
+        //    throw new \Exception('Missing library version argument');
+            self::$libVersion = $args[0];
+
+        foreach (self::$tools as $name => $binary) {
+            if (isset($cliOpts[$name])) {
+                self::$tools[$name] = $cliOpts[$name];
+            }
+        }
+
+        foreach (self::$options as $name => $value) {
+            if (isset($cliOpts[$name])) {
+                self::$options[$name] = $cliOpts[$name];
+            }
+        }
+
+        //pake_echo('---'.self::$libVersion.'---');
+    }
+
+    /**
+     * @param string $name
+     * @return string
+     */
+    public static function tool($name)
+    {
+        return self::$tools[$name];
+    }
+
+    /**
+     * @param string $name
+     * @return string
+     */
+    public static function option($name)
+    {
+        return self::$options[$name];
+    }
+
+    /**
+     * @param string $inFile
+     * @param string $xssFile
+     * @param string $outFileOrDir
+     * @throws \Exception
+     */
+    public static function applyXslt($inFile, $xssFile, $outFileOrDir)
+    {
+
+        if (!file_exists($inFile)) {
+            throw new \Exception("File $inFile cannot be found");
+        }
+        if (!file_exists($xssFile)) {
+            throw new \Exception("File $xssFile cannot be found");
+        }
+
+        // Load the XML source
+        $xml = new \DOMDocument();
+        $xml->load($inFile);
+        $xsl = new \DOMDocument();
+        $xsl->load($xssFile);
+
+        // Configure the transformer
+        $processor = new \XSLTProcessor();
+        if (version_compare(PHP_VERSION, '5.4', "<")) {
+            if (defined('XSL_SECPREF_WRITE_FILE')) {
+                ini_set("xsl.security_prefs", XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
+            }
+        } else {
+            // the php online docs only mention setSecurityPrefs, but somehow some installs have setSecurityPreferences...
+            if (method_exists('XSLTProcessor', 'setSecurityPrefs')) {
+                $processor->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
+            } else {
+                $processor->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
+            }
+        }
+        $processor->importStyleSheet($xsl); // attach the xsl rules
+
+        if (is_dir($outFileOrDir)) {
+            if (!$processor->setParameter('', 'base.dir', realpath($outFileOrDir))) {
+                echo "setting param base.dir KO\n";
+            }
+        }
+
+        $out = $processor->transformToXML($xml);
+
+        if (!is_dir($outFileOrDir)) {
+            file_put_contents($outFileOrDir, $out);
+        }
+    }
+
+    public static function highlightPhpInHtml($content)
+    {
+        $startTag = '<pre class="programlisting">';
+        $endTag = '</pre>';
+
+        //$content = file_get_contents($inFile);
+        $last = 0;
+        $out = '';
+        while (($start = strpos($content, $startTag, $last)) !== false) {
+            $end = strpos($content, $endTag, $start);
+            $code = substr($content, $start + strlen($startTag), $end - $start - strlen($startTag));
+            if ($code[strlen($code) - 1] == "\n") {
+                $code = substr($code, 0, -1);
+            }
+
+            $code = str_replace(array('&gt;', '&lt;'), array('>', '<'), $code);
+            $code = highlight_string('<?php ' . $code, true);
+            $code = str_replace('<span style="color: #0000BB">&lt;?php&nbsp;<br />', '<span style="color: #0000BB">', $code);
+
+            $out = $out . substr($content, $last, $start + strlen($startTag) - $last) . $code . $endTag;
+            $last = $end + strlen($endTag);
+        }
+        $out .= substr($content, $last, strlen($content));
+
+        return $out;
+    }
+}
+
+}
+
+namespace {
+
+use PhpXmlRpc\Builder;
+
+function run_default($task=null, $args=array(), $cliOpts=array())
+{
+    echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag] {\$task-options}\n";
+    echo "\n";
+    echo "  Run 'pake help' to list all pake options\n";
+    echo "  Run 'pake -T' to list available tasks\n";
+    echo "  Run 'pake -P' to list all available tasks (including hidden ones) and their dependencies\n";
+    echo "\n";
+    echo "  Task options:\n";
+    echo "      --repo=REPO      URL of the source repository to clone. Defaults to the github repo.\n";
+    echo "      --branch=BRANCH  The git branch to build from.\n";
+    echo "      --asciidoctor=ASCIIDOCTOR Location of the asciidoctor command-line tool\n";
+    echo "      --fop=FOP        Location of the apache fop command-line tool\n";
+    echo "      --php=PHP        Location of the php command-line interpreter\n";
+    echo "      --zip=ZIP        Location of the zip tool\n";
+}
+
+function run_getopts($task=null, $args=array(), $cliOpts=array())
+{
+    Builder::getOpts($args, $cliOpts);
+}
+
+/**
+ * Downloads source code in the build workspace directory, optionally checking out the given branch/tag
+ */
+function run_init($task=null, $args=array(), $cliOpts=array())
+{
+    // download the current version into the workspace
+    $targetDir = Builder::workspaceDir();
+
+    // check if workspace exists and is not already set to the correct repo
+    if (is_dir($targetDir) && pakeGit::isRepository($targetDir)) {
+        $repo = new pakeGit($targetDir);
+        $remotes = $repo->remotes();
+        if (trim($remotes['origin']['fetch']) != Builder::option('repo')) {
+            throw new Exception("Directory '$targetDir' exists and is not linked to correct git repo");
+        }
+
+        /// @todo should we not just fetch instead?
+        $repo->pull();
+    } else {
+        pake_mkdirs(dirname($targetDir));
+        $repo = pakeGit::clone_repository(Builder::option('repo'), Builder::workspaceDir());
+    }
+
+    $repo->checkout(Builder::option('branch'));
+}
+
+/**
+ * Runs all the build steps.
+ *
+ * (does nothing by itself, as all the steps are managed via task dependencies)
+ */
+function run_build($task=null, $args=array(), $cliOpts=array())
+{
+}
+
+function run_clean_doc()
+{
+    pake_remove_dir(Builder::workspaceDir().'/doc/api');
+    $finder = pakeFinder::type('file')->name('*.html');
+    pake_remove($finder, Builder::workspaceDir().'/doc/manual');
+    $finder = pakeFinder::type('file')->name('*.xml');
+    pake_remove($finder, Builder::workspaceDir().'/doc/manual');
+}
+
+/**
+ * Generates documentation in all formats
+ */
+function run_doc($task=null, $args=array(), $cliOpts=array())
+{
+    $docDir = Builder::workspaceDir().'/doc';
+
+    // API docs
+
+    // from phpdoc comments using phpdocumentor
+    $cmd = Builder::tool('php');
+    pake_sh("$cmd vendor/phpdocumentor/phpdocumentor/bin/phpdoc run -d ".Builder::workspaceDir().'/src'." -t ".Builder::workspaceDir().'/doc/api --title PHP-XMLRPC');
+
+    // User Manual
+
+    // html (single file) from asciidoc
+    $cmd = Builder::tool('asciidoctor');
+    pake_sh("$cmd -d book $docDir/manual/phpxmlrpc_manual.adoc");
+
+    // then docbook from asciidoc
+    /// @todo create phpxmlrpc_manual.xml with the good version number
+    /// @todo create phpxmlrpc_manual.xml with the date set to the one of last commit (or today?)
+    pake_sh("$cmd -d book  -b docbook $docDir/manual/phpxmlrpc_manual.adoc");
+
+    # Other tools for docbook...
+    #
+    # jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g.
+    #  jade -t xml -d custom.dsl xmlrpc_php.xml
+    #
+    # convertdoc command for xmlmind xxe editor
+    #  convertdoc docb.toHTML xmlrpc_php.xml -u out
+    #
+    # saxon + xerces xml parser + saxon extensions + xslthl: adds a little syntax highligting
+    # (bold and italics only, no color) for php source examples...
+    #  java \
+    #  -classpath c:\programmi\saxon\saxon.jar\;c:\programmi\saxon\xslthl.jar\;c:\programmi\xerces\xercesImpl.jar\;C:\htdocs\xmlrpc_cvs\docbook-xsl\extensions\saxon65.jar \
+    #  -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \
+    #  -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \
+    #  -Dxslthl.config=file:///c:/htdocs/xmlrpc_cvs/docbook-xsl/highlighting/xslthl-config.xml \
+    #  com.icl.saxon.StyleSheet -o xmlrpc_php.fo.xml xmlrpc_php.xml custom.fo.xsl use.extensions=1
+
+    // HTML (multiple files) from docbook - discontinued, as we use the nicer-looking html gotten from asciidoc
+    /*Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.xsl', $docDir.'/manual');
+    // post process html files to highlight php code samples
+    foreach(pakeFinder::type('file')->name('*.html')->in($docDir.'/manual') as $file)
+    {
+        file_put_contents($file, Builder::highlightPhpInHtml(file_get_contents($file)));
+    }*/
+
+    // PDF file from docbook
+
+    // convert to fo and then to pdf using apache fop
+    Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.fo.xsl', $docDir.'/manual/phpxmlrpc_manual.fo.xml');
+    $cmd = Builder::tool('fop');
+    pake_sh("$cmd $docDir/manual/phpxmlrpc_manual.fo.xml $docDir/manual/phpxmlrpc_manual.pdf");
+
+    // cleanup
+    unlink($docDir.'/manual/phpxmlrpc_manual.xml');
+    unlink($docDir.'/manual/phpxmlrpc_manual.fo.xml');
+}
+
+function run_clean_dist()
+{
+    pake_remove_dir(Builder::distDir());
+    $finder = pakeFinder::type('file')->name(Builder::distFiles());
+    pake_remove($finder, Builder::buildDir());
+}
+
+/**
+ * Creates the tarballs for a release
+ */
+function run_dist($task=null, $args=array(), $cliOpts=array())
+{
+    // copy workspace dir into dist dir, without git
+    pake_mkdirs(Builder::distDir());
+    $finder = pakeFinder::type('any')->ignore_version_control();
+    pake_mirror($finder, realpath(Builder::workspaceDir()), realpath(Builder::distDir()));
+
+    // remove unwanted files from dist dir
+
+    // also: do we still need to run dos2unix?
+
+    // create tarballs
+    $cwd = getcwd();
+    chdir(dirname(Builder::distDir()));
+    foreach(Builder::distFiles() as $distFile) {
+        // php can not really create good zip files via phar: they are not compressed!
+        if (substr($distFile, -4) == '.zip') {
+            $cmd = Builder::tool('zip');
+            $extra = '-9 -r';
+            pake_sh("$cmd $distFile $extra ".basename(Builder::distDir()));
+        }
+        else {
+            $finder = pakeFinder::type('any')->pattern(basename(Builder::distDir()).'/**');
+            // see https://bugs.php.net/bug.php?id=58852
+            $pharFile = str_replace(Builder::libVersion(), '_LIBVERSION_', $distFile);
+            pakeArchive::createArchive($finder, '.', $pharFile);
+            rename($pharFile, $distFile);
+        }
+    }
+    chdir($cwd);
+}
+
+function run_clean_workspace($task=null, $args=array(), $cliOpts=array())
+{
+    pake_remove_dir(Builder::workspaceDir());
+}
+
+/**
+ * Cleans up the whole build directory
+ * @todo 'make clean' usually just removes the results of the build, distclean removes all but sources
+ */
+function run_clean($task=null, $args=array(), $cliOpts=array())
+{
+    pake_remove_dir(Builder::buildDir());
+}
+
+// helper task: display help text
+pake_task( 'default' );
+// internal task: parse cli options
+pake_task('getopts');
+pake_task('init', 'getopts');
+pake_task('doc', 'getopts', 'init', 'clean-doc');
+pake_task('build', 'getopts', 'init', 'doc');
+pake_task('dist', 'getopts', 'init', 'build', 'clean-dist');
+pake_task('clean-doc', 'getopts');
+pake_task('clean-dist', 'getopts');
+pake_task('clean-workspace', 'getopts');
+pake_task('clean', 'getopts');
+
+}
diff --git a/src/Autoloader.php b/src/Autoloader.php
new file mode 100644 (file)
index 0000000..40ec219
--- /dev/null
@@ -0,0 +1,36 @@
+<?php
+
+namespace PhpXmlRpc;
+
+/**
+ * In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
+ * For usage, see any file in the demo/client directory
+ */
+class Autoloader
+{
+    /**
+     * Registers PhpXmlRpc\Autoloader as an SPL autoloader.
+     *
+     * @param bool $prepend Whether to prepend the autoloader or not.
+     */
+    public static function register($prepend = false)
+    {
+        spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
+    }
+
+    /**
+     * Handles autoloading of classes.
+     *
+     * @param string $class A class name.
+     */
+    public static function autoload($class)
+    {
+        if (0 !== strpos($class, 'PhpXmlRpc\\')) {
+            return;
+        }
+
+        if (is_file($file = __DIR__ . str_replace(array('PhpXmlRpc\\', '\\'), '/', $class).'.php')) {
+            require $file;
+        }
+    }
+}
diff --git a/src/Client.php b/src/Client.php
new file mode 100644 (file)
index 0000000..8fce704
--- /dev/null
@@ -0,0 +1,1090 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\Logger;
+
+class Client
+{
+    /// @todo: do these need to be public?
+    public $method = 'http';
+    public $server;
+    public $port = 0;
+    public $path;
+
+    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 $sslversion = 0; // corresponds to CURL_SSLVERSION_DEFAULT
+
+    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.
+     *
+     * 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
+     */
+    public $accepted_compression = array();
+    /**
+     * Name of compression scheme to be used for sending requests.
+     * 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).
+     */
+    public $xmlrpc_curl_handle = null;
+    /// Whether to use persistent connections for http 1.1 and https
+    public $keepalive = false;
+    /// Charset encodings that can be decoded without problems by the client
+    public $accepted_charset_encodings = array();
+    /// Charset encoding to be used in serializing request. NULL = use ASCII
+    public $request_charset_encoding = '';
+    /**
+     * Decides the content of Response objects returned by calls to send()
+     * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'.
+     */
+    public $return_type = 'xmlrpcvals';
+    /**
+     * Sent to servers in http headers.
+     */
+    public $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
+     */
+    public function __construct($path, $server = '', $port = '', $method = '')
+    {
+        // 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');
+
+        // 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;
+    }
+
+    /**
+     * 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;
+    }
+
+    /**
+     * 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;
+        $this->authtype = $t;
+    }
+
+    /**
+     * 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 $isDir set to true to indicate cacert is a dir. defaults to false
+     */
+    public function setCaCertificate($caCert, $isDir = false)
+    {
+        if ($isDir) {
+            $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
+     */
+    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
+     */
+    public function setSSLVerifyPeer($i)
+    {
+        $this->verifypeer = $i;
+    }
+
+    /**
+     * Set attributes for SSL communication: verify match of server cert w. hostname.
+     *
+     * @param int $i
+     */
+    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.
+     *
+     * @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;
+        $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 ''
+     */
+    public function setAcceptedCompression($compMethod)
+    {
+        if ($compMethod == 'any') {
+            $this->accepted_compression = array('gzip', 'deflate');
+        } 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).
+     *
+     * @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
+     *
+     * @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) {
+            $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
+     */
+    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.
+     *
+     * @param string $agentString
+     */
+    public function SetUserAgent($agentString)
+    {
+        $this->user_agent = $agentString;
+    }
+
+    /**
+     * Send an xmlrpc 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|Response[]
+     */
+    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)
+        if ($method == '') {
+            $method = $this->method;
+        }
+
+        if (is_array($req)) {
+            // $req is an array of Requests
+            $r = $this->multicall($req, $timeout, $method);
+
+            return $r;
+        } elseif (is_string($req)) {
+            $n = new Request('');
+            $n->payload = $req;
+            $req = $n;
+        }
+
+        // where req is a Request
+        $req->setDebug($this->debug);
+
+        if ($method == 'https') {
+            $r = $this->sendPayloadHTTPS(
+                $req,
+                $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,
+                $this->sslversion
+            );
+        } elseif ($method == 'http11') {
+            $r = $this->sendPayloadCURL(
+                $req,
+                $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(
+                $req,
+                $this->server,
+                $this->port,
+                $timeout,
+                $this->username,
+                $this->password,
+                $this->authtype,
+                $this->proxy,
+                $this->proxyport,
+                $this->proxy_user,
+                $this->proxy_pass,
+                $this->proxy_authtype,
+                $method
+            );
+        }
+
+        return $r;
+    }
+
+    /**
+     * @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
+     * @param string $method
+     * @return Response
+     */
+    protected function sendPayloadHTTP10($req, $server, $port, $timeout = 0,
+                                       $username = '', $password = '', $authType = 1, $proxyHost = '',
+                                       $proxyPort = 0, $proxyUsername = '', $proxyPassword = '', $proxyAuthType = 1,
+                                       $method='http')
+    {
+        if ($port == 0) {
+            $port = ( $method === "https" ) ? 443 : 80;
+        }
+
+        // Only create the payload if it was not created previously
+        if (empty($req->payload)) {
+            $req->createPayload($this->request_charset_encoding);
+        }
+
+        $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;
+                    $encodingHdr = "Content-Encoding: gzip\r\n";
+                }
+            } else {
+                $a = @gzcompress($payload);
+                if ($a) {
+                    $payload = $a;
+                    $encodingHdr = "Content-Encoding: deflate\r\n";
+                }
+            }
+        } else {
+            $encodingHdr = '';
+        }
+
+        // thanks to Grant Rauscher <grant7@firstworld.net> 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');
+            }
+        }
+
+        $acceptedEncoding = '';
+        if (is_array($this->accepted_compression) && count($this->accepted_compression)) {
+            $acceptedEncoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
+        }
+
+        $proxyCredentials = '';
+        if ($proxyHost) {
+            if ($proxyPort == 0) {
+                $proxyPort = 8080;
+            }
+            $connectServer = $proxyHost;
+            $connectPort = $proxyPort;
+            $transport = "tcp";
+            $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');
+                }
+                $proxyCredentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyUsername . ':' . $proxyPassword) . "\r\n";
+            }
+        } 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;
+        }
+
+        // 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 .
+            $proxyCredentials .
+            $acceptedEncoding .
+            $encodingHdr .
+            'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
+            $cookieHeader .
+            'Content-Type: ' . $req->content_type . "\r\nContent-Length: " .
+            strlen($payload) . "\r\n\r\n" .
+            $payload;
+
+        if ($this->debug > 1) {
+            Logger::instance()->debugMessage("---SENDING---\n$op\n---END---");
+        }
+
+        if ($timeout > 0) {
+            $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr, $timeout);
+        } else {
+            $fp = @stream_socket_client("$transport://$connectServer:$connectPort", $this->errno, $this->errstr);
+        }
+        if ($fp) {
+            if ($timeout > 0) {
+                stream_set_timeout($fp, $timeout);
+            }
+        } 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))) {
+            fclose($fp);
+            $this->errstr = 'Write error';
+            $r = new Response(0, PhpXmlRpc::$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 = $req->parseResponse($ipd, false, $this->return_type);
+
+        return $r;
+    }
+
+    /**
+     * @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)
+    {
+        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 <justin@voxel.net>
+     * Requires curl to be built into PHP
+     * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
+     *
+     * @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 string $method
+     * @param bool $keepAlive
+     * @param string $key
+     * @param string $keyPass
+     * @param int $sslVersion
+     * @return Response
+     */
+    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)
+    {
+        if (!function_exists('curl_init')) {
+            $this->errstr = 'CURL unavailable on this install';
+            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';
+                return new Response(0, PhpXmlRpc::$xmlrpcerr['no_ssl'], PhpXmlRpc::$xmlrpcstr['no_ssl']);
+            }
+        }
+
+        if ($port == 0) {
+            if ($method == 'http') {
+                $port = 80;
+            } else {
+                $port = 443;
+            }
+        }
+
+        // Only create the payload if it was not created previously
+        if (empty($req->payload)) {
+            $req->createPayload($this->request_charset_encoding);
+        }
+
+        // Deflate request body and set appropriate request headers
+        $payload = $req->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;
+                    $encodingHdr = 'Content-Encoding: gzip';
+                }
+            } else {
+                $a = @gzcompress($payload);
+                if ($a) {
+                    $payload = $a;
+                    $encodingHdr = 'Content-Encoding: deflate';
+                }
+            }
+        } else {
+            $encodingHdr = '';
+        }
+
+        if ($this->debug > 1) {
+            Logger::instance()->debugMessage("---SENDING---\n$payload\n---END---");
+        }
+
+        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, true);
+
+        if ($this->debug > 1) {
+            curl_setopt($curl, CURLOPT_VERBOSE, true);
+            /// @todo allow callers to redirect curlopt_stderr to some stream which can be buffered
+        }
+        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: ' . $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';
+        }
+        // request compression header
+        if ($encodingHdr) {
+            $headers[] = $encodingHdr;
+        }
+
+        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);
+            } elseif ($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);
+            // allow usage of different SSL versions
+            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
+            }
+            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) {
+                    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) {
+            $message = "---CURL INFO---\n";
+            foreach (curl_getinfo($curl) as $name => $val) {
+                if (is_array($val)) {
+                    $val = implode("\n", $val);
+                }
+                $message .= $name . ': ' . $val . "\n";
+            }
+            $message .= "---END---";
+            Logger::instance()->debugMessage($message);
+        }
+
+        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) {
+                $this->xmlrpc_curl_handle = null;
+            }
+        } else {
+            if (!$keepAlive) {
+                curl_close($curl);
+            }
+            $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);
+                $this->xmlrpc_curl_handle = null;
+            }
+        }
+
+        return $resp;
+    }
+
+    /**
+     * 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.
+     * 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 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($reqs, $timeout = 0, $method = '', $fallback = true)
+    {
+        if ($method == '') {
+            $method = $this->method;
+        }
+        if (!$this->no_multicall) {
+            $results = $this->_try_multicall($reqs, $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, '\PhpXmlRpc\Response')) {
+                        $result = $results;
+                    } else {
+                        $result = new Response(0, PhpXmlRpc::$xmlrpcerr['multicall_error'], PhpXmlRpc::$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 ($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 ($reqs as $req) {
+                $results[] = $result;
+            }
+        }
+
+        return $results;
+    }
+
+    /**
+     * 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($reqs, $timeout, $method)
+    {
+        // Construct multicall request
+        $calls = array();
+        foreach ($reqs as $req) {
+            $call['methodName'] = new Value($req->method(), 'string');
+            $numParams = $req->getNumParams();
+            $params = array();
+            for ($i = 0; $i < $numParams; $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'));
+
+        // 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;
+        } elseif ($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($reqs)) {
+                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 Response($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 Response(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->count();
+            if ($numRets != count($reqs)) {
+                return false;       // wrong number of return values.
+            }
+
+            $response = array();
+            foreach($rets as $val) {
+                switch ($val->kindOf()) {
+                    case 'array':
+                        if ($val->count() != 1) {
+                            return false;       // Bad value
+                        }
+                        // Normal return value
+                        $response[] = new Response($val[0]);
+                        break;
+                    case 'struct':
+                        $code = $val['faultCode'];
+                        if ($code->kindOf() != 'scalar' || $code->scalartyp() != 'int') {
+                            return false;
+                        }
+                        $str = $val['faultString'];
+                        if ($str->kindOf() != 'scalar' || $str->scalartyp() != 'string') {
+                            return false;
+                        }
+                        $response[] = new Response(0, $code->scalarval(), $str->scalarval());
+                        break;
+                    default:
+                        return false;
+                }
+            }
+
+            return $response;
+        }
+    }
+}
diff --git a/src/Encoder.php b/src/Encoder.php
new file mode 100644 (file)
index 0000000..b9bdb08
--- /dev/null
@@ -0,0 +1,314 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\XMLParser;
+
+class Encoder
+{
+    /**
+     * Takes an xmlrpc value in object format and translates it into native PHP types.
+     *
+     * Works with xmlrpc requests objects as input, too.
+     *
+     * Given proper options parameter, can rebuild generic php object instances
+     * (provided those have been encoded to xmlrpc format using a corresponding
+     * option in php_xmlrpc_encode())
+     * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
+     * This means that the remote communication end can decide which php code will
+     * get executed on your server, leaving the door possibly open to 'php-injection'
+     * style of attacks (provided you have some classes defined on your server that
+     * might wreak havoc if instances are built outside an appropriate context).
+     * Make sure you trust the remote server/client before eanbling this!
+     *
+     * @author Dan Libby (dan@libby.com)
+     *
+     * @param Value|Request $xmlrpcVal
+     * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects; if 'dates_as_objects' is set xmlrpc datetimes are decoded as php DateTime objects (standard is
+     *
+     * @return mixed
+     */
+    public function decode($xmlrpcVal, $options = array())
+    {
+        switch ($xmlrpcVal->kindOf()) {
+            case 'scalar':
+                if (in_array('extension_api', $options)) {
+                    reset($xmlrpcVal->me);
+                    list($typ, $val) = each($xmlrpcVal->me);
+                    switch ($typ) {
+                        case 'dateTime.iso8601':
+                            $xmlrpcVal->scalar = $val;
+                            $xmlrpcVal->type = 'datetime';
+                            $xmlrpcVal->timestamp = \PhpXmlRpc\Helper\Date::iso8601Decode($val);
+
+                            return $xmlrpcVal;
+                        case 'base64':
+                            $xmlrpcVal->scalar = $val;
+                            $xmlrpcVal->type = $typ;
+
+                            return $xmlrpcVal;
+                        default:
+                            return $xmlrpcVal->scalarval();
+                    }
+                }
+                if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalartyp() == 'dateTime.iso8601') {
+                    // we return a Datetime object instead of a string
+                    // since now the constructor of xmlrpc value accepts safely strings, ints and datetimes,
+                    // we cater to all 3 cases here
+                    $out = $xmlrpcVal->scalarval();
+                    if (is_string($out)) {
+                        $out = strtotime($out);
+                    }
+                    if (is_int($out)) {
+                        $result = new \Datetime();
+                        $result->setTimestamp($out);
+
+                        return $result;
+                    } elseif (is_a($out, 'Datetime')) {
+                        return $out;
+                    }
+                }
+
+                return $xmlrpcVal->scalarval();
+            case 'array':
+                $arr = array();
+                foreach($xmlrpcVal as $value) {
+                    $arr[] = $this->decode($value, $options);
+                }
+
+                return $arr;
+            case 'struct':
+                // If user said so, try to rebuild php objects for specific struct vals.
+                /// @todo should we raise a warning for class not found?
+                // shall we check for proper subclass of xmlrpc value instead of
+                // presence of _php_class to detect what we can do?
+                if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
+                    && class_exists($xmlrpcVal->_php_class)
+                ) {
+                    $obj = @new $xmlrpcVal->_php_class();
+                    foreach ($xmlrpcVal as $key => $value) {
+                        $obj->$key = $this->decode($value, $options);
+                    }
+
+                    return $obj;
+                } else {
+                    $arr = array();
+                    foreach ($xmlrpcVal as $key => $value) {
+                        $arr[$key] = $this->decode($value, $options);
+                    }
+
+                    return $arr;
+                }
+            case 'msg':
+                $paramCount = $xmlrpcVal->getNumParams();
+                $arr = array();
+                for ($i = 0; $i < $paramCount; $i++) {
+                    $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
+                }
+
+                return $arr;
+        }
+    }
+
+    /**
+     * Takes native php types and encodes them into xmlrpc PHP object format.
+     * It will not re-encode xmlrpc value objects.
+     *
+     * Feature creep -- could support more types via optional type argument
+     * (string => datetime support has been added, ??? => base64 not yet)
+     *
+     * If given a proper options parameter, php object instances will be encoded
+     * into 'special' xmlrpc values, that can later be decoded into php objects
+     * by calling php_xmlrpc_decode() with a corresponding option
+     *
+     * @author Dan Libby (dan@libby.com)
+     *
+     * @param mixed $phpVal the value to be converted into an xmlrpc value object
+     * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
+     *
+     * @return \PhpXmlrpc\Value
+     */
+    public function encode($phpVal, $options = array())
+    {
+        $type = gettype($phpVal);
+        switch ($type) {
+            case 'string':
+                if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $phpVal)) {
+                    $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
+                } else {
+                    $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
+                }
+                break;
+            case 'integer':
+                $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
+                break;
+            case 'double':
+                $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
+                break;
+            // <G_Giunta_2001-02-29>
+            // Add support for encoding/decoding of booleans, since they are supported in PHP
+            case 'boolean':
+                $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
+                break;
+            // </G_Giunta_2001-02-29>
+            case 'array':
+                // PHP arrays can be encoded to either xmlrpc structs or arrays,
+                // depending on wheter they are hashes or plain 0..n integer indexed
+                // A shorter one-liner would be
+                // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
+                // but execution time skyrockets!
+                $j = 0;
+                $arr = array();
+                $ko = false;
+                foreach ($phpVal as $key => $val) {
+                    $arr[$key] = $this->encode($val, $options);
+                    if (!$ko && $key !== $j) {
+                        $ko = true;
+                    }
+                    $j++;
+                }
+                if ($ko) {
+                    $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
+                } else {
+                    $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
+                }
+                break;
+            case 'object':
+                if (is_a($phpVal, 'PhpXmlRpc\Value')) {
+                    $xmlrpcVal = $phpVal;
+                } elseif (is_a($phpVal, 'DateTime')) {
+                    $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcStruct);
+                } else {
+                    $arr = array();
+                    reset($phpVal);
+                    while (list($k, $v) = each($phpVal)) {
+                        $arr[$k] = $this->encode($v, $options);
+                    }
+                    $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
+                    if (in_array('encode_php_objs', $options)) {
+                        // let's save original class name into xmlrpc value:
+                        // might be useful later on...
+                        $xmlrpcVal->_php_class = get_class($phpVal);
+                    }
+                }
+                break;
+            case 'NULL':
+                if (in_array('extension_api', $options)) {
+                    $xmlrpcVal = new Value('', Value::$xmlrpcString);
+                } elseif (in_array('null_extension', $options)) {
+                    $xmlrpcVal = new Value('', Value::$xmlrpcNull);
+                } else {
+                    $xmlrpcVal = new Value();
+                }
+                break;
+            case 'resource':
+                if (in_array('extension_api', $options)) {
+                    $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
+                } else {
+                    $xmlrpcVal = new Value();
+                }
+            // catch "user function", "unknown type"
+            default:
+                // giancarlo pinerolo <ping@alt.it>
+                // it has to return
+                // an empty object in case, not a boolean.
+                $xmlrpcVal = new Value();
+                break;
+        }
+
+        return $xmlrpcVal;
+    }
+
+    /**
+     * Convert the xml representation of a method response, method request or single
+     * xmlrpc value into the appropriate object (a.k.a. deserialize).
+     *
+     * @param string $xmlVal
+     * @param array $options
+     *
+     * @return mixed false on error, or an instance of either Value, Request or Response
+     */
+    public function decodeXml($xmlVal, $options = array())
+    {
+        // 'guestimate' encoding
+        $valEncoding = XMLParser::guessEncoding('', $xmlVal);
+        if ($valEncoding != '') {
+
+            // Since parsing will fail if charset is not specified in the xml prologue,
+            // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
+            // The following code might be better for mb_string enabled installs, but
+            // makes the lib about 200% slower...
+            //if (!is_valid_charset($valEncoding, array('UTF-8'))
+            if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
+                if ($valEncoding == 'ISO-8859-1') {
+                    $xmlVal = utf8_encode($xmlVal);
+                } else {
+                    if (extension_loaded('mbstring')) {
+                        $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
+                    }
+                }
+            }
+        }
+
+        $parser = xml_parser_create();
+        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
+        // What if internal encoding is not in one of the 3 allowed?
+        // we use the broadest one, ie. utf8!
+        if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
+        } else {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
+        }
+
+        $xmlRpcParser = new XMLParser();
+        xml_set_object($parser, $xmlRpcParser);
+
+        xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
+        xml_set_character_data_handler($parser, 'xmlrpc_cd');
+        xml_set_default_handler($parser, 'xmlrpc_dh');
+        if (!xml_parse($parser, $xmlVal, 1)) {
+            $errstr = sprintf('XML error: %s at line %d, column %d',
+                xml_error_string(xml_get_error_code($parser)),
+                xml_get_current_line_number($parser), xml_get_current_column_number($parser));
+            error_log($errstr);
+            xml_parser_free($parser);
+
+            return false;
+        }
+        xml_parser_free($parser);
+        if ($xmlRpcParser->_xh['isf'] > 1) {
+            // test that $xmlrpc->_xh['value'] is an obj, too???
+
+            error_log($xmlRpcParser->_xh['isf_reason']);
+
+            return false;
+        }
+        switch ($xmlRpcParser->_xh['rt']) {
+            case 'methodresponse':
+                $v = &$xmlRpcParser->_xh['value'];
+                if ($xmlRpcParser->_xh['isf'] == 1) {
+                    $vc = $v['faultCode'];
+                    $vs = $v['faultString'];
+                    $r = new Response(0, $vc->scalarval(), $vs->scalarval());
+                } else {
+                    $r = new Response($v);
+                }
+
+                return $r;
+            case 'methodcall':
+                $req = new Request($xmlRpcParser->_xh['method']);
+                for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
+                    $req->addParam($xmlRpcParser->_xh['params'][$i]);
+                }
+
+                return $req;
+            case 'value':
+                return $xmlRpcParser->_xh['value'];
+            default:
+                return false;
+        }
+    }
+
+}
diff --git a/src/Helper/Charset.php b/src/Helper/Charset.php
new file mode 100644 (file)
index 0000000..9000ffb
--- /dev/null
@@ -0,0 +1,262 @@
+<?php
+
+namespace PhpXmlRpc\Helper;
+
+use PhpXmlRpc\PhpXmlRpc;
+
+class Charset
+{
+    // tables used for transcoding different charsets into us-ascii xml
+    protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
+
+    /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
+    /// These will NOT be present in true ISO-8859-1, but will save the unwary
+    /// windows user from sending junk (though no luck when receiving them...)
+    /*
+    protected $xml_cp1252_Entities = array('in' => array(), out' => array(
+        '&#x20AC;', '?',        '&#x201A;', '&#x0192;',
+        '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
+        '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
+        '&#x0152;', '?',        '&#x017D;', '?',
+        '?',        '&#x2018;', '&#x2019;', '&#x201C;',
+        '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
+        '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
+        '&#x0153;', '?',        '&#x017E;', '&#x0178;'
+    ));
+    */
+
+    protected $charset_supersets = array(
+        'US-ASCII' => array('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
+            'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
+            'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
+            'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
+            'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',),
+    );
+
+    protected static $instance = null;
+
+    /**
+     * This class is singleton for performance reasons.
+     *
+     * @return Charset
+     */
+    public static function instance()
+    {
+        if (self::$instance === null) {
+            self::$instance = new self();
+        }
+
+        return self::$instance;
+    }
+
+    private function __construct()
+    {
+        for ($i = 0; $i < 32; $i++) {
+            $this->xml_iso88591_Entities["in"][] = chr($i);
+            $this->xml_iso88591_Entities["out"][] = "&#{$i};";
+        }
+
+        for ($i = 160; $i < 256; $i++) {
+            $this->xml_iso88591_Entities["in"][] = chr($i);
+            $this->xml_iso88591_Entities["out"][] = "&#{$i};";
+        }
+
+        /*for ($i = 128; $i < 160; $i++)
+        {
+            $this->xml_cp1252_Entities['in'][] = chr($i);
+        }*/
+    }
+
+    /**
+     * Convert a string to the correct XML representation in a target charset
+     * To help correct communication of non-ascii chars inside strings, regardless
+     * of the charset used when sending requests, parsing them, sending responses
+     * and parsing responses, an option is to convert all non-ascii chars present in the message
+     * into their equivalent 'charset entity'. Charset entities enumerated this way
+     * are independent of the charset encoding used to transmit them, and all XML
+     * parsers are bound to understand them.
+     * Note that in the std case we are not sending a charset encoding mime type
+     * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
+     *
+     * @todo do a bit of basic benchmarking (strtr vs. str_replace)
+     * @todo make usage of iconv() or recode_string() or mb_string() where available
+     *
+     * @param string $data
+     * @param string $srcEncoding
+     * @param string $destEncoding
+     *
+     * @return string
+     */
+    public function encodeEntities($data, $srcEncoding = '', $destEncoding = '')
+    {
+        if ($srcEncoding == '') {
+            // lame, but we know no better...
+            $srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding;
+        }
+
+        switch (strtoupper($srcEncoding . '_' . $destEncoding)) {
+            case 'ISO-8859-1_':
+            case 'ISO-8859-1_US-ASCII':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                $escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData);
+                break;
+            case 'ISO-8859-1_UTF-8':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                $escapedData = utf8_encode($escapedData);
+                break;
+            case 'ISO-8859-1_ISO-8859-1':
+            case 'US-ASCII_US-ASCII':
+            case 'US-ASCII_UTF-8':
+            case 'US-ASCII_':
+            case 'US-ASCII_ISO-8859-1':
+            case 'UTF-8_UTF-8':
+            //case 'CP1252_CP1252':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                break;
+            case 'UTF-8_':
+            case 'UTF-8_US-ASCII':
+            case 'UTF-8_ISO-8859-1':
+                // NB: this will choke on invalid UTF-8, going most likely beyond EOF
+                $escapedData = '';
+                // be kind to users creating string xmlrpc values out of different php types
+                $data = (string)$data;
+                $ns = strlen($data);
+                for ($nn = 0; $nn < $ns; $nn++) {
+                    $ch = $data[$nn];
+                    $ii = ord($ch);
+                    //1 7 0bbbbbbb (127)
+                    if ($ii < 128) {
+                        /// @todo shall we replace this with a (supposedly) faster str_replace?
+                        switch ($ii) {
+                            case 34:
+                                $escapedData .= '&quot;';
+                                break;
+                            case 38:
+                                $escapedData .= '&amp;';
+                                break;
+                            case 39:
+                                $escapedData .= '&apos;';
+                                break;
+                            case 60:
+                                $escapedData .= '&lt;';
+                                break;
+                            case 62:
+                                $escapedData .= '&gt;';
+                                break;
+                            default:
+                                $escapedData .= $ch;
+                        } // switch
+                    } //2 11 110bbbbb 10bbbbbb (2047)
+                    elseif ($ii >> 5 == 6) {
+                        $b1 = ($ii & 31);
+                        $ii = ord($data[$nn + 1]);
+                        $b2 = ($ii & 63);
+                        $ii = ($b1 * 64) + $b2;
+                        $ent = sprintf('&#%d;', $ii);
+                        $escapedData .= $ent;
+                        $nn += 1;
+                    } //3 16 1110bbbb 10bbbbbb 10bbbbbb
+                    elseif ($ii >> 4 == 14) {
+                        $b1 = ($ii & 15);
+                        $ii = ord($data[$nn + 1]);
+                        $b2 = ($ii & 63);
+                        $ii = ord($data[$nn + 2]);
+                        $b3 = ($ii & 63);
+                        $ii = ((($b1 * 64) + $b2) * 64) + $b3;
+                        $ent = sprintf('&#%d;', $ii);
+                        $escapedData .= $ent;
+                        $nn += 2;
+                    } //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
+                    elseif ($ii >> 3 == 30) {
+                        $b1 = ($ii & 7);
+                        $ii = ord($data[$nn + 1]);
+                        $b2 = ($ii & 63);
+                        $ii = ord($data[$nn + 2]);
+                        $b3 = ($ii & 63);
+                        $ii = ord($data[$nn + 3]);
+                        $b4 = ($ii & 63);
+                        $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
+                        $ent = sprintf('&#%d;', $ii);
+                        $escapedData .= $ent;
+                        $nn += 3;
+                    }
+                }
+                break;
+            /*
+            case 'CP1252_':
+            case 'CP1252_US-ASCII':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                $escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData);
+                $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
+                break;
+            case 'CP1252_UTF-8':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)
+                $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
+                $escapedData = utf8_encode($escapedData);
+                break;
+            case 'CP1252_ISO-8859-1':
+                $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
+                // we might as well replace all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...
+                $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
+                break;
+            */
+            default:
+                $escapedData = '';
+                error_log('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
+        }
+
+        return $escapedData;
+    }
+
+    /**
+     * Checks if a given charset encoding is present in a list of encodings or
+     * if it is a valid subset of any encoding in the list.
+     *
+     * @param string $encoding charset to be tested
+     * @param string|array $validList comma separated list of valid charsets (or array of charsets)
+     *
+     * @return bool
+     */
+    public function isValidCharset($encoding, $validList)
+    {
+        if (is_string($validList)) {
+            $validList = explode(',', $validList);
+        }
+        if (@in_array(strtoupper($encoding), $validList)) {
+            return true;
+        } else {
+            if (array_key_exists($encoding, $this->charset_supersets)) {
+                foreach ($validList as $allowed) {
+                    if (in_array($allowed, $this->charset_supersets[$encoding])) {
+                        return true;
+                    }
+                }
+            }
+
+            return false;
+        }
+    }
+
+    /**
+     * Used only for backwards compatibility
+     * @deprecated
+     *
+     * @param string $charset
+     *
+     * @return array
+     *
+     * @throws \Exception for unknown/unsupported charsets
+     */
+    public function getEntities($charset)
+    {
+        switch ($charset)
+        {
+            case 'iso88591':
+                return $this->xml_iso88591_Entities;
+            default:
+                throw new \Exception('Unsupported charset: ' . $charset);
+        }
+    }
+
+}
diff --git a/src/Helper/Date.php b/src/Helper/Date.php
new file mode 100644 (file)
index 0000000..f97f52c
--- /dev/null
@@ -0,0 +1,63 @@
+<?php
+
+namespace PhpXmlRpc\Helper;
+
+class Date
+{
+    /**
+     * Given a timestamp, return the corresponding ISO8601 encoded string.
+     *
+     * Really, timezones ought to be supported
+     * but the XML-RPC spec says:
+     *
+     * "Don't assume a timezone. It should be specified by the server in its
+     * documentation what assumptions it makes about timezones."
+     *
+     * These routines always assume localtime unless
+     * $utc is set to 1, in which case UTC is assumed
+     * and an adjustment for locale is made when encoding
+     *
+     * @param int $timet (timestamp)
+     * @param int $utc (0 or 1)
+     *
+     * @return string
+     */
+    public static function iso8601Encode($timet, $utc = 0)
+    {
+        if (!$utc) {
+            $t = strftime("%Y%m%dT%H:%M:%S", $timet);
+        } else {
+            if (function_exists('gmstrftime')) {
+                // gmstrftime doesn't exist in some versions
+                // of PHP
+                $t = gmstrftime("%Y%m%dT%H:%M:%S", $timet);
+            } else {
+                $t = strftime("%Y%m%dT%H:%M:%S", $timet - date('Z'));
+            }
+        }
+
+        return $t;
+    }
+
+    /**
+     * Given an ISO8601 date string, return a timet in the localtime, or UTC.
+     *
+     * @param string $idate
+     * @param int $utc either 0 or 1
+     *
+     * @return int (datetime)
+     */
+    public static function iso8601Decode($idate, $utc = 0)
+    {
+        $t = 0;
+        if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs)) {
+            if ($utc) {
+                $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
+            } else {
+                $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
+            }
+        }
+
+        return $t;
+    }
+}
diff --git a/src/Helper/Http.php b/src/Helper/Http.php
new file mode 100644 (file)
index 0000000..2faf583
--- /dev/null
@@ -0,0 +1,245 @@
+<?php
+
+namespace PhpXmlRpc\Helper;
+
+use PhpXmlRpc\PhpXmlRpc;
+
+class Http
+{
+    /**
+     * Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6
+     * Code shamelessly stolen from nusoap library by Dietrich Ayala.
+     *
+     * @param string $buffer the string to be decoded
+     *
+     * @return string
+     */
+    public static function decodeChunked($buffer)
+    {
+        // length := 0
+        $length = 0;
+        $new = '';
+
+        // read chunk-size, chunk-extension (if any) and crlf
+        // get the position of the linebreak
+        $chunkEnd = strpos($buffer, "\r\n") + 2;
+        $temp = substr($buffer, 0, $chunkEnd);
+        $chunkSize = hexdec(trim($temp));
+        $chunkStart = $chunkEnd;
+        while ($chunkSize > 0) {
+            $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
+
+            // just in case we got a broken connection
+            if ($chunkEnd == false) {
+                $chunk = substr($buffer, $chunkStart);
+                // append chunk-data to entity-body
+                $new .= $chunk;
+                $length += strlen($chunk);
+                break;
+            }
+
+            // read chunk-data and crlf
+            $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
+            // append chunk-data to entity-body
+            $new .= $chunk;
+            // length := length + chunk-size
+            $length += strlen($chunk);
+            // read chunk-size and crlf
+            $chunkStart = $chunkEnd + 2;
+
+            $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
+            if ($chunkEnd == false) {
+                break; //just in case we got a broken connection
+            }
+            $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
+            $chunkSize = hexdec(trim($temp));
+            $chunkStart = $chunkEnd;
+        }
+
+        return $new;
+    }
+
+    /**
+     * Parses HTTP an http response headers and separates them from the body.
+     *
+     * @param string $data the http response,headers and body. It will be stripped of headers
+     * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
+     *
+     * @return array with keys 'headers' and 'cookies'
+     * @throws \Exception
+     */
+    public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
+    {
+        $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
+
+        // Support "web-proxy-tunelling" connections for https through proxies
+        if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
+            // Look for CR/LF or simple LF as line separator,
+            // (even though it is not valid http)
+            $pos = strpos($data, "\r\n\r\n");
+            if ($pos || is_int($pos)) {
+                $bd = $pos + 4;
+            } else {
+                $pos = strpos($data, "\n\n");
+                if ($pos || is_int($pos)) {
+                    $bd = $pos + 2;
+                } else {
+                    // No separation between response headers and body: fault?
+                    $bd = 0;
+                }
+            }
+            if ($bd) {
+                // this filters out all http headers from proxy.
+                // maybe we could take them into account, too?
+                $data = substr($data, $bd);
+            } else {
+                error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
+                throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
+            }
+        }
+
+        // Strip HTTP 1.1 100 Continue header if present
+        while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
+            $pos = strpos($data, 'HTTP', 12);
+            // server sent a Continue header without any (valid) content following...
+            // give the client a chance to know it
+            if (!$pos && !is_int($pos)) {
+                // works fine in php 3, 4 and 5
+
+                break;
+            }
+            $data = substr($data, $pos);
+        }
+        if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
+            $errstr = substr($data, 0, strpos($data, "\n") - 1);
+            error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
+            throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']);
+        }
+
+        // be tolerant to usage of \n instead of \r\n to separate headers and data
+        // (even though it is not valid http)
+        $pos = strpos($data, "\r\n\r\n");
+        if ($pos || is_int($pos)) {
+            $bd = $pos + 4;
+        } else {
+            $pos = strpos($data, "\n\n");
+            if ($pos || is_int($pos)) {
+                $bd = $pos + 2;
+            } else {
+                // No separation between response headers and body: fault?
+                // we could take some action here instead of going on...
+                $bd = 0;
+            }
+        }
+        // be tolerant to line endings, and extra empty lines
+        $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
+        while (list(, $line) = @each($ar)) {
+            // take care of multi-line headers and cookies
+            $arr = explode(':', $line, 2);
+            if (count($arr) > 1) {
+                $headerName = strtolower(trim($arr[0]));
+                /// @todo some other headers (the ones that allow a CSV list of values)
+                /// do allow many values to be passed using multiple header lines.
+                /// We should add content to $xmlrpc->_xh['headers'][$headerName]
+                /// instead of replacing it for those...
+                if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
+                    if ($headerName == 'set-cookie2') {
+                        // version 2 cookies:
+                        // there could be many cookies on one line, comma separated
+                        $cookies = explode(',', $arr[1]);
+                    } else {
+                        $cookies = array($arr[1]);
+                    }
+                    foreach ($cookies as $cookie) {
+                        // glue together all received cookies, using a comma to separate them
+                        // (same as php does with getallheaders())
+                        if (isset($httpResponse['headers'][$headerName])) {
+                            $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
+                        } else {
+                            $httpResponse['headers'][$headerName] = trim($cookie);
+                        }
+                        // parse cookie attributes, in case user wants to correctly honour them
+                        // feature creep: only allow rfc-compliant cookie attributes?
+                        // @todo support for server sending multiple time cookie with same name, but using different PATHs
+                        $cookie = explode(';', $cookie);
+                        foreach ($cookie as $pos => $val) {
+                            $val = explode('=', $val, 2);
+                            $tag = trim($val[0]);
+                            $val = trim(@$val[1]);
+                            /// @todo with version 1 cookies, we should strip leading and trailing " chars
+                            if ($pos == 0) {
+                                $cookiename = $tag;
+                                $httpResponse['cookies'][$tag] = array();
+                                $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
+                            } else {
+                                if ($tag != 'value') {
+                                    $httpResponse['cookies'][$cookiename][$tag] = $val;
+                                }
+                            }
+                        }
+                    }
+                } else {
+                    $httpResponse['headers'][$headerName] = trim($arr[1]);
+                }
+            } elseif (isset($headerName)) {
+                /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
+                $httpResponse['headers'][$headerName] .= ' ' . trim($line);
+            }
+        }
+
+        $data = substr($data, $bd);
+
+        if ($debug && count($httpResponse['headers'])) {
+            $msg = '';
+            foreach ($httpResponse['headers'] as $header => $value) {
+                $msg .= "HEADER: $header: $value\n";
+            }
+            foreach ($httpResponse['cookies'] as $header => $value) {
+                $msg .= "COOKIE: $header={$value['value']}\n";
+            }
+            Logger::instance()->debugMessage($msg);
+        }
+
+        // if CURL was used for the call, http headers have been processed,
+        // and dechunking + reinflating have been carried out
+        if (!$headersProcessed) {
+            // Decode chunked encoding sent by http 1.1 servers
+            if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
+                if (!$data = Http::decodeChunked($data)) {
+                    error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
+                    throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']);
+                }
+            }
+
+            // Decode gzip-compressed stuff
+            // code shamelessly inspired from nusoap library by Dietrich Ayala
+            if (isset($httpResponse['headers']['content-encoding'])) {
+                $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
+                if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
+                    // if decoding works, use it. else assume data wasn't gzencoded
+                    if (function_exists('gzinflate')) {
+                        if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
+                            $data = $degzdata;
+                            if ($debug) {
+                                Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
+                            }
+                        } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
+                            $data = $degzdata;
+                            if ($debug) {
+                                Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
+                            }
+                        } else {
+                            error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
+                            throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']);
+                        }
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
+                        throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']);
+                    }
+                }
+            }
+        } // end of 'if needed, de-chunk, re-inflate response'
+
+        return $httpResponse;
+    }
+}
diff --git a/src/Helper/Logger.php b/src/Helper/Logger.php
new file mode 100644 (file)
index 0000000..77e0e14
--- /dev/null
@@ -0,0 +1,52 @@
+<?php
+
+namespace PhpXmlRpc\Helper;
+
+class Logger
+{
+    protected static $instance = null;
+
+    /**
+     * This class is singleton, so that later we can move to DI patterns.
+     *
+     * @return Logger
+     */
+    public static function instance()
+    {
+        if (self::$instance === null) {
+            self::$instance = new self();
+        }
+
+        return self::$instance;
+    }
+
+    /**
+     * Echoes a debug message, taking care of escaping it when not in console mode.
+     * NB: if the encoding of the message is not known or wrong, and we are working in web mode, there is no guarantee
+     *     of 100% accuracy, which kind of defeats the purpose of debugging
+     *
+     * @param string $message
+     * @param string $encoding
+     */
+    public function debugMessage($message, $encoding=null)
+    {
+        // US-ASCII is a warning for PHP and a fatal for HHVM
+        if ($encoding == 'US-ASCII') {
+            $encoding = 'UTF-8';
+        }
+
+        if (PHP_SAPI != 'cli') {
+            $flags = ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE;
+            if ($encoding != null) {
+                print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
+            } else {
+                print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
+            }
+        } else {
+            print "\n$message\n";
+        }
+
+        // let the user see this now in case there's a time out later...
+        flush();
+    }
+}
diff --git a/src/Helper/XMLParser.php b/src/Helper/XMLParser.php
new file mode 100644 (file)
index 0000000..d5c7176
--- /dev/null
@@ -0,0 +1,547 @@
+<?php
+
+namespace PhpXmlRpc\Helper;
+
+use PhpXmlRpc\PhpXmlRpc;
+use PhpXmlRpc\Value;
+
+/**
+ * Deals with parsing the XML.
+ */
+class XMLParser
+{
+    // used to store state during parsing
+    // quick explanation of components:
+    //   ac - used to accumulate values
+    //   stack - array with genealogy of xml elements names:
+    //           used to validate nesting of xmlrpc elements
+    //   valuestack - array used for parsing arrays and structs
+    //   lv - used to indicate "looking for a value": implements
+    //        the logic to allow values with no types to be strings
+    //   isf - used to indicate a parsing fault (2) or xmlrpc response fault (1)
+    //   isf_reason - used for storing xmlrpc response fault string
+    //   method - used to store method name
+    //   params - used to store parameters in method calls
+    //   pt - used to store the type of each received parameter. Useful if parameters are automatically decoded to php values
+    //   rt  - 'methodcall or 'methodresponse'
+    public $_xh = array(
+        'ac' => '',
+        'stack' => array(),
+        'valuestack' => array(),
+        'isf' => 0,
+        'isf_reason' => '',
+        'method' => false, // so we can check later if we got a methodname or not
+        'params' => array(),
+        'pt' => array(),
+        'rt' => '',
+    );
+
+    public $xmlrpc_valid_parents = array(
+        'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
+        'BOOLEAN' => array('VALUE'),
+        'I4' => array('VALUE'),
+        'INT' => array('VALUE'),
+        'STRING' => array('VALUE'),
+        'DOUBLE' => array('VALUE'),
+        'DATETIME.ISO8601' => array('VALUE'),
+        'BASE64' => array('VALUE'),
+        'MEMBER' => array('STRUCT'),
+        'NAME' => array('MEMBER'),
+        'DATA' => array('ARRAY'),
+        'ARRAY' => array('VALUE'),
+        'STRUCT' => array('VALUE'),
+        'PARAM' => array('PARAMS'),
+        'METHODNAME' => array('METHODCALL'),
+        'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
+        'FAULT' => array('METHODRESPONSE'),
+        'NIL' => array('VALUE'), // only used when extension activated
+        'EX:NIL' => array('VALUE'), // only used when extension activated
+    );
+
+    /**
+     * xml parser handler function for opening element tags.
+     */
+    public function xmlrpc_se($parser, $name, $attrs, $acceptSingleVals = false)
+    {
+        // if invalid xmlrpc already detected, skip all processing
+        if ($this->_xh['isf'] < 2) {
+            // check for correct element nesting
+            // top level element can only be of 2 types
+            /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
+            ///       there is only a single top level element in xml anyway
+            if (count($this->_xh['stack']) == 0) {
+                if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
+                        $name != 'VALUE' && !$acceptSingleVals)
+                ) {
+                    $this->_xh['isf'] = 2;
+                    $this->_xh['isf_reason'] = 'missing top level xmlrpc element';
+
+                    return;
+                } else {
+                    $this->_xh['rt'] = strtolower($name);
+                }
+            } else {
+                // not top level element: see if parent is OK
+                $parent = end($this->_xh['stack']);
+                if (!array_key_exists($name, $this->xmlrpc_valid_parents) || !in_array($parent, $this->xmlrpc_valid_parents[$name])) {
+                    $this->_xh['isf'] = 2;
+                    $this->_xh['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
+
+                    return;
+                }
+            }
+
+            switch ($name) {
+                // optimize for speed switch cases: most common cases first
+                case 'VALUE':
+                    /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
+                    $this->_xh['vt'] = 'value'; // indicator: no value found yet
+                    $this->_xh['ac'] = '';
+                    $this->_xh['lv'] = 1;
+                    $this->_xh['php_class'] = null;
+                    break;
+                case 'I4':
+                case 'INT':
+                case 'STRING':
+                case 'BOOLEAN':
+                case 'DOUBLE':
+                case 'DATETIME.ISO8601':
+                case 'BASE64':
+                    if ($this->_xh['vt'] != 'value') {
+                        //two data elements inside a value: an error occurred!
+                        $this->_xh['isf'] = 2;
+                        $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
+
+                        return;
+                    }
+                    $this->_xh['ac'] = ''; // reset the accumulator
+                    break;
+                case 'STRUCT':
+                case 'ARRAY':
+                    if ($this->_xh['vt'] != 'value') {
+                        //two data elements inside a value: an error occurred!
+                        $this->_xh['isf'] = 2;
+                        $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
+
+                        return;
+                    }
+                    // create an empty array to hold child values, and push it onto appropriate stack
+                    $curVal = array();
+                    $curVal['values'] = array();
+                    $curVal['type'] = $name;
+                    // check for out-of-band information to rebuild php objs
+                    // and in case it is found, save it
+                    if (@isset($attrs['PHP_CLASS'])) {
+                        $curVal['php_class'] = $attrs['PHP_CLASS'];
+                    }
+                    $this->_xh['valuestack'][] = $curVal;
+                    $this->_xh['vt'] = 'data'; // be prepared for a data element next
+                    break;
+                case 'DATA':
+                    if ($this->_xh['vt'] != 'data') {
+                        //two data elements inside a value: an error occurred!
+                        $this->_xh['isf'] = 2;
+                        $this->_xh['isf_reason'] = "found two data elements inside an array element";
+
+                        return;
+                    }
+                case 'METHODCALL':
+                case 'METHODRESPONSE':
+                case 'PARAMS':
+                    // valid elements that add little to processing
+                    break;
+                case 'METHODNAME':
+                case 'NAME':
+                    /// @todo we could check for 2 NAME elements inside a MEMBER element
+                    $this->_xh['ac'] = '';
+                    break;
+                case 'FAULT':
+                    $this->_xh['isf'] = 1;
+                    break;
+                case 'MEMBER':
+                    $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = ''; // set member name to null, in case we do not find in the xml later on
+                    //$this->_xh['ac']='';
+                // Drop trough intentionally
+                case 'PARAM':
+                    // clear value type, so we can check later if no value has been passed for this param/member
+                    $this->_xh['vt'] = null;
+                    break;
+                case 'NIL':
+                case 'EX:NIL':
+                    if (PhpXmlRpc::$xmlrpc_null_extension) {
+                        if ($this->_xh['vt'] != 'value') {
+                            //two data elements inside a value: an error occurred!
+                            $this->_xh['isf'] = 2;
+                            $this->_xh['isf_reason'] = "$name element following a {$this->_xh['vt']} element inside a single value";
+
+                            return;
+                        }
+                        $this->_xh['ac'] = ''; // reset the accumulator
+                        break;
+                    }
+                // we do not support the <NIL/> extension, so
+                // drop through intentionally
+                default:
+                    /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
+                    $this->_xh['isf'] = 2;
+                    $this->_xh['isf_reason'] = "found not-xmlrpc xml element $name";
+                    break;
+            }
+
+            // Save current element name to stack, to validate nesting
+            $this->_xh['stack'][] = $name;
+
+            /// @todo optimization creep: move this inside the big switch() above
+            if ($name != 'VALUE') {
+                $this->_xh['lv'] = 0;
+            }
+        }
+    }
+
+    /**
+     * Used in decoding xml chunks that might represent single xmlrpc values.
+     */
+    public function xmlrpc_se_any($parser, $name, $attrs)
+    {
+        $this->xmlrpc_se($parser, $name, $attrs, true);
+    }
+
+    /**
+     * xml parser handler function for close element tags.
+     */
+    public function xmlrpc_ee($parser, $name, $rebuildXmlrpcvals = true)
+    {
+        if ($this->_xh['isf'] < 2) {
+            // push this element name from stack
+            // NB: if XML validates, correct opening/closing is guaranteed and
+            // we do not have to check for $name == $currElem.
+            // we also checked for proper nesting at start of elements...
+            $currElem = array_pop($this->_xh['stack']);
+
+            switch ($name) {
+                case 'VALUE':
+                    // This if() detects if no scalar was inside <VALUE></VALUE>
+                    if ($this->_xh['vt'] == 'value') {
+                        $this->_xh['value'] = $this->_xh['ac'];
+                        $this->_xh['vt'] = Value::$xmlrpcString;
+                    }
+
+                    if ($rebuildXmlrpcvals) {
+                        // build the xmlrpc val out of the data received, and substitute it
+                        $temp = new Value($this->_xh['value'], $this->_xh['vt']);
+                        // in case we got info about underlying php class, save it
+                        // in the object we're rebuilding
+                        if (isset($this->_xh['php_class'])) {
+                            $temp->_php_class = $this->_xh['php_class'];
+                        }
+                        // check if we are inside an array or struct:
+                        // if value just built is inside an array, let's move it into array on the stack
+                        $vscount = count($this->_xh['valuestack']);
+                        if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
+                            $this->_xh['valuestack'][$vscount - 1]['values'][] = $temp;
+                        } else {
+                            $this->_xh['value'] = $temp;
+                        }
+                    } else {
+                        /// @todo this needs to treat correctly php-serialized objects,
+                        /// since std deserializing is done by php_xmlrpc_decode,
+                        /// which we will not be calling...
+                        if (isset($this->_xh['php_class'])) {
+                        }
+
+                        // check if we are inside an array or struct:
+                        // if value just built is inside an array, let's move it into array on the stack
+                        $vscount = count($this->_xh['valuestack']);
+                        if ($vscount && $this->_xh['valuestack'][$vscount - 1]['type'] == 'ARRAY') {
+                            $this->_xh['valuestack'][$vscount - 1]['values'][] = $this->_xh['value'];
+                        }
+                    }
+                    break;
+                case 'BOOLEAN':
+                case 'I4':
+                case 'INT':
+                case 'STRING':
+                case 'DOUBLE':
+                case 'DATETIME.ISO8601':
+                case 'BASE64':
+                    $this->_xh['vt'] = strtolower($name);
+                    /// @todo: optimization creep - remove the if/elseif cycle below
+                    /// since the case() in which we are already did that
+                    if ($name == 'STRING') {
+                        $this->_xh['value'] = $this->_xh['ac'];
+                    } elseif ($name == 'DATETIME.ISO8601') {
+                        if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->_xh['ac'])) {
+                            error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in DATETIME: ' . $this->_xh['ac']);
+                        }
+                        $this->_xh['vt'] = Value::$xmlrpcDateTime;
+                        $this->_xh['value'] = $this->_xh['ac'];
+                    } elseif ($name == 'BASE64') {
+                        /// @todo check for failure of base64 decoding / catch warnings
+                        $this->_xh['value'] = base64_decode($this->_xh['ac']);
+                    } elseif ($name == 'BOOLEAN') {
+                        // special case here: we translate boolean 1 or 0 into PHP
+                        // constants true or false.
+                        // Strings 'true' and 'false' are accepted, even though the
+                        // spec never mentions them (see eg. Blogger api docs)
+                        // NB: this simple checks helps a lot sanitizing input, ie no
+                        // security problems around here
+                        if ($this->_xh['ac'] == '1' || strcasecmp($this->_xh['ac'], 'true') == 0) {
+                            $this->_xh['value'] = true;
+                        } else {
+                            // log if receiving something strange, even though we set the value to false anyway
+                            if ($this->_xh['ac'] != '0' && strcasecmp($this->_xh['ac'], 'false') != 0) {
+                                error_log('XML-RPC: ' . __METHOD__ . ': invalid value received in BOOLEAN: ' . $this->_xh['ac']);
+                            }
+                            $this->_xh['value'] = false;
+                        }
+                    } elseif ($name == 'DOUBLE') {
+                        // we have a DOUBLE
+                        // we must check that only 0123456789-.<space> are characters here
+                        // NOTE: regexp could be much stricter than this...
+                        if (!preg_match('/^[+-eE0123456789 \t.]+$/', $this->_xh['ac'])) {
+                            /// @todo: find a better way of throwing an error than this!
+                            error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in DOUBLE: ' . $this->_xh['ac']);
+                            $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
+                        } else {
+                            // it's ok, add it on
+                            $this->_xh['value'] = (double)$this->_xh['ac'];
+                        }
+                    } else {
+                        // we have an I4/INT
+                        // we must check that only 0123456789-<space> are characters here
+                        if (!preg_match('/^[+-]?[0123456789 \t]+$/', $this->_xh['ac'])) {
+                            /// @todo find a better way of throwing an error than this!
+                            error_log('XML-RPC: ' . __METHOD__ . ': non numeric value received in INT: ' . $this->_xh['ac']);
+                            $this->_xh['value'] = 'ERROR_NON_NUMERIC_FOUND';
+                        } else {
+                            // it's ok, add it on
+                            $this->_xh['value'] = (int)$this->_xh['ac'];
+                        }
+                    }
+                    $this->_xh['lv'] = 3; // indicate we've found a value
+                    break;
+                case 'NAME':
+                    $this->_xh['valuestack'][count($this->_xh['valuestack']) - 1]['name'] = $this->_xh['ac'];
+                    break;
+                case 'MEMBER':
+                    // add to array in the stack the last element built,
+                    // unless no VALUE was found
+                    if ($this->_xh['vt']) {
+                        $vscount = count($this->_xh['valuestack']);
+                        $this->_xh['valuestack'][$vscount - 1]['values'][$this->_xh['valuestack'][$vscount - 1]['name']] = $this->_xh['value'];
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside STRUCT in received xml');
+                    }
+                    break;
+                case 'DATA':
+                    $this->_xh['vt'] = null; // reset this to check for 2 data elements in a row - even if they're empty
+                    break;
+                case 'STRUCT':
+                case 'ARRAY':
+                    // fetch out of stack array of values, and promote it to current value
+                    $currVal = array_pop($this->_xh['valuestack']);
+                    $this->_xh['value'] = $currVal['values'];
+                    $this->_xh['vt'] = strtolower($name);
+                    if (isset($currVal['php_class'])) {
+                        $this->_xh['php_class'] = $currVal['php_class'];
+                    }
+                    break;
+                case 'PARAM':
+                    // add to array of params the current value,
+                    // unless no VALUE was found
+                    if ($this->_xh['vt']) {
+                        $this->_xh['params'][] = $this->_xh['value'];
+                        $this->_xh['pt'][] = $this->_xh['vt'];
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': missing VALUE inside PARAM in received xml');
+                    }
+                    break;
+                case 'METHODNAME':
+                    $this->_xh['method'] = preg_replace('/^[\n\r\t ]+/', '', $this->_xh['ac']);
+                    break;
+                case 'NIL':
+                case 'EX:NIL':
+                    if (PhpXmlRpc::$xmlrpc_null_extension) {
+                        $this->_xh['vt'] = 'null';
+                        $this->_xh['value'] = null;
+                        $this->_xh['lv'] = 3;
+                        break;
+                    }
+                // drop through intentionally if nil extension not enabled
+                case 'PARAMS':
+                case 'FAULT':
+                case 'METHODCALL':
+                case 'METHORESPONSE':
+                    break;
+                default:
+                    // End of INVALID ELEMENT!
+                    // shall we add an assert here for unreachable code???
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Used in decoding xmlrpc requests/responses without rebuilding xmlrpc Values.
+     */
+    public function xmlrpc_ee_fast($parser, $name)
+    {
+        $this->xmlrpc_ee($parser, $name, false);
+    }
+
+    /**
+     * xml parser handler function for character data.
+     */
+    public function xmlrpc_cd($parser, $data)
+    {
+        // skip processing if xml fault already detected
+        if ($this->_xh['isf'] < 2) {
+            // "lookforvalue==3" means that we've found an entire value
+            // and should discard any further character data
+            if ($this->_xh['lv'] != 3) {
+                $this->_xh['ac'] .= $data;
+            }
+        }
+    }
+
+    /**
+     * xml parser handler function for 'other stuff', ie. not char data or
+     * element start/end tag. In fact it only gets called on unknown entities...
+     */
+    public function xmlrpc_dh($parser, $data)
+    {
+        // skip processing if xml fault already detected
+        if ($this->_xh['isf'] < 2) {
+            if (substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';') {
+                $this->_xh['ac'] .= $data;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * xml charset encoding guessing helper function.
+     * Tries to determine the charset encoding of an XML chunk received over HTTP.
+     * NB: according to the spec (RFC 3023), if text/xml content-type is received over HTTP without a content-type,
+     * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of non conforming (legacy?) clients/servers,
+     * which will be most probably using UTF-8 anyway...
+     * In order of importance checks:
+     * 1. http headers
+     * 2. BOM
+     * 3. XML declaration
+     * 4. guesses using mb_detect_encoding()
+     *
+     * @param string $httpHeader the http Content-type header
+     * @param string $xmlChunk xml content buffer
+     * @param string $encodingPrefs comma separated list of character encodings to be used as default (when mb extension is enabled).
+     *                              This can also be set globally using PhpXmlRpc::$xmlrpc_detectencodings
+     * @return string the encoding determined. Null if it can't be determined and mbstring is enabled,
+     *                PhpXmlRpc::$xmlrpc_defencoding if it can't be determined and mbstring is not enabled
+     *
+     * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
+     */
+    public static function guessEncoding($httpHeader = '', $xmlChunk = '', $encodingPrefs = null)
+    {
+        // discussion: see http://www.yale.edu/pclt/encoding/
+        // 1 - test if encoding is specified in HTTP HEADERS
+
+        // Details:
+        // LWS:           (\13\10)?( |\t)+
+        // token:         (any char but excluded stuff)+
+        // quoted string: " (any char but double quotes and control chars)* "
+        // header:        Content-type = ...; charset=value(; ...)*
+        //   where value is of type token, no LWS allowed between 'charset' and value
+        // Note: we do not check for invalid chars in VALUE:
+        //   this had better be done using pure ereg as below
+        // Note 2: we might be removing whitespace/tabs that ought to be left in if
+        //   the received charset is a quoted string. But nobody uses such charset names...
+
+        /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
+        $matches = array();
+        if (preg_match('/;\s*charset\s*=([^;]+)/i', $httpHeader, $matches)) {
+            return strtoupper(trim($matches[1], " \t\""));
+        }
+
+        // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
+        //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
+        //     NOTE: actually, according to the spec, even if we find the BOM and determine
+        //     an encoding, we should check if there is an encoding specified
+        //     in the xml declaration, and verify if they match.
+        /// @todo implement check as described above?
+        /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
+        if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
+            return 'UCS-4';
+        } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
+            return 'UTF-16';
+        } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
+            return 'UTF-8';
+        }
+
+        // 3 - test if encoding is specified in the xml declaration
+        // Details:
+        // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
+        // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
+        if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
+            '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
+            $xmlChunk, $matches)) {
+            return strtoupper(substr($matches[2], 1, -1));
+        }
+
+        // 4 - if mbstring is available, let it do the guesswork
+        if (extension_loaded('mbstring')) {
+            if ($encodingPrefs == null && PhpXmlRpc::$xmlrpc_detectencodings != null) {
+                $encodingPrefs = PhpXmlRpc::$xmlrpc_detectencodings;
+            }
+            if ($encodingPrefs) {
+                $enc = mb_detect_encoding($xmlChunk, $encodingPrefs);
+            } else {
+                $enc = mb_detect_encoding($xmlChunk);
+            }
+            // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
+            // IANA also likes better US-ASCII, so go with it
+            if ($enc == 'ASCII') {
+                $enc = 'US-' . $enc;
+            }
+
+            return $enc;
+        } else {
+            // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
+            // Both RFC 2616 (HTTP 1.1) and 1945 (HTTP 1.0) clearly state that for text/xxx content types
+            // this should be the standard. And we should be getting text/xml as request and response.
+            // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
+            return PhpXmlRpc::$xmlrpc_defencoding;
+        }
+    }
+
+    /**
+     * Helper function: checks if an xml chunk as a charset declaration (BOM or in the xml declaration)
+     *
+     * @param string $xmlChunk
+     * @return bool
+     */
+    public static function hasEncoding($xmlChunk)
+    {
+        // scan the first bytes of the data for a UTF-16 (or other) BOM pattern
+        //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
+        if (preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlChunk)) {
+            return true;
+        } elseif (preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlChunk)) {
+            return true;
+        } elseif (preg_match('/^(\xEF\xBB\xBF)/', $xmlChunk)) {
+            return true;
+        }
+
+        // test if encoding is specified in the xml declaration
+        // Details:
+        // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
+        // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
+        if (preg_match('/^<\?xml\s+version\s*=\s*' . "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))" .
+            '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
+            $xmlChunk, $matches)) {
+            return true;
+        }
+
+        return false;
+    }
+}
diff --git a/src/PhpXmlRpc.php b/src/PhpXmlRpc.php
new file mode 100644 (file)
index 0000000..086a90a
--- /dev/null
@@ -0,0 +1,147 @@
+<?php
+
+namespace PhpXmlRpc;
+
+class PhpXmlRpc
+{
+    static public $xmlrpcerr = array(
+        'unknown_method' => 1,
+        'invalid_return' => 2,
+        'incorrect_params' => 3,
+        'introspect_unknown' => 4,
+        'http_error' => 5,
+        'no_data' => 6,
+        'no_ssl' => 7,
+        'curl_fail' => 8,
+        'invalid_request' => 15,
+        'no_curl' => 16,
+        'server_error' => 17,
+        'multicall_error' => 18,
+        'multicall_notstruct' => 9,
+        'multicall_nomethod' => 10,
+        'multicall_notstring' => 11,
+        'multicall_recursion' => 12,
+        'multicall_noparams' => 13,
+        'multicall_notarray' => 14,
+
+        'cannot_decompress' => 103,
+        'decompress_fail' => 104,
+        'dechunk_fail' => 105,
+        'server_cannot_decompress' => 106,
+        'server_decompress_fail' => 107,
+    );
+
+    static public $xmlrpcstr = array(
+        'unknown_method' => 'Unknown method',
+        'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload',
+        'incorrect_params' => 'Incorrect parameters passed to method',
+        'introspect_unknown' => "Can't introspect: method unknown",
+        'http_error' => "Didn't receive 200 OK from remote server.",
+        'no_data' => 'No data received from server.',
+        'no_ssl' => 'No SSL support compiled in.',
+        'curl_fail' => 'CURL error',
+        'invalid_request' => 'Invalid request payload',
+        'no_curl' => 'No CURL support compiled in.',
+        'server_error' => 'Internal server error',
+        'multicall_error' => 'Received from server invalid multicall response',
+        'multicall_notstruct' => 'system.multicall expected struct',
+        'multicall_nomethod' => 'missing methodName',
+        'multicall_notstring' => 'methodName is not a string',
+        'multicall_recursion' => 'recursive system.multicall forbidden',
+        'multicall_noparams' => 'missing params',
+        'multicall_notarray' => 'params is not an array',
+
+        'cannot_decompress' => 'Received from server compressed HTTP and cannot decompress',
+        'decompress_fail' => 'Received from server invalid compressed HTTP',
+        'dechunk_fail' => 'Received from server invalid chunked HTTP',
+        'server_cannot_decompress' => 'Received from client compressed HTTP request and cannot decompress',
+        'server_decompress_fail' => 'Received from client invalid compressed HTTP request',
+    );
+
+    // The charset encoding used by the server for received requests and
+    // by the client for received responses when received charset cannot be determined
+    // and mbstring extension is not enabled
+    public static $xmlrpc_defencoding = "UTF-8";
+
+    // The list of encodings used by the server for requests and by the client for responses
+    // to detect the charset of the received payload when
+    // - the charset cannot be determined by looking at http headers, xml declaration or BOM
+    // - mbstring extension is enabled
+    public static $xmlrpc_detectencodings = array();
+
+    // The encoding used internally by PHP.
+    // String values received as xml will be converted to this, and php strings will be converted to xml
+    // as if having been coded with this.
+    // Valid also when defining names of xmlrpc methods
+    public static $xmlrpc_internalencoding = "UTF-8";
+
+    public static $xmlrpcName = "XML-RPC for PHP";
+    public static $xmlrpcVersion = "4.0.0.alpha";
+
+    // let user errors start at 800
+    public static $xmlrpcerruser = 800;
+    // let XML parse errors start at 100
+    public static $xmlrpcerrxml = 100;
+
+    // set to TRUE to enable correct decoding of <NIL/> and <EX:NIL/> values
+    public static $xmlrpc_null_extension = false;
+
+    // set to TRUE to enable encoding of php NULL values to <EX:NIL/> instead of <NIL/>
+    public static $xmlrpc_null_apache_encoding = false;
+
+    public static $xmlrpc_null_apache_encoding_ns = "http://ws.apache.org/xmlrpc/namespaces/extensions";
+
+    /**
+     * A function to be used for compatibility with legacy code: it creates all global variables which used to be declared,
+     * such as library version etc...
+     */
+    public static function exportGlobals()
+    {
+        $reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc');
+        foreach ($reflection->getStaticProperties() as $name => $value) {
+            $GLOBALS[$name] = $value;
+        }
+
+        // NB: all the variables exported into the global namespace below here do NOT guarantee 100%
+        // compatibility, as they are NOT reimported back during calls to importGlobals()
+
+        $reflection = new \ReflectionClass('PhpXmlRpc\Value');
+        foreach ($reflection->getStaticProperties() as $name => $value) {
+            $GLOBALS[$name] = $value;
+        }
+
+        $parser = new Helper\XMLParser();
+        $reflection = new \ReflectionClass('PhpXmlRpc\Helper\XMLParser');
+        foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $name => $value) {
+            if (in_array($value->getName(), array('xmlrpc_valid_parents')))
+            {
+                $GLOBALS[$value->getName()] = $value->getValue($parser);
+            }
+        }
+
+        $charset = Helper\Charset::instance();
+        $GLOBALS['xml_iso88591_Entities'] = $charset->getEntities('iso88591');
+    }
+
+    /**
+     * A function to be used for compatibility with legacy code: it gets the values of all global variables which used
+     * to be declared, such as library version etc... and sets them to php classes.
+     * It should be used by code which changed the values of those global variables to alter the working of the library.
+     * Example code:
+     * 1. include xmlrpc.inc
+     * 2. set the values, e.g. $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
+     * 3. import them: PhpXmlRpc\PhpXmlRpc::importGlobals();
+     * 4. run your own code.
+     */
+    public static function importGlobals()
+    {
+        $reflection = new \ReflectionClass('PhpXmlRpc\PhpXmlRpc');
+        $staticProperties = $reflection->getStaticProperties();
+        foreach ($staticProperties as $name => $value) {
+            if (isset($GLOBALS[$name])) {
+                self::$$name = $GLOBALS[$name];
+            }
+        }
+    }
+
+}
diff --git a/src/Request.php b/src/Request.php
new file mode 100644 (file)
index 0000000..52a3b97
--- /dev/null
@@ -0,0 +1,379 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\Charset;
+use PhpXmlRpc\Helper\Http;
+use PhpXmlRpc\Helper\Logger;
+use PhpXmlRpc\Helper\XMLParser;
+
+class Request
+{
+    /// @todo: do these need to be public?
+    public $payload;
+    public $methodname;
+    public $params = array();
+    public $debug = 0;
+    public $content_type = 'text/xml';
+
+    // holds data while parsing the response. NB: Not a full Response object
+    protected $httpResponse = array();
+
+    /**
+     * @param string $methodName the name of the method to invoke
+     * @param Value[] $params array of parameters to be passed to the method (Value objects)
+     */
+    public function __construct($methodName, $params = array())
+    {
+        $this->methodname = $methodName;
+        foreach ($params as $param) {
+            $this->addParam($param);
+        }
+    }
+
+    public function xml_header($charsetEncoding = '')
+    {
+        if ($charsetEncoding != '') {
+            return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
+        } else {
+            return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
+        }
+    }
+
+    public function xml_footer()
+    {
+        return '</methodCall>';
+    }
+
+    public function createPayload($charsetEncoding = '')
+    {
+        if ($charsetEncoding != '') {
+            $this->content_type = 'text/xml; charset=' . $charsetEncoding;
+        } else {
+            $this->content_type = 'text/xml';
+        }
+        $this->payload = $this->xml_header($charsetEncoding);
+        $this->payload .= '<methodName>' . Charset::instance()->encodeEntities($this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
+        $this->payload .= "<params>\n";
+        foreach ($this->params as $p) {
+            $this->payload .= "<param>\n" . $p->serialize($charsetEncoding) .
+                "</param>\n";
+        }
+        $this->payload .= "</params>\n";
+        $this->payload .= $this->xml_footer();
+    }
+
+    /**
+     * Gets/sets the xmlrpc method to be invoked.
+     *
+     * @param string $methodName the method to be set (leave empty not to set it)
+     *
+     * @return string the method that will be invoked
+     */
+    public function method($methodName = '')
+    {
+        if ($methodName != '') {
+            $this->methodname = $methodName;
+        }
+
+        return $this->methodname;
+    }
+
+    /**
+     * Returns xml representation of the message. XML prologue included.
+     *
+     * @param string $charsetEncoding
+     *
+     * @return string the xml representation of the message, xml prologue included
+     */
+    public function serialize($charsetEncoding = '')
+    {
+        $this->createPayload($charsetEncoding);
+
+        return $this->payload;
+    }
+
+    /**
+     * Add a parameter to the list of parameters to be used upon method invocation.
+     *
+     * @param Value $param
+     *
+     * @return boolean false on failure
+     */
+    public function addParam($param)
+    {
+        // add check: do not add to self params which are not xmlrpc values
+        if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
+            $this->params[] = $param;
+
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Returns the nth parameter in the request. The index zero-based.
+     *
+     * @param integer $i the index of the parameter to fetch (zero based)
+     *
+     * @return Value the i-th parameter
+     */
+    public function getParam($i)
+    {
+        return $this->params[$i];
+    }
+
+    /**
+     * Returns the number of parameters in the message.
+     *
+     * @return integer the number of parameters currently set
+     */
+    public function getNumParams()
+    {
+        return count($this->params);
+    }
+
+    /**
+     * Given an open file handle, read all data available and parse it as an xmlrpc response.
+     * NB: the file handle is not closed by this function.
+     * NNB: might have trouble in rare cases to work on network streams, as we
+     *      check for a read of 0 bytes instead of feof($fp).
+     *      But since checking for feof(null) returns false, we would risk an
+     *      infinite loop in that case, because we cannot trust the caller
+     *      to give us a valid pointer to an open file...
+     *
+     * @param resource $fp stream pointer
+     *
+     * @return Response
+     *
+     * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
+     */
+    public function parseResponseFile($fp)
+    {
+        $ipd = '';
+        while ($data = fread($fp, 32768)) {
+            $ipd .= $data;
+        }
+        return $this->parseResponse($ipd);
+    }
+
+    /**
+     * Parse the xmlrpc response contained in the string $data and return a Response object.
+     *
+     * @param string $data the xmlrpc response, eventually including http headers
+     * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
+     * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
+     *
+     * @return Response
+     */
+    public function parseResponse($data = '', $headersProcessed = false, $returnType = 'xmlrpcvals')
+    {
+        if ($this->debug) {
+            Logger::instance()->debugMessage("---GOT---\n$data\n---END---");
+        }
+
+        $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
+
+        if ($data == '') {
+            error_log('XML-RPC: ' . __METHOD__ . ': no response received from server.');
+            return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
+        }
+
+        // parse the HTTP headers of the response, if present, and separate them from data
+        if (substr($data, 0, 4) == 'HTTP') {
+            $httpParser = new Http();
+            try {
+                $this->httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug);
+            } catch(\Exception $e) {
+                $r = new Response(0, $e->getCode(), $e->getMessage());
+                // failed processing of HTTP response headers
+                // save into response obj the full payload received, for debugging
+                $r->raw_data = $data;
+
+                return $r;
+            }
+        }
+
+        // be tolerant of extra whitespace in response body
+        $data = trim($data);
+
+        /// @todo return an error msg if $data=='' ?
+
+        // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
+        // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
+        $pos = strrpos($data, '</methodResponse>');
+        if ($pos !== false) {
+            $data = substr($data, 0, $pos + 17);
+        }
+
+        // try to 'guestimate' the character encoding of the received response
+        $respEncoding = XMLParser::guessEncoding(@$this->httpResponse['headers']['content-type'], $data);
+
+        if ($this->debug) {
+            $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
+            if ($start) {
+                $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
+                $end = strpos($data, '-->', $start);
+                $comments = substr($data, $start, $end - $start);
+                Logger::instance()->debugMessage("---SERVER DEBUG INFO (DECODED) ---\n\t" .
+                    str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", $respEncoding);
+            }
+        }
+
+        // if user wants back raw xml, give it to him
+        if ($returnType == 'xml') {
+            $r = new Response($data, 0, '', 'xml');
+            $r->hdrs = $this->httpResponse['headers'];
+            $r->_cookies = $this->httpResponse['cookies'];
+            $r->raw_data = $this->httpResponse['raw_data'];
+
+            return $r;
+        }
+
+        if ($respEncoding != '') {
+
+            // Since parsing will fail if charset is not specified in the xml prologue,
+            // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
+            // The following code might be better for mb_string enabled installs, but
+            // makes the lib about 200% slower...
+            //if (!is_valid_charset($respEncoding, array('UTF-8')))
+            if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
+                if ($respEncoding == 'ISO-8859-1') {
+                    $data = utf8_encode($data);
+                } else {
+                    if (extension_loaded('mbstring')) {
+                        $data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of received response: ' . $respEncoding);
+                    }
+                }
+            }
+        }
+
+        $parser = xml_parser_create();
+        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
+        // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
+        // the xml parser to give us back data in the expected charset.
+        // What if internal encoding is not in one of the 3 allowed?
+        // we use the broadest one, ie. utf8
+        // This allows to send data which is native in various charset,
+        // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
+        if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
+        } else {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
+        }
+
+        $xmlRpcParser = new XMLParser();
+        xml_set_object($parser, $xmlRpcParser);
+
+        if ($returnType == 'phpvals') {
+            xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
+        } else {
+            xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
+        }
+
+        xml_set_character_data_handler($parser, 'xmlrpc_cd');
+        xml_set_default_handler($parser, 'xmlrpc_dh');
+
+        // first error check: xml not well formed
+        if (!xml_parse($parser, $data, count($data))) {
+            // thanks to Peter Kocks <peter.kocks@baygate.com>
+            if ((xml_get_current_line_number($parser)) == 1) {
+                $errStr = 'XML error at line 1, check URL';
+            } else {
+                $errStr = sprintf('XML error: %s at line %d, column %d',
+                    xml_error_string(xml_get_error_code($parser)),
+                    xml_get_current_line_number($parser), xml_get_current_column_number($parser));
+            }
+            error_log($errStr);
+            $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'], PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' (' . $errStr . ')');
+            xml_parser_free($parser);
+            if ($this->debug) {
+                print $errStr;
+            }
+            $r->hdrs = $this->httpResponse['headers'];
+            $r->_cookies = $this->httpResponse['cookies'];
+            $r->raw_data = $this->httpResponse['raw_data'];
+
+            return $r;
+        }
+        xml_parser_free($parser);
+        // second error check: xml well formed but not xml-rpc compliant
+        if ($xmlRpcParser->_xh['isf'] > 1) {
+            if ($this->debug) {
+                /// @todo echo something for user?
+            }
+
+            $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
+                PhpXmlRpc::$xmlrpcstr['invalid_return'] . ' ' . $xmlRpcParser->_xh['isf_reason']);
+        }
+        // third error check: parsing of the response has somehow gone boink.
+        // NB: shall we omit this check, since we trust the parsing code?
+        elseif ($returnType == 'xmlrpcvals' && !is_object($xmlRpcParser->_xh['value'])) {
+            // something odd has happened
+            // and it's time to generate a client side error
+            // indicating something odd went on
+            $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_return'],
+                PhpXmlRpc::$xmlrpcstr['invalid_return']);
+        } else {
+            if ($this->debug > 1) {
+                Logger::instance()->debugMessage(
+                    "---PARSED---\n".var_export($xmlRpcParser->_xh['value'], true)."\n---END---"
+                );
+            }
+
+            // note that using =& will raise an error if $xmlRpcParser->_xh['st'] does not generate an object.
+            $v = &$xmlRpcParser->_xh['value'];
+
+            if ($xmlRpcParser->_xh['isf']) {
+                /// @todo we should test here if server sent an int and a string, and/or coerce them into such...
+                if ($returnType == 'xmlrpcvals') {
+                    $errNo_v = $v['faultCode'];
+                    $errStr_v = $v['faultString'];
+                    $errNo = $errNo_v->scalarval();
+                    $errStr = $errStr_v->scalarval();
+                } else {
+                    $errNo = $v['faultCode'];
+                    $errStr = $v['faultString'];
+                }
+
+                if ($errNo == 0) {
+                    // FAULT returned, errno needs to reflect that
+                    $errNo = -1;
+                }
+
+                $r = new Response(0, $errNo, $errStr);
+            } else {
+                $r = new Response($v, 0, '', $returnType);
+            }
+        }
+
+        $r->hdrs = $this->httpResponse['headers'];
+        $r->_cookies = $this->httpResponse['cookies'];
+        $r->raw_data = $this->httpResponse['raw_data'];
+
+        return $r;
+    }
+
+    /**
+     * Kept the old name even if Request class was renamed, for compatibility.
+     *
+     * @return string
+     */
+    public function kindOf()
+    {
+        return 'msg';
+    }
+
+    /**
+     * Enables/disables the echoing to screen of the xmlrpc responses received.
+     *
+     * @param integer $in values 0, 1, 2 are supported
+     */
+    public function setDebug($in)
+    {
+        $this->debug = $in;
+    }
+}
diff --git a/src/Response.php b/src/Response.php
new file mode 100644 (file)
index 0000000..7e2ebb6
--- /dev/null
@@ -0,0 +1,151 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\Charset;
+
+class Response
+{
+    /// @todo: do these need to be public?
+    public $val = 0;
+    public $valType;
+    public $errno = 0;
+    public $errstr = '';
+    public $payload;
+    public $hdrs = array();
+    public $_cookies = array();
+    public $content_type = 'text/xml';
+    public $raw_data = '';
+
+    /**
+     * @param mixed $val either 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 xmlrpc value or a plain
+     * php val, or a complete xml chunk, depending on usage of Client::send() inside which creator is called...
+     */
+    public function __construct($val, $fCode = 0, $fString = '', $valType = '')
+    {
+        if ($fCode != 0) {
+            // error response
+            $this->errno = $fCode;
+            $this->errstr = $fString;
+        } else {
+            // successful response
+            $this->val = $val;
+            if ($valType == '') {
+                // user did not declare type of response value: try to guess it
+                if (is_object($this->val) && is_a($this->val, 'PhpXmlRpc\Value')) {
+                    $this->valtyp = 'xmlrpcvals';
+                } elseif (is_string($this->val)) {
+                    $this->valtyp = 'xml';
+                } else {
+                    $this->valtyp = 'phpvals';
+                }
+            } else {
+                // user declares type of resp value: believe him
+                $this->valtyp = $valType;
+            }
+        }
+    }
+
+    /**
+     * Returns the error code of the response.
+     *
+     * @return integer the error code of this response (0 for not-error responses)
+     */
+    public function faultCode()
+    {
+        return $this->errno;
+    }
+
+    /**
+     * Returns the error code of the response.
+     *
+     * @return string the error string of this response ('' for not-error responses)
+     */
+    public function faultString()
+    {
+        return $this->errstr;
+    }
+
+    /**
+     * Returns the value received by the server.
+     *
+     * @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()
+    {
+        return $this->val;
+    }
+
+    /**
+     * Returns an array with the cookies received from the server.
+     * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
+     * with attributes being e.g. 'expires', 'path', domain'.
+     * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
+     * are still present in the array. It is up to the user-defined code to decide
+     * how to use the received cookies, and whether they have to be sent back with the next
+     * request to the server (using Client::setCookie) or not.
+     *
+     * @return array array of cookies received from the server
+     */
+    public function cookies()
+    {
+        return $this->_cookies;
+    }
+
+    /**
+     * Returns xml representation of the response. XML prologue not included.
+     *
+     * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
+     *
+     * @return string the xml representation of the response
+     *
+     * @throws \Exception
+     */
+    public function serialize($charsetEncoding = '')
+    {
+        if ($charsetEncoding != '') {
+            $this->content_type = 'text/xml; charset=' . $charsetEncoding;
+        } else {
+            $this->content_type = 'text/xml';
+        }
+        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
+            $result = "<methodResponse xmlns:ex=\"" . PhpXmlRpc::$xmlrpc_null_apache_encoding_ns . "\">\n";
+        } else {
+            $result = "<methodResponse>\n";
+        }
+        if ($this->errno) {
+            // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
+            // by xml-encoding non ascii chars
+            $result .= "<fault>\n" .
+                "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
+                "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
+                Charset::instance()->encodeEntities($this->errstr, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</string></value>\n</member>\n" .
+                "</struct>\n</value>\n</fault>";
+        } else {
+            if (!is_object($this->val) || !is_a($this->val, 'PhpXmlRpc\Value')) {
+                if (is_string($this->val) && $this->valtyp == 'xml') {
+                    $result .= "<params>\n<param>\n" .
+                        $this->val .
+                        "</param>\n</params>";
+                } else {
+                    /// @todo try to build something serializable?
+                    throw new \Exception('cannot serialize xmlrpc response objects whose content is native php values');
+                }
+            } else {
+                $result .= "<params>\n<param>\n" .
+                    $this->val->serialize($charsetEncoding) .
+                    "</param>\n</params>";
+            }
+        }
+        $result .= "\n</methodResponse>";
+        $this->payload = $result;
+
+        return $result;
+    }
+}
diff --git a/src/Server.php b/src/Server.php
new file mode 100644 (file)
index 0000000..07cfb9b
--- /dev/null
@@ -0,0 +1,1054 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\XMLParser;
+use PhpXmlRpc\Helper\Charset;
+
+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 request 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 Encoder::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
+     */
+    public $debug = 1;
+    /**
+     * 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
+     */
+    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.
+     * Set at constructor time.
+     */
+    public $compress_response = false;
+    /**
+     * 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.
+     * Set at constructor time.
+     * UNUSED so far...
+     */
+    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)
+     */
+    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
+     */
+    public $user_data = null;
+
+    protected static $_xmlrpc_debuginfo = '';
+    protected static $_xmlrpcs_occurred_errors = '';
+    protected static $_xmlrpcs_prev_ehandler = '';
+
+    /**
+     * @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($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
+        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 ($dispatchMap) {
+            $this->dmap = $dispatchMap;
+            if ($serviceNow) {
+                $this->service();
+            }
+        }
+    }
+
+    /**
+     * Set debug level of server.
+     *
+     * @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),
+     *                    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($level)
+    {
+        $this->debug = $level;
+    }
+
+    /**
+     * 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 $msg
+     * @access public
+     */
+    public static function xmlrpc_debugmsg($msg)
+    {
+        static::$_xmlrpc_debuginfo .= $msg . "\n";
+    }
+
+    public static function error_occurred($msg)
+    {
+        static::$_xmlrpcs_occurred_errors .= $msg . "\n";
+    }
+
+    /**
+     * Return a string with the serialized representation of all debug info.
+     *
+     * @param string $charsetEncoding the target charset encoding for the serialization
+     *
+     * @return string an XML comment (or two)
+     */
+    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,
+        // 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 .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n" . base64_encode($this->debug_info) . "\n-->\n";
+        }
+        if (static::$_xmlrpc_debuginfo != '') {
+            $out .= "<!-- DEBUG INFO:\n" . Charset::instance()->encodeEntities(str_replace('--', '_-', static::$_xmlrpc_debuginfo), PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "\n-->\n";
+            // NB: a better solution MIGHT be to use CDATA, but we need to insert it
+            // into return payload AFTER the beginning tag
+            //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', 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 $returnPayload When true, return the response but do not echo it or any http header
+     *
+     * @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)
+    {
+        if ($data === null) {
+            $data = file_get_contents('php://input');
+        }
+        $rawData = $data;
+
+        // reset internal debug info
+        $this->debug_info = '';
+
+        // 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);
+        }
+
+        // save full body of request into response, for more debugging usages
+        $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($respCharset);
+        if ($this->debug > 0) {
+            $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($respCharset);
+        }
+        $payload = $payload . $r->payload;
+
+        if ($returnPayload) {
+            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
+            $phpNoSelfCompress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
+            if ($this->compress_response && function_exists('gzencode') && $respEncoding != ''
+                && $phpNoSelfCompress
+            ) {
+                if (strpos($respEncoding, 'gzip') !== false) {
+                    $payload = gzencode($payload);
+                    header("Content-Encoding: gzip");
+                    header("Vary: Accept-Encoding");
+                } elseif (strpos($respEncoding, '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 ($phpNoSelfCompress) {
+                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)
+     */
+    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|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, $sigs)
+    {
+        // check each possible signature in turn
+        if (is_object($in)) {
+            $numParams = $in->getNumParams();
+        } else {
+            $numParams = count($in);
+        }
+        foreach ($sigs 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] != Value::$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 Response|null on success or an error Response
+     */
+    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)
+        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'])) {
+            $contentEncoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
+        } else {
+            $contentEncoding = '';
+        }
+
+        // check if request body has been compressed and decompress it
+        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($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 ($contentEncoding == '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, PhpXmlRpc::$xmlrpcerr['server_decompress_fail'], PhpXmlRpc::$xmlrpcstr['server_decompress_fail']);
+
+                        return $r;
+                    }
+                } else {
+                    $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_cannot_decompress'], PhpXmlRpc::$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') {
+            $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.
+                /// @todo we should parse q=0.x preferences instead of getting first charset specified...
+                $clientAcceptedCharsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
+                // Give preference to internal encoding
+                $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;
+                        }
+                    }
+                    if ($respEncoding) {
+                        break;
+                    }
+                }
+            }
+        } else {
+            $respEncoding = $this->response_charset_encoding;
+        }
+
+        if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
+            $respCompression = $_SERVER['HTTP_ACCEPT_ENCODING'];
+        } else {
+            $respCompression = '';
+        }
+
+        // 'guestimate' request encoding
+        /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
+        $reqEncoding = XMLParser::guessEncoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
+            $data);
+
+        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 $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 = '')
+    {
+        // decompose incoming XML into request structure
+
+        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);
+                    }
+                }
+            }
+        }
+
+        $parser = xml_parser_create();
+        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
+        // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
+        // the xml parser to give us back data in the expected charset
+        // What if internal encoding is not in one of the 3 allowed?
+        // we use the broadest one, ie. utf8
+        // This allows to send data which is native in various charset,
+        // by extending xmlrpc_encode_entities() and setting xmlrpc_internalencoding
+        if (!in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
+        } else {
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, PhpXmlRpc::$xmlrpc_internalencoding);
+        }
+
+        $xmlRpcParser = new XMLParser();
+        xml_set_object($parser, $xmlRpcParser);
+
+        if ($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 (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) {
+                    $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
+                $req = new Request($xmlRpcParser->_xh['method']);
+                // now add parameters in
+                for ($i = 0; $i < count($xmlRpcParser->_xh['params']); $i++) {
+                    $req->addParam($xmlRpcParser->_xh['params'][$i]);
+                }
+
+                if ($this->debug > 1) {
+                    $this->debugmsg("\n+++PARSED+++\n" . var_export($req, true) . "\n+++END+++");
+                }
+                $r = $this->execute($req);
+            }
+        }
+
+        return $r;
+    }
+
+    /**
+     * Execute a method invoked by the client, checking parameters used.
+     *
+     * @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)
+     *
+     * @return Response
+     *
+     * @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 {
+            $methName = $req;
+        }
+        $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
+        $dmap = $sysCall ? $this->getSystemDispatchMap() : $this->dmap;
+
+        if (!isset($dmap[$methName]['function'])) {
+            // No such method
+            return new Response(0,
+                PhpXmlRpc::$xmlrpcerr['unknown_method'],
+                PhpXmlRpc::$xmlrpcstr['unknown_method']);
+        }
+
+        // Check signature
+        if (isset($dmap[$methName]['signature'])) {
+            $sig = $dmap[$methName]['signature'];
+            if (is_object($req)) {
+                list($ok, $errStr) = $this->verifySignature($req, $sig);
+            } else {
+                list($ok, $errStr) = $this->verifySignature($paramTypes, $sig);
+            }
+            if (!$ok) {
+                // Didn't match.
+                return new Response(
+                    0,
+                    PhpXmlRpc::$xmlrpcerr['incorrect_params'],
+                    PhpXmlRpc::$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);
+        }
+
+        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 '$funcName' registered as method handler is not callable");
+            return new Response(
+                0,
+                PhpXmlRpc::$xmlrpcerr['server_error'],
+                PhpXmlRpc::$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) {
+            self::$_xmlrpcs_prev_ehandler = set_error_handler(array('\PhpXmlRpc\Server', '_xmlrpcs_errorHandler'));
+        }
+
+        try {
+            // Allow mixed-convention servers
+            if (is_object($req)) {
+                if ($sysCall) {
+                    $r = call_user_func($func, $this, $req);
+                } else {
+                    $r = call_user_func($func, $req);
+                }
+                if (!is_a($r, 'PhpXmlRpc\Response')) {
+                    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 {
+                        $r = new Response(
+                            0,
+                            PhpXmlRpc::$xmlrpcerr['server_error'],
+                            PhpXmlRpc::$xmlrpcstr['server_error'] . ": function does not return xmlrpc response 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 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???
+                    $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:
+                    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:
+                    $r = new Response(0, $e->getCode(), $e->getMessage());
+                    break;
+                default:
+                    $r = new Response(0, PhpXmlRpc::$xmlrpcerr['server_error'], PhpXmlRpc::$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 (self::$_xmlrpcs_prev_ehandler) {
+                set_error_handler(self::$_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";
+    }
+
+    /**
+     * @param string $charsetEncoding
+     * @return string
+     */
+    protected function xml_header($charsetEncoding = '')
+    {
+        if ($charsetEncoding != '') {
+            return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\"?" . ">\n";
+        } else {
+            return "<?xml version=\"1.0\"?" . ">\n";
+        }
+    }
+
+    /* Functions that implement system.XXX methods of xmlrpc servers */
+
+    /**
+     * @return array
+     */
+    public 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(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')),
+            ),
+        );
+    }
+
+    /**
+     * @return array
+     */
+    public function getCapabilities()
+    {
+        $outAr = array(
+            // xmlrpc spec: always supported
+            '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' => array(
+                'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
+                'specVersion' => 1
+            ),
+            // introspection: version 2! we support 'mixed', too
+            'introspection' => array(
+                'specUrl' => 'http://phpxmlrpc.sourceforge.net/doc-2/ch10.html',
+                'specVersion' => 2,
+            ),
+        );
+
+        // NIL extension
+        if (PhpXmlRpc::$xmlrpc_null_extension) {
+            $outAr['nil'] = array(
+                'specUrl' => 'http://www.ontosys.com/xml-rpc/extensions.php',
+                'specVersion' => 1
+            );
+        }
+
+        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
+    {
+        $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');
+            }
+        }
+
+        return new Response(new Value($outAr, 'array'));
+    }
+
+    public static function _xmlrpcs_methodSignature($server, $req)
+    {
+        // let accept as parameter both an xmlrpc value or string
+        if (is_object($req)) {
+            $methName = $req->getParam(0);
+            $methName = $methName->scalarval();
+        } else {
+            $methName = $req;
+        }
+        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');
+                }
+                $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, PhpXmlRpc::$xmlrpcerr['introspect_unknown'], PhpXmlRpc::$xmlrpcstr['introspect_unknown']);
+        }
+
+        return $r;
+    }
+
+    public static function _xmlrpcs_methodHelp($server, $req)
+    {
+        // let accept as parameter both an xmlrpc value or string
+        if (is_object($req)) {
+            $methName = $req->getParam(0);
+            $methName = $methName->scalarval();
+        } else {
+            $methName = $req;
+        }
+        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'));
+            }
+        } 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)) {
+            $str = PhpXmlRpc::$xmlrpcstr["multicall_${err}"];
+            $code = PhpXmlRpc::$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 static::_xmlrpcs_multicall_error('notstruct');
+        }
+        $methName = @$call['methodName'];
+        if (!$methName) {
+            return static::_xmlrpcs_multicall_error('nomethod');
+        }
+        if ($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string') {
+            return static::_xmlrpcs_multicall_error('notstring');
+        }
+        if ($methName->scalarval() == 'system.multicall') {
+            return static::_xmlrpcs_multicall_error('recursion');
+        }
+
+        $params = @$call['params'];
+        if (!$params) {
+            return static::_xmlrpcs_multicall_error('noparams');
+        }
+        if ($params->kindOf() != 'array') {
+            return static::_xmlrpcs_multicall_error('notarray');
+        }
+
+        $req = new Request($methName->scalarval());
+        foreach($params as $i => $param) {
+            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));
+            }
+        }
+
+        $result = $server->execute($req);
+
+        if ($result->faultCode() != 0) {
+            return static::_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 static::_xmlrpcs_multicall_error('notstruct');
+        }
+        if (!array_key_exists('methodName', $call)) {
+            return static::_xmlrpcs_multicall_error('nomethod');
+        }
+        if (!is_string($call['methodName'])) {
+            return static::_xmlrpcs_multicall_error('notstring');
+        }
+        if ($call['methodName'] == 'system.multicall') {
+            return static::_xmlrpcs_multicall_error('recursion');
+        }
+        if (!array_key_exists('params', $call)) {
+            return static::_xmlrpcs_multicall_error('noparams');
+        }
+        if (!is_array($call['params'])) {
+            return static::_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();
+        $wrapper = new Wrapper();
+        foreach ($call['params'] as $val) {
+            $pt[] = $wrapper->php2XmlrpcType(gettype($val));
+        }
+
+        $result = $server->execute($call['methodName'], $call['params'], $pt);
+
+        if ($result->faultCode() != 0) {
+            return static::_xmlrpcs_multicall_error($result); // Method returned fault.
+        }
+
+        return new Value(array($result->value()), 'array');
+    }
+
+    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($req)) {
+            $calls = $req->getParam(0);
+            foreach($calls as $call) {
+                $result[] = static::_xmlrpcs_multicall_do_call($server, $call);
+            }
+        } else {
+            $numCalls = count($req);
+            for ($i = 0; $i < $numCalls; $i++) {
+                $result[$i] = static::_xmlrpcs_multicall_do_call_phpvals($server, $req[$i]);
+            }
+        }
+
+        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 (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)) {
+                error_log($errString);
+            }
+        } else {
+            // Pass control on to previous error handler, trying to avoid loops...
+            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(self::$_xmlrpcs_prev_ehandler, array($errCode, $errString, $filename, $lineNo, $context));
+                } else {
+                    $method = self::$_xmlrpcs_prev_ehandler;
+                    $method($errCode, $errString, $filename, $lineNo, $context);
+                }
+            }
+        }
+    }
+}
diff --git a/src/Value.php b/src/Value.php
new file mode 100644 (file)
index 0000000..f0d331a
--- /dev/null
@@ -0,0 +1,566 @@
+<?php
+
+namespace PhpXmlRpc;
+
+use PhpXmlRpc\Helper\Charset;
+
+class Value implements \Countable, \IteratorAggregate, \ArrayAccess
+{
+    public static $xmlrpcI4 = "i4";
+    public static $xmlrpcInt = "int";
+    public static $xmlrpcBoolean = "boolean";
+    public static $xmlrpcDouble = "double";
+    public static $xmlrpcString = "string";
+    public static $xmlrpcDateTime = "dateTime.iso8601";
+    public static $xmlrpcBase64 = "base64";
+    public static $xmlrpcArray = "array";
+    public static $xmlrpcStruct = "struct";
+    public static $xmlrpcValue = "undefined";
+    public static $xmlrpcNull = "null";
+
+    public static $xmlrpcTypes = array(
+        "i4" => 1,
+        "int" => 1,
+        "boolean" => 1,
+        "double" => 1,
+        "string" => 1,
+        "dateTime.iso8601" => 1,
+        "base64" => 1,
+        "array" => 2,
+        "struct" => 3,
+        "null" => 1,
+    );
+
+    /// @todo: do these need to be public?
+    public $me = array();
+    public $mytype = 0;
+    public $_php_class = null;
+
+    /**
+     * Build an xmlrpc value.
+     * When no value or type is passed in, the value is left uninitialized, and the value can be added later
+     *
+     * @param mixed $val
+     * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
+     */
+    public function __construct($val = -1, $type = '')
+    {
+        // optimization creep - do not call addXX, do it all inline.
+        // downside: booleans will not be coerced anymore
+        if ($val !== -1 || $type != '') {
+            switch ($type) {
+                case '':
+                    $this->mytype = 1;
+                    $this->me['string'] = $val;
+                    break;
+                case 'i4':
+                case 'int':
+                case 'double':
+                case 'string':
+                case 'boolean':
+                case 'dateTime.iso8601':
+                case 'base64':
+                case 'null':
+                    $this->mytype = 1;
+                    $this->me[$type] = $val;
+                    break;
+                case 'array':
+                    $this->mytype = 2;
+                    $this->me['array'] = $val;
+                    break;
+                case 'struct':
+                    $this->mytype = 3;
+                    $this->me['struct'] = $val;
+                    break;
+                default:
+                    error_log("XML-RPC: " . __METHOD__ . ": not a known type ($type)");
+            }
+        }
+    }
+
+    /**
+     * Add a single php value to an (uninitialized) xmlrpc value.
+     *
+     * @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])) {
+            $typeOf = static::$xmlrpcTypes[$type];
+        }
+
+        if ($typeOf !== 1) {
+            error_log("XML-RPC: " . __METHOD__ . ": not a scalar type ($type)");
+            return 0;
+        }
+
+        // coerce booleans into correct values
+        // NB: we should either do it for datetimes, integers and doubles, too,
+        // or just plain remove this check, implemented on booleans only...
+        if ($type == static::$xmlrpcBoolean) {
+            if (strcasecmp($val, 'true') == 0 || $val == 1 || ($val == true && strcasecmp($val, 'false'))) {
+                $val = true;
+            } else {
+                $val = false;
+            }
+        }
+
+        switch ($this->mytype) {
+            case 1:
+                error_log('XML-RPC: ' . __METHOD__ . ': scalar xmlrpc value can have only one value');
+                return 0;
+            case 3:
+                error_log('XML-RPC: ' . __METHOD__ . ': cannot add anonymous scalar to struct xmlrpc value');
+                return 0;
+            case 2:
+                // we're adding a scalar value to an array here
+                $this->me['array'][] = new Value($val, $type);
+
+                return 1;
+            default:
+                // a scalar, so set the value and remember we're scalar
+                $this->me[$type] = $val;
+                $this->mytype = $typeOf;
+
+                return 1;
+        }
+    }
+
+    /**
+     * Add an array of xmlrpc values objects to an xmlrpc value.
+     *
+     * @param Value[] $values
+     *
+     * @return int 1 or 0 on failure
+     *
+     * @todo add some checking for $values to be an array of xmlrpc values?
+     */
+    public function addArray($values)
+    {
+        if ($this->mytype == 0) {
+            $this->mytype = static::$xmlrpcTypes['array'];
+            $this->me['array'] = $values;
+
+            return 1;
+        } elseif ($this->mytype == 2) {
+            // we're adding to an array here
+            $this->me['array'] = array_merge($this->me['array'], $values);
+
+            return 1;
+        } else {
+            error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
+            return 0;
+        }
+    }
+
+    /**
+     * Add an array of named xmlrpc value objects to an xmlrpc value.
+     *
+     * @param Value[] $values
+     *
+     * @return int 1 or 0 on failure
+     *
+     * @todo add some checking for $values to be an array?
+     */
+    public function addStruct($values)
+    {
+        if ($this->mytype == 0) {
+            $this->mytype = static::$xmlrpcTypes['struct'];
+            $this->me['struct'] = $values;
+
+            return 1;
+        } elseif ($this->mytype == 3) {
+            // we're adding to a struct here
+            $this->me['struct'] = array_merge($this->me['struct'], $values);
+
+            return 1;
+        } else {
+            error_log('XML-RPC: ' . __METHOD__ . ': already initialized as a [' . $this->kindOf() . ']');
+            return 0;
+        }
+    }
+
+    /**
+     * Returns a string containing "struct", "array", "scalar" or "undef" describing the base type of the value.
+     *
+     * @return string
+     */
+    public function kindOf()
+    {
+        switch ($this->mytype) {
+            case 3:
+                return 'struct';
+                break;
+            case 2:
+                return 'array';
+                break;
+            case 1:
+                return 'scalar';
+                break;
+            default:
+                return 'undef';
+        }
+    }
+
+    protected function serializedata($typ, $val, $charsetEncoding = '')
+    {
+        $rs = '';
+
+        if (!isset(static::$xmlrpcTypes[$typ])) {
+            return $rs;
+        }
+
+        switch (static::$xmlrpcTypes[$typ]) {
+            case 1:
+                switch ($typ) {
+                    case static::$xmlrpcBase64:
+                        $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
+                        break;
+                    case static::$xmlrpcBoolean:
+                        $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
+                        break;
+                    case static::$xmlrpcString:
+                        // G. Giunta 2005/2/13: do NOT use htmlentities, since
+                        // it will produce named html entities, which are invalid xml
+                        $rs .= "<${typ}>" . Charset::instance()->encodeEntities($val, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</${typ}>";
+                        break;
+                    case static::$xmlrpcInt:
+                    case static::$xmlrpcI4:
+                        $rs .= "<${typ}>" . (int)$val . "</${typ}>";
+                        break;
+                    case static::$xmlrpcDouble:
+                        // avoid using standard conversion of float to string because it is locale-dependent,
+                        // and also because the xmlrpc spec forbids exponential notation.
+                        // sprintf('%F') could be most likely ok but it fails eg. on 2e-14.
+                        // The code below tries its best at keeping max precision while avoiding exp notation,
+                        // but there is of course no limit in the number of decimal places to be used...
+                        $rs .= "<${typ}>" . preg_replace('/\\.?0+$/', '', number_format((double)$val, 128, '.', '')) . "</${typ}>";
+                        break;
+                    case static::$xmlrpcDateTime:
+                        if (is_string($val)) {
+                            $rs .= "<${typ}>${val}</${typ}>";
+                        } elseif (is_a($val, 'DateTime')) {
+                            $rs .= "<${typ}>" . $val->format('Ymd\TH:i:s') . "</${typ}>";
+                        } elseif (is_int($val)) {
+                            $rs .= "<${typ}>" . strftime("%Y%m%dT%H:%M:%S", $val) . "</${typ}>";
+                        } else {
+                            // not really a good idea here: but what shall we output anyway? left for backward compat...
+                            $rs .= "<${typ}>${val}</${typ}>";
+                        }
+                        break;
+                    case static::$xmlrpcNull:
+                        if (PhpXmlRpc::$xmlrpc_null_apache_encoding) {
+                            $rs .= "<ex:nil/>";
+                        } else {
+                            $rs .= "<nil/>";
+                        }
+                        break;
+                    default:
+                        // no standard type value should arrive here, but provide a possibility
+                        // for xmlrpc values of unknown type...
+                        $rs .= "<${typ}>${val}</${typ}>";
+                }
+                break;
+            case 3:
+                // struct
+                if ($this->_php_class) {
+                    $rs .= '<struct php_class="' . $this->_php_class . "\">\n";
+                } else {
+                    $rs .= "<struct>\n";
+                }
+                $charsetEncoder = Charset::instance();
+                foreach ($val as $key2 => $val2) {
+                    $rs .= '<member><name>' . $charsetEncoder->encodeEntities($key2, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</name>\n";
+                    //$rs.=$this->serializeval($val2);
+                    $rs .= $val2->serialize($charsetEncoding);
+                    $rs .= "</member>\n";
+                }
+                $rs .= '</struct>';
+                break;
+            case 2:
+                // array
+                $rs .= "<array>\n<data>\n";
+                foreach ($val as $element) {
+                    //$rs.=$this->serializeval($val[$i]);
+                    $rs .= $element->serialize($charsetEncoding);
+                }
+                $rs .= "</data>\n</array>";
+                break;
+            default:
+                break;
+        }
+
+        return $rs;
+    }
+
+    /**
+     * Returns xml representation of the value. XML prologue not included.
+     *
+     * @param string $charsetEncoding the charset to be used for serialization. if null, US-ASCII is assumed
+     *
+     * @return string
+     */
+    public function serialize($charsetEncoding = '')
+    {
+        // 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);
+        list($typ, $val) = each($this->me);
+
+        return '<value>' . $this->serializedata($typ, $val, $charsetEncoding) . "</value>\n";
+        //}
+    }
+
+    /**
+     * Checks whether a struct member with a given name is present.
+     * Works only on xmlrpc values of type struct.
+     *
+     * @param string $key the name of the struct member to be looked up
+     *
+     * @return boolean
+     *
+     * @deprecated use array access, e.g. isset($val[$key])
+     */
+    public function structmemexists($key)
+    {
+        return array_key_exists($key, $this->me['struct']);
+    }
+
+    /**
+     * Returns the value of a given struct member (an xmlrpc value object in itself).
+     * Will raise a php warning if struct member of given name does not exist.
+     *
+     * @param string $key the name of the struct member to be looked up
+     *
+     * @return Value
+     *
+     * @deprecated use array access, e.g. $val[$key]
+     */
+    public function structmem($key)
+    {
+        return $this->me['struct'][$key];
+    }
+
+    /**
+     * Reset internal pointer for xmlrpc values of type struct.
+     * @deprecated iterate directly over the object using foreach instead
+     */
+    public function structreset()
+    {
+        reset($this->me['struct']);
+    }
+
+    /**
+     * Return next member element for xmlrpc values of type struct.
+     *
+     * @return Value
+     *
+     * @deprecated iterate directly over the object using foreach instead
+     */
+    public function structeach()
+    {
+        return each($this->me['struct']);
+    }
+
+    /**
+     * Returns the value of a scalar xmlrpc value.
+     *
+     * @return mixed
+     */
+    public function scalarval()
+    {
+        reset($this->me);
+        list(, $b) = each($this->me);
+
+        return $b;
+    }
+
+    /**
+     * Returns the type of the xmlrpc value.
+     * 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;
+        }
+
+        return $a;
+    }
+
+    /**
+     * Returns the m-th member of an xmlrpc value of struct type.
+     *
+     * @param integer $key the index of the value to be retrieved (zero based)
+     *
+     * @return Value
+     *
+     * @deprecated use array access, e.g. $val[$key]
+     */
+    public function arraymem($key)
+    {
+        return $this->me['array'][$key];
+    }
+
+    /**
+     * Returns the number of members in an xmlrpc value of array type.
+     *
+     * @return integer
+     *
+     * @deprecated use count() instead
+     */
+    public function arraysize()
+    {
+        return count($this->me['array']);
+    }
+
+    /**
+     * Returns the number of members in an xmlrpc value of struct type.
+     *
+     * @return integer
+     *
+     * @deprecated use count() instead
+     */
+    public function structsize()
+    {
+        return count($this->me['struct']);
+    }
+
+    /**
+     * Returns the number of members in an xmlrpc value:
+     * - 0 for uninitialized values
+     * - 1 for scalars
+     * - the number of elements for structs and arrays
+     *
+     * @return integer
+     */
+    public function count()
+    {
+        switch ($this->mytype) {
+            case 3:
+                return count($this->me['struct']);
+            case 2:
+                return count($this->me['array']);
+            case 1:
+                return 1;
+            default:
+                return 0;
+        }
+    }
+
+    /**
+     * Implements the IteratorAggregate interface
+     *
+     * @return ArrayIterator
+     */
+    public function getIterator() {
+        switch ($this->mytype) {
+            case 3:
+                return new \ArrayIterator($this->me['struct']);
+            case 2:
+                return new \ArrayIterator($this->me['array']);
+            case 1:
+                return new \ArrayIterator($this->me);
+            default:
+                return new \ArrayIterator();
+        }
+        return new \ArrayIterator();
+    }
+
+
+    public function offsetSet($offset, $value) {
+
+        switch ($this->mytype) {
+            case 3:
+                if (!($value instanceof \PhpXmlRpc\Value)) {
+                    throw new \Exception('It is only possible to add Value objects to an XML-RPC Struct');
+                }
+                if (is_null($offset)) {
+                    // disallow struct members with empty names
+                    throw new \Exception('It is not possible to add anonymous members to an XML-RPC Struct');
+                } else {
+                    $this->me['struct'][$offset] = $value;
+                }
+                return;
+            case 2:
+                if (!($value instanceof \PhpXmlRpc\Value)) {
+                    throw new \Exception('It is only possible to add Value objects to an XML-RPC Array');
+                }
+                if (is_null($offset)) {
+                    $this->me['array'][] = $value;
+                } else {
+                    // nb: we are not checking that $offset is above the existing array range...
+                    $this->me['array'][$offset] = $value;
+                }
+                return;
+            case 1:
+// todo: handle i4 vs int
+                reset($this->me);
+                list($type,) = 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
diff --git a/src/Wrapper.php b/src/Wrapper.php
new file mode 100644 (file)
index 0000000..7a8af5e
--- /dev/null
@@ -0,0 +1,1113 @@
+<?php
+/**
+ * @author Gaetano Giunta
+ * @copyright (C) 2006-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ */
+
+namespace PhpXmlRpc;
+
+/**
+ * PHP-XMLRPC "wrapper" class.
+ * 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 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)
+ */
+class Wrapper
+{
+    /// used to hold a reference to object instances whose methods get wrapped by wrapPhpFunction(), 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.
+     * 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
+     *
+     * @return string
+     */
+    public function php2XmlrpcType($phpType)
+    {
+        switch (strtolower($phpType)) {
+            case 'string':
+                return Value::$xmlrpcString;
+            case 'integer':
+            case Value::$xmlrpcInt: // 'int'
+            case Value::$xmlrpcI4:
+                return Value::$xmlrpcInt;
+            case Value::$xmlrpcDouble: // 'double'
+                return Value::$xmlrpcDouble;
+            case 'bool':
+            case Value::$xmlrpcBoolean: // 'boolean'
+            case 'false':
+            case 'true':
+                return Value::$xmlrpcBoolean;
+            case Value::$xmlrpcArray: // 'array':
+                return Value::$xmlrpcArray;
+            case 'object':
+            case Value::$xmlrpcStruct: // 'struct'
+                return Value::$xmlrpcStruct;
+            case Value::$xmlrpcBase64:
+                return Value::$xmlrpcBase64;
+            case 'resource':
+                return '';
+            default:
+                if (class_exists($phpType)) {
+                    return Value::$xmlrpcStruct;
+                } else {
+                    // unknown: might be any 'extended' xmlrpc type
+                    return Value::$xmlrpcValue;
+                }
+        }
+    }
+
+    /**
+     * Given a string defining a phpxmlrpc type return the corresponding php type.
+     *
+     * @param string $xmlrpcType
+     *
+     * @return string
+     */
+    public function xmlrpc2PhpType($xmlrpcType)
+    {
+        switch (strtolower($xmlrpcType)) {
+            case 'base64':
+            case 'datetime.iso8601':
+            case 'string':
+                return Value::$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 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)
+     *
+     * 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 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
+     *                            - 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 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 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 wrapPhpFunction($callable, $newFuncName = '', $extraOptions = array())
+    {
+        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
+
+        if (is_string($callable) && strpos($callable, '::') !== false) {
+            $callable = explode('::', $callable);
+        }
+        if (is_array($callable)) {
+            if (count($callable) < 2 || (!is_string($callable[0]) && !is_object($callable[0]))) {
+                error_log('XML-RPC: ' . __METHOD__ . ': syntax for function to be wrapped is wrong');
+                return false;
+            }
+            if (is_string($callable[0])) {
+                $plainFuncName = implode('::', $callable);
+            } elseif (is_object($callable[0])) {
+                $plainFuncName = get_class($callable[0]) . '->' . $callable[1];
+            }
+            $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;
+        } else {
+            $plainFuncName = $callable;
+            $exists = function_exists($callable);
+        }
+
+        if (!$exists) {
+            error_log('XML-RPC: ' . __METHOD__ . ': 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) {
+            $callable = $this->buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc);
+        } else {
+            $newFuncName = $this->newFunctionName($callable, $newFuncName, $extraOptions);
+            $code = $this->buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc);
+        }
+
+        $ret = array(
+            'function' => $callable,
+            'signature' => $funcSigs['sigs'],
+            'docstring' => $funcDesc['desc'],
+            'signature_docs' => $funcSigs['sigsDocs'],
+        );
+        if (!$buildIt) {
+            $ret['function'] = $newFuncName;
+            $ret['source'] = $code;
+        }
+        return $ret;
+    }
+
+    /**
+     * 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__ . ': method to be wrapped is private: ' . $plainFuncName);
+                return false;
+            }
+            if ($func->isProtected()) {
+                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is protected: ' . $plainFuncName);
+                return false;
+            }
+            if ($func->isConstructor()) {
+                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the constructor: ' . $plainFuncName);
+                return false;
+            }
+            if ($func->isDestructor()) {
+                error_log('XML-RPC: ' . __METHOD__ . ': method to be wrapped is the destructor: ' . $plainFuncName);
+                return false;
+            }
+            if ($func->isAbstract()) {
+                error_log('XML-RPC: ' . __METHOD__ . ': 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: ' . __METHOD__ . ': 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)) {
+                        $name = strtolower(trim($matches[2]));
+                        //$paramDocs[$name]['name'] = trim($matches[2]);
+                        $paramDocs[$name]['doc'] = isset($matches[3]) ? $matches[3] : '';
+                        $paramDocs[$name]['type'] = $matches[1];
+                    }
+                    $i++;
+                } elseif (strpos($doc, '@return') === 0) {
+                    // syntax: @return type [desc]
+                    if (preg_match('/@return\s+(\S+)(\s+.+)?/', $doc, $matches)) {
+                        $returns = $matches[1];
+                        if (isset($matches[2])) {
+                            $returnsDocs = trim($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++;
+        }
+
+        return array(
+            'desc' => $desc,
+            'docs' => $docs,
+            'params' => $params, // array, positionally indexed
+            'paramDocs' => $paramDocs, // array, indexed by name
+            'returns' => $returns,
+            'returnsDocs' =>$returnsDocs,
+        );
+    }
+
+    /**
+     * 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()
+     *
+     * @return array
+     */
+    protected function buildMethodSignatures($funcDesc)
+    {
+        $i = 0;
+        $parsVariations = array();
+        $pars = array();
+        $pNum = count($funcDesc['params']);
+        foreach ($funcDesc['params'] as $param) {
+            /* // 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
+                $parsVariations[] = $pars;
+            }
+
+            $pars[] = "\$p$i";
+            $i++;
+            if ($i == $pNum) {
+                // last allowed parameters combination
+                $parsVariations[] = $pars;
+            }
+        }
+
+        if (count($parsVariations) == 0) {
+            // only known good synopsis = no parameters
+            $parsVariations[] = array();
+        }
+
+        $sigs = array();
+        $sigsDocs = array();
+        foreach ($parsVariations as $pars) {
+            // build a signature
+            $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->php2XmlrpcType($funcDesc['paramDocs'][$name]['type']);
+                } else {
+                    $sig[] = Value::$xmlrpcValue;
+                }
+                $pSig[] = isset($funcDesc['paramDocs'][$name]['doc']) ? $funcDesc['paramDocs'][$name]['doc'] : '';
+            }
+            $sigs[] = $sig;
+            $sigsDocs[] = $pSig;
+        }
+
+        return array(
+            'sigs' => $sigs,
+            'sigsDocs' => $sigsDocs
+        );
+    }
+
+    /**
+     * Creates a closure that will execute $callable
+     * @todo validate params? In theory all validation is left to the dispatch map...
+     * @todo add support for $catchWarnings
+     *
+     * @param $callable
+     * @param array $extraOptions
+     * @param string $plainFuncName
+     * @param string $funcDesc
+     * @return \Closure
+     */
+    protected function buildWrapFunctionClosure($callable, $extraOptions, $plainFuncName, $funcDesc)
+    {
+        $function = function($req) use($callable, $extraOptions, $funcDesc)
+        {
+            $nameSpace = '\\PhpXmlRpc\\';
+            $encoderClass = $nameSpace.'Encoder';
+            $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']) {
+                $options[] = 'decode_php_objs';
+            }
+            $params = $encoder->decode($req, $options);
+
+            $result = call_user_func_array($callable, $params);
+
+            if (! is_a($result, $responseClass)) {
+                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($result);
+            }
+
+            return $result;
+        };
+
+        return $function;
+    }
+
+    /**
+     * 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)
+    {
+        // 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 {
+                if ($callable instanceof \Closure) {
+                    $xmlrpcFuncName = "{$prefix}_closure";
+                } else {
+                    $callable = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
+                        array('_', ''), $callable);
+                    $xmlrpcFuncName = "{$prefix}_$callable";
+                }
+            }
+        } else {
+            $xmlrpcFuncName = $newFuncName;
+        }
+
+        while (function_exists($xmlrpcFuncName)) {
+            $xmlrpcFuncName .= 'x';
+        }
+
+        return $xmlrpcFuncName;
+    }
+
+    /**
+     * @param $callable
+     * @param string $newFuncName
+     * @param array $extraOptions
+     * @param string $plainFuncName
+     * @param array $funcDesc
+     * @return string
+     *
+     * @todo add a nice phpdoc block in the generated source
+     */
+    protected function buildWrapFunctionSource($callable, $newFuncName, $extraOptions, $plainFuncName, $funcDesc)
+    {
+        $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'] ? '@' : '';
+
+        $i = 0;
+        $parsVariations = array();
+        $pars = array();
+        $pNum = count($funcDesc['params']);
+        foreach ($funcDesc['params'] as $param) {
+
+            if ($param['isoptional']) {
+                // this particular parameter is optional. save as valid previous list of parameters
+                $parsVariations[] = $pars;
+            }
+
+            $pars[] = "\$p[$i]";
+            $i++;
+            if ($i == $pNum) {
+                // last allowed parameters combination
+                $parsVariations[] = $pars;
+            }
+        }
+
+        if (count($parsVariations) == 0) {
+            // only known good synopsis = no parameters
+            $parsVariations[] = array();
+            $minPars = 0;
+            $maxPars = 0;
+        } else {
+            $minPars = count($parsVariations[0]);
+            $maxPars = count($parsVariations[count($parsVariations)-1]);
+        }
+
+        // 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 .= "\$p = \$encoder->decode(\$req);\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])) {
+            self::$objHolder[$newFuncName] = $callable[0];
+            $innerCode .= "\$obj = PhpXmlRpc\\Wrapper::\$objHolder['$newFuncName'];\n";
+            $realFuncName = '$obj->' . $callable[1];
+        } else {
+            $realFuncName = $plainFuncName;
+        }
+        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 .= "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;
+    }
+
+    /**
+     * 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 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 wrapPhpClass($className, $extraOptions = array())
+    {
+        $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))))
+                    ) {
+                        $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
+                        if ($methodWrap) {
+                            if (is_object($className)) {
+                                $realClassName = get_class($className);
+                            }else {
+                                $realClassName = $className;
+                            }
+                            $results[$prefix."$realClassName.$mName"] = $methodWrap;
+                        }
+                    }
+                }
+            }
+        }
+
+        return $results;
+    }
+
+    /**
+     * 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.
+     *
+     * @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, 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 \closure|array|false false on failure, closure by default and array for return_source = true
+     */
+    public function wrapXmlrpcMethod($client, $methodName, $extraOptions = array())
+    {
+        $newFuncName = isset($extraOptions['new_function_name']) ? $extraOptions['new_function_name'] : '';
+
+        $buildIt = isset($extraOptions['return_source']) ? !($extraOptions['return_source']) : true;
+
+        $mSig = $this->retrieveMethodSignature($client, $methodName, $extraOptions);
+        if (!$mSig) {
+            return false;
+        }
+
+        if ($buildIt) {
+            return $this->buildWrapMethodClosure($client, $methodName, $extraOptions, $mSig);
+        } else {
+            // 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;
+        }
+
+    }
+
+    /**
+     * 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: ' . __METHOD__ . ': 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: ' . __METHOD__ . ': could not retrieve method signature nr.' . $sigNum . ' from remote server for method ' . $methodName);
+            return false;
+        }
+
+        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') {
+                $mDesc = $mDesc->scalarval();
+            }
+        }
+
+        return $mDesc;
+    }
+
+    /**
+     * @param Client $client
+     * @param string $methodName
+     * @param array $extraOptions
+     * @param string $mSig
+     * @return \Closure
+     *
+     * @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)
+    {
+        // 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 {
+                $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? note that 'source' version does not...
+
+            // 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) {
+                    break;
+                }
+                $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);
+                }
+            }
+
+            $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);
+            }
+        };
+
+        return $function;
+    }
+
+    /**
+     * @param Client $client
+     * @param string $methodName
+     * @param array $extraOptions
+     * @param string $newFuncName
+     * @param array $mSig
+     * @param string $mDesc
+     * @return array
+     */
+    public 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 = '';
+        }
+
+        $namespace = '\\PhpXmlRpc\\';
+
+        $code = "function $newFuncName (";
+        if ($clientCopyMode < 2) {
+            // client copy mode 0 or 1 == full / partial client copy in emitted code
+            $verbatimClientCopy = !$clientCopyMode;
+            $innerCode = $this->buildClientWrapperCode($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->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->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) {
+            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);
+    }
+
+    /**
+     * 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 wrapXmlrpcMethod.
+     *
+     * For a slimmer alternative, see the code in demo/client/proxy.php
+     *
+     * 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 wrapXmlrpcMethod plus
+     *              - 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
+     *
+     * @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 wrapXmlrpcServer($client, $extraOptions = array())
+    {
+        $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
+        $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\\';
+
+        $reqClass = $namespace . 'Request';
+        $decoderClass = $namespace . 'Encoder';
+
+        $req = new $reqClass('system.listMethods');
+        $response = $client->send($req, $timeout, $protocol);
+        if ($response->faultCode()) {
+            error_log('XML-RPC: ' . __METHOD__ . ': could not retrieve method list from remote server');
+
+            return false;
+        } else {
+            $mList = $response->value();
+            if ($client->return_type != 'phpvals') {
+                $decoder = new $decoderClass();
+                $mList = $decoder->decode($mList);
+            }
+            if (!is_array($mList) || !count($mList)) {
+                error_log('XML-RPC: ' . __METHOD__ . ': 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{\npublic \$client;\n\n";
+                $source .= "function __construct()\n{\n";
+                $source .= $this->buildClientWrapperCode($client, $verbatimClientCopy, $prefix, $namespace);
+                $source .= "\$this->client = \$client;\n}\n\n";
+                $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) {
+                    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->wrapXmlrpcMethod($client, $mName, $opts);
+                        if ($methodWrap) {
+                            if (!$buildIt) {
+                                $source .= $methodWrap['docstring'];
+                            }
+                            $source .= $methodWrap['source'] . "\n";
+                        } else {
+                            error_log('XML-RPC: ' . __METHOD__ . ': will not create class method to wrap remote method ' . $mName);
+                        }
+                    }
+                }
+                $source .= "}\n";
+                if ($buildIt) {
+                    $allOK = 0;
+                    eval($source . '$allOK=1;');
+                    if ($allOK) {
+                        return $xmlrpcClassName;
+                    } else {
+                        error_log('XML-RPC: ' . __METHOD__ . ': could not create class ' . $xmlrpcClassName . ' to wrap remote server ' . $client->server);
+                        return false;
+                    }
+                } else {
+                    return array('class' => $xmlrpcClassName, 'code' => $source, 'docstring' => '');
+                }
+            }
+        }
+    }
+
+    /**
+     * 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 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
+     */
+    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";
+
+        // copy all client fields to the client that will be generated runtime
+        // (this provides for future expansion or subclassing of client obj)
+        if ($verbatimClientCopy) {
+            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/test/PHPUnit/Assert.php b/test/PHPUnit/Assert.php
deleted file mode 100644 (file)
index 04513d7..0000000
+++ /dev/null
@@ -1,400 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index be46b88..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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:
- *
- * <code>
- * <?php
- * class MathTest extends PHPUnit_TestCase {
- *     var $fValue1;
- *     var $fValue2;
- *
- *     function MathTest($name) {
- *         $this->PHPUnit_TestCase($name);
- *     }
- *
- *     function setUp() {
- *         $this->fValue1 = 2;
- *         $this->fValue2 = 3;
- *     }
- * }
- * ?>
- * </code>
- *
- * For each test implement a method which interacts with the fixture.
- * Verify the expected results with assertions specified by calling
- * assert with a boolean.
- *
- * <code>
- * <?php
- * function testPass() {
- *     $this->assertTrue($this->fValue1 + $this->fValue2 == 5);
- * }
- * ?>
- * </code>
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index bf9afe0..0000000
+++ /dev/null
@@ -1,130 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index f30d451..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index b74f837..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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:
- *
- * <code>
- * <?php
- * require_once 'PHPUnit.php';
- * require_once 'PHPUnit/TestListener.php';
- *
- * class MathTest extends PHPUnit_TestCase {
- *     var $fValue1;
- *     var $fValue2;
- *
- *     function MathTest($name) {
- *         $this->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();
- * ?>
- * </code>
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index 6d1c37a..0000000
+++ /dev/null
@@ -1,321 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 '<pre>' . htmlspecialchars($this->toString()) . '</pre>';
-    }
-
-    /**
-     * 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 (file)
index 55220b7..0000000
+++ /dev/null
@@ -1,239 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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.
- *
- * <code>
- * <?php
- * $suite = new PHPUnit_TestSuite();
- * $suite->addTest(new MathTest('testPass'));
- * ?>
- * </code>
- *
- * 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.
- *
- * <code>
- * <?php
- * $suite = new TestSuite('classname');
- * ?>
- * </code>
- *
- * This constructor creates a suite with all the methods starting with
- * "test" that take no arguments.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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 (file)
index 6c1c170..0000000
+++ /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
-     <http://www.php.net/>".
-
-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 <http://www.php.net>.
-
-This product includes the Zend Engine, freely available at
-<http://www.zend.com>.
diff --git a/test/benchmark.php b/test/benchmark.php
deleted file mode 100644 (file)
index 6758d26..0000000
+++ /dev/null
@@ -1,300 +0,0 @@
-<?php
-/**
- * Benchamrking suite for the PHP-XMLRPC lib
- * @author Gaetano Giunta
- * @copyright (c) 2005-2014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
- *
- * @todo add a test for response ok in call testing?
- **/
-
-       include(dirname(__FILE__).'/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 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<title>$title</title>\n</head>\n<body>\n<h1>$title</h1>\n<pre>\n";
-       }
-       else
-       {
-               echo "$title\n\n";
-       }
-
-       if(isset($_SERVER['REQUEST_METHOD']))
-       {
-               echo "<h3>Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."</h3>\n";
-               if ($xd) echo "<h4>XDEBUG profiling enabled: skipping remote tests. Trace file is: ".htmlspecialchars(xdebug_get_profiler_filename())."</h4>\n";
-               flush();
-               ob_flush();
-       }
-       else
-       {
-               echo "Using lib version: $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 = '<?xml version="1.0" ?>'."\n".$out->serialize();
-
-       begin_test('Data decoding (large array)', 'manual decoding');
-       for ($i = 0; $i < $num_tests; $i++)
-       {
-               $response =& $dummy->ParseResponse($in, true);
-               $value = $response->value();
-               $result = array();
-               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</pre>\n</body>\n</html>\n";
-       }
-?>
\ No newline at end of file
diff --git a/test/parse_args.php b/test/parse_args.php
deleted file mode 100644 (file)
index d47168c..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-<?php
-/**
- * Common parameter parsing for benchmarks and tests scripts
- *
- * @param integer DEBUG
- * @param string  LOCALSERVER
- * @param string  URI
- * @param string  HTTPSSERVER
- * @param string  HTTPSSURI
- * @param string  PROXY
- *
- * @copyright (C) 2007-20013 G. Giunta
- * @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']))
-       {
-               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($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 = dirname(__FILE__);
-       }
-?>
\ No newline at end of file
diff --git a/test/phpunit.php b/test/phpunit.php
deleted file mode 100644 (file)
index 8b82202..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP Version 4
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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:
- *
- * <code>
- * <?php
- * require_once 'PHPUnit.php';
- *
- * class MathTest extends PHPUnit_TestCase {
- *     var $fValue1;
- *     var $fValue2;
- *
- *     function MathTest($name) {
- *       $this->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();
- * ?>
- * </code>
- *
- * 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:
- *
- * <code>
- * <?php
- * $suite  = new PHPUnit_TestSuite('MathTest');
- * $result = PHPUnit::run($suite);
- * print $result->toHTML();
- * ?>
- * </code>
- *
- * @category   Testing
- * @package    PHPUnit
- * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright  2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @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:
- */
-?>
diff --git a/test/testsuite.php b/test/testsuite.php
deleted file mode 100644 (file)
index 39874ce..0000000
+++ /dev/null
@@ -1,1549 +0,0 @@
-<?php
-
-include(dirname(__FILE__).'/parse_args.php');
-
-require_once('xmlrpc.inc');
-require_once('xmlrpcs.inc');
-require_once('xmlrpc_wrappers.inc');
-
-require_once 'phpunit.php';
-//require_once 'PHPUnit/TestDecorator.php';
-
-// let testuite run for the needed time
-if ((int)ini_get('max_execution_time') < 180)
-    ini_set('max_execution_time', 180);
-
-$suite = new PHPUnit_TestSuite();
-
-// array with list of failed tests
-$failed_tests = array();
-
-class LocalhostTests extends PHPUnit_TestCase
-{
-    var $client = null;
-    var $method = 'http';
-    var $timeout = 10;
-    var $request_compression = null;
-    var $accepted_compression = '';
-
-    function fail($message = '')
-    {
-        PHPUnit_TestCase::fail($message);
-        // save in global var that this particular test has failed
-        // (but only if not called from subclass objects / multitests)
-        if (function_exists('debug_backtrace') && strtolower(get_class($this)) == 'localhosttests')
-        {
-            global $failed_tests;
-            $trace = debug_backtrace();
-            for ($i = 0; $i < count($trace); $i++)
-            {
-                if (strpos($trace[$i]['function'], 'test') === 0)
-                {
-                    $failed_tests[$trace[$i]['function']] = true;
-                    break;
-                }
-            }
-        }
-    }
-
-    function setUp()
-    {
-        global $DEBUG, $LOCALSERVER, $URI;
-        $server = explode(':', $LOCALSERVER);
-        if(count($server) > 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>e<v&gxs<ytjzkami<";
-        $f = new xmlrpcmsg('validator1.countTheEntities',array(
-            new xmlrpcval($sendstring, 'string')
-        ));
-        $v = $this->send($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 = "<?xml version=\"1.0\"?><methodCall><methodName>validator1.echoStructTest</methodName><params><param><value><struct><member><name>','')); echo('gotcha!'); die(); //</name></member></struct></value></param></params></methodCall>";
-        $v = $this->send($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_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(
-'<?xml version="1.0"?>
-<!-- $Id -->
-<!-- found by G. giunta, covers what happens when lib receives
-  UTF8 chars in response text and comments -->
-<!-- ���&#224;&#252;&#232; -->
-<methodResponse>
-<fault>
-<value>
-<struct>
-<member>
-<name>faultCode</name>
-<value><int>888</int></value>
-</member>
-<member>
-<name>faultString</name>
-<value><string>���&#224;&#252;&#232;</string></value>
-</member>
-</struct>
-</value>
-</fault>
-</methodResponse>');
-        $m=new xmlrpcmsg('dummy');
-        $r=$m->parseResponse($response);
-        $v=$r->faultString();
-        $this->assertEquals('���àüè', $v);
-    }
-
-    function testValidNumbers()
-    {
-        $m=new xmlrpcmsg('dummy');
-        $fp=
-'<?xml version="1.0"?>
-<methodResponse>
-<params>
-<param>
-<value>
-<struct>
-<member>
-<name>integer1</name>
-<value><int>01</int></value>
-</member>
-<member>
-<name>float1</name>
-<value><double>01.10</double></value>
-</member>
-<member>
-<name>integer2</name>
-<value><int>+1</int></value>
-</member>
-<member>
-<name>float2</name>
-<value><double>+1.10</double></value>
-</member>
-<member>
-<name>float3</name>
-<value><double>-1.10e2</double></value>
-</member>
-</struct>
-</value>
-</param>
-</params>
-</methodResponse>';
-        $r=$m->parseResponse($fp);
-        $v=$r->value();
-        $s=$v->structmem('integer1');
-        $t=$v->structmem('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 = '<?xml version="1.0"?>
-<methodCall>
-<methodName>system.methodHelp</methodName>
-<param>
-<value><string>system.methodHelp</string></value>
-</param>
-</methodCall>';
-        $r = $s->parserequest($f);
-        $this->assertEquals(15, $r->faultCode());
-        // omitting a 'param' tag
-$f = '<?xml version="1.0"?>
-<methodCall>
-<methodName>system.methodHelp</methodName>
-<params>
-<value><string>system.methodHelp</string></value>
-</params>
-</methodCall>';
-        $r = $s->parserequest($f);
-        $this->assertEquals(15, $r->faultCode());
-        // omitting a 'value' tag
-$f = '<?xml version="1.0"?>
-<methodCall>
-<methodName>system.methodHelp</methodName>
-<params>
-<param><string>system.methodHelp</string></param>
-</params>
-</methodCall>';
-        $r = $s->parserequest($f);
-        $this->assertEquals(15, $r->faultCode());
-    }
-
-    function testBrokenResponses()
-    {
-        $m=new xmlrpcmsg('dummy');
-        //$m->debug = 1;
-        // omitting the 'params' tag: no more tolerated by the lib...
-$f = '<?xml version="1.0"?>
-<methodResponse>
-<param>
-<value><string>system.methodHelp</string></value>
-</param>
-</methodResponse>';
-        $r = $m->parseResponse($f);
-        $this->assertEquals(2, $r->faultCode());
-        // omitting the 'param' tag: no more tolerated by the lib...
-$f = '<?xml version="1.0"?>
-<methodResponse>
-<params>
-<value><string>system.methodHelp</string></value>
-</params>
-</methodResponse>';
-        $r = $m->parseResponse($f);
-        $this->assertEquals(2, $r->faultCode());
-        // omitting a 'value' tag: KO
-$f = '<?xml version="1.0"?>
-<methodResponse>
-<params>
-<param><string>system.methodHelp</string></param>
-</params>
-</methodResponse>';
-        $r = $m->parseResponse($f);
-        $this->assertEquals(2, $r->faultCode());
-    }
-
-    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?
-
-
-
-<?xml version="1.0"?>
-<!-- First of all, let\'s check out if the lib properly handles a commented </methodResponse> tag... -->
-<methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
-
-
-and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
-<script type="text\javascript">document.write(\'Hello, my name is added nag, I\\\'m happy to serve your content for free\');</script>
- ';
-        $r = $s->parseResponse($f);
-        $v = $r->value();
-        $s = $v->structmem('content');
-        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
-    }
-
-    function testStringBug()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?>
-<!-- $Id -->
-<!-- found by 2z69xks7bpy001@sneakemail.com, amongst others
- covers what happens when there\'s character data after </string>
- and before </value> -->
-<methodResponse>
-<params>
-<param>
-<value>
-<struct>
-<member>
-<name>success</name>
-<value>
-<boolean>1</boolean>
-</value>
-</member>
-<member>
-<name>sessionID</name>
-<value>
-<string>S300510007I</string>
-</value>
-</member>
-</struct>
-</value>
-</param>
-</params>
-</methodResponse> ';
-        $r = $s->parseResponse($f);
-        $v = $r->value();
-        $s = $v->structmem('sessionID');
-        $this->assertEquals('S300510007I', $s->scalarval());
-    }
-
-    function testWhiteSpace()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
-
-
-and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->value();
-        $s = $v->structmem('content');
-        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
-    }
-
-    function testDoubleDataInArrayTag()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
-<data></data>
-<data></data>
-</array></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->faultCode();
-        $this->assertEquals(2, $v);
-$f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
-<data><value>Hello world</value></data>
-<data></data>
-</array></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->faultCode();
-        $this->assertEquals(2, $v);
-    }
-
-    function testDoubleStuffInValueTag()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?><methodResponse><params><param><value>
-<string>hello world</string>
-<array><data></data></array>
-</value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->faultCode();
-        $this->assertEquals(2, $v);
-$f = '<?xml version="1.0"?><methodResponse><params><param><value>
-<string>hello</string>
-<string>world</string>
-</value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->faultCode();
-        $this->assertEquals(2, $v);
-$f = '<?xml version="1.0"?><methodResponse><params><param><value>
-<string>hello</string>
-<struct><member><name>hello><value>world</value></member></struct>
-</value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f);
-        $v = $r->faultCode();
-        $this->assertEquals(2, $v);
-    }
-
-    function testAutodecodeResponse()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
-
-
-and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f, true, 'phpvals');
-        $v = $r->value();
-        $s = $v['content'];
-        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s);
-    }
-
-    function testNoDecodeResponse()
-    {
-        $s = new xmlrpcmsg('dummy');
-$f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
-
-
-and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>';
-        $r = $s->parseResponse($f, true, 'xml');
-        $v = $r->value();
-        $this->assertEquals($f, $v);
-    }
-
-    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("<value><string>&#954;&#8057;&#963;&#956;&#949;</string></value>\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".'<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>'.utf8_encode('������').'</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f, false, 'phpvals');
-        $v = $r->value();
-        $v = $v['content'];
-        $this->assertEquals("������", $v);
-$f = '<?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
-<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>'.utf8_encode('������').'</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
-';
-        $r = $s->parseResponse($f, false, 'phpvals');
-        $v = $r->value();
-        $v = $v['content'];
-        $this->assertEquals("������", $v);
-    }
-
-    function testUTF8IntString()
-    {
-        $v=new xmlrpcval(100, 'int');
-        $s=$v->serialize('UTF-8');
-        $this->assertequals("<value><int>100</int></value>\n", $s);
-    }
-
-    function testStringInt()
-    {
-        $v=new xmlrpcval('hello world', 'int');
-        $s=$v->serialize();
-        $this->assertequals("<value><int>0</int></value>\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( '#<value><ex:nil/></value>#', $s ));
-        // deserialization
-        $r = new xmlrpcresp($v);
-        $s = $r->serialize();
-        $r = $m->parseresponse($s);
-        $v = $r->value();
-        $this->assertequals('null', $v->scalartyp());
-        $GLOBALS['xmlrpc_null_extension'] = false;
-        $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_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 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<title>$title</title>\n</head>\n<body>\n<h1>$title</h1>\n";
-}
-else
-{
-    echo "$title\n\n";
-}
-
-if(isset($_SERVER['REQUEST_METHOD']))
-{
-    echo "<h3>Using lib version: $xmlrpcVersion on PHP version: ".phpversion()."</h3>\n";
-    echo '<h3>Running '.$suite->testCount().' tests (some of which are multiple) against servers: http://'.htmlspecialchars($LOCALSERVER.$URI).' and https://'.htmlspecialchars($HTTPSSERVER.$HTTPSURI)."\n ...</h3>\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";
-}
-
-// do some basic timing measurement
-list($micro, $sec) = explode(' ', microtime());
-$start_time = $sec + $micro;
-
-$PHPUnit = new PHPUnit;
-$result = $PHPUnit->run($suite, ($DEBUG == 0 ? '.' : '<hr/>'));
-
-list($micro, $sec) = explode(' ', microtime());
-$end_time = $sec + $micro;
-
-if(!isset($_SERVER['REQUEST_METHOD']))
-{
-    echo $result->toString()."\n";
-}
-
-if(isset($_SERVER['REQUEST_METHOD']))
-{
-    echo '<h3>'.$result->failureCount()." test failures</h3>\n";
-    printf("Time spent: %.2f secs<br/>\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'].'&amp;DEBUG=1' : $_SERVER['PHP_SELF'].'?DEBUG=1';
-    $t2 = strpos($_SERVER['PHP_SELF'], '?') ? $_SERVER['PHP_SELF'].'&amp;DEBUG=2' : $_SERVER['PHP_SELF'].'?DEBUG=2';
-    if(isset($_SERVER['REQUEST_METHOD']))
-    {
-        echo '<p>Run testsuite with <a href="'.$target.'">DEBUG=1</a> to have more detail about tests results. Or with <a href="'.$t2.'">DEBUG=2</a> for even more.</p>'."\n";
-    }
-    else
-    {
-        echo "Run testsuite with DEBUG=1 (or 2) to have more detail about tests results\n";
-    }
-}
-
-if(isset($_SERVER['REQUEST_METHOD']))
-{
-?>
-<a href="#" onclick="if (document.getElementById('opts').style.display == 'block') document.getElementById('opts').style.display = 'none'; else document.getElementById('opts').style.display = 'block';">More options...</a>
-<div id="opts" style="display: none;">
-<form method="GET" style="border: 1px solid silver; margin: 5px; padding: 5px; font-family: monospace;">
-HTTP Server:&nbsp;&nbsp;<input name="LOCALSERVER" size="30" value="<?php echo htmlspecialchars($LOCALSERVER); ?>"/> Path: <input name="URI"  size="30" value="<?php echo htmlspecialchars($URI); ?>"/><br/>
-HTTPS Server: <input name="HTTPSSERVER" size="30" value="<?php echo htmlspecialchars($HTTPSSERVER); ?>"/> Path: <input name="HTTPSURI"  size="30" value="<?php echo htmlspecialchars($HTTPSURI); ?>"/> Do not verify cert: <input name="HTTPSIGNOREPEER" value="true" type="checkbox" <?php if ($HTTPSIGNOREPEER) echo 'checked="checked"'; ?>/><br/>
-
-Proxy Server: <input name="PROXY" size="30" value="<?php echo isset($PROXY) ? htmlspecialchars($PROXY) : ''; ?>"/> <input type="submit" value="Run Testsuite"/>
-</form>
-</div>
-<?php
-    echo $result->toHTML()."\n</body>\n</html>\n";
-}
-else
-{
-    exit($result->failureCount());
-}
-?>
\ No newline at end of file
diff --git a/test/verify_compat.php b/test/verify_compat.php
deleted file mode 100644 (file)
index a9862c4..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-<?php
-/**
- * Verify compatibility level of current php install with php-xmlrpc lib
- *
- * @author Gaetano Giunta
- * @copyright (C) 2006-2014 G. Giunta
- * @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
- *
- * @todo add a test for php output buffering?
- */
-
-function phpxmlrpc_verify_compat($mode='client')
-{
-  $tests = array();
-
-  if ($mode == 'server')
-  {
-    // test for php version
-    $ver = phpversion();
-    $tests['php_version'] = array();
-    $tests['php_version']['description'] = 'PHP version found: '.$ver.".\n\n";
-    if (version_compare($ver, '5.1.0') < 0)
-    {
-      $tests['php_version']['status'] = 0;
-      $tests['php_version']['description'] .= 'This version of PHP is not compatible with this release of the PHP XMLRPC library. Please upgrade to php 5.1.0 or later';
-    }
-    else
-    {
-      $tests['php_version']['status'] = 2;
-      $tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
-    }
-
-    // test for zlib
-    $tests['zlib'] = array();
-    if (!function_exists('gzinflate'))
-    {
-      $tests['zlib']['status'] = 0;
-      $tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to receive compressed requests or send compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
-    }
-    else
-    {
-      $tests['zlib']['status'] = 2;
-      $tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to receive compressed requests and send compressed responses for the 'HTTP' protocol";
-    }
-
-    // test for dispaly of php errors in xml reponse
-    if (ini_get('display_errors'))
-    {
-      if (intval(ini_get('error_reporting')) && E_NOTICE )
-      {
-        $tests['display_errors']['status'] = 1;
-        $tests['display_errors']['description'] = "Error reporting level includes E_NOTICE errors, and display_errors is set to ON.\n\nAny error, warning or notice raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
-      }
-      else
-      {
-        $tests['display_errors']['status'] = 1;
-        $tests['display_errors']['description'] = "display_errors is set to ON.\n\nAny error raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
-      }
-    }
-
-  }
-  else
-  {
-
-    // test for php version
-    $ver = phpversion();
-    $tests['php_version'] = array();
-    $tests['php_version']['description'] = 'PHP version found: '.$ver.".\n\n";
-    if (version_compare($ver, '5.1.0') < 0)
-    {
-      $tests['php_version']['status'] = 0;
-      $tests['php_version']['description'] .= 'This version of PHP is not compatible with the PHP XMLRPC library. Please upgrade to 5.1.0 or later';
-    }
-    else
-    {
-      $tests['php_version']['status'] = 2;
-      $tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
-    }
-
-    // test for zlib
-    $tests['zlib'] = array();
-    if (!function_exists('gzinflate'))
-    {
-      $tests['zlib']['status'] = 0;
-      $tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to send compressed requests or receive compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
-    }
-    else
-    {
-      $tests['zlib']['status'] = 2;
-      $tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to send compressed requests and receive compressed responses for the 'HTTP' protocol";
-    }
-
-    // test for CURL
-    $tests['curl'] = array();
-    if (!extension_loaded('curl'))
-    {
-      $tests['curl']['status'] = 0;
-      $tests['curl']['description'] = "The cURL extension is not enabled.\n\nYou will not be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
-    }
-    else
-    {
-      $info = curl_version();
-      $tests['curl']['status'] = 2;
-      $tests['curl']['description'] = "The cURL extension is enabled.\n\nYou will be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
-      if (version_compare($ver, '4.3.8') < 0)
-      {
-        $tests['curl']['status'] = 1;
-        $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support keep-alives";
-      }
-      if (!((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
-      {
-        $tests['curl']['status'] = 1;
-        $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support compressed messages";
-      }
-      if (!((is_string($info) && strpos($info, 'OpenSSL') !== null) || isset($info['ssl_version'])))
-      {
-        $tests['curl']['status'] = 1;
-        $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support HTTPS connections";
-      }
-    }
-
-  }
-  return $tests;
-}
-
-?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
-<head>
-<title>PHP XMLRPC compatibility assessment</title>
-<style type="text/css">
-body, html {background-color: white; font-family: Arial, Verdana, Geneva, sans-serif; font-size: small; }
-table { border: 1px solid gray; padding: 0;}
-thead { background-color: silver; color: black; }
-td { margin: 0; padding: 0.5em; }
-tbody td { border-top: 1px solid gray; }
-.res0 { background-color: red; color: black; border-right: 1px solid gray; }
-.res1 { background-color: yellow; color: black; border-right: 1px solid gray; }
-.res2 { background-color: green; color: black; border-right: 1px solid gray; }
-.result { white-space: pre; }
-</style>
-</head>
-<body>
-<h1>PHPXMLRPC compatibility assessment with the current PHP install</h1>
-<h4>For phpxmlrpc version 3.0 or later</h4>
-<h3>Server usage</h3>
-<table cellspacing="0">
-<thead>
-<tr><td>Test</td><td>Result</td></tr>
-</thead>
-<tbody>
-<?php
-  $res = phpxmlrpc_verify_compat('server');
-  foreach($res as $test => $result)
-  {
-      echo '<tr><td class="res'.$result['status'].'">'.htmlspecialchars($test).'</td><td class="result">'.htmlspecialchars($result['description'])."</td></tr>\n";
-  }
-?>
-</tbody>
-</table>
-<h3>Client usage</h3>
-<table cellspacing="0">
-<thead>
-<tr><td>Test</td><td>Result</td></tr>
-</thead>
-<tbody>
-<?php
-  $res = phpxmlrpc_verify_compat('client');
-  foreach($res as $test => $result)
-  {
-      echo '<tr><td class="res'.$result['status'].'">'.htmlspecialchars($test).'</td><td class="result">'.htmlspecialchars($result['description'])."</td></tr>\n";
-  }
-?>
-</tbody>
-</table>
-</body>
-</html>
\ No newline at end of file
diff --git a/tests/1ParsingBugsTest.php b/tests/1ParsingBugsTest.php
new file mode 100644 (file)
index 0000000..d9a432a
--- /dev/null
@@ -0,0 +1,575 @@
+<?php
+/**
+ * NB: do not let your IDE fool you. The correct encoding for this file is NOT UTF8.
+ */
+include_once __DIR__ . '/../lib/xmlrpc.inc';
+include_once __DIR__ . '/../lib/xmlrpcs.inc';
+
+include_once __DIR__ . '/parse_args.php';
+
+/**
+ * Tests involving parsing of xml and handling of xmlrpc values
+ */
+class ParsingBugsTests extends PHPUnit_Framework_TestCase
+{
+    public $args = array();
+
+    protected function setUp()
+    {
+        $this->args = argParser::getArgs();
+        if ($this->args['DEBUG'] == 1)
+            ob_start();
+    }
+
+    protected function tearDown()
+    {
+        if ($this->args['DEBUG'] != 1)
+            return;
+        $out = ob_get_clean();
+        $status = $this->getStatus();
+        if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
+            || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
+            echo $out;
+        }
+    }
+
+    protected function newMsg($methodName, $params = array())
+    {
+        $msg = new xmlrpcmsg($methodName, $params);
+        $msg->setDebug($this->args['DEBUG']);
+        return $msg;
+    }
+
+    public function testMinusOneString()
+    {
+        $v = new xmlrpcval('-1');
+        $u = new xmlrpcval('-1', 'string');
+        $t = new xmlrpcval(-1, 'string');
+        $this->assertEquals($v->scalarval(), $u->scalarval());
+        $this->assertEquals($v->scalarval(), $t->scalarval());
+    }
+
+    /**
+     * This looks funny, and we might call it a bug. But we strive for 100 backwards compat...
+     */
+    public function testMinusOneInt()
+    {
+        $u = new xmlrpcval();
+        $v = new xmlrpcval(-1);
+        $this->assertEquals($u->scalarval(), $v->scalarval());
+    }
+
+    public function testUnicodeInMemberName()
+    {
+        $str = "G" . chr(252) . "nter, El" . chr(232) . "ne";
+        $v = array($str => new xmlrpcval(1));
+        $r = new xmlrpcresp(new xmlrpcval($v, 'struct'));
+        $r = $r->serialize();
+        $m = $this->newMsg('dummy');
+        $r = $m->parseResponse($r);
+        $v = $r->value();
+        $this->assertEquals(true, $v->structmemexists($str));
+    }
+
+    public function testUnicodeInErrorString()
+    {
+        $response = utf8_encode(
+            '<?xml version="1.0"?>
+<!-- $Id -->
+<!-- found by G. giunta, covers what happens when lib receives
+  UTF8 chars in response text and comments -->
+<!-- ' . chr(224) . chr(252) . chr(232) . '&#224;&#252;&#232; -->
+<methodResponse>
+<fault>
+<value>
+<struct>
+<member>
+<name>faultCode</name>
+<value><int>888</int></value>
+</member>
+<member>
+<name>faultString</name>
+<value><string>' . chr(224) . chr(252) . chr(232) . '&#224;&#252;&#232;</string></value>
+</member>
+</struct>
+</value>
+</fault>
+</methodResponse>');
+        $m = $this->newMsg('dummy');
+        $r = $m->parseResponse($response);
+        $v = $r->faultString();
+        $this->assertEquals(chr(224) . chr(252) . chr(232) . chr(224) . chr(252) . chr(232), $v);
+    }
+
+    public function testValidNumbers()
+    {
+        $m = $this->newMsg('dummy');
+        $fp =
+            '<?xml version="1.0"?>
+<methodResponse>
+<params>
+<param>
+<value>
+<struct>
+<member>
+<name>integer1</name>
+<value><int>01</int></value>
+</member>
+<member>
+<name>float1</name>
+<value><double>01.10</double></value>
+</member>
+<member>
+<name>integer2</name>
+<value><int>+1</int></value>
+</member>
+<member>
+<name>float2</name>
+<value><double>+1.10</double></value>
+</member>
+<member>
+<name>float3</name>
+<value><double>-1.10e2</double></value>
+</member>
+</struct>
+</value>
+</param>
+</params>
+</methodResponse>';
+        $r = $m->parseResponse($fp);
+        $v = $r->value();
+        $s = $v->structmem('integer1');
+        $t = $v->structmem('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());
+    }
+
+    public function testAddScalarToStruct()
+    {
+        $v = new xmlrpcval(array('a' => 'b'), 'struct');
+        // use @ operator in case error_log gets on screen
+        $r = @$v->addscalar('c');
+        $this->assertEquals(0, $r);
+    }
+
+    public function testAddStructToStruct()
+    {
+        $v = new xmlrpcval(array('a' => new xmlrpcval('b')), 'struct');
+        $r = $v->addstruct(array('b' => new xmlrpcval('c')));
+        $this->assertEquals(2, $v->structsize());
+        $this->assertEquals(1, $r);
+        $r = $v->addstruct(array('b' => new xmlrpcval('b')));
+        $this->assertEquals(2, $v->structsize());
+    }
+
+    public function testAddArrayToArray()
+    {
+        $v = new xmlrpcval(array(new xmlrpcval('a'), new xmlrpcval('b')), 'array');
+        $r = $v->addarray(array(new xmlrpcval('b'), new xmlrpcval('c')));
+        $this->assertEquals(4, $v->arraysize());
+        $this->assertEquals(1, $r);
+    }
+
+    public function testEncodeArray()
+    {
+        $r = range(1, 100);
+        $v = php_xmlrpc_encode($r);
+        $this->assertEquals('array', $v->kindof());
+    }
+
+    public function testEncodeRecursive()
+    {
+        $v = php_xmlrpc_encode(php_xmlrpc_encode('a simple string'));
+        $this->assertEquals('scalar', $v->kindof());
+    }
+
+    public function testBrokenRequests()
+    {
+        $s = new xmlrpc_server();
+        // omitting the 'params' tag: not tolerated by the lib anymore
+        $f = '<?xml version="1.0"?>
+<methodCall>
+<methodName>system.methodHelp</methodName>
+<param>
+<value><string>system.methodHelp</string></value>
+</param>
+</methodCall>';
+        $r = $s->parserequest($f);
+        $this->assertEquals(15, $r->faultCode());
+        // omitting a 'param' tag
+        $f = '<?xml version="1.0"?>
+<methodCall>
+<methodName>system.methodHelp</methodName>
+<params>
+<value><string>system.methodHelp</string></value>
+</params>
+</methodCall>';
+        $r = $s->parserequest($f);
+        $this->assertEquals(15, $r->faultCode());
+        // omitting a 'value' tag
+        $f = '<?xml version="1.0"?>
+<methodCall>
+<methodName>system.methodHelp</methodName>
+<params>
+<param><string>system.methodHelp</string></param>
+</params>
+</methodCall>';
+        $r = $s->parserequest($f);
+        $this->assertEquals(15, $r->faultCode());
+    }
+
+    public function testBrokenResponses()
+    {
+        $m = $this->newMsg('dummy');
+        // omitting the 'params' tag: no more tolerated by the lib...
+        $f = '<?xml version="1.0"?>
+<methodResponse>
+<param>
+<value><string>system.methodHelp</string></value>
+</param>
+</methodResponse>';
+        $r = $m->parseResponse($f);
+        $this->assertEquals(2, $r->faultCode());
+        // omitting the 'param' tag: no more tolerated by the lib...
+        $f = '<?xml version="1.0"?>
+<methodResponse>
+<params>
+<value><string>system.methodHelp</string></value>
+</params>
+</methodResponse>';
+        $r = $m->parseResponse($f);
+        $this->assertEquals(2, $r->faultCode());
+        // omitting a 'value' tag: KO
+        $f = '<?xml version="1.0"?>
+<methodResponse>
+<params>
+<param><string>system.methodHelp</string></param>
+</params>
+</methodResponse>';
+        $r = $m->parseResponse($f);
+        $this->assertEquals(2, $r->faultCode());
+    }
+
+    public function testBuggyHttp()
+    {
+        $s = $this->newMsg('dummy');
+        $f = 'HTTP/1.1 100 Welcome to the jungle
+
+HTTP/1.0 200 OK
+X-Content-Marx-Brothers: Harpo
+        Chico and Groucho
+Content-Length: who knows?
+
+
+
+<?xml version="1.0"?>
+<!-- First of all, let\'s check out if the lib properly handles a commented </methodResponse> tag... -->
+<methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
+
+
+and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+<script type="text\javascript">document.write(\'Hello, my name is added nag, I\\\'m happy to serve your content for free\');</script>
+ ';
+        $r = $s->parseResponse($f);
+        $v = $r->value();
+        $s = $v->structmem('content');
+        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
+    }
+
+    public function testStringBug()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?>
+<!-- $Id -->
+<!-- found by 2z69xks7bpy001@sneakemail.com, amongst others
+ covers what happens when there\'s character data after </string>
+ and before </value> -->
+<methodResponse>
+<params>
+<param>
+<value>
+<struct>
+<member>
+<name>success</name>
+<value>
+<boolean>1</boolean>
+</value>
+</member>
+<member>
+<name>sessionID</name>
+<value>
+<string>S300510007I</string>
+</value>
+</member>
+</struct>
+</value>
+</param>
+</params>
+</methodResponse> ';
+        $r = $s->parseResponse($f);
+        $v = $r->value();
+        $s = $v->structmem('sessionID');
+        $this->assertEquals('S300510007I', $s->scalarval());
+    }
+
+    public function testWhiteSpace()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
+
+
+and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->value();
+        $s = $v->structmem('content');
+        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s->scalarval());
+    }
+
+    public function testDoubleDataInArrayTag()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
+<data></data>
+<data></data>
+</array></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->faultCode();
+        $this->assertEquals(2, $v);
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value><array>
+<data><value>Hello world</value></data>
+<data></data>
+</array></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->faultCode();
+        $this->assertEquals(2, $v);
+    }
+
+    public function testDoubleStuffInValueTag()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value>
+<string>hello world</string>
+<array><data></data></array>
+</value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->faultCode();
+        $this->assertEquals(2, $v);
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value>
+<string>hello</string>
+<string>world</string>
+</value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->faultCode();
+        $this->assertEquals(2, $v);
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value>
+<string>hello</string>
+<struct><member><name>hello><value>world</value></member></struct>
+</value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f);
+        $v = $r->faultCode();
+        $this->assertEquals(2, $v);
+    }
+
+    public function testAutodecodeResponse()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
+
+
+and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f, true, 'phpvals');
+        $v = $r->value();
+        $s = $v['content'];
+        $this->assertEquals("hello world. 2 newlines follow\n\n\nand there they were.", $s);
+    }
+
+    public function testNoDecodeResponse()
+    {
+        $s = $this->newMsg('dummy');
+        $f = '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>hello world. 2 newlines follow
+
+
+and there they were.</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>';
+        $r = $s->parseResponse($f, true, 'xml');
+        $v = $r->value();
+        $this->assertEquals($f, $v);
+    }
+
+    public function testAutoCoDec()
+    {
+        $data1 = array(1, 1.0, 'hello world', true, '20051021T23:43:00', -1, 11.0, '~!@#$%^&*()_+|', false, '20051021T23:43:00');
+        $data2 = array('zero' => $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1);
+        $data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2);
+        //$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
+        $v1 = php_xmlrpc_encode($data, array('auto_dates'));
+        $v2 = php_xmlrpc_decode_xml($v1->serialize());
+        $this->assertEquals($v1, $v2);
+        $r1 = new PhpXmlRpc\Response($v1);
+        $r2 = php_xmlrpc_decode_xml($r1->serialize());
+        $r2->serialize(); // needed to set internal member payload
+        $this->assertEquals($r1, $r2);
+        $m1 = new PhpXmlRpc\Request('hello dolly', array($v1));
+        $m2 = php_xmlrpc_decode_xml($m1->serialize());
+        $m2->serialize(); // needed to set internal member payload
+        $this->assertEquals($m1, $m2);
+    }
+
+    public function testUTF8Request()
+    {
+        $sendstring = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string!
+        $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
+        \PhpXmlRpc\PhpXmlRpc::importGlobals();
+        $f = new xmlrpcval($sendstring, 'string');
+        $v = $f->serialize();
+        $this->assertEquals("<value><string>&#954;&#8057;&#963;&#956;&#949;</string></value>\n", $v);
+        $GLOBALS['xmlrpc_internalencoding'] = 'ISO-8859-1';
+        \PhpXmlRpc\PhpXmlRpc::importGlobals();
+    }
+
+    public function testUTF8Response()
+    {
+        $string = chr(224) . chr(252) . chr(232);
+
+        $s = $this->newMsg('dummy');
+        $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=UTF-8\r\n\r\n" . '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . utf8_encode($string) . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f, false, 'phpvals');
+        $v = $r->value();
+        $v = $v['content'];
+        $this->assertEquals($string, $v);
+
+        $f = '<?xml version="1.0" encoding="UTF-8"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . utf8_encode($string) . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f, false, 'phpvals');
+        $v = $r->value();
+        $v = $v['content'];
+        $this->assertEquals($string, $v);
+
+        $r = php_xmlrpc_decode_xml($f);
+        $v = $r->value();
+        $v = $v->structmem('content')->scalarval();
+        $this->assertEquals($string, $v);
+    }
+
+    public function testLatin1Response()
+    {
+        $string = chr(224) . chr(252) . chr(232);
+
+        $s = $this->newMsg('dummy');
+        $f = "HTTP/1.1 200 OK\r\nContent-type: text/xml; charset=ISO-8859-1\r\n\r\n" . '<?xml version="1.0"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . $string . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f, false, 'phpvals');
+        $v = $r->value();
+        $v = $v['content'];
+        $this->assertEquals($string, $v);
+
+        $f = '<?xml version="1.0" encoding="ISO-8859-1"?><methodResponse><params><param><value><struct><member><name>userid</name><value>311127</value></member>
+<member><name>dateCreated</name><value><dateTime.iso8601>20011126T09:17:52</dateTime.iso8601></value></member><member><name>content</name><value>' . $string . '</value></member><member><name>postid</name><value>7414222</value></member></struct></value></param></params></methodResponse>
+';
+        $r = $s->parseResponse($f, false, 'phpvals');
+        $v = $r->value();
+        $v = $v['content'];
+        $this->assertEquals($string, $v);
+
+        $r = php_xmlrpc_decode_xml($f);
+        $v = $r->value();
+        $v = $v->structmem('content')->scalarval();
+        $this->assertEquals($string, $v);
+    }
+
+    public function testUTF8IntString()
+    {
+        $v = new xmlrpcval(100, 'int');
+        $s = $v->serialize('UTF-8');
+        $this->assertequals("<value><int>100</int></value>\n", $s);
+    }
+
+    public function testStringInt()
+    {
+        $v = new xmlrpcval('hello world', 'int');
+        $s = $v->serialize();
+        $this->assertequals("<value><int>0</int></value>\n", $s);
+    }
+
+    public function testStructMemExists()
+    {
+        $v = php_xmlrpc_encode(array('hello' => 'world'));
+        $b = $v->structmemexists('hello');
+        $this->assertequals(true, $b);
+        $b = $v->structmemexists('world');
+        $this->assertequals(false, $b);
+    }
+
+    public function testNilvalue()
+    {
+        // default case: we do not accept nil values received
+        $v = new xmlrpcval('hello', 'null');
+        $r = new xmlrpcresp($v);
+        $s = $r->serialize();
+        $m = $this->newMsg('dummy');
+        $r = $m->parseresponse($s);
+        $this->assertequals(2, $r->faultCode());
+        // enable reception of nil values
+        $GLOBALS['xmlrpc_null_extension'] = true;
+        \PhpXmlRpc\PhpXmlRpc::importGlobals();
+        $r = $m->parseresponse($s);
+        $v = $r->value();
+        $this->assertequals('null', $v->scalartyp());
+        // test with the apache version: EX:NIL
+        $GLOBALS['xmlrpc_null_apache_encoding'] = true;
+        \PhpXmlRpc\PhpXmlRpc::importGlobals();
+        // serialization
+        $v = new xmlrpcval('hello', 'null');
+        $s = $v->serialize();
+        $this->assertequals(1, preg_match('#<value><ex:nil/></value>#', $s));
+        // deserialization
+        $r = new xmlrpcresp($v);
+        $s = $r->serialize();
+        $r = $m->parseresponse($s);
+        $v = $r->value();
+        $this->assertequals('null', $v->scalartyp());
+        $GLOBALS['xmlrpc_null_extension'] = false;
+        \PhpXmlRpc\PhpXmlRpc::importGlobals();
+        $r = $m->parseresponse($s);
+        $this->assertequals(2, $r->faultCode());
+    }
+
+    public function TestLocale()
+    {
+        $locale = setlocale(LC_NUMERIC, 0);
+        /// @todo on php 5.3/win setting locale to german does not seem to set decimal separator to comma...
+        if (setlocale(LC_NUMERIC, 'deu', 'de_DE@euro', 'de_DE', 'de', 'ge') !== false) {
+            $v = new xmlrpcval(1.1, 'double');
+            if (strpos($v->scalarval(), ',') == 1) {
+                $r = $v->serialize();
+                $this->assertequals(false, strpos($r, ','));
+                setlocale(LC_NUMERIC, $locale);
+            } else {
+                setlocale(LC_NUMERIC, $locale);
+                $this->markTestSkipped('did not find a locale which sets decimal separator to comma');
+            }
+        } else {
+            $this->markTestSkipped('did not find a locale which sets decimal separator to comma');
+        }
+    }
+}
diff --git a/tests/2InvalidHostTest.php b/tests/2InvalidHostTest.php
new file mode 100644 (file)
index 0000000..1c81b55
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+
+include_once __DIR__ . '/../lib/xmlrpc.inc';
+
+include_once __DIR__ . '/parse_args.php';
+
+/**
+ * Tests involving requests sent to non-existing servers
+ */
+class InvalidHostTest extends PHPUnit_Framework_TestCase
+{
+    /** @var xmlrpc_client $client */
+    public $client = null;
+    public $args = array();
+
+    public function setUp()
+    {
+        $this->args = argParser::getArgs();
+
+        $this->client = new xmlrpc_client('/NOTEXIST.php', $this->args['LOCALSERVER'], 80);
+        $this->client->setDebug($this->args['DEBUG']);
+
+        if ($this->args['DEBUG'] == 1)
+            ob_start();
+    }
+
+    protected function tearDown()
+    {
+        if ($this->args['DEBUG'] != 1)
+            return;
+        $out = ob_get_clean();
+        $status = $this->getStatus();
+        if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
+            || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
+            echo $out;
+        }
+    }
+
+    public function test404()
+    {
+        $m = new xmlrpcmsg('examples.echo', array(
+            new xmlrpcval('hello', 'string'),
+        ));
+        $r = $this->client->send($m, 5);
+        $this->assertEquals(5, $r->faultCode());
+    }
+
+    public function testSrvNotFound()
+    {
+        $m = new xmlrpcmsg('examples.echo', array(
+            new xmlrpcval('hello', 'string'),
+        ));
+        $this->client->server .= 'XXX';
+        $r = $this->client->send($m, 5);
+        // make sure there's no freaking catchall DNS in effect
+        $dnsinfo = dns_get_record($this->client->server);
+        if ($dnsinfo) {
+            $this->markTestSkipped('Seems like there is a catchall DNS in effect: host ' . $this->client->server . ' found');
+        } else {
+            $this->assertEquals(5, $r->faultCode());
+        }
+    }
+
+    public function testCurlKAErr()
+    {
+        if (!function_exists('curl_init')) {
+            $this->markTestSkipped('CURL missing: cannot test curl keepalive errors');
+
+            return;
+        }
+        $m = new xmlrpcmsg('examples.stringecho', array(
+            new xmlrpcval('hello', 'string'),
+        ));
+        // test 2 calls w. keepalive: 1st time connection ko, second time ok
+        $this->client->server .= 'XXX';
+        $this->client->keepalive = true;
+        $r = $this->client->send($m, 5, 'http11');
+        // in case we have a "universal dns resolver" getting in the way, we might get a 302 instead of a 404
+        $this->assertTrue($r->faultCode() === 8 || $r->faultCode() == 5);
+
+        // now test a successful connection
+        $server = explode(':', $this->args['LOCALSERVER']);
+        if (count($server) > 1) {
+            $this->client->port = $server[1];
+        }
+        $this->client->server = $server[0];
+        $this->client->path = $this->args['URI'];
+
+        $r = $this->client->send($m, 5, 'http11');
+        $this->assertEquals(0, $r->faultCode());
+        $ro = $r->value();
+        is_object($ro) && $this->assertEquals('hello', $ro->scalarVal());
+    }
+}
diff --git a/tests/3LocalhostTest.php b/tests/3LocalhostTest.php
new file mode 100644 (file)
index 0000000..0290dbf
--- /dev/null
@@ -0,0 +1,955 @@
+<?php
+
+include_once __DIR__ . '/../lib/xmlrpc.inc';
+include_once __DIR__ . '/../lib/xmlrpc_wrappers.inc';
+
+include_once __DIR__ . '/parse_args.php';
+
+/**
+ * Tests which involve interaction between the client and the server.
+ * They are run against the server found in demo/server.php
+ */
+class LocalhostTest extends PHPUnit_Framework_TestCase
+{
+    /** @var xmlrpc_client $client */
+    protected $client = null;
+    protected $method = 'http';
+    protected $timeout = 10;
+    protected $request_compression = null;
+    protected $accepted_compression = '';
+    protected $args = array();
+
+    protected static $failed_tests = array();
+
+    protected $testId;
+    /** @var boolean $collectCodeCoverageInformation */
+    protected $collectCodeCoverageInformation;
+    protected $coverageScriptUrl;
+
+    public static function fail($message = '')
+    {
+        // save in a static var that this particular test has failed
+        // (but only if not called from subclass objects / multitests)
+        if (function_exists('debug_backtrace') && strtolower(get_called_class()) == 'localhosttests') {
+            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
+            for ($i = 0; $i < count($trace); $i++) {
+                if (strpos($trace[$i]['function'], 'test') === 0) {
+                    self::$failed_tests[$trace[$i]['function']] = true;
+                    break;
+                }
+            }
+        }
+
+        parent::fail($message);
+    }
+
+    /**
+     * Reimplemented to allow us to collect code coverage info from the target server.
+     * Code taken from PHPUnit_Extensions_Selenium2TestCase
+     *
+     * @param PHPUnit_Framework_TestResult $result
+     * @return PHPUnit_Framework_TestResult
+     * @throws Exception
+     */
+    public function run(PHPUnit_Framework_TestResult $result = NULL)
+    {
+        $this->testId = get_class($this) . '__' . $this->getName();
+
+        if ($result === NULL) {
+            $result = $this->createResult();
+        }
+
+        $this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation();
+
+        parent::run($result);
+
+        if ($this->collectCodeCoverageInformation) {
+            $coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage(
+                $this->coverageScriptUrl,
+                $this->testId
+            );
+            $result->getCodeCoverage()->append(
+                $coverage->get(), $this
+            );
+        }
+
+        // do not call this before to give the time to the Listeners to run
+        //$this->getStrategy()->endOfTest($this->session);
+
+        return $result;
+    }
+
+    public function setUp()
+    {
+        $this->args = argParser::getArgs();
+
+        $server = explode(':', $this->args['LOCALSERVER']);
+        if (count($server) > 1) {
+            $this->client = new xmlrpc_client($this->args['URI'], $server[0], $server[1]);
+        } else {
+            $this->client = new xmlrpc_client($this->args['URI'], $this->args['LOCALSERVER']);
+        }
+
+        $this->client->setDebug($this->args['DEBUG']);
+        $this->client->request_compression = $this->request_compression;
+        $this->client->accepted_compression = $this->accepted_compression;
+
+        $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
+
+        if ($this->args['DEBUG'] == 1)
+            ob_start();
+    }
+
+    protected function tearDown()
+    {
+        if ($this->args['DEBUG'] != 1)
+            return;
+        $out = ob_get_clean();
+        $status = $this->getStatus();
+        if ($status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR
+            || $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) {
+            echo $out;
+        }
+    }
+
+    /**
+     * @param PhpXmlRpc\Request|array $msg
+     * @param int|array $errorCode
+     * @param bool $returnResponse
+     * @return mixed|\PhpXmlRpc\Response|\PhpXmlRpc\Response[]|\PhpXmlRpc\Value|string|void
+     */
+    protected function send($msg, $errorCode = 0, $returnResponse = false)
+    {
+        if ($this->collectCodeCoverageInformation) {
+            $this->client->setCookie('PHPUNIT_SELENIUM_TEST_ID', $this->testId);
+        }
+
+        $r = $this->client->send($msg, $this->timeout, $this->method);
+        // for multicall, return directly array of responses
+        if (is_array($r)) {
+            return $r;
+        }
+        if (is_array($errorCode)) {
+            $this->assertContains($r->faultCode(), $errorCode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
+        } else {
+            $this->assertEquals($errorCode, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
+        }
+        if (!$r->faultCode()) {
+            if ($returnResponse) {
+                return $r;
+            } else {
+                return $r->value();
+            }
+        } else {
+            return;
+        }
+    }
+
+    public function testString()
+    {
+        $sendString = "here are 3 \"entities\": < > & " .
+            "and here's a dollar sign: \$pretendvarname and a backslash too: " . chr(92) .
+            " - isn't that great? \\\"hackery\\\" at it's best " .
+            " also don't want to miss out on \$item[0]. " .
+            "The real weird stuff follows: CRLF here" . chr(13) . chr(10) .
+            "a simple CR here" . chr(13) .
+            "a simple LF here" . chr(10) .
+            "and then LFCR" . chr(10) . chr(13) .
+            "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->";
+        $m = new xmlrpcmsg('examples.stringecho', array(
+            new xmlrpcval($sendString, 'string'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            // when sending/receiving non-US-ASCII encoded strings, XML says cr-lf can be normalized.
+            // so we relax our tests...
+            $l1 = strlen($sendString);
+            $l2 = strlen($v->scalarval());
+            if ($l1 == $l2) {
+                $this->assertEquals($sendString, $v->scalarval());
+            } else {
+                $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval());
+            }
+        }
+    }
+
+    public function testLatin1String()
+    {
+        $sendString =
+            "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne";
+        $x = '<?xml version="1.0" encoding="ISO-8859-1"?><methodCall><methodName>examples.stringecho</methodName><params><param><value>'.
+            $sendString.
+            '</value></param></params></methodCall>';
+        $v = $this->send($x);
+        if ($v) {
+            $this->assertEquals($sendString, $v->scalarval());
+        }
+    }
+
+    public function testExoticCharsetsRequests()
+    {
+        // note that we should disable this call also when mbstring is missing server-side
+        if (!function_exists('mb_convert_encoding')) {
+            $this->markTestSkipped('Miss mbstring extension to test exotic charsets');
+            return;
+        }
+        $sendString = 'κόσμε'; // Greek word 'kosme'. NB: NOT a valid ISO8859 string!
+        $str = '<?xml version="1.0" encoding="_ENC_"?>
+<methodCall>
+    <methodName>examples.stringecho</methodName>
+    <params>
+        <param>
+        <value><string>'.$sendString.'</string></value>
+        </param>
+    </params>
+</methodCall>';
+
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
+        // we have to set the encoding declaration either in the http header or xml prolog, as mb_detect_encoding
+        // (used on the server side) will fail recognizing these 2 charsets
+        $v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UCS-4', $str), 'UCS-4', 'UTF-8'));
+        $this->assertEquals($sendString, $v->scalarval());
+        $v = $this->send(mb_convert_encoding(str_replace('_ENC_', 'UTF-16', $str), 'UTF-16', 'UTF-8'));
+        $this->assertEquals($sendString, $v->scalarval());
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
+    }
+
+    public function testExoticCharsetsRequests2()
+    {
+        // note that we should disable this call also when mbstring is missing server-side
+        if (!function_exists('mb_convert_encoding')) {
+            $this->markTestSkipped('Miss mbstring extension to test exotic charsets');
+            return;
+        }
+        $sendString = '安室奈美恵'; // No idea what this means :-) NB: NOT a valid ISO8859 string!
+        $str = '<?xml version="1.0"?>
+<methodCall>
+    <methodName>examples.stringecho</methodName>
+    <params>
+        <param>
+        <value><string>'.$sendString.'</string></value>
+        </param>
+    </params>
+</methodCall>';
+
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
+        // no encoding declaration either in the http header or xml prolog, let mb_detect_encoding
+        // (used on the server side) sort it out
+        $this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=EUC-JP&DETECT_ENCODINGS[]=UTF-8';
+        $v = $this->send(mb_convert_encoding($str, 'EUC-JP', 'UTF-8'));
+        $this->assertEquals($sendString, $v->scalarval());
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
+    }
+
+    public function testExoticCharsetsRequests3()
+    {
+        // note that we should disable this call also when mbstring is missing server-side
+        if (!function_exists('mb_convert_encoding')) {
+            $this->markTestSkipped('Miss mbstring extension to test exotic charsets');
+            return;
+        }
+        $sendString = utf8_decode('élève');
+        $str = '<?xml version="1.0"?>
+<methodCall>
+    <methodName>examples.stringecho</methodName>
+    <params>
+        <param>
+        <value><string>'.$sendString.'</string></value>
+        </param>
+    </params>
+</methodCall>';
+
+        // no encoding declaration either in the http header or xml prolog, let mb_detect_encoding
+        // (used on the server side) sort it out
+        $this->client->path = $this->args['URI'].'?DETECT_ENCODINGS[]=ISO-8859-1&DETECT_ENCODINGS[]=UTF-8';
+        $v = $this->send($str);
+        $this->assertEquals($sendString, $v->scalarval());
+    }
+
+    /*public function testLatin1Method()
+    {
+        $f = new xmlrpcmsg("tests.iso88591methodname." . chr(224) . chr(252) . chr(232), array(
+            new xmlrpcval('hello')
+        ));
+        $v = $this->send($f);
+        if ($v) {
+            $this->assertEquals('hello', $v->scalarval());
+        }
+    }*/
+
+    public function testUtf8Method()
+    {
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'UTF-8';
+        $m = new xmlrpcmsg("tests.utf8methodname." . 'κόσμε', array(
+            new xmlrpcval('hello')
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals('hello', $v->scalarval());
+        }
+        PhpXmlRpc\PhpXmlRpc::$xmlrpc_internalencoding = 'ISO-8859-1';
+    }
+
+    public function testAddingDoubles()
+    {
+        // note that rounding errors mean we
+        // keep precision to sensible levels here ;-)
+        $a = 12.13;
+        $b = -23.98;
+        $m = new xmlrpcmsg('examples.addtwodouble', array(
+            new xmlrpcval($a, 'double'),
+            new xmlrpcval($b, 'double'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals($a + $b, $v->scalarval());
+        }
+    }
+
+    public function testAdding()
+    {
+        $m = new xmlrpcmsg('examples.addtwo', array(
+            new xmlrpcval(12, 'int'),
+            new xmlrpcval(-23, 'int'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals(12 - 23, $v->scalarval());
+        }
+    }
+
+    public function testInvalidNumber()
+    {
+        $m = new xmlrpcmsg('examples.addtwo', array(
+            new xmlrpcval('fred', 'int'),
+            new xmlrpcval("\"; exec('ls')", 'int'),
+        ));
+        $v = $this->send($m);
+        /// @todo a fault condition should be generated here
+        /// by the server, which we pick up on
+        if ($v) {
+            $this->assertEquals(0, $v->scalarval());
+        }
+    }
+
+    public function testBoolean()
+    {
+        $m = new xmlrpcmsg('examples.invertBooleans', array(
+            new xmlrpcval(array(
+                new xmlrpcval(true, 'boolean'),
+                new xmlrpcval(false, 'boolean'),
+                new xmlrpcval(1, 'boolean'),
+                new xmlrpcval(0, 'boolean')
+            ),
+                'array'
+            ),));
+        $answer = '0101';
+        $v = $this->send($m);
+        if ($v) {
+            $sz = $v->arraysize();
+            $got = '';
+            for ($i = 0; $i < $sz; $i++) {
+                $b = $v->arraymem($i);
+                if ($b->scalarval()) {
+                    $got .= '1';
+                } else {
+                    $got .= '0';
+                }
+            }
+            $this->assertEquals($answer, $got);
+        }
+    }
+
+    public function testBase64()
+    {
+        $sendString = 'Mary had a little lamb,
+Whose fleece was white as snow,
+And everywhere that Mary went
+the lamb was sure to go.
+
+Mary had a little lamb
+She tied it to a pylon
+Ten thousand volts went down its back
+And turned it into nylon';
+        $m = new xmlrpcmsg('examples.decode64', array(
+            new xmlrpcval($sendString, 'base64'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            if (strlen($sendString) == strlen($v->scalarval())) {
+                $this->assertEquals($sendString, $v->scalarval());
+            } else {
+                $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendString), $v->scalarval());
+            }
+        }
+    }
+
+    public function testDateTime()
+    {
+        $time = time();
+        $t1 = new xmlrpcval($time, 'dateTime.iso8601');
+        $t2 = new xmlrpcval(iso8601_encode($time), 'dateTime.iso8601');
+        $this->assertEquals($t1->serialize(), $t2->serialize());
+        if (class_exists('DateTime')) {
+            $datetime = new DateTime();
+            // skip this test for php 5.2. It is a bit harder there to build a DateTime from unix timestamp with proper TZ info
+            if (is_callable(array($datetime, 'setTimestamp'))) {
+                $t3 = new xmlrpcval($datetime->setTimestamp($time), 'dateTime.iso8601');
+                $this->assertEquals($t1->serialize(), $t3->serialize());
+            }
+        }
+    }
+
+    public function testCountEntities()
+    {
+        $sendString = "h'fd>onc>>l>>rw&bpu>q>e<v&gxs<ytjzkami<";
+        $m = new xmlrpcmsg('validator1.countTheEntities', array(
+            new xmlrpcval($sendString, 'string'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $got = '';
+            $expected = '37210';
+            $expect_array = array('ctLeftAngleBrackets', 'ctRightAngleBrackets', 'ctAmpersands', 'ctApostrophes', 'ctQuotes');
+            while (list(, $val) = each($expect_array)) {
+                $b = $v->structmem($val);
+                $got .= $b->me['int'];
+            }
+            $this->assertEquals($expected, $got);
+        }
+    }
+
+    public function _multicall_msg($method, $params)
+    {
+        $struct['methodName'] = new xmlrpcval($method, 'string');
+        $struct['params'] = new xmlrpcval($params, 'array');
+
+        return new xmlrpcval($struct, 'struct');
+    }
+
+    public function testServerMulticall()
+    {
+        // We manually construct a system.multicall() call to ensure
+        // that the server supports it.
+
+        // NB: This test will NOT pass if server does not support system.multicall.
+
+        // Based on http://xmlrpc-c.sourceforge.net/hacks/test_multicall.py
+        $good1 = $this->_multicall_msg(
+            'system.methodHelp',
+            array(php_xmlrpc_encode('system.listMethods')));
+        $bad = $this->_multicall_msg(
+            'test.nosuch',
+            array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
+        $recursive = $this->_multicall_msg(
+            'system.multicall',
+            array(new xmlrpcval(array(), 'array')));
+        $good2 = $this->_multicall_msg(
+            'system.methodSignature',
+            array(php_xmlrpc_encode('system.listMethods')));
+        $arg = new xmlrpcval(
+            array($good1, $bad, $recursive, $good2),
+            'array'
+        );
+
+        $m = new xmlrpcmsg('system.multicall', array($arg));
+        $v = $this->send($m);
+        if ($v) {
+            //$this->assertTrue($r->faultCode() == 0, "fault from system.multicall");
+            $this->assertTrue($v->arraysize() == 4, "bad number of return values");
+
+            $r1 = $v->arraymem(0);
+            $this->assertTrue(
+                $r1->kindOf() == 'array' && $r1->arraysize() == 1,
+                "did not get array of size 1 from good1"
+            );
+
+            $r2 = $v->arraymem(1);
+            $this->assertTrue(
+                $r2->kindOf() == 'struct',
+                "no fault from bad"
+            );
+
+            $r3 = $v->arraymem(2);
+            $this->assertTrue(
+                $r3->kindOf() == 'struct',
+                "recursive system.multicall did not fail"
+            );
+
+            $r4 = $v->arraymem(3);
+            $this->assertTrue(
+                $r4->kindOf() == 'array' && $r4->arraysize() == 1,
+                "did not get array of size 1 from good2"
+            );
+        }
+    }
+
+    public function testClientMulticall1()
+    {
+        // NB: This test will NOT pass if server does not support system.multicall.
+
+        $this->client->no_multicall = false;
+
+        $good1 = new xmlrpcmsg('system.methodHelp',
+            array(php_xmlrpc_encode('system.listMethods')));
+        $bad = new xmlrpcmsg('test.nosuch',
+            array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
+        $recursive = new xmlrpcmsg('system.multicall',
+            array(new xmlrpcval(array(), 'array')));
+        $good2 = new xmlrpcmsg('system.methodSignature',
+            array(php_xmlrpc_encode('system.listMethods'))
+        );
+
+        $r = $this->send(array($good1, $bad, $recursive, $good2));
+        if ($r) {
+            $this->assertTrue(count($r) == 4, "wrong number of return values");
+        }
+
+        $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
+        if (!$r[0]->faultCode()) {
+            $val = $r[0]->value();
+            $this->assertTrue(
+                $val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
+                "good1 did not return string"
+            );
+        }
+        $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
+        $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
+        $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
+        if (!$r[3]->faultCode()) {
+            $val = $r[3]->value();
+            $this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
+        }
+        // This is the only assert in this test which should fail
+        // if the test server does not support system.multicall.
+        $this->assertTrue($this->client->no_multicall == false,
+            "server does not support system.multicall"
+        );
+    }
+
+    public function testClientMulticall2()
+    {
+        // NB: This test will NOT pass if server does not support system.multicall.
+
+        $this->client->no_multicall = true;
+
+        $good1 = new xmlrpcmsg('system.methodHelp',
+            array(php_xmlrpc_encode('system.listMethods')));
+        $bad = new xmlrpcmsg('test.nosuch',
+            array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
+        $recursive = new xmlrpcmsg('system.multicall',
+            array(new xmlrpcval(array(), 'array')));
+        $good2 = new xmlrpcmsg('system.methodSignature',
+            array(php_xmlrpc_encode('system.listMethods'))
+        );
+
+        $r = $this->send(array($good1, $bad, $recursive, $good2));
+        if ($r) {
+            $this->assertTrue(count($r) == 4, "wrong number of return values");
+        }
+
+        $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
+        if (!$r[0]->faultCode()) {
+            $val = $r[0]->value();
+            $this->assertTrue(
+                $val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
+                "good1 did not return string");
+        }
+        $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
+        $this->assertTrue($r[2]->faultCode() == 0, "fault from (non recursive) system.multicall");
+        $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
+        if (!$r[3]->faultCode()) {
+            $val = $r[3]->value();
+            $this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
+        }
+    }
+
+    public function testClientMulticall3()
+    {
+        // NB: This test will NOT pass if server does not support system.multicall.
+
+        $this->client->return_type = 'phpvals';
+        $this->client->no_multicall = false;
+
+        $good1 = new xmlrpcmsg('system.methodHelp',
+            array(php_xmlrpc_encode('system.listMethods')));
+        $bad = new xmlrpcmsg('test.nosuch',
+            array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
+        $recursive = new xmlrpcmsg('system.multicall',
+            array(new xmlrpcval(array(), 'array')));
+        $good2 = new xmlrpcmsg('system.methodSignature',
+            array(php_xmlrpc_encode('system.listMethods'))
+        );
+
+        $r = $this->send(array($good1, $bad, $recursive, $good2));
+        if ($r) {
+            $this->assertTrue(count($r) == 4, "wrong number of return values");
+        }
+        $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
+        if (!$r[0]->faultCode()) {
+            $val = $r[0]->value();
+            $this->assertTrue(
+                is_string($val), "good1 did not return string");
+        }
+        $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
+        $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
+        $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
+        if (!$r[3]->faultCode()) {
+            $val = $r[3]->value();
+            $this->assertTrue(is_array($val), "good2 did not return array");
+        }
+        $this->client->return_type = 'xmlrpcvals';
+    }
+
+    public function testCatchWarnings()
+    {
+        $m = new xmlrpcmsg('tests.generatePHPWarning', array(
+            new xmlrpcval('whatever', 'string'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals(true, $v->scalarval());
+        }
+    }
+
+    public function testCatchExceptions()
+    {
+        $m = new xmlrpcmsg('tests.raiseException', array(
+            new xmlrpcval('whatever', 'string'),
+        ));
+        $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
+        $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1';
+        $v = $this->send($m, 1); // the error code of the expected exception
+        $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2';
+        // depending on whether display_errors is ON or OFF on the server, we will get back a different error here,
+        // as php will generate an http status code of either 200 or 500...
+        $v = $this->send($m, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error']));
+    }
+
+    public function testZeroParams()
+    {
+        $m = new xmlrpcmsg('system.listMethods');
+        $v = $this->send($m);
+    }
+
+    public function testNullParams()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.12', array(
+            new xmlrpcval('whatever', 'null'),
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals('Michigan', $v->scalarval());
+        }
+        $m = new xmlrpcmsg('tests.getStateName.12', array(
+            new xmlrpcval(23, 'int'),
+            new xmlrpcval('whatever', 'null'),
+        ));
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals('Michigan', $v->scalarval());
+        }
+        $m = new xmlrpcmsg('tests.getStateName.12', array(
+            new xmlrpcval(23, 'int')
+        ));
+        $v = $this->send($m, array($GLOBALS['xmlrpcerr']['incorrect_params']));
+    }
+
+    public function testCodeInjectionServerSide()
+    {
+        $m = new xmlrpcmsg('system.MethodHelp');
+        $m->payload = "<?xml version=\"1.0\"?><methodCall><methodName>validator1.echoStructTest</methodName><params><param><value><struct><member><name>','')); echo('gotcha!'); die(); //</name></member></struct></value></param></params></methodCall>";
+        $v = $this->send($m);
+        if ($v) {
+            $this->assertEquals(0, $v->structsize());
+        }
+    }
+
+    public function testServerWrappedFunction()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.2', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        // this generates an exception in the function which was wrapped, which is by default wrapped in a known error response
+        $m = new xmlrpcmsg('tests.getStateName.2', array(
+            new xmlrpcval(0, 'int'),
+        ));
+        $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
+
+        // check if the generated function dispatch map is fine, by checking if the server registered it
+        $m = new xmlrpcmsg('system.methodSignature', array(
+            new xmlrpcval('tests.getStateName.2'),
+        ));
+        $v = $this->send($m);
+        $encoder = new \PhpXmlRpc\Encoder();
+        $this->assertEquals(array(array('string', 'int')), $encoder->decode($v));
+    }
+
+    public function testServerWrappedFunctionAsSource()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.6', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        // this generates an exception in the function which was wrapped, which is by default wrapped in a known error response
+        $m = new xmlrpcmsg('tests.getStateName.6', array(
+            new xmlrpcval(0, 'int'),
+        ));
+        $v = $this->send($m, $GLOBALS['xmlrpcerr']['server_error']);
+    }
+
+    public function testServerWrappedObjectMethods()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.3', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.4', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.5', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.7', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.8', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.9', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+    }
+
+    public function testServerWrappedObjectMethodsAsSource()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.7', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.8', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+
+        $m = new xmlrpcmsg('tests.getStateName.9', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+    }
+
+    public function testServerClosure()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.10', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+    }
+
+    public function testServerWrappedClosure()
+    {
+        $m = new xmlrpcmsg('tests.getStateName.11', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+    }
+
+    public function testServerWrappedClass()
+    {
+        $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.findState', array(
+            new xmlrpcval(23, 'int'),
+        ));
+        $v = $this->send($m);
+        $this->assertEquals('Michigan', $v->scalarval());
+    }
+
+    public function testWrappedMethod()
+    {
+        // make a 'deep client copy' as the original one might have many properties set
+        $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0));
+        if ($func == false) {
+            $this->fail('Registration of examples.getStateName failed');
+        } else {
+            $v = $func(23);
+            // work around bug in current (or old?) version of phpunit when reporting the error
+            /*if (is_object($v)) {
+                $v = var_export($v, true);
+            }*/
+            $this->assertEquals('Michigan', $v);
+        }
+    }
+
+    public function testWrappedMethodAsSource()
+    {
+        // make a 'deep client copy' as the original one might have many properties set
+        $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 0, 'return_source' => true));
+        if ($func == false) {
+            $this->fail('Registration of examples.getStateName failed');
+        } else {
+            eval($func['source']);
+            $func = $func['function'];
+            $v = $func(23);
+            // work around bug in current (or old?) version of phpunit when reporting the error
+            /*if (is_object($v)) {
+                $v = var_export($v, true);
+            }*/
+            $this->assertEquals('Michigan', $v);
+        }
+    }
+
+    public function testWrappedClass()
+    {
+        // make a 'deep client copy' as the original one might have many properties set
+        // also for speed only wrap one method of the whole server
+        $class = wrap_xmlrpc_server($this->client, array('simple_client_copy' => 0, 'method_filter' => '/examples\.getStateName/' ));
+        if ($class == '') {
+            $this->fail('Registration of remote server failed');
+        } else {
+            $obj = new $class();
+            $v = $obj->examples_getStateName(23);
+            // work around bug in current (or old?) version of phpunit when reporting the error
+            /*if (is_object($v)) {
+                $v = var_export($v, true);
+            }*/
+            $this->assertEquals('Michigan', $v);
+        }
+    }
+
+    public function testTransferOfObjectViaWrapping()
+    {
+        // make a 'deep client copy' as the original one might have many properties set
+        $func = wrap_xmlrpc_method($this->client, 'tests.returnPhpObject', array('simple_client_copy' => true,
+            'decode_php_objs' => true));
+        if ($func == false) {
+            $this->fail('Registration of tests.returnPhpObject failed');
+        } else {
+            $v = $func();
+            $obj = new stdClass();
+            $obj->hello = 'world';
+            $this->assertEquals($obj, $v);
+        }
+    }
+
+    public function testGetCookies()
+    {
+        // let server set to us some cookies we tell it
+        $cookies = array(
+            //'c1' => array(),
+            'c2' => array('value' => 'c2'),
+            'c3' => array('value' => 'c3', 'expires' => time() + 60 * 60 * 24 * 30),
+            'c4' => array('value' => 'c4', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/'),
+            'c5' => array('value' => 'c5', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'localhost'),
+        );
+        $cookiesval = php_xmlrpc_encode($cookies);
+        $m = new xmlrpcmsg('examples.setcookies', array($cookiesval));
+        $r = $this->send($m, 0, true);
+        if ($r) {
+            $v = $r->value();
+            $this->assertEquals(1, $v->scalarval());
+            // now check if we decoded the cookies as we had set them
+            $rcookies = $r->cookies();
+            // remove extra cookies which might have been set by proxies
+            foreach ($rcookies as $c => $v) {
+                if (!in_array($c, array('c2', 'c3', 'c4', 'c5'))) {
+                    unset($rcookies[$c]);
+                }
+                // Seems like we get this when using php-fpm and php 5.5+ ...
+                if (isset($rcookies[$c]['Max-Age'])) {
+                    unset($rcookies[$c]['Max-Age']);
+                }
+            }
+            foreach ($cookies as $c => $v) {
+                // format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT'
+                // but PHP versions differ on that, some use 'Mon, 31-Oct-2005 13:50:56 GMT'...
+                if (isset($v['expires'])) {
+                    if (isset($rcookies[$c]['expires']) && strpos($rcookies[$c]['expires'], '-')) {
+                        $cookies[$c]['expires'] = gmdate('D, d\-M\-Y H:i:s \G\M\T', $cookies[$c]['expires']);
+                    } else {
+                        $cookies[$c]['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $cookies[$c]['expires']);
+                    }
+                }
+            }
+
+            $this->assertEquals($cookies, $rcookies);
+        }
+    }
+
+    public function testSetCookies()
+    {
+        // let server set to us some cookies we tell it
+        $cookies = array(
+            'c0' => null,
+            'c1' => 1,
+            'c2' => '2 3',
+            'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-',
+        );
+        $m = new xmlrpcmsg('examples.getcookies', array());
+        foreach ($cookies as $cookie => $val) {
+            $this->client->setCookie($cookie, $val);
+            $cookies[$cookie] = (string)$cookies[$cookie];
+        }
+        $r = $this->client->send($m, $this->timeout, $this->method);
+        $this->assertEquals(0, $r->faultCode(), 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
+        if (!$r->faultCode()) {
+            $v = $r->value();
+            $v = php_xmlrpc_decode($v);
+
+            // take care for the extra cookie used for coverage collection
+            if (isset($v['PHPUNIT_SELENIUM_TEST_ID'])) {
+                unset($v['PHPUNIT_SELENIUM_TEST_ID']);
+            }
+
+            // on IIS and Apache getallheaders returns something slightly different...
+            $this->assertEquals($cookies, $v);
+        }
+    }
+
+    public function testServerComments()
+    {
+        $m = new xmlrpcmsg('tests.xmlrpcServerMethodsContainer.debugMessageGenerator', array(
+            new xmlrpcval('hello world', 'string'),
+        ));
+        $r = $this->send($m, 0, true);
+        $this->assertContains('hello world', $r->raw_data);
+    }
+
+    public function testSendTwiceSameMsg()
+    {
+        $m = new xmlrpcmsg('examples.stringecho', array(
+            new xmlrpcval('hello world', 'string'),
+        ));
+        $v1 = $this->send($m);
+        $v2 = $this->send($m);
+        if ($v1 && $v2) {
+            $this->assertEquals($v1, $v2);
+        }
+    }
+}
diff --git a/tests/4LocalhostMultiTest.php b/tests/4LocalhostMultiTest.php
new file mode 100644 (file)
index 0000000..e5d365a
--- /dev/null
@@ -0,0 +1,215 @@
+<?php
+
+include_once __DIR__ . '/../lib/xmlrpc.inc';
+include_once __DIR__ . '/../lib/xmlrpc_wrappers.inc';
+
+include_once __DIR__ . '/parse_args.php';
+
+include_once __DIR__ . '/3LocalhostTest.php';
+
+/**
+ * Tests which stress http features of the library.
+ * Each of these tests iterates over (almost) all of the 'localhost' tests
+ */
+class LocalhostMultiTest extends LocalhostTest
+{
+    /**
+     * @todo reintroduce skipping of tests which failed when executed individually if test runs happen as separate processes
+     * @todo reintroduce skipping of tests within the loop
+     */
+    function _runtests()
+    {
+        $unsafeMethods = array('testHttps', 'testCatchExceptions', 'testUtf8Method', 'testServerComments', 'testExoticCharsetsRequests', 'testExoticCharsetsRequests2', 'testExoticCharsetsRequests3');
+        foreach(get_class_methods('LocalhostTest') as $method)
+        {
+            if(strpos($method, 'test') === 0 && !in_array($method, $unsafeMethods))
+            {
+                if (!isset(self::$failed_tests[$method]))
+                    $this->$method();
+            }
+            /*if ($this->_failed)
+            {
+                break;
+            }*/
+        }
+    }
+
+    function testDeflate()
+    {
+        if(!function_exists('gzdeflate'))
+        {
+            $this->markTestSkipped('Zlib missing: cannot test deflate functionality');
+            return;
+        }
+        $this->client->accepted_compression = array('deflate');
+        $this->client->request_compression = 'deflate';
+        $this->_runtests();
+    }
+
+    function testGzip()
+    {
+        if(!function_exists('gzdeflate'))
+        {
+            $this->markTestSkipped('Zlib missing: cannot test gzip functionality');
+            return;
+        }
+        $this->client->accepted_compression = array('gzip');
+        $this->client->request_compression = 'gzip';
+        $this->_runtests();
+    }
+
+    function testKeepAlives()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test http 1.1');
+            return;
+        }
+        $this->method = 'http11';
+        $this->client->keepalive = true;
+        $this->_runtests();
+    }
+
+    function testProxy()
+    {
+        if ($this->args['PROXYSERVER'])
+        {
+            $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
+            $this->_runtests();
+        }
+        else
+            $this->markTestSkipped('PROXY definition missing: cannot test proxy');
+    }
+
+    function testHttp11()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test http 1.1');
+            return;
+        }
+        $this->method = 'http11'; // not an error the double assignment!
+        $this->client->method = 'http11';
+        //$this->client->verifyhost = 0;
+        //$this->client->verifypeer = 0;
+        $this->client->keepalive = false;
+        $this->_runtests();
+    }
+
+    function testHttp11Gzip()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test http 1.1');
+            return;
+        }
+        $this->method = 'http11'; // not an error the double assignment!
+        $this->client->method = 'http11';
+        $this->client->keepalive = false;
+        $this->client->accepted_compression = array('gzip');
+        $this->client->request_compression = 'gzip';
+        $this->_runtests();
+    }
+
+    function testHttp11Deflate()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test http 1.1');
+            return;
+        }
+        $this->method = 'http11'; // not an error the double assignment!
+        $this->client->method = 'http11';
+        $this->client->keepalive = false;
+        $this->client->accepted_compression = array('deflate');
+        $this->client->request_compression = 'deflate';
+        $this->_runtests();
+    }
+
+    function testHttp11Proxy()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test http 1.1 w. proxy');
+            return;
+        }
+        else if ($this->args['PROXYSERVER'] == '')
+        {
+            $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1');
+            return;
+        }
+        $this->method = 'http11'; // not an error the double assignment!
+        $this->client->method = 'http11';
+        $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
+        //$this->client->verifyhost = 0;
+        //$this->client->verifypeer = 0;
+        $this->client->keepalive = false;
+        $this->_runtests();
+    }
+
+    function testHttps()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test https functionality');
+            return;
+        }
+        $this->client->server = $this->args['HTTPSSERVER'];
+        $this->method = 'https';
+        $this->client->method = 'https';
+        $this->client->path = $this->args['HTTPSURI'];
+        $this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']);
+        $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']);
+        $this->client->setSSLVersion($this->args['SSLVERSION']);
+        $this->_runtests();
+    }
+
+    function testHttpsProxy()
+    {
+        if(!function_exists('curl_init'))
+        {
+            $this->markTestSkipped('CURL missing: cannot test https functionality');
+            return;
+        }
+        else if ($this->args['PROXYSERVER'] == '')
+        {
+            $this->markTestSkipped('PROXY definition missing: cannot test proxy w. http 1.1');
+            return;
+        }
+        $this->client->server = $this->args['HTTPSSERVER'];
+        $this->method = 'https';
+        $this->client->method = 'https';
+        $this->client->setProxy($this->args['PROXYSERVER'], $this->args['PROXYPORT']);
+        $this->client->path = $this->args['HTTPSURI'];
+        $this->client->setSSLVerifyPeer(!$this->args['HTTPSIGNOREPEER']);
+        $this->client->setSSLVerifyHost($this->args['HTTPSVERIFYHOST']);
+        $this->client->setSSLVersion($this->args['SSLVERSION']);
+        $this->_runtests();
+    }
+
+    function testUTF8Responses()
+    {
+        //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8';
+        $this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=UTF-8';
+        $this->_runtests();
+    }
+
+    function testUTF8Requests()
+    {
+        $this->client->request_charset_encoding = 'UTF-8';
+        $this->_runtests();
+    }
+
+    function testISOResponses()
+    {
+        //$this->client->path = strpos($URI, '?') === null ? $URI.'?RESPONSE_ENCODING=UTF-8' : $URI.'&RESPONSE_ENCODING=UTF-8';
+        $this->client->path = $this->args['URI'].'?RESPONSE_ENCODING=ISO-8859-1';
+        $this->_runtests();
+    }
+
+    function testISORequests()
+    {
+        $this->client->request_charset_encoding = 'ISO-8859-1';
+        $this->_runtests();
+    }
+}
diff --git a/tests/5DemofilesTest.php b/tests/5DemofilesTest.php
new file mode 100644 (file)
index 0000000..3cbb5b4
--- /dev/null
@@ -0,0 +1,76 @@
+<?php
+
+include_once __DIR__ . '/LocalFileTestCase.php';
+
+/**
+ * Tests for php files in the 'demo' directory
+ */
+class DemoFilesTest extends PhpXmlRpc_LocalFileTestCase
+{
+    public function setUp()
+    {
+        $this->args = argParser::getArgs();
+
+        $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/demo/', $this->args['URI'] );
+
+        $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
+    }
+
+    public function testAgeSort()
+    {
+        $page = $this->request('client/agesort.php');
+    }
+
+    public function testGetStateName()
+    {
+        $page = $this->request('client/getstatename.php');
+        $page = $this->request('client/getstatename.php', 'POST', array('stateno' => '1'));
+    }
+
+    public function testIntrospect()
+    {
+        $page = $this->request('client/introspect.php');
+    }
+
+    public function testMail()
+    {
+        $page = $this->request('client/mail.php');
+        $page = $this->request('client/mail.php', 'POST', array(
+            "mailto" => '',
+            "mailsub" => '',
+            "mailmsg" => '',
+            "mailfrom" => '',
+            "mailcc" => '',
+            "mailbcc" => '',
+        ));
+    }
+
+    public function testProxy()
+    {
+        $page = $this->request('client/proxy.php', 'GET', null, true);
+    }
+
+    public function testWhich()
+    {
+        $page = $this->request('client/which.php');
+    }
+
+    public function testWrap()
+    {
+        $page = $this->request('client/wrap.php');
+    }
+
+    public function testDiscussServer()
+    {
+        $page = $this->request('server/discuss.php');
+        $this->assertContains('<name>faultCode</name>', $page);
+        $this->assertRegexp('#<int>10(5|3)</int>#', $page);
+    }
+
+    public function testProxyServer()
+    {
+        $page = $this->request('server/proxy.php');
+        $this->assertContains('<name>faultCode</name>', $page);
+        $this->assertRegexp('#<int>10(5|3)</int>#', $page);
+    }
+}
diff --git a/tests/6DebuggerTest.php b/tests/6DebuggerTest.php
new file mode 100644 (file)
index 0000000..db0e850
--- /dev/null
@@ -0,0 +1,37 @@
+<?php
+
+include_once __DIR__ . '/LocalFileTestCase.php';
+
+class DebuggerTest extends PhpXmlRpc_LocalFileTestCase
+{
+    public function setUp()
+    {
+        $this->args = argParser::getArgs();
+
+        $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/debugger/', $this->args['URI'] );
+
+        $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
+    }
+
+    public function testIndex()
+    {
+        $page = $this->request('index.php');
+    }
+
+    public function testController()
+    {
+        $page = $this->request('controller.php');
+    }
+
+    /**
+     * @todo test:
+     * - list methods
+     * - describe a method
+     * - execute a method
+     * - wrap a method
+     */
+    public function testAction()
+    {
+        $page = $this->request('action.php');
+    }
+}
diff --git a/tests/7ExtraTest.php b/tests/7ExtraTest.php
new file mode 100644 (file)
index 0000000..14488e8
--- /dev/null
@@ -0,0 +1,23 @@
+<?php
+
+include_once __DIR__ . '/LocalFileTestCase.php';
+
+/**
+ * Tests for php files in the 'extras' directory
+ */
+class ExtraTest extends PhpXmlRpc_LocalFileTestCase
+{
+    public function setUp()
+    {
+        $this->args = argParser::getArgs();
+
+        $this->baseUrl = $this->args['LOCALSERVER'] . str_replace( '/demo/server/server.php', '/tests/', $this->args['URI'] );
+
+        $this->coverageScriptUrl = 'http://' . $this->args['LOCALSERVER'] . '/' . str_replace( '/demo/server/server.php', 'tests/phpunit_coverage.php', $this->args['URI'] );
+    }
+
+    public function testVerifyCompat()
+    {
+        $page = $this->request('verify_compat.php');
+    }
+}
\ No newline at end of file
diff --git a/tests/LocalFileTestCase.php b/tests/LocalFileTestCase.php
new file mode 100644 (file)
index 0000000..59818c8
--- /dev/null
@@ -0,0 +1,80 @@
+<?php
+
+include_once __DIR__ . '/parse_args.php';
+
+abstract class PhpXmlRpc_LocalFileTestCase extends PHPUnit_Framework_TestCase
+{
+    public $args = array();
+
+    protected $baseUrl;
+
+    protected $testId;
+    /** @var boolean $collectCodeCoverageInformation */
+    protected $collectCodeCoverageInformation;
+    protected $coverageScriptUrl;
+
+    public function run(PHPUnit_Framework_TestResult $result = NULL)
+    {
+        $this->testId = get_class($this) . '__' . $this->getName();
+
+        if ($result === NULL) {
+            $result = $this->createResult();
+        }
+
+        $this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation();
+
+        parent::run($result);
+
+        if ($this->collectCodeCoverageInformation) {
+            $coverage = new PHPUnit_Extensions_SeleniumCommon_RemoteCoverage(
+                $this->coverageScriptUrl,
+                $this->testId
+            );
+            $result->getCodeCoverage()->append(
+                $coverage->get(), $this
+            );
+        }
+
+        // do not call this before to give the time to the Listeners to run
+        //$this->getStrategy()->endOfTest($this->session);
+
+        return $result;
+    }
+
+    protected function request($file, $method = 'GET', $payload = '', $emptyPageOk = false)
+    {
+        $url = $this->baseUrl . $file;
+
+        $ch = curl_init($url);
+        curl_setopt_array($ch, array(
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_FAILONERROR => true
+        ));
+        if ($method == 'POST')
+        {
+            curl_setopt_array($ch, array(
+                CURLOPT_POST => true,
+                CURLOPT_POSTFIELDS => $payload
+            ));
+        }
+        if ($this->collectCodeCoverageInformation)
+        {
+            curl_setopt($ch, CURLOPT_COOKIE, 'PHPUNIT_SELENIUM_TEST_ID=true');
+        }
+        if ($this->args['DEBUG'] > 0) {
+            curl_setopt($ch, CURLOPT_VERBOSE, 1);
+        }
+        $page = curl_exec($ch);
+        curl_close($ch);
+
+        $this->assertNotFalse($page);
+        if (!$emptyPageOk) {
+            $this->assertNotEquals('', $page);
+        }
+        $this->assertNotContains('Fatal error', $page);
+        $this->assertNotContains('Notice:', $page);
+
+        return $page;
+    }
+
+}
diff --git a/tests/benchmark.php b/tests/benchmark.php
new file mode 100644 (file)
index 0000000..43cbc42
--- /dev/null
@@ -0,0 +1,311 @@
+<?php
+/**
+ * Benchmarking suite for the PHP-XMLRPC lib.
+ *
+ * @author Gaetano Giunta
+ * @copyright (c) 2005-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ *
+ * @todo add a test for response ok in call testing
+ * @todo add support for --help option to give users the list of supported parameters
+ **/
+
+use PhpXmlRpc\PhpXmlRpc;
+use PhpXmlRpc\Value;
+use PhpXmlRpc\Request;
+use PhpXmlRpc\Client;
+use PhpXmlRpc\Response;
+use PhpXmlRpc\Encoder;
+
+include_once __DIR__ . '/../vendor/autoload.php';
+
+include __DIR__ . '/parse_args.php';
+$args = argParser::getArgs();
+
+function begin_test($test_name, $test_case)
+{
+    global $test_results;
+    if (!isset($test_results[$test_name])) {
+        $test_results[$test_name] = array();
+    }
+    $test_results[$test_name][$test_case] = array();
+    $test_results[$test_name][$test_case]['time'] = microtime(true);
+}
+
+function end_test($test_name, $test_case, $test_result)
+{
+    global $test_results;
+    $end = microtime(true);
+    if (!isset($test_results[$test_name][$test_case])) {
+        trigger_error('ending test that was not started');
+    }
+    $test_results[$test_name][$test_case]['time'] = $end - $test_results[$test_name][$test_case]['time'];
+    $test_results[$test_name][$test_case]['result'] = $test_result;
+    echo '.';
+    flush();
+    @ob_flush();
+}
+
+// Set up PHP structures to be used in many tests
+
+$data1 = array(1, 1.0, 'hello world', true, '20051021T23:43:00', -1, 11.0, '~!@#$%^&*()_+|', false, '20051021T23:43:00');
+$data2 = array('zero' => $data1, 'one' => $data1, 'two' => $data1, 'three' => $data1, 'four' => $data1, 'five' => $data1, 'six' => $data1, 'seven' => $data1, 'eight' => $data1, 'nine' => $data1);
+$data = array($data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2, $data2);
+$keys = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
+
+// Begin execution
+
+$test_results = array();
+$is_web = isset($_SERVER['REQUEST_METHOD']);
+$xd = extension_loaded('xdebug') && ini_get('xdebug.profiler_enable');
+if ($xd) {
+    $num_tests = 1;
+} else {
+    $num_tests = 10;
+}
+
+$title = 'XML-RPC Benchmark Tests';
+
+if ($is_web) {
+    echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n<head>\n<title>$title</title>\n</head>\n<body>\n<h1>$title</h1>\n<pre>\n";
+} else {
+    echo "$title\n\n";
+}
+
+if ($is_web) {
+    echo "<h3>Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "</h3>\n";
+    if ($xd) {
+        echo "<h4>XDEBUG profiling enabled: skipping remote tests. Trace file is: " . htmlspecialchars(xdebug_get_profiler_filename()) . "</h4>\n";
+    }
+    flush();
+    ob_flush();
+} else {
+    echo "Using lib version: " . PhpXmlRpc::$xmlrpcVersion . " on PHP version: " . phpversion() . "\n";
+    if ($xd) {
+        echo "XDEBUG profiling enabled: skipping remote tests\nTrace file is: " . xdebug_get_profiler_filename() . "\n";
+    }
+}
+
+// test 'manual style' data encoding vs. 'automatic style' encoding
+begin_test('Data encoding (large array)', 'manual encoding');
+for ($i = 0; $i < $num_tests; $i++) {
+    $vals = array();
+    for ($j = 0; $j < 10; $j++) {
+        $valarray = array();
+        foreach ($data[$j] as $key => $val) {
+            $values = array();
+            $values[] = new Value($val[0], 'int');
+            $values[] = new Value($val[1], 'double');
+            $values[] = new Value($val[2], 'string');
+            $values[] = new Value($val[3], 'boolean');
+            $values[] = new Value($val[4], 'dateTime.iso8601');
+            $values[] = new Value($val[5], 'int');
+            $values[] = new Value($val[6], 'double');
+            $values[] = new Value($val[7], 'string');
+            $values[] = new Value($val[8], 'boolean');
+            $values[] = new Value($val[9], 'dateTime.iso8601');
+            $valarray[$key] = new Value($values, 'array');
+        }
+        $vals[] = new Value($valarray, 'struct');
+    }
+    $value = new Value($vals, 'array');
+    $out = $value->serialize();
+}
+end_test('Data encoding (large array)', 'manual encoding', $out);
+
+begin_test('Data encoding (large array)', 'automatic encoding');
+$encoder = new Encoder();
+for ($i = 0; $i < $num_tests; $i++) {
+    $value = $encoder->encode($data, array('auto_dates'));
+    $out = $value->serialize();
+}
+end_test('Data encoding (large array)', 'automatic encoding', $out);
+
+if (function_exists('xmlrpc_set_type')) {
+    begin_test('Data encoding (large array)', 'xmlrpc-epi encoding');
+    for ($i = 0; $i < $num_tests; $i++) {
+        for ($j = 0; $j < 10; $j++) {
+            foreach ($keys as $k) {
+                xmlrpc_set_type($data[$j][$k][4], 'datetime');
+                xmlrpc_set_type($data[$j][$k][8], 'datetime');
+            }
+        }
+        $out = xmlrpc_encode($data);
+    }
+    end_test('Data encoding (large array)', 'xmlrpc-epi encoding', $out);
+}
+
+// test 'old style' data decoding vs. 'automatic style' decoding
+$dummy = new Request('');
+$out = new Response($value);
+$in = '<?xml version="1.0" ?>' . "\n" . $out->serialize();
+
+begin_test('Data decoding (large array)', 'manual decoding');
+for ($i = 0; $i < $num_tests; $i++) {
+    $response = $dummy->ParseResponse($in, true);
+    $value = $response->value();
+    $result = array();
+    foreach($value as $val1) {
+        $out = array();
+        foreach($val1 as $name => $val) {
+            $out[$name] = array();
+            foreach($val as $data) {
+                $out[$name][] = $data->scalarval();
+            }
+        }
+        $result[] = $out;
+    }
+}
+end_test('Data decoding (large array)', 'manual decoding', $result);
+
+begin_test('Data decoding (large array)', 'manual decoding deprecated');
+for ($i = 0; $i < $num_tests; $i++) {
+    $response = $dummy->ParseResponse($in, true);
+    $value = $response->value();
+    $result = array();
+    $l = $value->arraysize();
+    for ($k = 0; $k < $l; $k++) {
+        $val1 = $value->arraymem($k);
+        $out = array();
+        while (list($name, $val) = $val1->structeach()) {
+            $out[$name] = array();
+            $m = $val->arraysize();
+            for ($j = 0; $j < $m; $j++) {
+                $data = $val->arraymem($j);
+                $out[$name][] = $data->scalarval();
+            }
+        } // while
+        $result[] = $out;
+    }
+}
+end_test('Data decoding (large array)', 'manual decoding deprecated', $result);
+
+begin_test('Data decoding (large array)', 'automatic decoding');
+for ($i = 0; $i < $num_tests; $i++) {
+    $response = $dummy->ParseResponse($in, true, 'phpvals');
+    $value = $response->value();
+}
+end_test('Data decoding (large array)', 'automatic decoding', $value);
+
+if (function_exists('xmlrpc_decode')) {
+    begin_test('Data decoding (large array)', 'xmlrpc-epi decoding');
+    for ($i = 0; $i < $num_tests; $i++) {
+        $response = $dummy->ParseResponse($in, true, 'xml');
+        $value = xmlrpc_decode($response->value());
+    }
+    end_test('Data decoding (large array)', 'xmlrpc-epi decoding', $value);
+}
+
+if (!$xd) {
+
+    /// test multicall vs. many calls vs. keep-alives
+    $encoder = new Encoder();
+    $value = $encoder->encode($data1, array('auto_dates'));
+    $req = new Request('interopEchoTests.echoValue', array($value));
+    $reqs = array();
+    for ($i = 0; $i < 25; $i++) {
+        $reqs[] = $req;
+    }
+    $server = explode(':', $args['LOCALSERVER']);
+    if (count($server) > 1) {
+        $srv = $server[1] . '://' . $server[0] . $args['URI'];
+        $c = new Client($args['URI'], $server[0], $server[1]);
+    } else {
+        $srv = $args['LOCALSERVER'] . $args['URI'];
+        $c = new Client($args['URI'], $args['LOCALSERVER']);
+    }
+    // do not interfere with http compression
+    $c->accepted_compression = array();
+    //$c->debug=true;
+
+    $testName = "Repeated send (small array) to $srv";
+
+    if (function_exists('gzinflate')) {
+        $c->accepted_compression = null;
+    }
+    begin_test($testName, 'http 10');
+    $response = array();
+    for ($i = 0; $i < 25; $i++) {
+        $resp = $c->send($req);
+        $response[] = $resp->value();
+    }
+    end_test($testName, 'http 10', $response);
+
+    if (function_exists('curl_init')) {
+        begin_test($testName, 'http 11 w. keep-alive');
+        $response = array();
+        for ($i = 0; $i < 25; $i++) {
+            $resp = $c->send($req, 10, 'http11');
+            $response[] = $resp->value();
+        }
+        end_test($testName, 'http 11 w. keep-alive', $response);
+
+        $c->keepalive = false;
+        begin_test($testName, 'http 11');
+        $response = array();
+        for ($i = 0; $i < 25; $i++) {
+            $resp = $c->send($req, 10, 'http11');
+            $response[] = $resp->value();
+        }
+        end_test($testName, 'http 11', $response);
+    }
+
+    begin_test($testName, 'multicall');
+    $response = $c->send($reqs);
+    foreach ($response as $key => & $val) {
+        $val = $val->value();
+    }
+    end_test($testName, 'multicall', $response);
+
+    if (function_exists('gzinflate')) {
+        $c->accepted_compression = array('gzip');
+        $c->request_compression = 'gzip';
+
+        begin_test($testName, 'http 10 w. compression');
+        $response = array();
+        for ($i = 0; $i < 25; $i++) {
+            $resp = $c->send($req);
+            $response[] = $resp->value();
+        }
+        end_test($testName, 'http 10 w. compression', $response);
+
+        if (function_exists('curl_init')) {
+            begin_test($testName, 'http 11 w. keep-alive and compression');
+            $response = array();
+            for ($i = 0; $i < 25; $i++) {
+                $resp = $c->send($req, 10, 'http11');
+                $response[] = $resp->value();
+            }
+            end_test($testName, 'http 11 w. keep-alive and compression', $response);
+
+            $c->keepalive = false;
+            begin_test($testName, 'http 11 w. compression');
+            $response = array();
+            for ($i = 0; $i < 25; $i++) {
+                $resp = $c->send($req, 10, 'http11');
+                $response[] = $resp->value();
+            }
+            end_test($testName, 'http 11 w. compression', $response);
+        }
+
+        begin_test($testName, 'multicall w. compression');
+        $response = $c->send($reqs);
+        foreach ($response as $key => & $val) {
+            $val = $val->value();
+        }
+        end_test($testName, 'multicall w. compression', $response);
+    }
+} // end of 'if no xdebug profiling'
+
+
+echo "\n";
+foreach ($test_results as $test => $results) {
+    echo "\nTEST: $test\n";
+    foreach ($results as $case => $data) {
+        echo "  $case: {$data['time']} secs - Output data CRC: " . crc32(serialize($data['result'])) . "\n";
+    }
+}
+
+if ($is_web) {
+    echo "\n</pre>\n</body>\n</html>\n";
+}
diff --git a/tests/ci/travis/apache_vhost b/tests/ci/travis/apache_vhost
new file mode 100644 (file)
index 0000000..87841d6
--- /dev/null
@@ -0,0 +1,68 @@
+# Configuration file for Apache running on Travis.
+# PHP setup in FCGI mode
+
+<VirtualHost *:80>
+
+  DocumentRoot %TRAVIS_BUILD_DIR%
+
+  ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
+  CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
+
+  <Directory "%TRAVIS_BUILD_DIR%">
+    Options FollowSymLinks MultiViews ExecCGI
+    AllowOverride All
+    Order deny,allow
+    Allow from all
+  </Directory>
+
+  # Wire up Apache to use Travis CI's php-fpm.
+  <IfModule mod_fastcgi.c>
+    AddHandler php5-fcgi .php
+    Action php5-fcgi /php5-fcgi
+    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
+    FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
+  </IfModule>
+
+</VirtualHost>
+
+<IfModule mod_ssl.c>
+
+<VirtualHost _default_:443>
+
+  DocumentRoot %TRAVIS_BUILD_DIR%
+
+  ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
+  CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
+
+  <Directory "%TRAVIS_BUILD_DIR%">
+    Options FollowSymLinks MultiViews ExecCGI
+    AllowOverride All
+    Order deny,allow
+    Allow from all
+  </Directory>
+
+  # Wire up Apache to use Travis CI's php-fpm.
+  <IfModule mod_fastcgi.c>
+    AddHandler php5-fcgi .php
+    Action php5-fcgi /php5-fcgi
+    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
+    #FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
+  </IfModule>
+
+  SSLEngine on
+  # This cert is bundled by default in Ubuntu
+  SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
+  SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
+
+  <FilesMatch "\.(cgi|shtml|phtml|php)$">
+    SSLOptions +StdEnvVars
+  </FilesMatch>
+
+  BrowserMatch "MSIE [2-6]" \
+  nokeepalive ssl-unclean-shutdown \
+  downgrade-1.0 force-response-1.0
+  BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
+
+</VirtualHost>
+
+</IfModule>
diff --git a/tests/ci/travis/apache_vhost_hhvm b/tests/ci/travis/apache_vhost_hhvm
new file mode 100644 (file)
index 0000000..63e57da
--- /dev/null
@@ -0,0 +1,74 @@
+# Configuration file for Apache running on Travis.
+# HHVM setup in FCGI mode
+
+<VirtualHost *:80>
+
+  DocumentRoot %TRAVIS_BUILD_DIR%
+
+  ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
+  CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
+
+  <Directory "%TRAVIS_BUILD_DIR%">
+    Options FollowSymLinks MultiViews ExecCGI
+    AllowOverride All
+    Order deny,allow
+    Allow from all
+  </Directory>
+
+  # Configure Apache for HHVM FastCGI.
+  # See https://github.com/facebook/hhvm/wiki/fastcgi
+  <IfModule mod_fastcgi.c>
+    <FilesMatch \.php$>
+      SetHandler hhvm-php-extension
+    </FilesMatch>
+    Alias /hhvm /hhvm
+    Action hhvm-php-extension /hhvm virtual
+    FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300
+  </IfModule>
+
+</VirtualHost>
+
+<IfModule mod_ssl.c>
+
+<VirtualHost _default_:443>
+
+  DocumentRoot %TRAVIS_BUILD_DIR%
+
+  ErrorLog "%TRAVIS_BUILD_DIR%/apache_error.log"
+  CustomLog "%TRAVIS_BUILD_DIR%/apache_access.log" combined
+
+  <Directory "%TRAVIS_BUILD_DIR%">
+    Options FollowSymLinks MultiViews ExecCGI
+    AllowOverride All
+    Order deny,allow
+    Allow from all
+  </Directory>
+
+  # Configure Apache for HHVM FastCGI.
+  # See https://github.com/facebook/hhvm/wiki/fastcgi
+  <IfModule mod_fastcgi.c>
+    <FilesMatch \.php$>
+      SetHandler hhvm-php-extension
+    </FilesMatch>
+    Alias /hhvm /hhvm
+    Action hhvm-php-extension /hhvm virtual
+    #FastCgiExternalServer /hhvm -host 127.0.0.1:9000 -pass-header Authorization -idle-timeout 300
+  </IfModule>
+
+  SSLEngine on
+  # This cert is bundled by default in Ubuntu
+  SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
+  SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
+
+  <FilesMatch "\.(cgi|shtml|phtml|php)$">
+    SSLOptions +StdEnvVars
+  </FilesMatch>
+
+  BrowserMatch "MSIE [2-6]" \
+  nokeepalive ssl-unclean-shutdown \
+  downgrade-1.0 force-response-1.0
+  BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
+
+</VirtualHost>
+
+</IfModule>
diff --git a/tests/ci/travis/privoxy b/tests/ci/travis/privoxy
new file mode 100644 (file)
index 0000000..67d8ff8
--- /dev/null
@@ -0,0 +1 @@
+listen-address 127.0.0.1:8080
diff --git a/tests/ci/travis/setup_apache.sh b/tests/ci/travis/setup_apache.sh
new file mode 100755 (executable)
index 0000000..a39d676
--- /dev/null
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+# set up Apache for php-fpm
+# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php
+
+sudo a2enmod rewrite actions fastcgi alias ssl
+
+# configure apache virtual hosts
+sudo cp -f tests/ci/travis/apache_vhost /etc/apache2/sites-available/default
+sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default
+sudo service apache2 restart
diff --git a/tests/ci/travis/setup_apache_hhvm.sh b/tests/ci/travis/setup_apache_hhvm.sh
new file mode 100755 (executable)
index 0000000..a72941d
--- /dev/null
@@ -0,0 +1,11 @@
+#!/bin/sh
+
+# set up Apache for hhvm-fcgi
+# @see https://github.com/travis-ci/travis-ci.github.com/blob/master/docs/user/languages/php.md#apache--php
+
+sudo a2enmod rewrite actions fastcgi alias ssl
+
+# configure apache virtual hosts
+sudo cp -f tests/ci/travis/apache_vhost_hhvm /etc/apache2/sites-available/default
+sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default
+sudo service apache2 restart
diff --git a/tests/ci/travis/setup_hhvm.sh b/tests/ci/travis/setup_hhvm.sh
new file mode 100755 (executable)
index 0000000..289e750
--- /dev/null
@@ -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 100755 (executable)
index 0000000..7788fdc
--- /dev/null
@@ -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
diff --git a/tests/ci/travis/setup_privoxy.sh b/tests/ci/travis/setup_privoxy.sh
new file mode 100755 (executable)
index 0000000..12e0e61
--- /dev/null
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+# configure privoxy
+
+sudo cp -f tests/ci/travis/privoxy /etc/privoxy/config
+sudo service privoxy restart
diff --git a/tests/parse_args.php b/tests/parse_args.php
new file mode 100644 (file)
index 0000000..6660b9e
--- /dev/null
@@ -0,0 +1,124 @@
+<?php
+
+/**
+ * Common parameter parsing for benchmark and tests scripts.
+ *
+ * @param integer DEBUG
+ * @param string  LOCALSERVER
+ * @param string  URI
+ * @param string  HTTPSSERVER
+ * @param string  HTTPSSURI
+ * @param string  PROXY
+ * @param string  NOPROXY
+ * @param bool    HTTPSIGNOREPEER
+ * @param int     HTTPSVERIFYHOST
+ * @param int     SSLVERSION
+ *
+ * @copyright (C) 2007-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ **/
+class argParser
+{
+    public static function getArgs()
+    {
+        global $argv;
+
+        $args = array(
+            'DEBUG' => 0,
+            'LOCALSERVER' => 'localhost',
+            'HTTPSSERVER' => 'gggeek.ssl.altervista.org',
+            'HTTPSURI' => '/sw/xmlrpc/demo/server/server.php',
+            'HTTPSIGNOREPEER' => false,
+            'HTTPSVERIFYHOST' => 2,
+            'SSLVERSION' => 0,
+            'PROXYSERVER' => null,
+            'NOPROXY' => false,
+            'LOCALPATH' => __DIR__,
+        );
+
+        // check for command line vs web page input params
+        if (!isset($_SERVER['REQUEST_METHOD'])) {
+            if (isset($argv)) {
+                foreach ($argv as $param) {
+                    $param = explode('=', $param);
+                    if (count($param) > 1) {
+                        $pname = strtoupper(ltrim($param[0], '-'));
+                        $$pname = $param[1];
+                    }
+                }
+            }
+        } else {
+            // NB: we might as well consider using $_GET stuff later on...
+            extract($_GET);
+            extract($_POST);
+        }
+
+        if (isset($DEBUG)) {
+            $args['DEBUG'] = intval($DEBUG);
+        }
+        if (isset($LOCALSERVER)) {
+            $args['LOCALSERVER'] = $LOCALSERVER;
+        } else {
+            if (isset($HTTP_HOST)) {
+                $args['LOCALSERVER'] = $HTTP_HOST;
+            } elseif (isset($_SERVER['HTTP_HOST'])) {
+                $args['LOCALSERVER'] = $_SERVER['HTTP_HOST'];
+            }
+        }
+        if (isset($HTTPSSERVER)) {
+            $args['HTTPSSERVER'] = $HTTPSSERVER;
+        }
+        if (isset($HTTPSURI)) {
+            $args['HTTPSURI'] = $HTTPSURI;
+        }
+        if (isset($HTTPSIGNOREPEER)) {
+            $args['HTTPSIGNOREPEER'] = (bool)$HTTPSIGNOREPEER;
+        }
+        if (isset($HTTPSVERIFYHOST)) {
+            $args['HTTPSVERIFYHOST'] = (int)$HTTPSVERIFYHOST;
+        }
+        if (isset($SSLVERSION)) {
+            $args['SSLVERSION'] = (int)$SSLVERSION;
+        }
+        if (isset($PROXY)) {
+            $arr = explode(':', $PROXY);
+            $args['PROXYSERVER'] = $arr[0];
+            if (count($arr) > 1) {
+                $args['PROXYPORT'] = $arr[1];
+            } else {
+                $args['PROXYPORT'] = 8080;
+            }
+        }
+        // used to silence testsuite warnings about proxy code not being tested
+        if (isset($NOPROXY)) {
+            $args['NOPROXY'] = true;
+        }
+        if (!isset($URI)) {
+            // GUESTIMATE the url of local demo server
+            // play nice to php 3 and 4-5 in retrieving URL of server.php
+            /// @todo filter out query string from REQUEST_URI
+            if (isset($REQUEST_URI)) {
+                $URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $REQUEST_URI);
+                $URI = str_replace('/testsuite.php', '/server.php', $URI);
+                $URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI);
+                $URI = str_replace('/benchmark.php', '/server.php', $URI);
+            } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['REQUEST_METHOD'])) {
+                $URI = str_replace('/tests/testsuite.php', '/demo/server/server.php', $_SERVER['PHP_SELF']);
+                $URI = str_replace('/testsuite.php', '/server.php', $URI);
+                $URI = str_replace('/tests/benchmark.php', '/demo/server/server.php', $URI);
+                $URI = str_replace('/benchmark.php', '/server.php', $URI);
+            } else {
+                $URI = '/demo/server/server.php';
+            }
+        }
+        if ($URI[0] != '/') {
+            $URI = '/' . $URI;
+        }
+        $args['URI'] = $URI;
+        if (isset($LOCALPATH)) {
+            $args['LOCALPATH'] = $LOCALPATH;
+        }
+
+        return $args;
+    }
+}
diff --git a/tests/phpunit_coverage.php b/tests/phpunit_coverage.php
new file mode 100644 (file)
index 0000000..ae7b998
--- /dev/null
@@ -0,0 +1,16 @@
+<?php
+/**
+ * Used to serve back the server-side code coverage results to phpunit-selenium
+ *
+ * @copyright (C) 2007-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ **/
+
+$coverageFile = realpath(__DIR__ . "/../vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumCommon/phpunit_coverage.php");
+
+// has to be the same value as used in server.php
+$GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = '/tmp/phpxmlrpc_coverage';
+
+chdir($GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY']);
+
+include_once $coverageFile;
\ No newline at end of file
diff --git a/tests/verify_compat.php b/tests/verify_compat.php
new file mode 100644 (file)
index 0000000..1d9f90c
--- /dev/null
@@ -0,0 +1,193 @@
+<?php
+/**
+ * Verify compatibility level of current php install with php-xmlrpc lib.
+ *
+ * @author Gaetano Giunta
+ * @copyright (C) 2006-2015 G. Giunta
+ * @license code licensed under the BSD License: see file license.txt
+ *
+ * @todo add a test for php output buffering?
+ */
+
+function phpxmlrpc_verify_compat($mode = 'client')
+{
+    $tests = array();
+
+    if ($mode == 'server') {
+        // test for php version
+        $ver = phpversion();
+        $tests['php_version'] = array();
+        $tests['php_version']['description'] = 'PHP version found: ' . $ver . ".\n\n";
+        if (version_compare($ver, '5.3.0') < 0) {
+            $tests['php_version']['status'] = 0;
+            $tests['php_version']['description'] .= 'This version of PHP is not compatible with this release of the PHP XMLRPC library. Please upgrade to php 5.1.0 or later';
+        } else {
+            $tests['php_version']['status'] = 2;
+            $tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
+        }
+
+        // test for zlib
+        $tests['zlib'] = array();
+        if (!function_exists('gzinflate')) {
+            $tests['zlib']['status'] = 0;
+            $tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to receive compressed requests or send compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
+        } else {
+            $tests['zlib']['status'] = 2;
+            $tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to receive compressed requests and send compressed responses for the 'HTTP' protocol";
+        }
+
+        // test for dispaly of php errors in xml reponse
+        if (ini_get('display_errors')) {
+            if (intval(ini_get('error_reporting')) && E_NOTICE) {
+                $tests['display_errors']['status'] = 1;
+                $tests['display_errors']['description'] = "Error reporting level includes E_NOTICE errors, and display_errors is set to ON.\n\nAny error, warning or notice raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
+            } else {
+                $tests['display_errors']['status'] = 1;
+                $tests['display_errors']['description'] = "display_errors is set to ON.\n\nAny error raised while executing php code exposed as xmlrpc method will result in an invalid xmlrpc response";
+            }
+        }
+    } else {
+
+        // test for php version
+        $ver = phpversion();
+        $tests['php_version'] = array();
+        $tests['php_version']['description'] = 'PHP version found: ' . $ver . ".\n\n";
+        if (version_compare($ver, '5.3.0') < 0) {
+            $tests['php_version']['status'] = 0;
+            $tests['php_version']['description'] .= 'This version of PHP is not compatible with the PHP XMLRPC library. Please upgrade to 5.1.0 or later';
+        } else {
+            $tests['php_version']['status'] = 2;
+            $tests['php_version']['description'] .= 'This version of PHP is fully compatible with the PHP XMLRPC library';
+        }
+
+        // test for zlib
+        $tests['zlib'] = array();
+        if (!function_exists('gzinflate')) {
+            $tests['zlib']['status'] = 0;
+            $tests['zlib']['description'] = "The zlib extension is not enabled.\n\nYou will not be able to send compressed requests or receive compressed responses, unless using the cURL library (for 'HTTPS' and 'HTTP 1.1' connections)";
+        } else {
+            $tests['zlib']['status'] = 2;
+            $tests['zlib']['description'] = "The zlib extension is enabled.\n\nYou will be able to send compressed requests and receive compressed responses for the 'HTTP' protocol";
+        }
+
+        // test for CURL
+        $tests['curl'] = array();
+        if (!extension_loaded('curl')) {
+            $tests['curl']['status'] = 0;
+            $tests['curl']['description'] = "The cURL extension is not enabled.\n\nYou will not be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
+        } else {
+            $info = curl_version();
+            $tests['curl']['status'] = 2;
+            $tests['curl']['description'] = "The cURL extension is enabled.\n\nYou will be able to send and receive messages using 'HTTPS' and 'HTTP 1.1' protocols";
+            if (version_compare($ver, '4.3.8') < 0) {
+                $tests['curl']['status'] = 1;
+                $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support keep-alives";
+            }
+            if (!((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version']))) {
+                $tests['curl']['status'] = 1;
+                $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support compressed messages";
+            }
+            if (!((is_string($info) && strpos($info, 'OpenSSL') !== null) || isset($info['ssl_version']))) {
+                $tests['curl']['status'] = 1;
+                $tests['curl']['description'] .= ".\nPlease note that the current cURL install does not support HTTPS connections";
+            }
+        }
+    }
+
+    return $tests;
+}
+
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+    <title>PHP XMLRPC compatibility assessment</title>
+    <style type="text/css">
+        body, html {
+            background-color: white;
+            font-family: Arial, Verdana, Geneva, sans-serif;
+            font-size: small;
+        }
+
+        table {
+            border: 1px solid gray;
+            padding: 0;
+        }
+
+        thead {
+            background-color: silver;
+            color: black;
+        }
+
+        td {
+            margin: 0;
+            padding: 0.5em;
+        }
+
+        tbody td {
+            border-top: 1px solid gray;
+        }
+
+        .res0 {
+            background-color: red;
+            color: black;
+            border-right: 1px solid gray;
+        }
+
+        .res1 {
+            background-color: yellow;
+            color: black;
+            border-right: 1px solid gray;
+        }
+
+        .res2 {
+            background-color: green;
+            color: black;
+            border-right: 1px solid gray;
+        }
+
+        .result {
+            white-space: pre;
+        }
+    </style>
+</head>
+<body>
+<h1>PHPXMLRPC compatibility assessment with the current PHP install</h1>
+<h4>For phpxmlrpc version 4.0 or later</h4>
+
+<h3>Server usage</h3>
+<table cellspacing="0">
+    <thead>
+    <tr>
+        <td>Test</td>
+        <td>Result</td>
+    </tr>
+    </thead>
+    <tbody>
+    <?php
+    $res = phpxmlrpc_verify_compat('server');
+    foreach ($res as $test => $result) {
+        echo '<tr><td class="res' . $result['status'] . '">' . htmlspecialchars($test) . '</td><td class="result">' . htmlspecialchars($result['description']) . "</td></tr>\n";
+    }
+    ?>
+    </tbody>
+</table>
+<h3>Client usage</h3>
+<table cellspacing="0">
+    <thead>
+    <tr>
+        <td>Test</td>
+        <td>Result</td>
+    </tr>
+    </thead>
+    <tbody>
+    <?php
+    $res = phpxmlrpc_verify_compat('client');
+    foreach ($res as $test => $result) {
+        echo '<tr><td class="res' . $result['status'] . '">' . htmlspecialchars($test) . '</td><td class="result">' . htmlspecialchars($result['description']) . "</td></tr>\n";
+    }
+    ?>
+    </tbody>
+</table>
+</body>
+</html>