translation update
[dokuwiki.git] / inc / IXR_Library.php
blob979dc4d16d29ee4ebb7d238ba4cd515d9ea0d905
1 <?php
2 /**
3 * IXR - The Inutio XML-RPC Library - (c) Incutio Ltd 2002
5 * @version 1.61
6 * @author Simon Willison
7 * @date 11th July 2003
8 * @link http://scripts.incutio.com/xmlrpc/
9 * @link http://scripts.incutio.com/xmlrpc/manual.php
10 * @license Artistic License http://www.opensource.org/licenses/artistic-license.php
12 * Modified for DokuWiki
13 * @author Andreas Gohr <andi@splitbrain.org>
17 class IXR_Value {
18 var $data;
19 var $type;
20 function IXR_Value ($data, $type = false) {
21 $this->data = $data;
22 if (!$type) {
23 $type = $this->calculateType();
25 $this->type = $type;
26 if ($type == 'struct') {
27 /* Turn all the values in the array in to new IXR_Value objects */
28 foreach ($this->data as $key => $value) {
29 $this->data[$key] = new IXR_Value($value);
32 if ($type == 'array') {
33 for ($i = 0, $j = count($this->data); $i < $j; $i++) {
34 $this->data[$i] = new IXR_Value($this->data[$i]);
38 function calculateType() {
39 if ($this->data === true || $this->data === false) {
40 return 'boolean';
42 if (is_integer($this->data)) {
43 return 'int';
45 if (is_double($this->data)) {
46 return 'double';
48 // Deal with IXR object types base64 and date
49 if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
50 return 'date';
52 if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
53 return 'base64';
55 // If it is a normal PHP object convert it in to a struct
56 if (is_object($this->data)) {
58 $this->data = get_object_vars($this->data);
59 return 'struct';
61 if (!is_array($this->data)) {
62 return 'string';
64 /* We have an array - is it an array or a struct ? */
65 if ($this->isStruct($this->data)) {
66 return 'struct';
67 } else {
68 return 'array';
71 function getXml() {
72 /* Return XML for this value */
73 switch ($this->type) {
74 case 'boolean':
75 return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
76 break;
77 case 'int':
78 return '<int>'.$this->data.'</int>';
79 break;
80 case 'double':
81 return '<double>'.$this->data.'</double>';
82 break;
83 case 'string':
84 return '<string>'.htmlspecialchars($this->data).'</string>';
85 break;
86 case 'array':
87 $return = '<array><data>'."\n";
88 foreach ($this->data as $item) {
89 $return .= ' <value>'.$item->getXml()."</value>\n";
91 $return .= '</data></array>';
92 return $return;
93 break;
94 case 'struct':
95 $return = '<struct>'."\n";
96 foreach ($this->data as $name => $value) {
97 $return .= " <member><name>$name</name><value>";
98 $return .= $value->getXml()."</value></member>\n";
100 $return .= '</struct>';
101 return $return;
102 break;
103 case 'date':
104 case 'base64':
105 return $this->data->getXml();
106 break;
108 return false;
110 function isStruct($array) {
111 /* Nasty function to check if an array is a struct or not */
112 $expected = 0;
113 foreach ($array as $key => $value) {
114 if ((string)$key != (string)$expected) {
115 return true;
117 $expected++;
119 return false;
124 class IXR_Message {
125 var $message;
126 var $messageType; // methodCall / methodResponse / fault
127 var $faultCode;
128 var $faultString;
129 var $methodName;
130 var $params;
131 // Current variable stacks
132 var $_arraystructs = array(); // The stack used to keep track of the current array/struct
133 var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array
134 var $_currentStructName = array(); // A stack as well
135 var $_param;
136 var $_value;
137 var $_currentTag;
138 var $_currentTagContents;
139 var $_lastseen;
140 // The XML parser
141 var $_parser;
142 function IXR_Message ($message) {
143 $this->message = $message;
145 function parse() {
146 // first remove the XML declaration
147 $this->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message);
148 // workaround for a bug in PHP/libxml2, see http://bugs.php.net/bug.php?id=45996
149 $this->message = str_replace('&lt;', '&#60;', $this->message);
150 $this->message = str_replace('&gt;', '&#62;', $this->message);
151 $this->message = str_replace('&amp;', '&#38;', $this->message);
152 $this->message = str_replace('&apos;', '&#39;', $this->message);
153 $this->message = str_replace('&quot;', '&#34;', $this->message);
154 $this->message = str_replace("\x0b", ' ', $this->message); //vertical tab
155 if (trim($this->message) == '') {
156 return false;
158 $this->_parser = xml_parser_create();
159 // Set XML parser to take the case of tags in to account
160 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
161 // Set XML parser callback functions
162 xml_set_object($this->_parser, $this);
163 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
164 xml_set_character_data_handler($this->_parser, 'cdata');
165 if (!xml_parse($this->_parser, $this->message)) {
166 /* die(sprintf('XML error: %s at line %d',
167 xml_error_string(xml_get_error_code($this->_parser)),
168 xml_get_current_line_number($this->_parser))); */
169 return false;
171 xml_parser_free($this->_parser);
172 // Grab the error messages, if any
173 if ($this->messageType == 'fault') {
174 $this->faultCode = $this->params[0]['faultCode'];
175 $this->faultString = $this->params[0]['faultString'];
177 return true;
179 function tag_open($parser, $tag, $attr) {
180 $this->currentTag = $tag;
181 $this->_currentTagContents = '';
182 switch($tag) {
183 case 'methodCall':
184 case 'methodResponse':
185 case 'fault':
186 $this->messageType = $tag;
187 break;
188 /* Deal with stacks of arrays and structs */
189 case 'data': // data is to all intents and puposes more interesting than array
190 $this->_arraystructstypes[] = 'array';
191 $this->_arraystructs[] = array();
192 break;
193 case 'struct':
194 $this->_arraystructstypes[] = 'struct';
195 $this->_arraystructs[] = array();
196 break;
198 $this->_lastseen = $tag;
200 function cdata($parser, $cdata) {
201 $this->_currentTagContents .= $cdata;
203 function tag_close($parser, $tag) {
204 $valueFlag = false;
205 switch($tag) {
206 case 'int':
207 case 'i4':
208 $value = (int)trim($this->_currentTagContents);
209 $this->_currentTagContents = '';
210 $valueFlag = true;
211 break;
212 case 'double':
213 $value = (double)trim($this->_currentTagContents);
214 $this->_currentTagContents = '';
215 $valueFlag = true;
216 break;
217 case 'string':
218 $value = (string)$this->_currentTagContents;
219 $this->_currentTagContents = '';
220 $valueFlag = true;
221 break;
222 case 'dateTime.iso8601':
223 $value = new IXR_Date(trim($this->_currentTagContents));
224 // $value = $iso->getTimestamp();
225 $this->_currentTagContents = '';
226 $valueFlag = true;
227 break;
228 case 'value':
229 // "If no type is indicated, the type is string."
230 if($this->_lastseen == 'value'){
231 $value = (string)$this->_currentTagContents;
232 $this->_currentTagContents = '';
233 $valueFlag = true;
235 break;
236 case 'boolean':
237 $value = (boolean)trim($this->_currentTagContents);
238 $this->_currentTagContents = '';
239 $valueFlag = true;
240 break;
241 case 'base64':
242 $value = base64_decode($this->_currentTagContents);
243 $this->_currentTagContents = '';
244 $valueFlag = true;
245 break;
246 /* Deal with stacks of arrays and structs */
247 case 'data':
248 case 'struct':
249 $value = array_pop($this->_arraystructs);
250 array_pop($this->_arraystructstypes);
251 $valueFlag = true;
252 break;
253 case 'member':
254 array_pop($this->_currentStructName);
255 break;
256 case 'name':
257 $this->_currentStructName[] = trim($this->_currentTagContents);
258 $this->_currentTagContents = '';
259 break;
260 case 'methodName':
261 $this->methodName = trim($this->_currentTagContents);
262 $this->_currentTagContents = '';
263 break;
265 if ($valueFlag) {
267 if (!is_array($value) && !is_object($value)) {
268 $value = trim($value);
271 if (count($this->_arraystructs) > 0) {
272 // Add value to struct or array
273 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
274 // Add to struct
275 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
276 } else {
277 // Add to array
278 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
280 } else {
281 // Just add as a paramater
282 $this->params[] = $value;
285 $this->_lastseen = $tag;
290 class IXR_Server {
291 var $data;
292 var $callbacks = array();
293 var $message;
294 var $capabilities;
295 function IXR_Server($callbacks = false, $data = false) {
296 $this->setCapabilities();
297 if ($callbacks) {
298 $this->callbacks = $callbacks;
300 $this->setCallbacks();
301 $this->serve($data);
303 function serve($data = false) {
304 if (!$data) {
306 $postData = trim(http_get_raw_post_data());
307 if (!$postData) {
308 die('XML-RPC server accepts POST requests only.');
310 $data = $postData;
312 $this->message = new IXR_Message($data);
313 if (!$this->message->parse()) {
314 $this->error(-32700, 'parse error. not well formed');
316 if ($this->message->messageType != 'methodCall') {
317 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
319 $result = $this->call($this->message->methodName, $this->message->params);
320 // Is the result an error?
321 if (is_a($result, 'IXR_Error')) {
322 $this->error($result);
324 // Encode the result
325 $r = new IXR_Value($result);
326 $resultxml = $r->getXml();
327 // Create the XML
328 $xml = <<<EOD
329 <methodResponse>
330 <params>
331 <param>
332 <value>
333 $resultxml
334 </value>
335 </param>
336 </params>
337 </methodResponse>
339 EOD;
340 // Send it
341 $this->output($xml);
343 function call($methodname, $args) {
344 if (!$this->hasMethod($methodname)) {
345 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
347 $method = $this->callbacks[$methodname];
348 // Perform the callback and send the response
350 # Removed for DokuWiki to have a more consistent interface
351 # if (count($args) == 1) {
352 # // If only one paramater just send that instead of the whole array
353 # $args = $args[0];
356 # Adjusted for DokuWiki to use call_user_func_array
358 // args need to be an array
359 $args = (array) $args;
361 // Are we dealing with a function or a method?
362 if (substr($method, 0, 5) == 'this:') {
363 // It's a class method - check it exists
364 $method = substr($method, 5);
365 if (!method_exists($this, $method)) {
366 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
368 // Call the method
369 #$result = $this->$method($args);
370 $result = call_user_func_array(array(&$this,$method),$args);
371 } elseif (substr($method, 0, 7) == 'plugin:') {
372 list($pluginname, $callback) = explode(':', substr($method, 7), 2);
373 if(!plugin_isdisabled($pluginname)) {
374 $plugin = plugin_load('action', $pluginname);
375 return call_user_func_array(array($plugin, $callback), $args);
376 } else {
377 return new IXR_Error(-99999, 'server error');
379 } else {
380 // It's a function - does it exist?
381 if (!function_exists($method)) {
382 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
384 // Call the function
385 #$result = $method($args);
386 $result = call_user_func_array($method,$args);
388 return $result;
391 function error($error, $message = false) {
392 // Accepts either an error object or an error code and message
393 if ($message && !is_object($error)) {
394 $error = new IXR_Error($error, $message);
396 $this->output($error->getXml());
398 function output($xml) {
399 header('Content-Type: text/xml; charset=utf-8');
400 echo '<?xml version="1.0"?>', "\n", $xml;
401 exit;
403 function hasMethod($method) {
404 return in_array($method, array_keys($this->callbacks));
406 function setCapabilities() {
407 // Initialises capabilities array
408 $this->capabilities = array(
409 'xmlrpc' => array(
410 'specUrl' => 'http://www.xmlrpc.com/spec',
411 'specVersion' => 1
413 'faults_interop' => array(
414 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
415 'specVersion' => 20010516
417 'system.multicall' => array(
418 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
419 'specVersion' => 1
423 function getCapabilities() {
424 return $this->capabilities;
426 function setCallbacks() {
427 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
428 $this->callbacks['system.listMethods'] = 'this:listMethods';
429 $this->callbacks['system.multicall'] = 'this:multiCall';
431 function listMethods() {
432 // Returns a list of methods - uses array_reverse to ensure user defined
433 // methods are listed before server defined methods
434 return array_reverse(array_keys($this->callbacks));
436 function multiCall($methodcalls) {
437 // See http://www.xmlrpc.com/discuss/msgReader$1208
438 $return = array();
439 foreach ($methodcalls as $call) {
440 $method = $call['methodName'];
441 $params = $call['params'];
442 if ($method == 'system.multicall') {
443 $result = new IXR_Error(-32800, 'Recursive calls to system.multicall are forbidden');
444 } else {
445 $result = $this->call($method, $params);
447 if (is_a($result, 'IXR_Error')) {
448 $return[] = array(
449 'faultCode' => $result->code,
450 'faultString' => $result->message
452 } else {
453 $return[] = array($result);
456 return $return;
460 class IXR_Request {
461 var $method;
462 var $args;
463 var $xml;
464 function IXR_Request($method, $args) {
465 $this->method = $method;
466 $this->args = $args;
467 $this->xml = <<<EOD
468 <?xml version="1.0"?>
469 <methodCall>
470 <methodName>{$this->method}</methodName>
471 <params>
473 EOD;
474 foreach ($this->args as $arg) {
475 $this->xml .= '<param><value>';
476 $v = new IXR_Value($arg);
477 $this->xml .= $v->getXml();
478 $this->xml .= "</value></param>\n";
480 $this->xml .= '</params></methodCall>';
482 function getLength() {
483 return strlen($this->xml);
485 function getXml() {
486 return $this->xml;
491 * Changed for DokuWiki to use DokuHTTPClient
493 * This should be compatible to the original class, but uses DokuWiki's
494 * HTTP client library which will respect proxy settings
496 * Because the XMLRPC client is not used in DokuWiki currently this is completely
497 * untested
499 class IXR_Client extends DokuHTTPClient {
500 var $posturl = '';
501 var $message = false;
502 var $xmlerror = false;
504 function IXR_Client($server, $path = false, $port = 80) {
505 parent::__construct();
506 if (!$path) {
507 // Assume we have been given a URL instead
508 $this->posturl = $server;
509 }else{
510 $this->posturl = 'http://'.$server.':'.$port.$path;
514 function query() {
515 $args = func_get_args();
516 $method = array_shift($args);
517 $request = new IXR_Request($method, $args);
518 $xml = $request->getXml();
520 $this->headers['Content-Type'] = 'text/xml';
521 if(!$this->sendRequest($this->posturl,$xml,'POST')){
522 $this->xmlerror = new IXR_Error(-32300, 'transport error - '.$this->error);
523 return false;
526 // Check HTTP Response code
527 if($this->status < 200 || $this->status > 206){
528 $this->xmlerror = new IXR_Error(-32300, 'transport error - HTTP status '.$this->status);
529 return false;
532 // Now parse what we've got back
533 $this->message = new IXR_Message($this->resp_body);
534 if (!$this->message->parse()) {
535 // XML error
536 $this->xmlerror = new IXR_Error(-32700, 'parse error. not well formed');
537 return false;
539 // Is the message a fault?
540 if ($this->message->messageType == 'fault') {
541 $this->xmlerror = new IXR_Error($this->message->faultCode, $this->message->faultString);
542 return false;
544 // Message must be OK
545 return true;
547 function getResponse() {
548 // methodResponses can only have one param - return that
549 return $this->message->params[0];
551 function isError() {
552 return (is_object($this->xmlerror));
554 function getErrorCode() {
555 return $this->xmlerror->code;
557 function getErrorMessage() {
558 return $this->xmlerror->message;
563 class IXR_Error {
564 var $code;
565 var $message;
566 function IXR_Error($code, $message) {
567 $this->code = $code;
568 $this->message = $message;
570 function getXml() {
571 $xml = <<<EOD
572 <methodResponse>
573 <fault>
574 <value>
575 <struct>
576 <member>
577 <name>faultCode</name>
578 <value><int>{$this->code}</int></value>
579 </member>
580 <member>
581 <name>faultString</name>
582 <value><string>{$this->message}</string></value>
583 </member>
584 </struct>
585 </value>
586 </fault>
587 </methodResponse>
589 EOD;
590 return $xml;
595 class IXR_Date {
596 var $year;
597 var $month;
598 var $day;
599 var $hour;
600 var $minute;
601 var $second;
602 function IXR_Date($time) {
603 // $time can be a PHP timestamp or an ISO one
604 if (is_numeric($time)) {
605 $this->parseTimestamp($time);
606 } else {
607 $this->parseIso($time);
610 function parseTimestamp($timestamp) {
611 $this->year = gmdate('Y', $timestamp);
612 $this->month = gmdate('m', $timestamp);
613 $this->day = gmdate('d', $timestamp);
614 $this->hour = gmdate('H', $timestamp);
615 $this->minute = gmdate('i', $timestamp);
616 $this->second = gmdate('s', $timestamp);
618 function parseIso($iso) {
619 if(preg_match('/^(\d\d\d\d)-?(\d\d)-?(\d\d)([T ](\d\d):(\d\d)(:(\d\d))?)?/',$iso,$match)){
620 $this->year = (int) $match[1];
621 $this->month = (int) $match[2];
622 $this->day = (int) $match[3];
623 $this->hour = (int) $match[5];
624 $this->minute = (int) $match[6];
625 $this->second = (int) $match[8];
628 function getIso() {
629 return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second;
631 function getXml() {
632 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
634 function getTimestamp() {
635 return gmmktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
640 class IXR_Base64 {
641 var $data;
642 function IXR_Base64($data) {
643 $this->data = $data;
645 function getXml() {
646 return '<base64>'.base64_encode($this->data).'</base64>';
651 class IXR_IntrospectionServer extends IXR_Server {
652 var $signatures;
653 var $help;
654 function IXR_IntrospectionServer() {
655 $this->setCallbacks();
656 $this->setCapabilities();
657 $this->capabilities['introspection'] = array(
658 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
659 'specVersion' => 1
661 $this->addCallback(
662 'system.methodSignature',
663 'this:methodSignature',
664 array('array', 'string'),
665 'Returns an array describing the return type and required parameters of a method'
667 $this->addCallback(
668 'system.getCapabilities',
669 'this:getCapabilities',
670 array('struct'),
671 'Returns a struct describing the XML-RPC specifications supported by this server'
673 $this->addCallback(
674 'system.listMethods',
675 'this:listMethods',
676 array('array'),
677 'Returns an array of available methods on this server'
679 $this->addCallback(
680 'system.methodHelp',
681 'this:methodHelp',
682 array('string', 'string'),
683 'Returns a documentation string for the specified method'
686 function addCallback($method, $callback, $args, $help) {
687 $this->callbacks[$method] = $callback;
688 $this->signatures[$method] = $args;
689 $this->help[$method] = $help;
691 function call($methodname, $args) {
692 // Make sure it's in an array
693 if ($args && !is_array($args)) {
694 $args = array($args);
696 // Over-rides default call method, adds signature check
697 if (!$this->hasMethod($methodname)) {
698 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
700 $method = $this->callbacks[$methodname];
701 $signature = $this->signatures[$methodname];
702 $returnType = array_shift($signature);
703 // Check the number of arguments. Check only, if the minimum count of parameters is specified. More parameters are possible.
704 // This is a hack to allow optional parameters...
705 if (count($args) < count($signature)) {
706 // print 'Num of args: '.count($args).' Num in signature: '.count($signature);
707 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
709 // Check the argument types
710 $ok = true;
711 $argsbackup = $args;
712 for ($i = 0, $j = count($args); $i < $j; $i++) {
713 $arg = array_shift($args);
714 $type = array_shift($signature);
715 switch ($type) {
716 case 'int':
717 case 'i4':
718 if (is_array($arg) || !is_int($arg)) {
719 $ok = false;
721 break;
722 case 'base64':
723 case 'string':
724 if (!is_string($arg)) {
725 $ok = false;
727 break;
728 case 'boolean':
729 if ($arg !== false && $arg !== true) {
730 $ok = false;
732 break;
733 case 'float':
734 case 'double':
735 if (!is_float($arg)) {
736 $ok = false;
738 break;
739 case 'date':
740 case 'dateTime.iso8601':
741 if (!is_a($arg, 'IXR_Date')) {
742 $ok = false;
744 break;
746 if (!$ok) {
747 return new IXR_Error(-32602, 'server error. invalid method parameters');
750 // It passed the test - run the "real" method call
751 return parent::call($methodname, $argsbackup);
753 function methodSignature($method) {
754 if (!$this->hasMethod($method)) {
755 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
757 // We should be returning an array of types
758 $types = $this->signatures[$method];
759 $return = array();
760 foreach ($types as $type) {
761 switch ($type) {
762 case 'string':
763 $return[] = 'string';
764 break;
765 case 'int':
766 case 'i4':
767 $return[] = 42;
768 break;
769 case 'double':
770 $return[] = 3.1415;
771 break;
772 case 'dateTime.iso8601':
773 $return[] = new IXR_Date(time());
774 break;
775 case 'boolean':
776 $return[] = true;
777 break;
778 case 'base64':
779 $return[] = new IXR_Base64('base64');
780 break;
781 case 'array':
782 $return[] = array('array');
783 break;
784 case 'struct':
785 $return[] = array('struct' => 'struct');
786 break;
789 return $return;
791 function methodHelp($method) {
792 return $this->help[$method];
797 class IXR_ClientMulticall extends IXR_Client {
798 var $calls = array();
799 function IXR_ClientMulticall($server, $path = false, $port = 80) {
800 parent::IXR_Client($server, $path, $port);
801 //$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
803 function addCall() {
804 $args = func_get_args();
805 $methodName = array_shift($args);
806 $struct = array(
807 'methodName' => $methodName,
808 'params' => $args
810 $this->calls[] = $struct;
812 function query() {
813 // Prepare multicall, then call the parent::query() method
814 return parent::query('system.multicall', $this->calls);