Skip to content
Snippets Groups Projects
IXR_Library.php 32.2 KiB
Newer Older
Andreas Gohr's avatar
Andreas Gohr committed
<?php
Andreas Gohr's avatar
Andreas Gohr committed
/**
 * IXR - The Incutio XML-RPC Library
 *
 * Copyright (c) 2010, Incutio Ltd.
 * 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 Incutio Ltd. 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 COPYRIGHT HOLDER 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.
 *
 * @package IXR
 * @since 1.5
 *
 * @copyright  Incutio Ltd 2010 (http://www.incutio.com)
 * @version    1.7.4 7th September 2010
 * @author     Simon Willison
 * @link       http://scripts.incutio.com/xmlrpc/ Site/manual
Andreas Gohr's avatar
Andreas Gohr committed
 *
 * Modified for DokuWiki
 * @author  Andreas Gohr <andi@splitbrain.org>
 */
class IXR_Value {
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /** @var  IXR_Value[]|IXR_Date|IXR_Base64|int|bool|double|string */
Andreas Gohr's avatar
Andreas Gohr committed
    var $data;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var string */
Andreas Gohr's avatar
Andreas Gohr committed
    var $type;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param mixed $data
     * @param bool $type
     */
    function __construct($data, $type = false) {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->data = $data;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$type) {
Andreas Gohr's avatar
Andreas Gohr committed
            $type = $this->calculateType();
        }
        $this->type = $type;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($type == 'struct') {
            // Turn all the values in the array in to new IXR_Value objects
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            foreach($this->data as $key => $value) {
Andreas Gohr's avatar
Andreas Gohr committed
                $this->data[$key] = new IXR_Value($value);
            }
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($type == 'array') {
            for($i = 0, $j = count($this->data); $i < $j; $i++) {
Andreas Gohr's avatar
Andreas Gohr committed
                $this->data[$i] = new IXR_Value($this->data[$i]);
            }
        }
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function calculateType() {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->data === true || $this->data === false) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'boolean';
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_integer($this->data)) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'int';
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_double($this->data)) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'double';
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Deal with IXR object types base64 and date
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_object($this->data) && is_a($this->data, 'IXR_Date')) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'date';
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'base64';
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // If it is a normal PHP object convert it in to a struct
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_object($this->data)) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->data = get_object_vars($this->data);
            return 'struct';
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!is_array($this->data)) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'string';
        }

        // We have an array - is it an array or a struct?
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->isStruct($this->data)) {
Andreas Gohr's avatar
Andreas Gohr committed
            return 'struct';
        } else {
            return 'array';
        }
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return bool|string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getXml() {
        // Return XML for this value
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        switch($this->type) {
Andreas Gohr's avatar
Andreas Gohr committed
            case 'boolean':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                return '<boolean>' . (($this->data) ? '1' : '0') . '</boolean>';
Andreas Gohr's avatar
Andreas Gohr committed
                break;
            case 'int':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                return '<int>' . $this->data . '</int>';
Andreas Gohr's avatar
Andreas Gohr committed
                break;
            case 'double':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                return '<double>' . $this->data . '</double>';
Andreas Gohr's avatar
Andreas Gohr committed
                break;
            case 'string':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                return '<string>' . htmlspecialchars($this->data) . '</string>';
Andreas Gohr's avatar
Andreas Gohr committed
                break;
            case 'array':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $return = '<array><data>' . "\n";
                foreach($this->data as $item) {
                    $return .= '  <value>' . $item->getXml() . "</value>\n";
Andreas Gohr's avatar
Andreas Gohr committed
                }
                $return .= '</data></array>';
                return $return;
                break;
            case 'struct':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $return = '<struct>' . "\n";
                foreach($this->data as $name => $value) {
Andreas Gohr's avatar
Andreas Gohr committed
                    $return .= "  <member><name>$name</name><value>";
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                    $return .= $value->getXml() . "</value></member>\n";
Andreas Gohr's avatar
Andreas Gohr committed
                }
                $return .= '</struct>';
                return $return;
                break;
            case 'date':
            case 'base64':
                return $this->data->getXml();
                break;
        }
        return false;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Checks whether or not the supplied array is a struct or not
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param array $array
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function isStruct($array) {
        $expected = 0;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        foreach($array as $key => $value) {
            if((string) $key != (string) $expected) {
Andreas Gohr's avatar
Andreas Gohr committed
                return true;
            }
            $expected++;
        }
        return false;
    }
}

Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_MESSAGE
 *
 * @package IXR
 * @since 1.5
 *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Message {
    var $message;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    var $messageType; // methodCall / methodResponse / fault
Andreas Gohr's avatar
Andreas Gohr committed
    var $faultCode;
    var $faultString;
    var $methodName;
    var $params;
Andreas Gohr's avatar
Andreas Gohr committed
    // Current variable stacks
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    var $_arraystructs = array(); // The stack used to keep track of the current array/struct
Andreas Gohr's avatar
Andreas Gohr committed
    var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    var $_currentStructName = array(); // A stack as well
Andreas Gohr's avatar
Andreas Gohr committed
    var $_param;
    var $_value;
    var $_currentTag;
    var $_currentTagContents;
Andreas Gohr's avatar
Andreas Gohr committed
    // The XML parser
    var $_parser;
    function __construct($message) {
        $this->message =& $message;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return bool
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function parse() {
        // first remove the XML declaration
        // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages
        $header = preg_replace('/<\?xml.*?\?' . '>/', '', substr($this->message, 0, 100), 1);
        $this->message = substr_replace($this->message, $header, 0, 100);

        // workaround for a bug in PHP/libxml2, see http://bugs.php.net/bug.php?id=45996
        $this->message = str_replace('&lt;', '&#60;', $this->message);
        $this->message = str_replace('&gt;', '&#62;', $this->message);
        $this->message = str_replace('&amp;', '&#38;', $this->message);
        $this->message = str_replace('&apos;', '&#39;', $this->message);
        $this->message = str_replace('&quot;', '&#34;', $this->message);
        $this->message = str_replace("\x0b", ' ', $this->message); //vertical tab
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(trim($this->message) == '') {
Andreas Gohr's avatar
Andreas Gohr committed
            return false;
        }
        $this->_parser = xml_parser_create();
        // Set XML parser to take the case of tags in to account
        xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
        // Set XML parser callback functions
        xml_set_object($this->_parser, $this);
        xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->_parser, 'cdata');
        $chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages
        $final = false;
        do {
            if(strlen($this->message) <= $chunk_size) {
                $final = true;
            }
            $part = substr($this->message, 0, $chunk_size);
            $this->message = substr($this->message, $chunk_size);
            if(!xml_parse($this->_parser, $part, $final)) {
                return false;
            }
            if($final) {
                break;
            }
        } while(true);
Andreas Gohr's avatar
Andreas Gohr committed
        xml_parser_free($this->_parser);
Andreas Gohr's avatar
Andreas Gohr committed
        // Grab the error messages, if any
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->messageType == 'fault') {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->faultCode = $this->params[0]['faultCode'];
            $this->faultString = $this->params[0]['faultString'];
        }
        return true;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param $parser
     * @param string $tag
     * @param $attr
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function tag_open($parser, $tag, $attr) {
        $this->_currentTagContents = '';
        $this->_currentTag = $tag;

Andreas Gohr's avatar
Andreas Gohr committed
        switch($tag) {
            case 'methodCall':
            case 'methodResponse':
            case 'fault':
                $this->messageType = $tag;
                break;
            /* Deal with stacks of arrays and structs */
            case 'data': // data is to all intents and purposes more interesting than array
Andreas Gohr's avatar
Andreas Gohr committed
                $this->_arraystructstypes[] = 'array';
                $this->_arraystructs[] = array();
                break;
            case 'struct':
                $this->_arraystructstypes[] = 'struct';
                $this->_arraystructs[] = array();
                break;
        }
        $this->_lastseen = $tag;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param $parser
     * @param string $cdata
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function cdata($parser, $cdata) {
        $this->_currentTagContents .= $cdata;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param $parser
     * @param $tag
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function tag_close($parser, $tag) {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        $value = null;
Andreas Gohr's avatar
Andreas Gohr committed
        $valueFlag = false;
        switch($tag) {
            case 'int':
            case 'i4':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $value = (int) trim($this->_currentTagContents);
Andreas Gohr's avatar
Andreas Gohr committed
                $valueFlag = true;
                break;
            case 'double':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $value = (double) trim($this->_currentTagContents);
Andreas Gohr's avatar
Andreas Gohr committed
                $valueFlag = true;
                break;
            case 'string':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $value = (string) $this->_currentTagContents;
Andreas Gohr's avatar
Andreas Gohr committed
                $valueFlag = true;
                break;
            case 'dateTime.iso8601':
                $value = new IXR_Date(trim($this->_currentTagContents));
                $valueFlag = true;
                break;
            case 'value':
                // "If no type is indicated, the type is string."
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                if($this->_lastseen == 'value') {
                    $value = (string) $this->_currentTagContents;
                    $valueFlag = true;
                }
Andreas Gohr's avatar
Andreas Gohr committed
                break;
            case 'boolean':
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                $value = (boolean) trim($this->_currentTagContents);
Andreas Gohr's avatar
Andreas Gohr committed
                $valueFlag = true;
                break;
            case 'base64':
                $value = base64_decode($this->_currentTagContents);
                $valueFlag = true;
                break;
            /* Deal with stacks of arrays and structs */
            case 'data':
            case 'struct':
                $value = array_pop($this->_arraystructs);
                array_pop($this->_arraystructstypes);
                $valueFlag = true;
                break;
            case 'member':
                array_pop($this->_currentStructName);
                break;
            case 'name':
                $this->_currentStructName[] = trim($this->_currentTagContents);
                break;
            case 'methodName':
                $this->methodName = trim($this->_currentTagContents);
                break;
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($valueFlag) {
            if(count($this->_arraystructs) > 0) {
Andreas Gohr's avatar
Andreas Gohr committed
                // Add value to struct or array
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                if($this->_arraystructstypes[count($this->_arraystructstypes) - 1] == 'struct') {
Andreas Gohr's avatar
Andreas Gohr committed
                    // Add to struct
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                    $this->_arraystructs[count($this->_arraystructs) - 1][$this->_currentStructName[count($this->_currentStructName) - 1]] = $value;
Andreas Gohr's avatar
Andreas Gohr committed
                } else {
                    // Add to array
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                    $this->_arraystructs[count($this->_arraystructs) - 1][] = $value;
Andreas Gohr's avatar
Andreas Gohr committed
                }
            } else {
                // Just add as a parameter
Andreas Gohr's avatar
Andreas Gohr committed
                $this->params[] = $value;
            }
        }
        $this->_currentTagContents = '';
        $this->_lastseen = $tag;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_Server
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Server {
    var $data;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var array */
Andreas Gohr's avatar
Andreas Gohr committed
    var $callbacks = array();
    var $message;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var array */
Andreas Gohr's avatar
Andreas Gohr committed
    var $capabilities;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param array|bool $callbacks
     * @param bool $data
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     */
    function __construct($callbacks = false, $data = false, $wait = false) {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->setCapabilities();
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($callbacks) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->callbacks = $callbacks;
        }
        $this->setCallbacks();

        if(!$wait) {
            $this->serve($data);
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param bool|string $data
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function serve($data = false) {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$data) {

            $postData = trim(http_get_raw_post_data());
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            if(!$postData) {
                header('Content-Type: text/plain'); // merged from WP #9093
                die('XML-RPC server accepts POST requests only.');
Andreas Gohr's avatar
Andreas Gohr committed
        }
        $this->message = new IXR_Message($data);
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$this->message->parse()) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->error(-32700, 'parse error. not well formed');
        }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->message->messageType != 'methodCall') {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
        }
        $result = $this->call($this->message->methodName, $this->message->params);
Andreas Gohr's avatar
Andreas Gohr committed
        // Is the result an error?
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_a($result, 'IXR_Error')) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->error($result);
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Encode the result
        $r = new IXR_Value($result);
        $resultxml = $r->getXml();
Andreas Gohr's avatar
Andreas Gohr committed
        // Create the XML
        $xml = <<<EOD
<methodResponse>
  <params>
    <param>
      <value>
        $resultxml
      </value>
    </param>
  </params>
</methodResponse>

EOD;
        // Send it
        $this->output($xml);
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param string $methodname
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param array $args
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @return IXR_Error|mixed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function call($methodname, $args) {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$this->hasMethod($methodname)) {
            return new IXR_Error(-32601, 'server error. requested method ' . $methodname . ' does not exist.');
Andreas Gohr's avatar
Andreas Gohr committed
        }
        $method = $this->callbacks[$methodname];
Andreas Gohr's avatar
Andreas Gohr committed
        // Perform the callback and send the response

        # Removed for DokuWiki to have a more consistent interface
        #        if (count($args) == 1) {
        #            // If only one parameter just send that instead of the whole array
        #            $args = $args[0];
        #        }
        # Adjusted for DokuWiki to use call_user_func_array
        // args need to be an array
        $args = (array) $args;

Andreas Gohr's avatar
Andreas Gohr committed
        // Are we dealing with a function or a method?
        if(is_string($method) && substr($method, 0, 5) == 'this:') {
Andreas Gohr's avatar
Andreas Gohr committed
            // It's a class method - check it exists
            $method = substr($method, 5);
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            if(!method_exists($this, $method)) {
                return new IXR_Error(-32601, 'server error. requested class method "' . $method . '" does not exist.');
Andreas Gohr's avatar
Andreas Gohr committed
            }
            // Call the method
            #$result = $this->$method($args);
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            $result = call_user_func_array(array(&$this, $method), $args);
        } elseif(substr($method, 0, 7) == 'plugin:') {
            list($pluginname, $callback) = explode(':', substr($method, 7), 2);
            if(!plugin_isdisabled($pluginname)) {
                $plugin = plugin_load('action', $pluginname);
                return call_user_func_array(array($plugin, $callback), $args);
            } else {
                return new IXR_Error(-99999, 'server error');
            }
Andreas Gohr's avatar
Andreas Gohr committed
        } else {
            // It's a function - does it exist?
            if(is_array($method)) {
                if(!is_callable(array($method[0], $method[1]))) {
                    return new IXR_Error(-32601, 'server error. requested object method "' . $method[1] . '" does not exist.');
                }
            } else if(!function_exists($method)) {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
                return new IXR_Error(-32601, 'server error. requested function "' . $method . '" does not exist.');
Andreas Gohr's avatar
Andreas Gohr committed
            // Call the function
            $result = call_user_func($method, $args);
Andreas Gohr's avatar
Andreas Gohr committed
        }
        return $result;
    }

Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /**
     * @param int $error
     * @param string|bool $message
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function error($error, $message = false) {
        // Accepts either an error object or an error code and message
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($message && !is_object($error)) {
Andreas Gohr's avatar
Andreas Gohr committed
            $error = new IXR_Error($error, $message);
        }
        $this->output($error->getXml());
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function output($xml) {
        header('Content-Type: text/xml; charset=utf-8');
        echo '<?xml version="1.0"?>', "\n", $xml;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param string $method
     * @return bool
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function hasMethod($method) {
        return in_array($method, array_keys($this->callbacks));
    }
Andreas Gohr's avatar
Andreas Gohr committed
    function setCapabilities() {
        // Initialises capabilities array
        $this->capabilities = array(
            'xmlrpc' => array(
                'specUrl' => 'http://www.xmlrpc.com/spec',
                'specVersion' => 1
            ),
            'faults_interop' => array(
                'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
                'specVersion' => 20010516
            ),
            'system.multicall' => array(
                'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
                'specVersion' => 1
            ),
        );
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return mixed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getCapabilities() {
        return $this->capabilities;
    }
Andreas Gohr's avatar
Andreas Gohr committed
    function setCallbacks() {
        $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
        $this->callbacks['system.listMethods'] = 'this:listMethods';
        $this->callbacks['system.multicall'] = 'this:multiCall';
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return array
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function listMethods() {
        // Returns a list of methods - uses array_reverse to ensure user defined
        // methods are listed before server defined methods
        return array_reverse(array_keys($this->callbacks));
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param array $methodcalls
     * @return array
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function multiCall($methodcalls) {
        // See http://www.xmlrpc.com/discuss/msgReader$1208
        $return = array();
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        foreach($methodcalls as $call) {
Andreas Gohr's avatar
Andreas Gohr committed
            $method = $call['methodName'];
            $params = $call['params'];
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            if($method == 'system.multicall') {
                $result = new IXR_Error(-32800, 'Recursive calls to system.multicall are forbidden');
Andreas Gohr's avatar
Andreas Gohr committed
            } else {
                $result = $this->call($method, $params);
            }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            if(is_a($result, 'IXR_Error')) {
Andreas Gohr's avatar
Andreas Gohr committed
                $return[] = array(
                    'faultCode' => $result->code,
                    'faultString' => $result->message
                );
            } else {
                $return[] = array($result);
            }
        }
        return $return;
    }
}

Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_Request
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Request {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var string */
Andreas Gohr's avatar
Andreas Gohr committed
    var $method;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var array */
Andreas Gohr's avatar
Andreas Gohr committed
    var $args;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var string */
Andreas Gohr's avatar
Andreas Gohr committed
    var $xml;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param string $method
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param array $args
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     */
    function __construct($method, $args) {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->method = $method;
        $this->args = $args;
        $this->xml = <<<EOD
<?xml version="1.0"?>
<methodCall>
<methodName>{$this->method}</methodName>
<params>

EOD;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        foreach($this->args as $arg) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->xml .= '<param><value>';
            $v = new IXR_Value($arg);
            $this->xml .= $v->getXml();
            $this->xml .= "</value></param>\n";
        }
        $this->xml .= '</params></methodCall>';
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return int
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getLength() {
        return strlen($this->xml);
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getXml() {
        return $this->xml;
    }
}

 * IXR_Client
 *
 * @package IXR
 * @since 1.5
 *
 * Changed for DokuWiki to use DokuHTTPClient
 *
 * This should be compatible to the original class, but uses DokuWiki's
 * HTTP client library which will respect proxy settings
 *
 * Because the XMLRPC client is not used in DokuWiki currently this is completely
 * untested
 */
class IXR_Client extends DokuHTTPClient {
    var $posturl = '';
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var IXR_Message|bool */
Andreas Gohr's avatar
Andreas Gohr committed
    var $message = false;

    // Storage place for an error message
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var IXR_Error|bool */
    var $xmlerror = false;

Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /**
     * @param string $server
     * @param string|bool $path
     * @param int $port
     * @param int $timeout
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     */
    function __construct($server, $path = false, $port = 80, $timeout = 15) {
        parent::__construct();
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$path) {
Andreas Gohr's avatar
Andreas Gohr committed
            // Assume we have been given a URL instead
            $this->posturl = $server;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        } else {
            $this->posturl = 'http://' . $server . ':' . $port . $path;
        $this->timeout = $timeout;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /**
     * parameters: method and arguments
     * @return bool success or error
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function query() {
        $args = func_get_args();
        $method = array_shift($args);
        $request = new IXR_Request($method, $args);
        $xml = $request->getXml();
        $this->headers['Content-Type'] = 'text/xml';
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$this->sendRequest($this->posturl, $xml, 'POST')) {
            $this->xmlerror = new IXR_Error(-32300, 'transport error - ' . $this->error);
Andreas Gohr's avatar
Andreas Gohr committed
            return false;
        }
        // Check HTTP Response code
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->status < 200 || $this->status > 206) {
            $this->xmlerror = new IXR_Error(-32300, 'transport error - HTTP status ' . $this->status);
Andreas Gohr's avatar
Andreas Gohr committed
        // Now parse what we've got back
        $this->message = new IXR_Message($this->resp_body);
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$this->message->parse()) {
Andreas Gohr's avatar
Andreas Gohr committed
            // XML error
            $this->xmlerror = new IXR_Error(-32700, 'parse error. not well formed');
Andreas Gohr's avatar
Andreas Gohr committed
            return false;
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Is the message a fault?
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($this->message->messageType == 'fault') {
            $this->xmlerror = new IXR_Error($this->message->faultCode, $this->message->faultString);
Andreas Gohr's avatar
Andreas Gohr committed
            return false;
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Message must be OK
        return true;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return mixed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getResponse() {
        // methodResponses can only have one param - return that
        return $this->message->params[0];
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return bool
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function isError() {
        return (is_object($this->xmlerror));
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return int
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getErrorCode() {
        return $this->xmlerror->code;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getErrorMessage() {
        return $this->xmlerror->message;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_Error
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Error {
    var $code;
    var $message;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param int $code
     * @param string $message
     */
    function __construct($code, $message) {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->code = $code;
        $this->message = htmlspecialchars($message);
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getXml() {
        $xml = <<<EOD
<methodResponse>
  <fault>
    <value>
      <struct>
        <member>
          <name>faultCode</name>
          <value><int>{$this->code}</int></value>
        </member>
        <member>
          <name>faultString</name>
          <value><string>{$this->message}</string></value>
        </member>
      </struct>
    </value>
  </fault>
</methodResponse>

EOD;
        return $xml;
    }
}

Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_Date
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Date {

    /** @var DateTime */
    protected $date;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param int|string $time
     */
    public function __construct($time) {
Andreas Gohr's avatar
Andreas Gohr committed
        // $time can be a PHP timestamp or an ISO one
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(is_numeric($time)) {
Andreas Gohr's avatar
Andreas Gohr committed
            $this->parseTimestamp($time);
        } else {
            $this->parseIso($time);
        }
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Parse unix timestamp
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param int $timestamp
     */
    protected function parseTimestamp($timestamp) {
        $this->date = new DateTime('@' . $timestamp);
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Parses less or more complete iso dates and much more, if no timezone given assumes UTC
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param string $iso
     */
    protected function parseIso($iso) {
        $this->date = new DateTime($iso, new DateTimeZone("UTC"));
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Returns date in ISO 8601 format
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @return string
     */
    public function getIso() {
        return $this->date->format(DateTime::ISO8601);
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Returns date in valid xml
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @return string
     */
    public function getXml() {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        return '<dateTime.iso8601>' . $this->getIso() . '</dateTime.iso8601>';
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * Returns Unix timestamp
     *
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @return int
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getTimestamp() {
        return $this->date->getTimestamp();
Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_Base64
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_Base64 {
    var $data;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param string $data
     */
    function __construct($data) {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->data = $data;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @return string
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function getXml() {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        return '<base64>' . base64_encode($this->data) . '</base64>';
Gerrit Uitslag's avatar
Gerrit Uitslag committed
/**
 * IXR_IntrospectionServer
 *
 * @package IXR
 * @since 1.5
Gerrit Uitslag's avatar
Gerrit Uitslag committed
 */
Andreas Gohr's avatar
Andreas Gohr committed
class IXR_IntrospectionServer extends IXR_Server {
Gerrit Uitslag's avatar
Gerrit Uitslag committed
    /** @var array[] */
    var $signatures;
    /** @var string[] */
Andreas Gohr's avatar
Andreas Gohr committed
    var $help;
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    function __construct() {
Andreas Gohr's avatar
Andreas Gohr committed
        $this->setCallbacks();
        $this->setCapabilities();
        $this->capabilities['introspection'] = array(
            'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
            'specVersion' => 1
        );
        $this->addCallback(
            'system.methodSignature',
            'this:methodSignature',
            array('array', 'string'),
            'Returns an array describing the return type and required parameters of a method'
        );
        $this->addCallback(
            'system.getCapabilities',
            'this:getCapabilities',
            array('struct'),
            'Returns a struct describing the XML-RPC specifications supported by this server'
        );
        $this->addCallback(
            'system.listMethods',
            'this:listMethods',
            array('array'),
            'Returns an array of available methods on this server'
        );
        $this->addCallback(
            'system.methodHelp',
            'this:methodHelp',
            array('string', 'string'),
            'Returns a documentation string for the specified method'
        );
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param string $method
     * @param string $callback
     * @param string[] $args
Gerrit Uitslag's avatar
Gerrit Uitslag committed
     * @param string $help
Andreas Gohr's avatar
Andreas Gohr committed
    function addCallback($method, $callback, $args, $help) {
        $this->callbacks[$method] = $callback;
        $this->signatures[$method] = $args;
        $this->help[$method] = $help;
    }
Gerrit Uitslag's avatar
Gerrit Uitslag committed

    /**
     * @param string $methodname
     * @param array $args
     * @return IXR_Error|mixed
     */
Andreas Gohr's avatar
Andreas Gohr committed
    function call($methodname, $args) {
        // Make sure it's in an array
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if($args && !is_array($args)) {
Andreas Gohr's avatar
Andreas Gohr committed
            $args = array($args);
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Over-rides default call method, adds signature check
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(!$this->hasMethod($methodname)) {
            return new IXR_Error(-32601, 'server error. requested method "' . $this->message->methodName . '" not specified.');
Andreas Gohr's avatar
Andreas Gohr committed
        }
        $method = $this->callbacks[$methodname];
        $signature = $this->signatures[$methodname];
        $returnType = array_shift($signature);
Dennis Ploeger's avatar
Dennis Ploeger committed
        // Check the number of arguments. Check only, if the minimum count of parameters is specified. More parameters are possible.
        // This is a hack to allow optional parameters...
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        if(count($args) < count($signature)) {
Andreas Gohr's avatar
Andreas Gohr committed
            // print 'Num of args: '.count($args).' Num in signature: '.count($signature);
            return new IXR_Error(-32602, 'server error. wrong number of method parameters');
        }
Andreas Gohr's avatar
Andreas Gohr committed
        // Check the argument types
        $ok = true;
        $argsbackup = $args;
Gerrit Uitslag's avatar
Gerrit Uitslag committed
        for($i = 0, $j = count($args); $i < $j; $i++) {
Andreas Gohr's avatar
Andreas Gohr committed
            $arg = array_shift($args);
            $type = array_shift($signature);
Gerrit Uitslag's avatar
Gerrit Uitslag committed
            switch($type) {
Andreas Gohr's avatar
Andreas Gohr committed
                case 'int':